hashmap: Add pa_hashmap_remove_all()
[platform/upstream/pulseaudio.git] / src / modules / module-esound-sink.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2004-2006 Lennart Poettering
5
6   PulseAudio 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.1 of the License,
9   or (at your option) any later version.
10
11   PulseAudio 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 PulseAudio; 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 <stdlib.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #ifdef HAVE_NETINET_IN_H
33 #include <netinet/in.h>
34 #endif
35
36 #ifdef HAVE_NETINET_TCP_H
37 #include <netinet/tcp.h>
38 #endif
39
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43
44 #ifdef HAVE_LINUX_SOCKIOS_H
45 #include <linux/sockios.h>
46 #endif
47
48 #include <pulse/rtclock.h>
49 #include <pulse/timeval.h>
50 #include <pulse/xmalloc.h>
51
52 #include <pulsecore/socket.h>
53 #include <pulsecore/core-error.h>
54 #include <pulsecore/iochannel.h>
55 #include <pulsecore/sink.h>
56 #include <pulsecore/module.h>
57 #include <pulsecore/core-util.h>
58 #include <pulsecore/modargs.h>
59 #include <pulsecore/log.h>
60 #include <pulsecore/socket-client.h>
61 #include <pulsecore/esound.h>
62 #include <pulsecore/authkey.h>
63 #include <pulsecore/thread-mq.h>
64 #include <pulsecore/thread.h>
65 #include <pulsecore/time-smoother.h>
66 #include <pulsecore/socket-util.h>
67 #include <pulsecore/rtpoll.h>
68 #include <pulsecore/poll.h>
69
70 #include "module-esound-sink-symdef.h"
71
72 PA_MODULE_AUTHOR("Lennart Poettering");
73 PA_MODULE_DESCRIPTION("ESOUND Sink");
74 PA_MODULE_VERSION(PACKAGE_VERSION);
75 PA_MODULE_LOAD_ONCE(FALSE);
76 PA_MODULE_USAGE(
77         "sink_name=<name for the sink> "
78         "sink_properties=<properties for the sink> "
79         "server=<address> cookie=<filename>  "
80         "format=<sample format> "
81         "rate=<sample rate> "
82         "channels=<number of channels>");
83
84 #define DEFAULT_SINK_NAME "esound_out"
85
86 struct userdata {
87     pa_core *core;
88     pa_module *module;
89     pa_sink *sink;
90
91     pa_thread_mq thread_mq;
92     pa_rtpoll *rtpoll;
93     pa_rtpoll_item *rtpoll_item;
94     pa_thread *thread;
95
96     pa_memchunk memchunk;
97
98     void *write_data;
99     size_t write_length, write_index;
100
101     void *read_data;
102     size_t read_length, read_index;
103
104     enum {
105         STATE_AUTH,
106         STATE_LATENCY,
107         STATE_PREPARE,
108         STATE_RUNNING,
109         STATE_DEAD
110     } state;
111
112     pa_usec_t latency;
113
114     esd_format_t format;
115     int32_t rate;
116
117     pa_smoother *smoother;
118     int fd;
119
120     int64_t offset;
121
122     pa_iochannel *io;
123     pa_socket_client *client;
124
125     size_t block_size;
126 };
127
128 static const char* const valid_modargs[] = {
129     "sink_name",
130     "sink_properties",
131     "server",
132     "cookie",
133     "format",
134     "rate",
135     "channels",
136     NULL
137 };
138
139 enum {
140     SINK_MESSAGE_PASS_SOCKET = PA_SINK_MESSAGE_MAX
141 };
142
143 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
144     struct userdata *u = PA_SINK(o)->userdata;
145
146     switch (code) {
147
148         case PA_SINK_MESSAGE_SET_STATE:
149
150             switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
151
152                 case PA_SINK_SUSPENDED:
153                     pa_assert(PA_SINK_IS_OPENED(u->sink->thread_info.state));
154
155                     pa_smoother_pause(u->smoother, pa_rtclock_now());
156                     break;
157
158                 case PA_SINK_IDLE:
159                 case PA_SINK_RUNNING:
160
161                     if (u->sink->thread_info.state == PA_SINK_SUSPENDED)
162                         pa_smoother_resume(u->smoother, pa_rtclock_now(), TRUE);
163
164                     break;
165
166                 case PA_SINK_UNLINKED:
167                 case PA_SINK_INIT:
168                 case PA_SINK_INVALID_STATE:
169                     ;
170             }
171
172             break;
173
174         case PA_SINK_MESSAGE_GET_LATENCY: {
175             pa_usec_t w, r;
176
177             r = pa_smoother_get(u->smoother, pa_rtclock_now());
178             w = pa_bytes_to_usec((uint64_t) u->offset + u->memchunk.length, &u->sink->sample_spec);
179
180             *((pa_usec_t*) data) = w > r ? w - r : 0;
181             return 0;
182         }
183
184         case SINK_MESSAGE_PASS_SOCKET: {
185             struct pollfd *pollfd;
186
187             pa_assert(!u->rtpoll_item);
188
189             u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
190             pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
191             pollfd->fd = u->fd;
192             pollfd->events = pollfd->revents = 0;
193
194             return 0;
195         }
196     }
197
198     return pa_sink_process_msg(o, code, data, offset, chunk);
199 }
200
201 static void thread_func(void *userdata) {
202     struct userdata *u = userdata;
203     int write_type = 0;
204
205     pa_assert(u);
206
207     pa_log_debug("Thread starting up");
208
209     pa_thread_mq_install(&u->thread_mq);
210
211     pa_smoother_set_time_offset(u->smoother, pa_rtclock_now());
212
213     for (;;) {
214         int ret;
215
216         if (PA_UNLIKELY(u->sink->thread_info.rewind_requested))
217             pa_sink_process_rewind(u->sink, 0);
218
219         if (u->rtpoll_item) {
220             struct pollfd *pollfd;
221             pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
222
223             /* Render some data and write it to the fifo */
224             if (PA_SINK_IS_OPENED(u->sink->thread_info.state) && pollfd->revents) {
225                 pa_usec_t usec;
226                 int64_t n;
227
228                 for (;;) {
229                     ssize_t l;
230                     void *p;
231
232                     if (u->memchunk.length <= 0)
233                         pa_sink_render(u->sink, u->block_size, &u->memchunk);
234
235                     pa_assert(u->memchunk.length > 0);
236
237                     p = pa_memblock_acquire(u->memchunk.memblock);
238                     l = pa_write(u->fd, (uint8_t*) p + u->memchunk.index, u->memchunk.length, &write_type);
239                     pa_memblock_release(u->memchunk.memblock);
240
241                     pa_assert(l != 0);
242
243                     if (l < 0) {
244
245                         if (errno == EINTR)
246                             continue;
247                         else if (errno == EAGAIN) {
248
249                             /* OK, we filled all socket buffers up
250                              * now. */
251                             goto filled_up;
252
253                         } else {
254                             pa_log("Failed to write data to FIFO: %s", pa_cstrerror(errno));
255                             goto fail;
256                         }
257
258                     } else {
259                         u->offset += l;
260
261                         u->memchunk.index += (size_t) l;
262                         u->memchunk.length -= (size_t) l;
263
264                         if (u->memchunk.length <= 0) {
265                             pa_memblock_unref(u->memchunk.memblock);
266                             pa_memchunk_reset(&u->memchunk);
267                         }
268
269                         pollfd->revents = 0;
270
271                         if (u->memchunk.length > 0)
272
273                             /* OK, we wrote less that we asked for,
274                              * hence we can assume that the socket
275                              * buffers are full now */
276                             goto filled_up;
277                     }
278                 }
279
280             filled_up:
281
282                 /* At this spot we know that the socket buffers are
283                  * fully filled up. This is the best time to estimate
284                  * the playback position of the server */
285
286                 n = u->offset;
287
288 #ifdef SIOCOUTQ
289                 {
290                     int l;
291                     if (ioctl(u->fd, SIOCOUTQ, &l) >= 0 && l > 0)
292                         n -= l;
293                 }
294 #endif
295
296                 usec = pa_bytes_to_usec((uint64_t) n, &u->sink->sample_spec);
297
298                 if (usec > u->latency)
299                     usec -= u->latency;
300                 else
301                     usec = 0;
302
303                 pa_smoother_put(u->smoother, pa_rtclock_now(), usec);
304             }
305
306             /* Hmm, nothing to do. Let's sleep */
307             pollfd->events = (short) (PA_SINK_IS_OPENED(u->sink->thread_info.state) ? POLLOUT : 0);
308         }
309
310         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
311             goto fail;
312
313         if (ret == 0)
314             goto finish;
315
316         if (u->rtpoll_item) {
317             struct pollfd* pollfd;
318
319             pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
320
321             if (pollfd->revents & ~POLLOUT) {
322                 pa_log("FIFO shutdown.");
323                 goto fail;
324             }
325         }
326     }
327
328 fail:
329     /* If this was no regular exit from the loop we have to continue
330      * processing messages until we received PA_MESSAGE_SHUTDOWN */
331     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
332     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
333
334 finish:
335     pa_log_debug("Thread shutting down");
336 }
337
338 static int do_write(struct userdata *u) {
339     ssize_t r;
340     pa_assert(u);
341
342     if (!pa_iochannel_is_writable(u->io))
343         return 0;
344
345     if (u->write_data) {
346         pa_assert(u->write_index < u->write_length);
347
348         if ((r = pa_iochannel_write(u->io, (uint8_t*) u->write_data + u->write_index, u->write_length - u->write_index)) <= 0) {
349             pa_log("write() failed: %s", pa_cstrerror(errno));
350             return -1;
351         }
352
353         u->write_index += (size_t) r;
354         pa_assert(u->write_index <= u->write_length);
355
356         if (u->write_index == u->write_length) {
357             pa_xfree(u->write_data);
358             u->write_data = NULL;
359             u->write_index = u->write_length = 0;
360         }
361     }
362
363     if (!u->write_data && u->state == STATE_PREPARE) {
364         int so_sndbuf = 0;
365         socklen_t sl = sizeof(int);
366
367         /* OK, we're done with sending all control data we need to, so
368          * let's hand the socket over to the IO thread now */
369
370         pa_assert(u->fd < 0);
371         u->fd = pa_iochannel_get_send_fd(u->io);
372
373         pa_iochannel_set_noclose(u->io, TRUE);
374         pa_iochannel_free(u->io);
375         u->io = NULL;
376
377         pa_make_tcp_socket_low_delay(u->fd);
378
379         if (getsockopt(u->fd, SOL_SOCKET, SO_SNDBUF, (void *) &so_sndbuf, &sl) < 0)
380             pa_log_warn("getsockopt(SO_SNDBUF) failed: %s", pa_cstrerror(errno));
381         else {
382             pa_log_debug("SO_SNDBUF is %zu.", (size_t) so_sndbuf);
383             pa_sink_set_max_request(u->sink, PA_MAX((size_t) so_sndbuf, u->block_size));
384         }
385
386         pa_log_debug("Connection authenticated, handing fd to IO thread...");
387
388         pa_asyncmsgq_post(u->thread_mq.inq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_PASS_SOCKET, NULL, 0, NULL, NULL);
389         u->state = STATE_RUNNING;
390     }
391
392     return 0;
393 }
394
395 static int handle_response(struct userdata *u) {
396     pa_assert(u);
397
398     switch (u->state) {
399
400         case STATE_AUTH:
401             pa_assert(u->read_length == sizeof(int32_t));
402
403             /* Process auth data */
404             if (!*(int32_t*) u->read_data) {
405                 pa_log("Authentication failed: %s", pa_cstrerror(errno));
406                 return -1;
407             }
408
409             /* Request latency data */
410             pa_assert(!u->write_data);
411             *(int32_t*) (u->write_data = pa_xmalloc(u->write_length = sizeof(int32_t))) = ESD_PROTO_LATENCY;
412
413             u->write_index = 0;
414             u->state = STATE_LATENCY;
415
416             /* Space for next response */
417             pa_assert(u->read_length >= sizeof(int32_t));
418             u->read_index = 0;
419             u->read_length = sizeof(int32_t);
420
421             break;
422
423         case STATE_LATENCY: {
424             int32_t *p;
425             pa_assert(u->read_length == sizeof(int32_t));
426
427             /* Process latency info */
428             u->latency = (pa_usec_t) ((double) (*(int32_t*) u->read_data) * 1000000 / 44100);
429             if (u->latency > 10000000) {
430                 pa_log_warn("Invalid latency information received from server");
431                 u->latency = 0;
432             }
433
434             /* Create stream */
435             pa_assert(!u->write_data);
436             p = u->write_data = pa_xmalloc0(u->write_length = sizeof(int32_t)*3+ESD_NAME_MAX);
437             *(p++) = ESD_PROTO_STREAM_PLAY;
438             *(p++) = u->format;
439             *(p++) = u->rate;
440             pa_strlcpy((char*) p, "PulseAudio Tunnel", ESD_NAME_MAX);
441
442             u->write_index = 0;
443             u->state = STATE_PREPARE;
444
445             /* Don't read any further */
446             pa_xfree(u->read_data);
447             u->read_data = NULL;
448             u->read_index = u->read_length = 0;
449
450             break;
451         }
452
453         default:
454             pa_assert_not_reached();
455     }
456
457     return 0;
458 }
459
460 static int do_read(struct userdata *u) {
461     pa_assert(u);
462
463     if (!pa_iochannel_is_readable(u->io))
464         return 0;
465
466     if (u->state == STATE_AUTH || u->state == STATE_LATENCY) {
467         ssize_t r;
468
469         if (!u->read_data)
470             return 0;
471
472         pa_assert(u->read_index < u->read_length);
473
474         if ((r = pa_iochannel_read(u->io, (uint8_t*) u->read_data + u->read_index, u->read_length - u->read_index)) <= 0) {
475             pa_log("read() failed: %s", r < 0 ? pa_cstrerror(errno) : "EOF");
476             return -1;
477         }
478
479         u->read_index += (size_t) r;
480         pa_assert(u->read_index <= u->read_length);
481
482         if (u->read_index == u->read_length)
483             return handle_response(u);
484     }
485
486     return 0;
487 }
488
489 static void io_callback(pa_iochannel *io, void*userdata) {
490     struct userdata *u = userdata;
491     pa_assert(u);
492
493     if (do_read(u) < 0 || do_write(u) < 0) {
494
495         if (u->io) {
496             pa_iochannel_free(u->io);
497             u->io = NULL;
498         }
499
500         pa_module_unload_request(u->module, TRUE);
501     }
502 }
503
504 static void on_connection(pa_socket_client *c, pa_iochannel*io, void *userdata) {
505     struct userdata *u = userdata;
506
507     pa_socket_client_unref(u->client);
508     u->client = NULL;
509
510     if (!io) {
511         pa_log("Connection failed: %s", pa_cstrerror(errno));
512         pa_module_unload_request(u->module, TRUE);
513         return;
514     }
515
516     pa_assert(!u->io);
517     u->io = io;
518     pa_iochannel_set_callback(u->io, io_callback, u);
519
520     pa_log_debug("Connection established, authenticating ...");
521 }
522
523 int pa__init(pa_module*m) {
524     struct userdata *u = NULL;
525     pa_sample_spec ss;
526     pa_modargs *ma = NULL;
527     const char *espeaker;
528     uint32_t key;
529     pa_sink_new_data data;
530
531     pa_assert(m);
532
533     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
534         pa_log("failed to parse module arguments");
535         goto fail;
536     }
537
538     ss = m->core->default_sample_spec;
539     if (pa_modargs_get_sample_spec(ma, &ss) < 0) {
540         pa_log("invalid sample format specification");
541         goto fail;
542     }
543
544     if ((ss.format != PA_SAMPLE_U8 && ss.format != PA_SAMPLE_S16NE) ||
545         (ss.channels > 2)) {
546         pa_log("esound sample type support is limited to mono/stereo and U8 or S16NE sample data");
547         goto fail;
548     }
549
550     u = pa_xnew0(struct userdata, 1);
551     u->core = m->core;
552     u->module = m;
553     m->userdata = u;
554     u->fd = -1;
555     u->smoother = pa_smoother_new(
556             PA_USEC_PER_SEC,
557             PA_USEC_PER_SEC*2,
558             TRUE,
559             TRUE,
560             10,
561             0,
562             FALSE);
563     pa_memchunk_reset(&u->memchunk);
564     u->offset = 0;
565
566     u->rtpoll = pa_rtpoll_new();
567     pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll);
568     u->rtpoll_item = NULL;
569
570     u->format =
571         (ss.format == PA_SAMPLE_U8 ? ESD_BITS8 : ESD_BITS16) |
572         (ss.channels == 2 ? ESD_STEREO : ESD_MONO);
573     u->rate = (int32_t) ss.rate;
574     u->block_size = pa_usec_to_bytes(PA_USEC_PER_SEC/20, &ss);
575
576     u->read_data = u->write_data = NULL;
577     u->read_index = u->write_index = u->read_length = u->write_length = 0;
578
579     u->state = STATE_AUTH;
580     u->latency = 0;
581
582     if (!(espeaker = getenv("ESPEAKER")))
583         espeaker = ESD_UNIX_SOCKET_NAME;
584
585     espeaker = pa_modargs_get_value(ma, "server", espeaker);
586
587     pa_sink_new_data_init(&data);
588     data.driver = __FILE__;
589     data.module = m;
590     pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
591     pa_sink_new_data_set_sample_spec(&data, &ss);
592     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, espeaker);
593     pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "esd");
594     pa_proplist_setf(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "EsounD Output on %s", espeaker);
595
596     if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
597         pa_log("Invalid properties");
598         pa_sink_new_data_done(&data);
599         goto fail;
600     }
601
602     u->sink = pa_sink_new(m->core, &data, PA_SINK_LATENCY|PA_SINK_NETWORK);
603     pa_sink_new_data_done(&data);
604
605     if (!u->sink) {
606         pa_log("Failed to create sink.");
607         goto fail;
608     }
609
610     u->sink->parent.process_msg = sink_process_msg;
611     u->sink->userdata = u;
612
613     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
614     pa_sink_set_rtpoll(u->sink, u->rtpoll);
615
616     if (!(u->client = pa_socket_client_new_string(u->core->mainloop, TRUE, espeaker, ESD_DEFAULT_PORT))) {
617         pa_log("Failed to connect to server.");
618         goto fail;
619     }
620
621     pa_socket_client_set_callback(u->client, on_connection, u);
622
623     /* Prepare the initial request */
624     u->write_data = pa_xmalloc(u->write_length = ESD_KEY_LEN + sizeof(int32_t));
625     if (pa_authkey_load_auto(pa_modargs_get_value(ma, "cookie", ".esd_auth"), TRUE, u->write_data, ESD_KEY_LEN) < 0) {
626         pa_log("Failed to load cookie");
627         goto fail;
628     }
629
630     key = ESD_ENDIAN_KEY;
631     memcpy((uint8_t*) u->write_data + ESD_KEY_LEN, &key, sizeof(key));
632
633     /* Reserve space for the response */
634     u->read_data = pa_xmalloc(u->read_length = sizeof(int32_t));
635
636     if (!(u->thread = pa_thread_new("esound-sink", thread_func, u))) {
637         pa_log("Failed to create thread.");
638         goto fail;
639     }
640
641     pa_sink_put(u->sink);
642
643     pa_modargs_free(ma);
644
645     return 0;
646
647 fail:
648     if (ma)
649         pa_modargs_free(ma);
650
651     pa__done(m);
652
653     return -1;
654 }
655
656 int pa__get_n_used(pa_module *m) {
657     struct userdata *u;
658
659     pa_assert(m);
660     pa_assert_se(u = m->userdata);
661
662     return pa_sink_linked_by(u->sink);
663 }
664
665 void pa__done(pa_module*m) {
666     struct userdata *u;
667     pa_assert(m);
668
669     if (!(u = m->userdata))
670         return;
671
672     if (u->sink)
673         pa_sink_unlink(u->sink);
674
675     if (u->thread) {
676         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
677         pa_thread_free(u->thread);
678     }
679
680     pa_thread_mq_done(&u->thread_mq);
681
682     if (u->sink)
683         pa_sink_unref(u->sink);
684
685     if (u->io)
686         pa_iochannel_free(u->io);
687
688     if (u->rtpoll_item)
689         pa_rtpoll_item_free(u->rtpoll_item);
690
691     if (u->rtpoll)
692         pa_rtpoll_free(u->rtpoll);
693
694     if (u->memchunk.memblock)
695         pa_memblock_unref(u->memchunk.memblock);
696
697     if (u->client)
698         pa_socket_client_unref(u->client);
699
700     pa_xfree(u->read_data);
701     pa_xfree(u->write_data);
702
703     if (u->smoother)
704         pa_smoother_free(u->smoother);
705
706     if (u->fd >= 0)
707         pa_close(u->fd);
708
709     pa_xfree(u);
710 }