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