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