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