raop: Change socket buffer size handling to avoid playback underruns
[profile/ivi/pulseaudio.git] / src / modules / raop / raop_client.c
1 /***
2   This file is part of PulseAudio.
3
4   Copyright 2008 Colin Guthrie
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 <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <sys/ioctl.h>
31
32 #ifdef HAVE_SYS_FILIO_H
33 #include <sys/filio.h>
34 #endif
35
36 /* TODO: Replace OpenSSL with NSS */
37 #include <openssl/err.h>
38 #include <openssl/rand.h>
39 #include <openssl/aes.h>
40 #include <openssl/rsa.h>
41 #include <openssl/engine.h>
42
43 #include <pulse/xmalloc.h>
44
45 #include <pulsecore/core-error.h>
46 #include <pulsecore/core-util.h>
47 #include <pulsecore/iochannel.h>
48 #include <pulsecore/socket-util.h>
49 #include <pulsecore/log.h>
50 #include <pulsecore/macro.h>
51 #include <pulsecore/memchunk.h>
52 #include <pulsecore/random.h>
53
54 #include "raop_client.h"
55 #include "rtsp_client.h"
56 #include "base64.h"
57
58 #define AES_CHUNKSIZE 16
59
60 #define JACK_STATUS_DISCONNECTED 0
61 #define JACK_STATUS_CONNECTED 1
62
63 #define JACK_TYPE_ANALOG 0
64 #define JACK_TYPE_DIGITAL 1
65
66 #define VOLUME_DEF -30
67 #define VOLUME_MIN -144
68 #define VOLUME_MAX 0
69
70
71 struct pa_raop_client {
72     pa_core *core;
73     char *host;
74     char *sid;
75     pa_rtsp_client *rtsp;
76
77     uint8_t jack_type;
78     uint8_t jack_status;
79
80     /* Encryption Related bits */
81     AES_KEY aes;
82     uint8_t aes_iv[AES_CHUNKSIZE]; /* initialization vector for aes-cbc */
83     uint8_t aes_nv[AES_CHUNKSIZE]; /* next vector for aes-cbc */
84     uint8_t aes_key[AES_CHUNKSIZE]; /* key for aes-cbc */
85
86     pa_socket_client *sc;
87     int fd;
88
89     uint16_t seq;
90     uint32_t rtptime;
91
92     pa_raop_client_cb_t callback;
93     void* userdata;
94     pa_raop_client_closed_cb_t closed_callback;
95     void* closed_userdata;
96 };
97
98 /**
99  * Function to write bits into a buffer.
100  * @param buffer Handle to the buffer. It will be incremented if new data requires it.
101  * @param bit_pos A pointer to a position buffer to keep track the current write location (0 for MSB, 7 for LSB)
102  * @param size A pointer to the byte size currently written. This allows the calling function to do simple buffer overflow checks
103  * @param data The data to write
104  * @param data_bit_len The number of bits from data to write
105  */
106 static inline void bit_writer(uint8_t **buffer, uint8_t *bit_pos, int *size, uint8_t data, uint8_t data_bit_len) {
107     int bits_left, bit_overflow;
108     uint8_t bit_data;
109
110     if (!data_bit_len)
111         return;
112
113     /* If bit pos is zero, we will definatly use at least one bit from the current byte so size increments. */
114     if (!*bit_pos)
115         *size += 1;
116
117     /* Calc the number of bits left in the current byte of buffer */
118     bits_left = 7 - *bit_pos  + 1;
119     /* Calc the overflow of bits in relation to how much space we have left... */
120     bit_overflow = bits_left - data_bit_len;
121     if (bit_overflow >= 0) {
122         /* We can fit the new data in our current byte */
123         /* As we write from MSB->LSB we need to left shift by the overflow amount */
124         bit_data = data << bit_overflow;
125         if (*bit_pos)
126             **buffer |= bit_data;
127         else
128             **buffer = bit_data;
129         /* If our data fits exactly into the current byte, we need to increment our pointer */
130         if (0 == bit_overflow) {
131             /* Do not increment size as it will be incremeneted on next call as bit_pos is zero */
132             *buffer += 1;
133             *bit_pos = 0;
134         } else {
135             *bit_pos += data_bit_len;
136         }
137     } else {
138         /* bit_overflow is negative, there for we will need a new byte from our buffer */
139         /* Firstly fill up what's left in the current byte */
140         bit_data = data >> -bit_overflow;
141         **buffer |= bit_data;
142         /* Increment our buffer pointer and size counter*/
143         *buffer += 1;
144         *size += 1;
145         **buffer = data << (8 + bit_overflow);
146         *bit_pos = -bit_overflow;
147     }
148 }
149
150 static int rsa_encrypt(uint8_t *text, int len, uint8_t *res) {
151     const char n[] =
152         "59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUtwC"
153         "5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDR"
154         "KSKv6kDqnw4UwPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuB"
155         "OitnZ/bDzPHrTOZz0Dew0uowxf/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJ"
156         "Q+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/UAaHqn9JdsBWLUEpVviYnh"
157         "imNVvYFZeCXg/IdTQ+x4IRdiXNv5hEew==";
158     const char e[] = "AQAB";
159     uint8_t modules[256];
160     uint8_t exponent[8];
161     int size;
162     RSA *rsa;
163
164     rsa = RSA_new();
165     size = pa_base64_decode(n, modules);
166     rsa->n = BN_bin2bn(modules, size, NULL);
167     size = pa_base64_decode(e, exponent);
168     rsa->e = BN_bin2bn(exponent, size, NULL);
169
170     size = RSA_public_encrypt(len, text, res, rsa, RSA_PKCS1_OAEP_PADDING);
171     RSA_free(rsa);
172     return size;
173 }
174
175 static int aes_encrypt(pa_raop_client* c, uint8_t *data, int size) {
176     uint8_t *buf;
177     int i=0, j;
178
179     pa_assert(c);
180
181     memcpy(c->aes_nv, c->aes_iv, AES_CHUNKSIZE);
182     while (i+AES_CHUNKSIZE <= size) {
183         buf = data + i;
184         for (j=0; j<AES_CHUNKSIZE; ++j)
185             buf[j] ^= c->aes_nv[j];
186
187         AES_encrypt(buf, buf, &c->aes);
188         memcpy(c->aes_nv, buf, AES_CHUNKSIZE);
189         i += AES_CHUNKSIZE;
190     }
191     return i;
192 }
193
194 static inline void rtrimchar(char *str, char rc) {
195     char *sp = str + strlen(str) - 1;
196     while (sp >= str && *sp == rc) {
197         *sp = '\0';
198         sp -= 1;
199     }
200 }
201
202 static void on_connection(pa_socket_client *sc, pa_iochannel *io, void *userdata) {
203     pa_raop_client *c = userdata;
204
205     pa_assert(sc);
206     pa_assert(c);
207     pa_assert(c->sc == sc);
208     pa_assert(c->fd < 0);
209     pa_assert(c->callback);
210
211     pa_socket_client_unref(c->sc);
212     c->sc = NULL;
213
214     if (!io) {
215         pa_log("Connection failed: %s", pa_cstrerror(errno));
216         return;
217     }
218
219     c->fd = pa_iochannel_get_send_fd(io);
220
221     pa_iochannel_set_noclose(io, TRUE);
222     pa_iochannel_free(io);
223
224     pa_make_tcp_socket_low_delay(c->fd);
225
226     pa_log_debug("Connection established");
227     c->callback(c->fd, c->userdata);
228 }
229
230 static void rtsp_cb(pa_rtsp_client *rtsp, pa_rtsp_state state, pa_headerlist* headers, void *userdata) {
231     pa_raop_client* c = userdata;
232     pa_assert(c);
233     pa_assert(rtsp);
234     pa_assert(rtsp == c->rtsp);
235
236     switch (state) {
237         case STATE_CONNECT: {
238             int i;
239             uint8_t rsakey[512];
240             char *key, *iv, *sac, *sdp;
241             uint16_t rand_data;
242             const char *ip;
243             char *url;
244
245             pa_log_debug("RAOP: CONNECTED");
246             ip = pa_rtsp_localip(c->rtsp);
247             /* First of all set the url properly */
248             url = pa_sprintf_malloc("rtsp://%s/%s", ip, c->sid);
249             pa_rtsp_set_url(c->rtsp, url);
250             pa_xfree(url);
251
252             /* Now encrypt our aes_public key to send to the device */
253             i = rsa_encrypt(c->aes_key, AES_CHUNKSIZE, rsakey);
254             pa_base64_encode(rsakey, i, &key);
255             rtrimchar(key, '=');
256             pa_base64_encode(c->aes_iv, AES_CHUNKSIZE, &iv);
257             rtrimchar(iv, '=');
258
259             pa_random(&rand_data, sizeof(rand_data));
260             pa_base64_encode(&rand_data, AES_CHUNKSIZE, &sac);
261             rtrimchar(sac, '=');
262             pa_rtsp_add_header(c->rtsp, "Apple-Challenge", sac);
263             sdp = pa_sprintf_malloc(
264                 "v=0\r\n"
265                 "o=iTunes %s 0 IN IP4 %s\r\n"
266                 "s=iTunes\r\n"
267                 "c=IN IP4 %s\r\n"
268                 "t=0 0\r\n"
269                 "m=audio 0 RTP/AVP 96\r\n"
270                 "a=rtpmap:96 AppleLossless\r\n"
271                 "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
272                 "a=rsaaeskey:%s\r\n"
273                 "a=aesiv:%s\r\n",
274                 c->sid, ip, c->host, key, iv);
275             pa_rtsp_announce(c->rtsp, sdp);
276             pa_xfree(key);
277             pa_xfree(iv);
278             pa_xfree(sac);
279             pa_xfree(sdp);
280             break;
281         }
282
283         case STATE_ANNOUNCE:
284             pa_log_debug("RAOP: ANNOUNCED");
285             pa_rtsp_remove_header(c->rtsp, "Apple-Challenge");
286             pa_rtsp_setup(c->rtsp);
287             break;
288
289         case STATE_SETUP: {
290             char *aj = pa_xstrdup(pa_headerlist_gets(headers, "Audio-Jack-Status"));
291             pa_log_debug("RAOP: SETUP");
292             if (aj) {
293                 char *token, *pc;
294                 char delimiters[] = ";";
295                 const char* token_state = NULL;
296                 c->jack_type = JACK_TYPE_ANALOG;
297                 c->jack_status = JACK_STATUS_DISCONNECTED;
298
299                 while ((token = pa_split(aj, delimiters, &token_state))) {
300                     if ((pc = strstr(token, "="))) {
301                       *pc = 0;
302                       if (!strcmp(token, "type") && !strcmp(pc+1, "digital")) {
303                           c->jack_type = JACK_TYPE_DIGITAL;
304                       }
305                     } else {
306                         if (!strcmp(token,"connected"))
307                             c->jack_status = JACK_STATUS_CONNECTED;
308                     }
309                     pa_xfree(token);
310                 }
311                 pa_xfree(aj);
312             } else {
313                 pa_log_warn("Audio Jack Status missing");
314             }
315             pa_rtsp_record(c->rtsp, &c->seq, &c->rtptime);
316             break;
317         }
318
319         case STATE_RECORD: {
320             uint32_t port = pa_rtsp_serverport(c->rtsp);
321             pa_log_debug("RAOP: RECORDED");
322
323             if (!(c->sc = pa_socket_client_new_string(c->core->mainloop, TRUE, c->host, port))) {
324                 pa_log("failed to connect to server '%s:%d'", c->host, port);
325                 return;
326             }
327             pa_socket_client_set_callback(c->sc, on_connection, c);
328             break;
329         }
330
331         case STATE_FLUSH:
332             pa_log_debug("RAOP: FLUSHED");
333             break;
334
335         case STATE_TEARDOWN:
336             pa_log_debug("RAOP: TEARDOWN");
337             break;
338
339         case STATE_SET_PARAMETER:
340             pa_log_debug("RAOP: SET_PARAMETER");
341             break;
342
343         case STATE_DISCONNECTED:
344             pa_assert(c->closed_callback);
345             pa_assert(c->rtsp);
346
347             pa_log_debug("RTSP control channel closed");
348             pa_rtsp_client_free(c->rtsp);
349             c->rtsp = NULL;
350             if (c->fd > 0) {
351                 /* We do not close the fd, we leave it to the closed callback to do that */
352                 c->fd = -1;
353             }
354             if (c->sc) {
355                 pa_socket_client_unref(c->sc);
356                 c->sc = NULL;
357             }
358             pa_xfree(c->sid);
359             c->sid = NULL;
360             c->closed_callback(c->closed_userdata);
361             break;
362     }
363 }
364
365 pa_raop_client* pa_raop_client_new(pa_core *core, const char* host) {
366     pa_raop_client* c = pa_xnew0(pa_raop_client, 1);
367
368     pa_assert(core);
369     pa_assert(host);
370
371     c->core = core;
372     c->fd = -1;
373     c->host = pa_xstrdup(host);
374
375     if (pa_raop_connect(c)) {
376         pa_raop_client_free(c);
377         return NULL;
378     }
379     return c;
380 }
381
382
383 void pa_raop_client_free(pa_raop_client* c) {
384     pa_assert(c);
385
386     if (c->rtsp)
387         pa_rtsp_client_free(c->rtsp);
388     pa_xfree(c->host);
389     pa_xfree(c);
390 }
391
392
393 int pa_raop_connect(pa_raop_client* c) {
394     char *sci;
395     struct {
396         uint32_t a;
397         uint32_t b;
398         uint32_t c;
399     } rand_data;
400
401     pa_assert(c);
402
403     if (c->rtsp) {
404         pa_log_debug("Connection already in progress");
405         return 0;
406     }
407
408     c->rtsp = pa_rtsp_client_new(c->core->mainloop, c->host, 5000, "iTunes/4.6 (Macintosh; U; PPC Mac OS X 10.3)");
409
410     /* Initialise the AES encryption system */
411     pa_random(c->aes_iv, sizeof(c->aes_iv));
412     pa_random(c->aes_key, sizeof(c->aes_key));
413     memcpy(c->aes_nv, c->aes_iv, sizeof(c->aes_nv));
414     AES_set_encrypt_key(c->aes_key, 128, &c->aes);
415
416     /* Generate random instance id */
417     pa_random(&rand_data, sizeof(rand_data));
418     c->sid = pa_sprintf_malloc("%u", rand_data.a);
419     sci = pa_sprintf_malloc("%08x%08x",rand_data.b, rand_data.c);
420     pa_rtsp_add_header(c->rtsp, "Client-Instance", sci);
421     pa_xfree(sci);
422     pa_rtsp_set_callback(c->rtsp, rtsp_cb, c);
423     return pa_rtsp_connect(c->rtsp);
424 }
425
426
427 int pa_raop_flush(pa_raop_client* c) {
428     pa_assert(c);
429
430     pa_rtsp_flush(c->rtsp, c->seq, c->rtptime);
431     return 0;
432 }
433
434
435 int pa_raop_client_set_volume(pa_raop_client* c, pa_volume_t volume) {
436     int rv;
437     double db;
438     char *param;
439
440     pa_assert(c);
441
442     db = pa_sw_volume_to_dB(volume);
443     if (db < VOLUME_MIN)
444         db = VOLUME_MIN;
445     else if (db > VOLUME_MAX)
446         db = VOLUME_MAX;
447
448     param = pa_sprintf_malloc("volume: %0.6f\r\n",  db);
449
450     /* We just hit and hope, cannot wait for the callback */
451     rv = pa_rtsp_setparameter(c->rtsp, param);
452     pa_xfree(param);
453     return rv;
454 }
455
456
457 int pa_raop_client_encode_sample(pa_raop_client* c, pa_memchunk* raw, pa_memchunk* encoded) {
458     uint16_t len;
459     size_t bufmax;
460     uint8_t *bp, bpos;
461     uint8_t *ibp, *maxibp;
462     int size;
463     uint8_t *b, *p;
464     uint32_t bsize;
465     size_t length;
466     static uint8_t header[] = {
467         0x24, 0x00, 0x00, 0x00,
468         0xF0, 0xFF, 0x00, 0x00,
469         0x00, 0x00, 0x00, 0x00,
470         0x00, 0x00, 0x00, 0x00,
471     };
472     int header_size = sizeof(header);
473
474     pa_assert(c);
475     pa_assert(c->fd > 0);
476     pa_assert(raw);
477     pa_assert(raw->memblock);
478     pa_assert(raw->length > 0);
479     pa_assert(encoded);
480
481     /* We have to send 4 byte chunks */
482     bsize = (int)(raw->length / 4);
483     length = bsize * 4;
484
485     /* Leave 16 bytes extra to allow for the ALAC header which is about 55 bits */
486     bufmax = length + header_size + 16;
487     pa_memchunk_reset(encoded);
488     encoded->memblock = pa_memblock_new(c->core->mempool, bufmax);
489     b = pa_memblock_acquire(encoded->memblock);
490     memcpy(b, header, header_size);
491
492     /* Now write the actual samples */
493     bp = b + header_size;
494     size = bpos = 0;
495     bit_writer(&bp,&bpos,&size,1,3); /* channel=1, stereo */
496     bit_writer(&bp,&bpos,&size,0,4); /* unknown */
497     bit_writer(&bp,&bpos,&size,0,8); /* unknown */
498     bit_writer(&bp,&bpos,&size,0,4); /* unknown */
499     bit_writer(&bp,&bpos,&size,1,1); /* hassize */
500     bit_writer(&bp,&bpos,&size,0,2); /* unused */
501     bit_writer(&bp,&bpos,&size,1,1); /* is-not-compressed */
502
503     /* size of data, integer, big endian */
504     bit_writer(&bp,&bpos,&size,(bsize>>24)&0xff,8);
505     bit_writer(&bp,&bpos,&size,(bsize>>16)&0xff,8);
506     bit_writer(&bp,&bpos,&size,(bsize>>8)&0xff,8);
507     bit_writer(&bp,&bpos,&size,(bsize)&0xff,8);
508
509     ibp = p = pa_memblock_acquire(raw->memblock);
510     maxibp = p + raw->length - 4;
511     while (ibp <= maxibp) {
512         /* Byte swap stereo data */
513         bit_writer(&bp,&bpos,&size,*(ibp+1),8);
514         bit_writer(&bp,&bpos,&size,*(ibp+0),8);
515         bit_writer(&bp,&bpos,&size,*(ibp+3),8);
516         bit_writer(&bp,&bpos,&size,*(ibp+2),8);
517         ibp += 4;
518         raw->index += 4;
519         raw->length -= 4;
520     }
521     pa_memblock_release(raw->memblock);
522     encoded->length = header_size + size;
523
524     /* store the lenght (endian swapped: make this better) */
525     len = size + header_size - 4;
526     *(b + 2) = len >> 8;
527     *(b + 3) = len & 0xff;
528
529     /* encrypt our data */
530     aes_encrypt(c, (b + header_size), size);
531
532     /* We're done with the chunk */
533     pa_memblock_release(encoded->memblock);
534
535     return 0;
536 }
537
538
539 void pa_raop_client_set_callback(pa_raop_client* c, pa_raop_client_cb_t callback, void *userdata) {
540     pa_assert(c);
541
542     c->callback = callback;
543     c->userdata = userdata;
544 }
545
546 void pa_raop_client_set_closed_callback(pa_raop_client* c, pa_raop_client_closed_cb_t callback, void *userdata) {
547     pa_assert(c);
548
549     c->closed_callback = callback;
550     c->closed_userdata = userdata;
551 }