4498a750d8c500f10cc43d6c93e0927462237ed8
[platform/upstream/pulseaudio.git] / polyp / protocol-esound.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 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 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 #include <errno.h>
27 #include <string.h>
28 #include <stdio.h>
29 #include <assert.h>
30 #include <stdlib.h>
31 #include <limits.h>
32
33 #include "protocol-esound.h"
34 #include "esound.h"
35 #include "memblock.h"
36 #include "client.h"
37 #include "sink-input.h"
38 #include "sink.h"
39 #include "source-output.h"
40 #include "source.h"
41 #include "sample.h"
42 #include "scache.h"
43 #include "sample-util.h"
44 #include "authkey.h"
45 #include "debug.h"
46 #include "namereg.h"
47 #include "xmalloc.h"
48 #include "log.h"
49
50 #define DEFAULT_COOKIE_FILE ".esd_auth"
51
52 #define PLAYBACK_BUFFER_SECONDS (.5)
53 #define PLAYBACK_BUFFER_FRAGMENTS (10)
54 #define RECORD_BUFFER_SECONDS (5)
55 #define RECORD_BUFFER_FRAGMENTS (100)
56
57 #define MAX_CACHE_SAMPLE_SIZE (1024000)
58
59 #define SCACHE_PREFIX "esound."
60
61 /* This is heavily based on esound's code */
62
63 struct connection {
64     uint32_t index;
65     int dead;
66     struct pa_protocol_esound *protocol;
67     struct pa_iochannel *io;
68     struct pa_client *client;
69     int authorized, swap_byte_order;
70     void *write_data;
71     size_t write_data_alloc, write_data_index, write_data_length;
72     void *read_data;
73     size_t read_data_alloc, read_data_length;
74     esd_proto_t request;
75     esd_client_state_t state;
76     struct pa_sink_input *sink_input;
77     struct pa_source_output *source_output;
78     struct pa_memblockq *input_memblockq, *output_memblockq;
79     struct pa_defer_event *defer_event;
80     
81     struct {
82         struct pa_memblock *current_memblock;
83         size_t memblock_index, fragment_size;
84     } playback;
85
86     struct {
87         struct pa_memchunk memchunk;
88         char *name;
89         struct pa_sample_spec sample_spec;
90     } scache;
91 };
92
93 struct pa_protocol_esound {
94     int public;
95     struct pa_module *module;
96     struct pa_core *core;
97     struct pa_socket_server *server;
98     struct pa_idxset *connections;
99     char *sink_name, *source_name;
100     unsigned n_player;
101     uint8_t esd_key[ESD_KEY_LEN];
102 };
103
104 typedef struct proto_handler {
105     size_t data_length;
106     int (*proc)(struct connection *c, esd_proto_t request, const void *data, size_t length);
107     const char *description;
108 } esd_proto_handler_info_t;
109
110 static void sink_input_drop_cb(struct pa_sink_input *i, const struct pa_memchunk *chunk, size_t length);
111 static int sink_input_peek_cb(struct pa_sink_input *i, struct pa_memchunk *chunk);
112 static void sink_input_kill_cb(struct pa_sink_input *i);
113 static pa_usec_t sink_input_get_latency_cb(struct pa_sink_input *i);
114 static pa_usec_t source_output_get_latency_cb(struct pa_source_output *o);
115
116 static void source_output_push_cb(struct pa_source_output *o, const struct pa_memchunk *chunk);
117 static void source_output_kill_cb(struct pa_source_output *o);
118
119 static int esd_proto_connect(struct connection *c, esd_proto_t request, const void *data, size_t length);
120 static int esd_proto_stream_play(struct connection *c, esd_proto_t request, const void *data, size_t length);
121 static int esd_proto_stream_record(struct connection *c, esd_proto_t request, const void *data, size_t length);
122 static int esd_proto_get_latency(struct connection *c, esd_proto_t request, const void *data, size_t length);
123 static int esd_proto_server_info(struct connection *c, esd_proto_t request, const void *data, size_t length);
124 static int esd_proto_all_info(struct connection *c, esd_proto_t request, const void *data, size_t length);
125 static int esd_proto_stream_pan(struct connection *c, esd_proto_t request, const void *data, size_t length);
126 static int esd_proto_sample_cache(struct connection *c, esd_proto_t request, const void *data, size_t length);
127 static int esd_proto_sample_free_or_play(struct connection *c, esd_proto_t request, const void *data, size_t length);
128 static int esd_proto_sample_get_id(struct connection *c, esd_proto_t request, const void *data, size_t length);
129 static int esd_proto_standby_or_resume(struct connection *c, esd_proto_t request, const void *data, size_t length);
130
131 /* the big map of protocol handler info */
132 static struct proto_handler proto_map[ESD_PROTO_MAX] = {
133     { ESD_KEY_LEN + sizeof(int),      esd_proto_connect, "connect" },
134     { ESD_KEY_LEN + sizeof(int),      NULL, "lock" },
135     { ESD_KEY_LEN + sizeof(int),      NULL, "unlock" },
136
137     { ESD_NAME_MAX + 2 * sizeof(int), esd_proto_stream_play, "stream play" },
138     { ESD_NAME_MAX + 2 * sizeof(int), esd_proto_stream_record, "stream rec" },
139     { ESD_NAME_MAX + 2 * sizeof(int), esd_proto_stream_record, "stream mon" },
140
141     { ESD_NAME_MAX + 3 * sizeof(int), esd_proto_sample_cache, "sample cache" },                      /* 6 */
142     { sizeof(int),                    esd_proto_sample_free_or_play, "sample free" },
143     { sizeof(int),                    esd_proto_sample_free_or_play, "sample play" },                /* 8 */
144     { sizeof(int),                    NULL, "sample loop" },
145     { sizeof(int),                    NULL, "sample stop" },
146     { -1,                             NULL, "TODO: sample kill" },
147
148     { ESD_KEY_LEN + sizeof(int),      esd_proto_standby_or_resume, "standby" },  /* NOOP! */
149     { ESD_KEY_LEN + sizeof(int),      esd_proto_standby_or_resume, "resume" },   /* NOOP! */         /* 13 */
150
151     { ESD_NAME_MAX,                   esd_proto_sample_get_id, "sample getid" },                     /* 14 */
152     { ESD_NAME_MAX + 2 * sizeof(int), NULL, "stream filter" },
153
154     { sizeof(int),                    esd_proto_server_info, "server info" },
155     { sizeof(int),                    esd_proto_all_info, "all info" },
156     { -1,                             NULL, "TODO: subscribe" },
157     { -1,                             NULL, "TODO: unsubscribe" },
158
159     { 3 * sizeof(int),                esd_proto_stream_pan, "stream pan"},
160     { 3 * sizeof(int),                NULL, "sample pan" },
161      
162     { sizeof(int),                    NULL, "standby mode" },
163     { 0,                              esd_proto_get_latency, "get latency" }
164 };
165
166
167 static void connection_free(struct connection *c) {
168     assert(c);
169     pa_idxset_remove_by_data(c->protocol->connections, c, NULL);
170
171     if (c->state == ESD_STREAMING_DATA)
172         c->protocol->n_player--;
173     
174     pa_client_free(c->client);
175
176     if (c->sink_input) {
177         pa_sink_input_disconnect(c->sink_input);
178         pa_sink_input_unref(c->sink_input);
179     }
180     
181     if (c->source_output) {
182         pa_source_output_disconnect(c->source_output);
183         pa_source_output_unref(c->source_output);
184     }
185     
186     if (c->input_memblockq)
187         pa_memblockq_free(c->input_memblockq);
188     if (c->output_memblockq)
189         pa_memblockq_free(c->output_memblockq);
190
191     if (c->playback.current_memblock)
192         pa_memblock_unref(c->playback.current_memblock);
193     
194     pa_xfree(c->read_data);
195     pa_xfree(c->write_data);
196     
197     pa_iochannel_free(c->io);
198     
199     if (c->defer_event)
200         c->protocol->core->mainloop->defer_free(c->defer_event);
201
202     if (c->scache.memchunk.memblock)
203         pa_memblock_unref(c->scache.memchunk.memblock);
204     pa_xfree(c->scache.name);
205     
206     pa_xfree(c);
207 }
208
209 static void* connection_write(struct connection *c, size_t length) {
210     size_t t, i;
211     assert(c);
212
213     assert(c->protocol && c->protocol->core && c->protocol->core->mainloop && c->protocol->core->mainloop->defer_enable);
214     c->protocol->core->mainloop->defer_enable(c->defer_event, 1);
215
216     t = c->write_data_length+length;
217     
218     if (c->write_data_alloc < t)
219         c->write_data = pa_xrealloc(c->write_data, c->write_data_alloc = t);
220
221     assert(c->write_data);
222
223     i = c->write_data_length;
224     c->write_data_length += length;
225     
226     return (uint8_t*) c->write_data+i;
227 }
228
229 static void format_esd2native(int format, struct pa_sample_spec *ss) {
230     assert(ss);
231
232     ss->channels = ((format & ESD_MASK_CHAN) == ESD_STEREO) ? 2 : 1;
233     ss->format = ((format & ESD_MASK_BITS) == ESD_BITS16) ? PA_SAMPLE_S16NE : PA_SAMPLE_U8;
234 }
235
236 static int format_native2esd(struct pa_sample_spec *ss) {
237     int format = 0;
238     
239     format = (ss->format == PA_SAMPLE_U8) ? ESD_BITS8 : ESD_BITS16;
240     format |= (ss->channels >= 2) ? ESD_STEREO : ESD_MONO;
241
242     return format;
243 }
244
245 /*** esound commands ***/
246
247 static int esd_proto_connect(struct connection *c, esd_proto_t request, const void *data, size_t length) {
248     uint32_t ekey;
249     int *ok;
250     assert(length == (ESD_KEY_LEN + sizeof(uint32_t)));
251
252     if (!c->authorized) {
253         if (memcmp(data, c->protocol->esd_key, ESD_KEY_LEN) != 0) {
254             pa_log(__FILE__": kicked client with invalid authorization key.\n");
255             return -1;
256         }
257
258         c->authorized = 1;
259     }
260     
261     ekey = *(uint32_t*)((uint8_t*) data+ESD_KEY_LEN);
262     if (ekey == ESD_ENDIAN_KEY)
263         c->swap_byte_order = 0;
264     else if (ekey == ESD_SWAP_ENDIAN_KEY)
265         c->swap_byte_order = 1;
266     else {
267         pa_log(__FILE__": client sent invalid endian key\n");
268         return -1;
269     }
270
271     ok = connection_write(c, sizeof(int));
272     assert(ok);
273     *ok = 1;
274     return 0;
275 }
276
277 static int esd_proto_stream_play(struct connection *c, esd_proto_t request, const void *data, size_t length) {
278     char name[ESD_NAME_MAX];
279     int format, rate;
280     struct pa_sink *sink;
281     struct pa_sample_spec ss;
282     size_t l;
283     assert(c && length == (sizeof(int)*2+ESD_NAME_MAX));
284     
285     format = maybe_swap_endian_32(c->swap_byte_order, *(int*)data);
286     rate = maybe_swap_endian_32(c->swap_byte_order, *((int*)data + 1));
287
288     ss.rate = rate;
289     format_esd2native(format, &ss);
290
291     if (!pa_sample_spec_valid(&ss))
292         return -1;
293
294     if (!(sink = pa_namereg_get(c->protocol->core, c->protocol->sink_name, PA_NAMEREG_SINK, 1))) {
295         pa_log(__FILE__": No output sink\n");
296         return -1;
297     }
298     
299     strncpy(name, (char*) data + sizeof(int)*2, sizeof(name));
300     name[sizeof(name)-1] = 0;
301
302     pa_client_set_name(c->client, name);
303
304     assert(!c->input_memblockq);
305
306     l = (size_t) (pa_bytes_per_second(&ss)*PLAYBACK_BUFFER_SECONDS); 
307     c->input_memblockq = pa_memblockq_new(l, 0, pa_frame_size(&ss), l/2, l/PLAYBACK_BUFFER_FRAGMENTS, c->protocol->core->memblock_stat);
308     assert(c->input_memblockq);
309     pa_iochannel_socket_set_rcvbuf(c->io, l/PLAYBACK_BUFFER_FRAGMENTS*2);
310     c->playback.fragment_size = l/10;
311     
312     assert(!c->sink_input);
313     c->sink_input = pa_sink_input_new(sink, name, &ss, 0, -1);
314     assert(c->sink_input);
315
316     c->sink_input->owner = c->protocol->module;
317     c->sink_input->client = c->client;
318     c->sink_input->peek = sink_input_peek_cb;
319     c->sink_input->drop = sink_input_drop_cb;
320     c->sink_input->kill = sink_input_kill_cb;
321     c->sink_input->get_latency = sink_input_get_latency_cb;
322     c->sink_input->userdata = c;
323
324     c->state = ESD_STREAMING_DATA;
325
326     c->protocol->n_player++;
327     
328     return 0;
329 }
330
331 static int esd_proto_stream_record(struct connection *c, esd_proto_t request, const void *data, size_t length) {
332     char name[ESD_NAME_MAX];
333     int format, rate;
334     struct pa_source *source;
335     struct pa_sample_spec ss;
336     size_t l;
337     assert(c && length == (sizeof(int)*2+ESD_NAME_MAX));
338     
339     format = maybe_swap_endian_32(c->swap_byte_order, *(int*)data);
340     rate = maybe_swap_endian_32(c->swap_byte_order, *((int*)data + 1));
341
342     ss.rate = rate;
343     format_esd2native(format, &ss);
344
345     if (!pa_sample_spec_valid(&ss))
346         return -1;
347
348     if (request == ESD_PROTO_STREAM_MON) {
349         struct pa_sink* sink;
350
351         if (!(sink = pa_namereg_get(c->protocol->core, c->protocol->sink_name, PA_NAMEREG_SINK, 1)))
352             return -1;
353
354         if (!(source = sink->monitor_source))
355             return -1;
356     } else {
357         assert(request == ESD_PROTO_STREAM_REC);
358         
359         if (!(source = pa_namereg_get(c->protocol->core, c->protocol->source_name, PA_NAMEREG_SOURCE, 1)))
360             return -1;
361     }
362     
363     strncpy(name, (char*) data + sizeof(int)*2, sizeof(name));
364     name[sizeof(name)-1] = 0;
365
366     pa_client_set_name(c->client, name);
367
368     assert(!c->output_memblockq);
369
370     l = (size_t) (pa_bytes_per_second(&ss)*RECORD_BUFFER_SECONDS); 
371     c->output_memblockq = pa_memblockq_new(l, 0, pa_frame_size(&ss), 0, 0, c->protocol->core->memblock_stat);
372     assert(c->output_memblockq);
373     pa_iochannel_socket_set_sndbuf(c->io, l/RECORD_BUFFER_FRAGMENTS*2);
374     
375     assert(!c->source_output);
376     c->source_output = pa_source_output_new(source, name, &ss, -1);
377     assert(c->source_output);
378     
379     c->source_output->owner = c->protocol->module;
380     c->source_output->client = c->client;
381     c->source_output->push = source_output_push_cb;
382     c->source_output->kill = source_output_kill_cb;
383     c->source_output->get_latency = source_output_get_latency_cb;
384     c->source_output->userdata = c;
385
386     c->state = ESD_STREAMING_DATA;
387
388     c->protocol->n_player++;
389     
390     return 0;
391 }
392
393 static int esd_proto_get_latency(struct connection *c, esd_proto_t request, const void *data, size_t length) {
394     struct pa_sink *sink;
395     int latency, *lag;
396     assert(c && !data && length == 0);
397
398     if (!(sink = pa_namereg_get(c->protocol->core, c->protocol->sink_name, PA_NAMEREG_SINK, 1)))
399         latency = 0;
400     else {
401         double usec = pa_sink_get_latency(sink);
402         usec += PLAYBACK_BUFFER_SECONDS*1000000;          /* A better estimation would be a good idea! */
403         latency = (int) ((usec*44100)/1000000);
404     }
405     
406     lag = connection_write(c, sizeof(int));
407     assert(lag);
408     *lag = c->swap_byte_order ? swap_endian_32(latency) : latency;
409     return 0;
410 }
411
412 static int esd_proto_server_info(struct connection *c, esd_proto_t request, const void *data, size_t length) {
413     int rate = 44100, format = ESD_STEREO|ESD_BITS16;
414     int *response;
415     struct pa_sink *sink;
416     assert(c && data && length == sizeof(int));
417
418     if ((sink = pa_namereg_get(c->protocol->core, c->protocol->sink_name, PA_NAMEREG_SINK, 1))) {
419         rate = sink->sample_spec.rate;
420         format = format_native2esd(&sink->sample_spec);
421     }
422     
423     response = connection_write(c, sizeof(int)*3);
424     assert(response);
425     *(response++) = 0;
426     *(response++) = maybe_swap_endian_32(c->swap_byte_order, rate);
427     *(response++) = maybe_swap_endian_32(c->swap_byte_order, format);
428     return 0;
429 }
430
431 static int esd_proto_all_info(struct connection *c, esd_proto_t request, const void *data, size_t length) {
432     uint8_t *response;
433     size_t t, k, s;
434     struct connection *conn;
435     size_t index = PA_IDXSET_INVALID;
436     unsigned nsamples;
437     assert(c && data && length == sizeof(int));
438     
439     if (esd_proto_server_info(c, request, data, length) < 0)
440         return -1;
441
442     k = sizeof(int)*5+ESD_NAME_MAX;
443     s = sizeof(int)*6+ESD_NAME_MAX;
444     nsamples = c->protocol->core->scache ? pa_idxset_ncontents(c->protocol->core->scache) : 0;
445     response = connection_write(c, (t = s*(nsamples+1) + k*(c->protocol->n_player+1)));
446     assert(k);
447
448     for (conn = pa_idxset_first(c->protocol->connections, &index); conn; conn = pa_idxset_next(c->protocol->connections, &index)) {
449         int format = ESD_BITS16 | ESD_STEREO, rate = 44100, volume = 0xFF;
450
451         if (conn->state != ESD_STREAMING_DATA)
452             continue;
453
454         assert(t >= s+k+k);
455         
456         if (conn->sink_input) {
457             rate = conn->sink_input->sample_spec.rate;
458             volume = (conn->sink_input->volume*0xFF)/0x100;
459             format = format_native2esd(&conn->sink_input->sample_spec);
460         }
461         
462         /* id */
463         *((int*) response) = maybe_swap_endian_32(c->swap_byte_order, (int) (conn->index+1));
464         response += sizeof(int);
465
466         /* name */
467         assert(conn->client);
468         strncpy((char*) response, conn->client->name, ESD_NAME_MAX);
469         response += ESD_NAME_MAX;
470
471         /* rate */
472         *((int*) response) = maybe_swap_endian_32(c->swap_byte_order,  rate);
473         response += sizeof(int);
474
475         /* left */
476         *((int*) response) = maybe_swap_endian_32(c->swap_byte_order,  volume);
477         response += sizeof(int);
478
479         /*right*/
480         *((int*) response) = maybe_swap_endian_32(c->swap_byte_order,  volume);
481         response += sizeof(int);
482
483         /*format*/
484         *((int*) response) = maybe_swap_endian_32(c->swap_byte_order, format);
485         response += sizeof(int);
486
487         t-= k;
488     }
489
490     assert(t == s*(nsamples+1)+k);
491     memset(response, 0, k);
492     response += k;
493     t -= k;
494
495     if (nsamples) {
496         struct pa_scache_entry *ce;
497         
498         index = PA_IDXSET_INVALID;
499         for (ce = pa_idxset_first(c->protocol->core->scache, &index); ce; ce = pa_idxset_next(c->protocol->core->scache, &index)) {
500             assert(t >= s*2);
501             
502             /* id */
503             *((int*) response) = maybe_swap_endian_32(c->swap_byte_order, (int) (ce->index+1));
504             response += sizeof(int);
505             
506             /* name */
507             if (strncmp(ce->name, SCACHE_PREFIX, sizeof(SCACHE_PREFIX)-1) == 0)
508                 strncpy((char*) response, ce->name+sizeof(SCACHE_PREFIX)-1, ESD_NAME_MAX);
509             else
510                 snprintf((char*) response, ESD_NAME_MAX, "native.%s", ce->name);
511             response += ESD_NAME_MAX;
512             
513             /* rate */
514             *((int*) response) = maybe_swap_endian_32(c->swap_byte_order, ce->sample_spec.rate);
515             response += sizeof(int);
516             
517             /* left */
518             *((int*) response) = maybe_swap_endian_32(c->swap_byte_order, (ce->volume*0xFF)/0x100);
519             response += sizeof(int);
520             
521             /*right*/
522             *((int*) response) = maybe_swap_endian_32(c->swap_byte_order, (ce->volume*0xFF)/0x100);
523             response += sizeof(int);
524             
525             /*format*/
526             *((int*) response) = maybe_swap_endian_32(c->swap_byte_order, format_native2esd(&ce->sample_spec));
527             response += sizeof(int);
528
529             /*length*/
530             *((int*) response) = maybe_swap_endian_32(c->swap_byte_order, (int) ce->memchunk.length);
531             response += sizeof(int);
532
533             t -= s;
534         }
535     }
536
537     assert(t == s);
538     memset(response, 0, s);
539
540     return 0;
541 }
542
543 static int esd_proto_stream_pan(struct connection *c, esd_proto_t request, const void *data, size_t length) {
544     int *ok;
545     uint32_t index, volume;
546     struct connection *conn;
547     assert(c && data && length == sizeof(int)*3);
548     
549     index = (uint32_t) maybe_swap_endian_32(c->swap_byte_order, *(int*)data)-1;
550     volume = (uint32_t) maybe_swap_endian_32(c->swap_byte_order, *((int*)data + 1));
551     volume = (volume*0x100)/0xFF;
552
553     ok = connection_write(c, sizeof(int));
554     assert(ok);
555
556     if ((conn = pa_idxset_get_by_index(c->protocol->connections, index))) {
557         assert(conn->sink_input);
558         conn->sink_input->volume = volume;
559         *ok = 1;
560     } else
561         *ok = 0;
562     
563     return 0;
564 }
565
566 static int esd_proto_sample_cache(struct connection *c, esd_proto_t request, const void *data, size_t length) {
567     struct pa_sample_spec ss;
568     int format, rate;
569     size_t sc_length;
570     uint32_t index;
571     int *ok;
572     char name[ESD_NAME_MAX+sizeof(SCACHE_PREFIX)-1];
573     assert(c && data && length == (ESD_NAME_MAX+3*sizeof(int)));
574
575     format = maybe_swap_endian_32(c->swap_byte_order, *(int*)data);
576     rate = maybe_swap_endian_32(c->swap_byte_order, *((int*)data + 1));
577     
578     ss.rate = rate;
579     format_esd2native(format, &ss);
580
581     sc_length = (size_t) maybe_swap_endian_32(c->swap_byte_order, (*((int*)data + 2)));
582
583     if (sc_length >= MAX_CACHE_SAMPLE_SIZE)
584         return -1;
585
586     strcpy(name, SCACHE_PREFIX);
587     strncpy(name+sizeof(SCACHE_PREFIX)-1, (char*) data+3*sizeof(int), ESD_NAME_MAX);
588     name[sizeof(name)-1] = 0;
589     
590     assert(!c->scache.memchunk.memblock);
591     c->scache.memchunk.memblock = pa_memblock_new(sc_length, c->protocol->core->memblock_stat);
592     c->scache.memchunk.index = 0;
593     c->scache.memchunk.length = sc_length;
594     c->scache.sample_spec = ss;
595     assert(!c->scache.name);
596     c->scache.name = pa_xstrdup(name);
597
598     c->state = ESD_CACHING_SAMPLE;
599
600     pa_scache_add_item(c->protocol->core, c->scache.name, NULL, NULL, &index);
601
602     ok = connection_write(c, sizeof(int));
603     assert(ok);
604     
605     *ok = index+1;
606     
607     return 0;
608 }
609
610 static int esd_proto_sample_get_id(struct connection *c, esd_proto_t request, const void *data, size_t length) {
611     int *ok;
612     uint32_t index;
613     char name[ESD_NAME_MAX+sizeof(SCACHE_PREFIX)-1];
614     assert(c && data && length == ESD_NAME_MAX);
615
616     ok = connection_write(c, sizeof(int));
617     assert(ok);
618
619     *ok = -1;
620
621     strcpy(name, SCACHE_PREFIX);
622     strncpy(name+sizeof(SCACHE_PREFIX)-1, data, ESD_NAME_MAX);
623     name[sizeof(name)-1] = 0;
624
625     if ((index = pa_scache_get_id_by_name(c->protocol->core, name)) != PA_IDXSET_INVALID)
626         *ok = (int) index +1;
627
628     return 0;
629 }
630
631 static int esd_proto_sample_free_or_play(struct connection *c, esd_proto_t request, const void *data, size_t length) {
632     int *ok;
633     const char *name;
634     uint32_t index;
635     assert(c && data && length == sizeof(int));
636
637     index = (uint32_t) maybe_swap_endian_32(c->swap_byte_order, *(int*)data)-1;
638
639     ok = connection_write(c, sizeof(int));
640     assert(ok);
641
642     *ok = 0;
643     
644     if ((name = pa_scache_get_name_by_id(c->protocol->core, index))) {
645         if (request == ESD_PROTO_SAMPLE_PLAY) {
646             struct pa_sink *sink;
647         
648             if ((sink = pa_namereg_get(c->protocol->core, c->protocol->sink_name, PA_NAMEREG_SINK, 1)))
649                 if (pa_scache_play_item(c->protocol->core, name, sink, PA_VOLUME_NORM) >= 0)
650                     *ok = (int) index+1;
651         } else {
652             assert(request == ESD_PROTO_SAMPLE_FREE);
653
654             if (pa_scache_remove_item(c->protocol->core, name) >= 0)
655                 *ok = (int) index+1;
656         }
657     }
658     
659     return 0;
660 }
661
662 static int esd_proto_standby_or_resume(struct connection *c, esd_proto_t request, const void *data, size_t length) {
663     int *ok;
664     ok = connection_write(c, sizeof(int)*2);
665     assert(ok);
666     ok[0] = 1;
667     ok[1] = 1;
668     return 0;
669 }
670
671 /*** client callbacks ***/
672
673 static void client_kill_cb(struct pa_client *c) {
674     assert(c && c->userdata);
675     connection_free(c->userdata);
676 }
677
678 /*** pa_iochannel callbacks ***/
679
680 static int do_read(struct connection *c) {
681     assert(c && c->io);
682
683     if (c->state == ESD_NEXT_REQUEST) {
684         ssize_t r;
685         assert(c->read_data_length < sizeof(c->request));
686
687         if ((r = pa_iochannel_read(c->io, ((uint8_t*) &c->request) + c->read_data_length, sizeof(c->request) - c->read_data_length)) <= 0) {
688             pa_log(__FILE__": read() failed: %s\n", r == 0 ? "EOF" : strerror(errno));
689             return -1;
690         }
691
692         if ((c->read_data_length+= r) >= sizeof(c->request)) {
693             struct proto_handler *handler;
694             
695             if (c->swap_byte_order)
696                 c->request = swap_endian_32(c->request);
697
698             if (c->request < ESD_PROTO_CONNECT || c->request > ESD_PROTO_MAX) {
699                 pa_log(__FILE__": recieved invalid request.\n");
700                 return -1;
701             }
702
703             handler = proto_map+c->request;
704
705             pa_log(__FILE__": executing request #%u\n", c->request);
706
707             if (!handler->proc) {
708                 pa_log(__FILE__": recieved unimplemented request #%u.\n", c->request);
709                 return -1;
710             }
711             
712             if (handler->data_length == 0) {
713                 c->read_data_length = 0;
714
715                 if (handler->proc(c, c->request, NULL, 0) < 0)
716                     return -1;
717                 
718             } else {
719                 if (c->read_data_alloc < handler->data_length)
720                     c->read_data = pa_xrealloc(c->read_data, c->read_data_alloc = handler->data_length);
721                 assert(c->read_data);
722                 
723                 c->state = ESD_NEEDS_REQDATA;
724                 c->read_data_length = 0;
725             }
726         }
727
728     } else if (c->state == ESD_NEEDS_REQDATA) {
729         ssize_t r;
730         struct proto_handler *handler = proto_map+c->request;
731
732         assert(handler->proc);
733         
734         assert(c->read_data && c->read_data_length < handler->data_length);
735
736         if ((r = pa_iochannel_read(c->io, (uint8_t*) c->read_data + c->read_data_length, handler->data_length - c->read_data_length)) <= 0) {
737             pa_log(__FILE__": read() failed: %s\n", r == 0 ? "EOF" : strerror(errno));
738             return -1;
739         }
740
741         if ((c->read_data_length+= r) >= handler->data_length) {
742             size_t l = c->read_data_length;
743             assert(handler->proc);
744
745             c->state = ESD_NEXT_REQUEST;
746             c->read_data_length = 0;
747             
748             if (handler->proc(c, c->request, c->read_data, l) < 0)
749                 return -1;
750         }
751     } else if (c->state == ESD_CACHING_SAMPLE) {
752         ssize_t r;
753
754         assert(c->scache.memchunk.memblock && c->scache.name && c->scache.memchunk.index < c->scache.memchunk.length);
755         
756         if ((r = pa_iochannel_read(c->io, (uint8_t*) c->scache.memchunk.memblock->data+c->scache.memchunk.index, c->scache.memchunk.length-c->scache.memchunk.index)) <= 0) {
757             pa_log(__FILE__": read() failed: %s\n", r == 0 ? "EOF" : strerror(errno));
758             return -1;
759         }
760
761         c->scache.memchunk.index += r;
762         assert(c->scache.memchunk.index <= c->scache.memchunk.length);
763         
764         if (c->scache.memchunk.index == c->scache.memchunk.length) {
765             uint32_t index;
766             int *ok;
767             
768             c->scache.memchunk.index = 0;
769             pa_scache_add_item(c->protocol->core, c->scache.name, &c->scache.sample_spec, &c->scache.memchunk, &index);
770
771             pa_memblock_unref(c->scache.memchunk.memblock);
772             c->scache.memchunk.memblock = NULL;
773             c->scache.memchunk.index = c->scache.memchunk.length = 0;
774
775             pa_xfree(c->scache.name);
776             c->scache.name = NULL;
777
778             c->state = ESD_NEXT_REQUEST;
779
780             ok = connection_write(c, sizeof(int));
781             assert(ok);
782             *ok = index+1;
783         }
784         
785     } else if (c->state == ESD_STREAMING_DATA && c->sink_input) {
786         struct pa_memchunk chunk;
787         ssize_t r;
788         size_t l;
789
790         assert(c->input_memblockq);
791
792         if (!(l = pa_memblockq_missing(c->input_memblockq)))
793             return 0;
794
795         if (l > c->playback.fragment_size)
796             l = c->playback.fragment_size;
797
798         if (c->playback.current_memblock) 
799             if (c->playback.current_memblock->length - c->playback.memblock_index < l) {
800                 pa_memblock_unref(c->playback.current_memblock);
801                 c->playback.current_memblock = NULL;
802                 c->playback.memblock_index = 0;
803             }
804         
805         if (!c->playback.current_memblock) {
806             c->playback.current_memblock = pa_memblock_new(c->playback.fragment_size*2, c->protocol->core->memblock_stat);
807             assert(c->playback.current_memblock && c->playback.current_memblock->length >= l);
808             c->playback.memblock_index = 0;
809         }
810
811         if ((r = pa_iochannel_read(c->io, (uint8_t*) c->playback.current_memblock->data+c->playback.memblock_index, l)) <= 0) {
812             pa_log(__FILE__": read() failed: %s\n", r == 0 ? "EOF" : strerror(errno));
813             return -1;
814         }
815         
816         chunk.memblock = c->playback.current_memblock;
817         chunk.index = c->playback.memblock_index;
818         chunk.length = r;
819         assert(chunk.memblock);
820
821         c->playback.memblock_index += r;
822         
823         assert(c->input_memblockq);
824         pa_memblockq_push_align(c->input_memblockq, &chunk, 0);
825         assert(c->sink_input);
826         pa_sink_notify(c->sink_input->sink);
827     }
828     
829     return 0;
830 }
831
832 static int do_write(struct connection *c) {
833     assert(c && c->io);
834
835     if (c->write_data_length) {
836         ssize_t r;
837         
838         assert(c->write_data_index < c->write_data_length);
839         if ((r = pa_iochannel_write(c->io, (uint8_t*) c->write_data+c->write_data_index, c->write_data_length-c->write_data_index)) < 0) {
840             pa_log(__FILE__": write() failed: %s\n", strerror(errno));
841             return -1;
842         }
843         
844         if ((c->write_data_index +=r) >= c->write_data_length)
845             c->write_data_length = c->write_data_index = 0;
846         
847     } else if (c->state == ESD_STREAMING_DATA && c->source_output) {
848         struct pa_memchunk chunk;
849         ssize_t r;
850
851         assert(c->output_memblockq);
852         if (pa_memblockq_peek(c->output_memblockq, &chunk) < 0)
853             return 0;
854         
855         assert(chunk.memblock && chunk.length);
856         
857         if ((r = pa_iochannel_write(c->io, (uint8_t*) chunk.memblock->data+chunk.index, chunk.length)) < 0) {
858             pa_memblock_unref(chunk.memblock);
859             pa_log(__FILE__": write(): %s\n", strerror(errno));
860             return -1;
861         }
862     
863         pa_memblockq_drop(c->output_memblockq, &chunk, r);
864         pa_memblock_unref(chunk.memblock);
865     }
866     
867     return 0;
868 }
869
870 static void do_work(struct connection *c) {
871     assert(c);
872
873     assert(c->protocol && c->protocol->core && c->protocol->core->mainloop && c->protocol->core->mainloop->defer_enable);
874     c->protocol->core->mainloop->defer_enable(c->defer_event, 0);
875     
876     if (c->dead)
877         return;
878     
879     if (pa_iochannel_is_readable(c->io))
880         if (do_read(c) < 0)
881             goto fail;
882
883     if (pa_iochannel_is_writable(c->io))
884         if (do_write(c) < 0)
885             goto fail;
886
887     return;
888
889 fail:
890
891     if (c->state == ESD_STREAMING_DATA && c->sink_input) {
892         c->dead = 1;
893         pa_memblockq_prebuf_disable(c->input_memblockq);
894         c->protocol->core->mainloop->defer_enable(c->defer_event, 0);
895     } else
896         connection_free(c);
897 }
898
899 static void io_callback(struct pa_iochannel*io, void *userdata) {
900     struct connection *c = userdata;
901     assert(io && c && c->io == io);
902
903     do_work(c);
904 }
905
906 /*** defer callback ***/
907
908 static void defer_callback(struct pa_mainloop_api*a, struct pa_defer_event *e, void *userdata) {
909     struct connection *c = userdata;
910     assert(a && c && c->defer_event == e);
911
912     do_work(c);
913 }
914
915 /*** sink_input callbacks ***/
916
917 static int sink_input_peek_cb(struct pa_sink_input *i, struct pa_memchunk *chunk) {
918     struct connection*c;
919     assert(i && i->userdata && chunk);
920     c = i->userdata;
921     
922     if (pa_memblockq_peek(c->input_memblockq, chunk) < 0) {
923
924         if (c->dead)
925             connection_free(c);
926         
927         return -1;
928     }
929
930     return 0;
931 }
932
933 static void sink_input_drop_cb(struct pa_sink_input *i, const struct pa_memchunk *chunk, size_t length) {
934     struct connection*c = i->userdata;
935     assert(i && c && length);
936
937     pa_memblockq_drop(c->input_memblockq, chunk, length);
938
939     /* do something */
940     assert(c->protocol && c->protocol->core && c->protocol->core->mainloop && c->protocol->core->mainloop->defer_enable);
941
942     if (!c->dead)
943         c->protocol->core->mainloop->defer_enable(c->defer_event, 1);
944
945 /*     assert(pa_memblockq_get_length(c->input_memblockq) > 2048); */
946 }
947
948 static void sink_input_kill_cb(struct pa_sink_input *i) {
949     assert(i && i->userdata);
950     connection_free((struct connection *) i->userdata);
951 }
952
953 static pa_usec_t sink_input_get_latency_cb(struct pa_sink_input *i) {
954     struct connection*c = i->userdata;
955     assert(i && c);
956     return pa_bytes_to_usec(pa_memblockq_get_length(c->input_memblockq), &c->sink_input->sample_spec);
957 }
958
959 /*** source_output callbacks ***/
960
961 static void source_output_push_cb(struct pa_source_output *o, const struct pa_memchunk *chunk) {
962     struct connection *c = o->userdata;
963     assert(o && c && chunk);
964
965     pa_memblockq_push(c->output_memblockq, chunk, 0);
966
967     /* do something */
968     assert(c->protocol && c->protocol->core && c->protocol->core->mainloop && c->protocol->core->mainloop->defer_enable);
969
970     if (!c->dead)
971         c->protocol->core->mainloop->defer_enable(c->defer_event, 1);
972 }
973
974 static void source_output_kill_cb(struct pa_source_output *o) {
975     assert(o && o->userdata);
976     connection_free((struct connection *) o->userdata);
977 }
978
979 static pa_usec_t source_output_get_latency_cb(struct pa_source_output *o) {
980     struct connection*c = o->userdata;
981     assert(o && c);
982     return pa_bytes_to_usec(pa_memblockq_get_length(c->output_memblockq), &c->source_output->sample_spec);
983 }
984
985 /*** socket server callback ***/
986
987 static void on_connection(struct pa_socket_server*s, struct pa_iochannel *io, void *userdata) {
988     struct connection *c;
989     char cname[256];
990     assert(s && io && userdata);
991
992     c = pa_xmalloc(sizeof(struct connection));
993     c->protocol = userdata;
994     c->io = io;
995     pa_iochannel_set_callback(c->io, io_callback, c);
996
997     pa_iochannel_socket_peer_to_string(io, cname, sizeof(cname));
998     assert(c->protocol->core);
999     c->client = pa_client_new(c->protocol->core, "ESOUND", cname);
1000     assert(c->client);
1001     c->client->owner = c->protocol->module;
1002     c->client->kill = client_kill_cb;
1003     c->client->userdata = c;
1004     
1005     c->authorized = c->protocol->public;
1006     c->swap_byte_order = 0;
1007     c->dead = 0;
1008
1009     c->read_data_length = 0;
1010     c->read_data = pa_xmalloc(c->read_data_alloc = proto_map[ESD_PROTO_CONNECT].data_length);
1011
1012     c->write_data_length = c->write_data_index = c->write_data_alloc = 0;
1013     c->write_data = NULL;
1014
1015     c->state = ESD_NEEDS_REQDATA;
1016     c->request = ESD_PROTO_CONNECT;
1017
1018     c->sink_input = NULL;
1019     c->input_memblockq = NULL;
1020
1021     c->source_output = NULL;
1022     c->output_memblockq = NULL;
1023
1024     c->playback.current_memblock = NULL;
1025     c->playback.memblock_index = 0;
1026     c->playback.fragment_size = 0;
1027
1028     c->scache.memchunk.length = c->scache.memchunk.index = 0;
1029     c->scache.memchunk.memblock = NULL;
1030     c->scache.name = NULL;
1031     
1032     c->defer_event = c->protocol->core->mainloop->defer_new(c->protocol->core->mainloop, defer_callback, c);
1033     assert(c->defer_event);
1034     c->protocol->core->mainloop->defer_enable(c->defer_event, 0);
1035
1036     pa_idxset_put(c->protocol->connections, c, &c->index);
1037 }
1038
1039 /*** entry points ***/
1040
1041 struct pa_protocol_esound* pa_protocol_esound_new(struct pa_core*core, struct pa_socket_server *server, struct pa_module *m, struct pa_modargs *ma) {
1042     struct pa_protocol_esound *p;
1043     int public;
1044     assert(core && server && ma);
1045
1046     p = pa_xmalloc(sizeof(struct pa_protocol_esound));
1047
1048     if (pa_modargs_get_value_boolean(ma, "public", &public) < 0) {
1049         pa_log(__FILE__": public= expects a boolean argument.\n");
1050         return NULL;
1051     }
1052
1053     if (pa_authkey_load_auto(pa_modargs_get_value(ma, "cookie", DEFAULT_COOKIE_FILE), p->esd_key, sizeof(p->esd_key)) < 0) {
1054         pa_xfree(p);
1055         return NULL;
1056     }
1057
1058     p->module = m;
1059     p->public = public;
1060     p->server = server;
1061     pa_socket_server_set_callback(p->server, on_connection, p);
1062     p->core = core;
1063     p->connections = pa_idxset_new(NULL, NULL);
1064     assert(p->connections);
1065
1066     p->sink_name = pa_xstrdup(pa_modargs_get_value(ma, "sink", NULL));
1067     p->source_name = pa_xstrdup(pa_modargs_get_value(ma, "source", NULL));
1068     p->n_player = 0;
1069
1070     return p;
1071 }
1072
1073 void pa_protocol_esound_free(struct pa_protocol_esound *p) {
1074     struct connection *c;
1075     assert(p);
1076
1077     while ((c = pa_idxset_first(p->connections, NULL)))
1078         connection_free(c);
1079
1080     pa_idxset_free(p->connections, NULL, NULL);
1081     pa_socket_server_unref(p->server);
1082     pa_xfree(p);
1083 }