A very rough first version of the sink.
[platform/upstream/pulseaudio.git] / src / modules / module-raop-sink.c
1 /* $Id$ */
2
3 /***
4   This file is part of PulseAudio.
5
6   Copyright 2008 Colin Guthrie
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/authkey.h>
58 #include <pulsecore/thread-mq.h>
59 #include <pulsecore/thread.h>
60 #include <pulsecore/time-smoother.h>
61 #include <pulsecore/rtclock.h>
62 #include <pulsecore/socket-util.h>
63
64 #include "module-raop-sink-symdef.h"
65 #include "rtp.h"
66 #include "sdp.h"
67 #include "sap.h"
68 #include "raop_client.h"
69
70 PA_MODULE_AUTHOR("Colin Guthrie");
71 PA_MODULE_DESCRIPTION("RAOP Sink (Apple Airtunes)");
72 PA_MODULE_VERSION(PACKAGE_VERSION);
73 PA_MODULE_LOAD_ONCE(FALSE);
74 PA_MODULE_USAGE(
75         "sink_name=<name for the sink> "
76         "server=<address> cookie=<filename>  "
77         "format=<sample format> "
78         "channels=<number of channels> "
79         "rate=<sample rate>");
80
81 #define DEFAULT_SINK_NAME "airtunes"
82
83 struct userdata {
84     pa_core *core;
85     pa_module *module;
86     pa_sink *sink;
87
88     pa_thread_mq thread_mq;
89     pa_rtpoll *rtpoll;
90     pa_rtpoll_item *rtpoll_item;
91     pa_thread *thread;
92
93     pa_memchunk raw_memchunk;
94     pa_memchunk encoded_memchunk;
95
96     void *write_data;
97     size_t write_length, write_index;
98
99     void *read_data;
100     size_t read_length, read_index;
101
102     pa_usec_t latency;
103
104     /*esd_format_t format;*/
105     int32_t rate;
106
107     pa_smoother *smoother;
108     int fd;
109
110     int64_t offset;
111     int64_t encoding_overhead;
112     double encoding_ratio;
113
114     pa_raop_client *raop;
115
116     size_t block_size;
117 };
118
119 static const char* const valid_modargs[] = {
120     "server",
121     "rate",
122     "format",
123     "channels",
124     "sink_name",
125     NULL
126 };
127
128 enum {
129     SINK_MESSAGE_PASS_SOCKET = PA_SINK_MESSAGE_MAX
130 };
131
132 static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
133     struct userdata *u = PA_SINK(o)->userdata;
134
135     switch (code) {
136
137         case PA_SINK_MESSAGE_SET_STATE:
138
139             switch ((pa_sink_state_t) PA_PTR_TO_UINT(data)) {
140
141                 case PA_SINK_SUSPENDED:
142                     pa_assert(PA_SINK_OPENED(u->sink->thread_info.state));
143
144                     pa_smoother_pause(u->smoother, pa_rtclock_usec());
145                     break;
146
147                 case PA_SINK_IDLE:
148                 case PA_SINK_RUNNING:
149
150                     if (u->sink->thread_info.state == PA_SINK_SUSPENDED)
151                         pa_smoother_resume(u->smoother, pa_rtclock_usec());
152
153                     break;
154
155                 case PA_SINK_UNLINKED:
156                 case PA_SINK_INIT:
157                     ;
158             }
159
160             break;
161
162         case PA_SINK_MESSAGE_GET_LATENCY: {
163             pa_usec_t w, r;
164
165             r = pa_smoother_get(u->smoother, pa_rtclock_usec());
166             w = pa_bytes_to_usec((u->offset - u->encoding_overhead + (u->encoded_memchunk.length / u->encoding_ratio)), &u->sink->sample_spec);
167
168             *((pa_usec_t*) data) = w > r ? w - r : 0;
169             break;
170         }
171
172         case SINK_MESSAGE_PASS_SOCKET: {
173             struct pollfd *pollfd;
174
175             pa_assert(!u->rtpoll_item);
176
177             u->rtpoll_item = pa_rtpoll_item_new(u->rtpoll, PA_RTPOLL_NEVER, 1);
178             pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
179             pollfd->fd = u->fd;
180             pollfd->events = pollfd->revents = 0;
181
182             return 0;
183         }
184     }
185
186     return pa_sink_process_msg(o, code, data, offset, chunk);
187 }
188
189 static void thread_func(void *userdata) {
190     struct userdata *u = userdata;
191     int write_type = 0;
192
193     pa_assert(u);
194
195     pa_log_debug("Thread starting up");
196
197     pa_thread_mq_install(&u->thread_mq);
198     pa_rtpoll_install(u->rtpoll);
199
200     pa_smoother_set_time_offset(u->smoother, pa_rtclock_usec());
201
202     for (;;) {
203         int ret;
204
205         if (u->rtpoll_item) {
206             struct pollfd *pollfd;
207             pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
208
209             /* Render some data and write it to the fifo */
210             if (PA_SINK_OPENED(u->sink->thread_info.state) && pollfd->revents) {
211                 pa_usec_t usec;
212                 int64_t n;
213
214                 for (;;) {
215                     ssize_t l;
216                     void *p;
217
218                     if (u->raw_memchunk.length <= 0) {
219                         /* Grab unencoded data */
220                         pa_sink_render(u->sink, u->block_size, &u->raw_memchunk);
221                     }
222                     pa_assert(u->raw_memchunk.length > 0);
223
224                     if (u->encoded_memchunk.length <= 0) {
225                         /* Encode it */
226                         size_t rl = u->raw_memchunk.length;
227                         if (u->encoded_memchunk.memblock)
228                             pa_memblock_unref(u->encoded_memchunk.memblock);
229                         u->encoded_memchunk = pa_raop_client_encode_sample(u->raop, u->core->mempool, &u->raw_memchunk);
230                         u->encoding_overhead += (u->encoded_memchunk.length - (rl - u->raw_memchunk.length));
231                         u->encoding_ratio = u->encoded_memchunk.length / (rl - u->raw_memchunk.length);
232                     }
233                     pa_assert(u->encoded_memchunk.length > 0);
234
235                     p = pa_memblock_acquire(u->encoded_memchunk.memblock);
236                     l = pa_write(u->fd, (uint8_t*) p + u->encoded_memchunk.index, u->encoded_memchunk.length, &write_type);
237                     pa_memblock_release(u->encoded_memchunk.memblock);
238
239                     pa_assert(l != 0);
240
241                     if (l < 0) {
242
243                         if (errno == EINTR)
244                             continue;
245                         else if (errno == EAGAIN) {
246
247                             /* OK, we filled all socket buffers up
248                              * now. */
249                             goto filled_up;
250
251                         } else {
252                             pa_log("Failed to write data to FIFO: %s", pa_cstrerror(errno));
253                             goto fail;
254                         }
255
256                     } else {
257                         u->offset += l;
258
259                         u->encoded_memchunk.index += l;
260                         u->encoded_memchunk.length -= l;
261
262                         if (u->encoded_memchunk.length <= 0) {
263                             pa_memblock_unref(u->encoded_memchunk.memblock);
264                             pa_memchunk_reset(&u->encoded_memchunk);
265                         }
266
267                         pollfd->revents = 0;
268
269                         if (u->encoded_memchunk.length > 0)
270
271                             /* OK, we wrote less that we asked for,
272                              * hence we can assume that the socket
273                              * buffers are full now */
274                             goto filled_up;
275                     }
276                 }
277
278             filled_up:
279
280                 /* At this spot we know that the socket buffers are
281                  * fully filled up. This is the best time to estimate
282                  * the playback position of the server */
283
284                 n = u->offset;
285
286 #ifdef SIOCOUTQ
287                 {
288                     int l;
289                     if (ioctl(u->fd, SIOCOUTQ, &l) >= 0 && l > 0)
290                         n -= l;
291                 }
292 #endif
293
294                 usec = pa_bytes_to_usec(n, &u->sink->sample_spec);
295
296                 if (usec > u->latency)
297                     usec -= u->latency;
298                 else
299                     usec = 0;
300
301                 pa_smoother_put(u->smoother, pa_rtclock_usec(), usec);
302             }
303
304             /* Hmm, nothing to do. Let's sleep */
305             pollfd->events = PA_SINK_OPENED(u->sink->thread_info.state)  ? POLLOUT : 0;
306         }
307
308         if ((ret = pa_rtpoll_run(u->rtpoll, TRUE)) < 0)
309             goto fail;
310
311         if (ret == 0)
312             goto finish;
313
314         if (u->rtpoll_item) {
315             struct pollfd* pollfd;
316
317             pollfd = pa_rtpoll_item_get_pollfd(u->rtpoll_item, NULL);
318
319             if (pollfd->revents & ~POLLOUT) {
320                 pa_log("FIFO shutdown.");
321                 goto fail;
322             }
323         }
324     }
325
326 fail:
327     /* If this was no regular exit from the loop we have to continue
328      * processing messages until we received PA_MESSAGE_SHUTDOWN */
329     pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
330     pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
331
332 finish:
333     pa_log_debug("Thread shutting down");
334 }
335
336 static void on_connection(PA_GCC_UNUSED int fd, void*userdata) {
337     struct userdata *u = userdata;
338     pa_assert(u);
339
340     pa_assert(u->fd < 0);
341     u->fd = fd;
342
343     pa_log_debug("Connection authenticated, handing fd to IO thread...");
344
345     pa_asyncmsgq_post(u->thread_mq.inq, PA_MSGOBJECT(u->sink), SINK_MESSAGE_PASS_SOCKET, NULL, 0, NULL, NULL);
346 }
347
348 int pa__init(pa_module*m) {
349     struct userdata *u = NULL;
350     const char *p;
351     pa_sample_spec ss;
352     pa_modargs *ma = NULL;
353     char *t;
354
355     pa_assert(m);
356
357     if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
358         pa_log("failed to parse module arguments");
359         goto fail;
360     }
361
362     ss = m->core->default_sample_spec;
363     if (pa_modargs_get_sample_spec(ma, &ss) < 0) {
364         pa_log("invalid sample format specification");
365         goto fail;
366     }
367
368     if ((/*ss.format != PA_SAMPLE_U8 &&*/ ss.format != PA_SAMPLE_S16NE) ||
369         (ss.channels > 2)) {
370         pa_log("sample type support is limited to mono/stereo and U8 or S16NE sample data");
371         goto fail;
372     }
373
374     u = pa_xnew0(struct userdata, 1);
375     u->core = m->core;
376     u->module = m;
377     m->userdata = u;
378     u->fd = -1;
379     u->smoother = pa_smoother_new(PA_USEC_PER_SEC, PA_USEC_PER_SEC*2, TRUE);
380     pa_memchunk_reset(&u->raw_memchunk);
381     pa_memchunk_reset(&u->encoded_memchunk);
382     u->offset = 0;
383     u->encoding_overhead = 0;
384     u->encoding_ratio = 1.0;
385
386     pa_thread_mq_init(&u->thread_mq, m->core->mainloop);
387     u->rtpoll = pa_rtpoll_new();
388     pa_rtpoll_item_new_asyncmsgq(u->rtpoll, PA_RTPOLL_EARLY, u->thread_mq.inq);
389     u->rtpoll_item = NULL;
390
391     /*u->format =
392         (ss.format == PA_SAMPLE_U8 ? ESD_BITS8 : ESD_BITS16) |
393         (ss.channels == 2 ? ESD_STEREO : ESD_MONO);*/
394     u->rate = ss.rate;
395     u->block_size = pa_usec_to_bytes(PA_USEC_PER_SEC/20, &ss);
396
397     u->read_data = u->write_data = NULL;
398     u->read_index = u->write_index = u->read_length = u->write_length = 0;
399
400     /*u->state = STATE_AUTH;*/
401     u->latency = 0;
402
403     if (!(u->sink = pa_sink_new(m->core, __FILE__, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME), 0, &ss, NULL))) {
404         pa_log("Failed to create sink.");
405         goto fail;
406     }
407
408     u->sink->parent.process_msg = sink_process_msg;
409     u->sink->userdata = u;
410     u->sink->flags = PA_SINK_LATENCY|PA_SINK_NETWORK;
411
412     pa_sink_set_module(u->sink, m);
413     pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
414     pa_sink_set_rtpoll(u->sink, u->rtpoll);
415
416     if (!(p = pa_modargs_get_value(ma, "server", NULL))) {
417         pa_log("No server argument given.");
418         goto fail;
419     }
420
421     if (!(u->raop = pa_raop_client_new(u->core->mainloop, p))) {
422         pa_log("Failed to connect to server.");
423         goto fail;
424     }
425
426     pa_raop_client_set_callback(u->raop, on_connection, u);
427     pa_sink_set_description(u->sink, t = pa_sprintf_malloc("Airtunes sink '%s'", p));
428     pa_xfree(t);
429
430
431     if (!(u->thread = pa_thread_new(thread_func, u))) {
432         pa_log("Failed to create thread.");
433         goto fail;
434     }
435
436     pa_sink_put(u->sink);
437
438     pa_modargs_free(ma);
439
440     return 0;
441
442 fail:
443     if (ma)
444         pa_modargs_free(ma);
445
446     pa__done(m);
447
448     return -1;
449 }
450
451 void pa__done(pa_module*m) {
452     struct userdata *u;
453     pa_assert(m);
454
455     if (!(u = m->userdata))
456         return;
457
458     if (u->sink)
459         pa_sink_unlink(u->sink);
460
461     if (u->thread) {
462         pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
463         pa_thread_free(u->thread);
464     }
465
466     pa_thread_mq_done(&u->thread_mq);
467
468     if (u->sink)
469         pa_sink_unref(u->sink);
470
471     if (u->rtpoll_item)
472         pa_rtpoll_item_free(u->rtpoll_item);
473
474     if (u->rtpoll)
475         pa_rtpoll_free(u->rtpoll);
476
477     if (u->raw_memchunk.memblock)
478         pa_memblock_unref(u->raw_memchunk.memblock);
479
480     if (u->encoded_memchunk.memblock)
481         pa_memblock_unref(u->encoded_memchunk.memblock);
482
483     if (u->raop)
484         pa_raop_client_free(u->raop);
485
486     pa_xfree(u->read_data);
487     pa_xfree(u->write_data);
488
489     if (u->smoother)
490         pa_smoother_free(u->smoother);
491
492     if (u->fd >= 0)
493         pa_close(u->fd);
494
495     pa_xfree(u);
496 }