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