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