7869d1d53c5d59fd597b7b1159acb50573a0c206
[deb_shairplay.git] / src / lib / raop_buffer.c
1 /**
2 * Copyright (C) 2011-2012 Juho Vähä-Herttua
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 */
14
15 #include <stdlib.h>
16 #include <string.h>
17 #include <assert.h>
18 #include <math.h>
19
20 #include "raop_buffer.h"
21 #include "raop_rtp.h"
22 #include "utils.h"
23
24 #include <stdint.h>
25 #include "crypto/crypto.h"
26 #include "alac/alac.h"
27
28 #define RAOP_BUFFER_LENGTH 16
29
30 typedef struct {
31 /* Packet available */
32 int available;
33
34 /* RTP header */
35 unsigned char flags;
36 unsigned char type;
37 unsigned short seqnum;
38 unsigned int timestamp;
39 unsigned int ssrc;
40
41 /* Audio buffer of valid length */
42 int audio_buffer_size;
43 int audio_buffer_len;
44 void *audio_buffer;
45 } raop_buffer_entry_t;
46
47 struct raop_buffer_s {
48 /* AES key and IV */
49 unsigned char aeskey[RAOP_AESKEY_LEN];
50 unsigned char aesiv[RAOP_AESIV_LEN];
51
52 /* ALAC decoder */
53 ALACSpecificConfig alacConfig;
54 alac_file *alac;
55
56 /* First and last seqnum */
57 int is_empty;
58 unsigned short first_seqnum;
59 unsigned short last_seqnum;
60
61 /* RTP buffer entries */
62 raop_buffer_entry_t entries[RAOP_BUFFER_LENGTH];
63
64 /* Buffer of all audio buffers */
65 int buffer_size;
66 void *buffer;
67 };
68
69
70
71 static int
72 get_fmtp_info(ALACSpecificConfig *config, const char *fmtp)
73 {
74 int intarr[12];
75 char *strptr;
76 int i;
77
78 /* Parse fmtp string to integers */
79 strptr = strdup(fmtp);
80 for (i=0; i<12; i++) {
81 if (strptr == NULL) {
82 free(strptr);
83 return -1;
84 }
85 intarr[i] = atoi(utils_strsep(&strptr, " "));
86 }
87 free(strptr);
88 strptr = NULL;
89
90 /* Fill the config struct */
91 config->frameLength = intarr[1];
92 config->compatibleVersion = intarr[2];
93 config->bitDepth = intarr[3];
94 config->pb = intarr[4];
95 config->mb = intarr[5];
96 config->kb = intarr[6];
97 config->numChannels = intarr[7];
98 config->maxRun = intarr[8];
99 config->maxFrameBytes = intarr[9];
100 config->avgBitRate = intarr[10];
101 config->sampleRate = intarr[11];
102
103 /* Validate supported audio types */
104 if (config->bitDepth != 16) {
105 return -2;
106 }
107 if (config->numChannels != 2) {
108 return -3;
109 }
110
111 return 0;
112 }
113
114 static void
115 set_decoder_info(alac_file *alac, ALACSpecificConfig *config)
116 {
117 unsigned char decoder_info[48];
118 memset(decoder_info, 0, sizeof(decoder_info));
119
120 #define SET_UINT16(buf, value)do{\
121 (buf)[0] = (unsigned char)((value) >> 8);\
122 (buf)[1] = (unsigned char)(value);\
123 }while(0)
124
125 #define SET_UINT32(buf, value)do{\
126 (buf)[0] = (unsigned char)((value) >> 24);\
127 (buf)[1] = (unsigned char)((value) >> 16);\
128 (buf)[2] = (unsigned char)((value) >> 8);\
129 (buf)[3] = (unsigned char)(value);\
130 }while(0)
131
132 /* Construct decoder info buffer */
133 SET_UINT32(&decoder_info[24], config->frameLength);
134 decoder_info[28] = config->compatibleVersion;
135 decoder_info[29] = config->bitDepth;
136 decoder_info[30] = config->pb;
137 decoder_info[31] = config->mb;
138 decoder_info[32] = config->kb;
139 decoder_info[33] = config->numChannels;
140 SET_UINT16(&decoder_info[34], config->maxRun);
141 SET_UINT32(&decoder_info[36], config->maxFrameBytes);
142 SET_UINT32(&decoder_info[40], config->avgBitRate);
143 SET_UINT32(&decoder_info[44], config->sampleRate);
144 alac_set_info(alac, (char *) decoder_info);
145 }
146
147 raop_buffer_t *
148 raop_buffer_init(const char *fmtp,
149 const unsigned char *aeskey,
150 const unsigned char *aesiv)
151 {
152 raop_buffer_t *raop_buffer;
153 int audio_buffer_size;
154 ALACSpecificConfig *alacConfig;
155 int i;
156
157 assert(fmtp);
158 assert(aeskey);
159 assert(aesiv);
160
161 raop_buffer = calloc(1, sizeof(raop_buffer_t));
162 if (!raop_buffer) {
163 return NULL;
164 }
165
166 /* Parse fmtp information */
167 alacConfig = &raop_buffer->alacConfig;
168 if (get_fmtp_info(alacConfig, fmtp) < 0) {
169 free(raop_buffer);
170 return NULL;
171 }
172
173 /* Allocate the output audio buffers */
174 audio_buffer_size = alacConfig->frameLength *
175 alacConfig->numChannels *
176 alacConfig->bitDepth/8;
177 raop_buffer->buffer_size = audio_buffer_size *
178 RAOP_BUFFER_LENGTH;
179 raop_buffer->buffer = malloc(raop_buffer->buffer_size);
180 if (!raop_buffer->buffer) {
181 free(raop_buffer);
182 return NULL;
183 }
184 for (i=0; i<RAOP_BUFFER_LENGTH; i++) {
185 raop_buffer_entry_t *entry = &raop_buffer->entries[i];
186 entry->audio_buffer_size = audio_buffer_size;
187 entry->audio_buffer_len = 0;
188 entry->audio_buffer = raop_buffer->buffer+i*audio_buffer_size;
189 }
190
191 /* Initialize ALAC decoder */
192 raop_buffer->alac = create_alac(alacConfig->bitDepth,
193 alacConfig->numChannels);
194 if (!raop_buffer->alac) {
195 free(raop_buffer->buffer);
196 free(raop_buffer);
197 return NULL;
198 }
199 set_decoder_info(raop_buffer->alac, alacConfig);
200
201 /* Initialize AES keys */
202 memcpy(raop_buffer->aeskey, aeskey, RAOP_AESKEY_LEN);
203 memcpy(raop_buffer->aesiv, aesiv, RAOP_AESIV_LEN);
204
205 /* Mark buffer as empty */
206 raop_buffer->is_empty = 1;
207 return raop_buffer;
208 }
209
210 void
211 raop_buffer_destroy(raop_buffer_t *raop_buffer)
212 {
213 if (raop_buffer) {
214 destroy_alac(raop_buffer->alac);
215 free(raop_buffer->buffer);
216 free(raop_buffer);
217 }
218 }
219
220 const ALACSpecificConfig *
221 raop_buffer_get_config(raop_buffer_t *raop_buffer)
222 {
223 assert(raop_buffer);
224
225 return &raop_buffer->alacConfig;
226 }
227
228 static short
229 seqnum_cmp(unsigned short s1, unsigned short s2)
230 {
231 return (s1 - s2);
232 }
233
234 int
235 raop_buffer_queue(raop_buffer_t *raop_buffer, unsigned char *data, unsigned short datalen, int use_seqnum)
236 {
237 unsigned char packetbuf[RAOP_PACKET_LEN];
238 unsigned short seqnum;
239 raop_buffer_entry_t *entry;
240 int encryptedlen;
241 AES_CTX aes_ctx;
242 int outputlen;
243
244 assert(raop_buffer);
245
246 /* Check packet data length is valid */
247 if (datalen < 12 || datalen > RAOP_PACKET_LEN) {
248 return -1;
249 }
250
251 /* Get correct seqnum for the packet */
252 if (use_seqnum) {
253 seqnum = (data[2] << 8) | data[3];
254 } else {
255 seqnum = raop_buffer->first_seqnum;
256 }
257
258 /* If this packet is too late, just skip it */
259 if (!raop_buffer->is_empty && seqnum_cmp(seqnum, raop_buffer->first_seqnum) < 0) {
260 return 0;
261 }
262
263 /* Check that there is always space in the buffer, otherwise flush */
264 if (seqnum_cmp(seqnum, raop_buffer->first_seqnum+RAOP_BUFFER_LENGTH) >= 0) {
265 raop_buffer_flush(raop_buffer, seqnum);
266 }
267
268 /* Get entry corresponding our seqnum */
269 entry = &raop_buffer->entries[seqnum % RAOP_BUFFER_LENGTH];
270 if (entry->available && seqnum_cmp(entry->seqnum, seqnum) == 0) {
271 /* Packet resend, we can safely ignore */
272 return 0;
273 }
274
275 /* Update the raop_buffer entry header */
276 entry->flags = data[0];
277 entry->type = data[1];
278 entry->seqnum = seqnum;
279 entry->timestamp = (data[4] << 24) | (data[5] << 16) |
280 (data[6] << 8) | data[7];
281 entry->ssrc = (data[8] << 24) | (data[9] << 16) |
282 (data[10] << 8) | data[11];
283 entry->available = 1;
284
285 /* Decrypt audio data */
286 encryptedlen = (datalen-12)/16*16;
287 AES_set_key(&aes_ctx, raop_buffer->aeskey, raop_buffer->aesiv, AES_MODE_128);
288 AES_convert_key(&aes_ctx);
289 AES_cbc_decrypt(&aes_ctx, &data[12], packetbuf, encryptedlen);
290 memcpy(packetbuf+encryptedlen, &data[12+encryptedlen], datalen-12-encryptedlen);
291
292 /* Decode ALAC audio data */
293 outputlen = entry->audio_buffer_size;
294 decode_frame(raop_buffer->alac, packetbuf, entry->audio_buffer, &outputlen);
295 entry->audio_buffer_len = outputlen;
296
297 /* Update the raop_buffer seqnums */
298 if (raop_buffer->is_empty) {
299 raop_buffer->first_seqnum = seqnum;
300 raop_buffer->last_seqnum = seqnum;
301 raop_buffer->is_empty = 0;
302 }
303 if (seqnum_cmp(seqnum, raop_buffer->last_seqnum) > 0) {
304 raop_buffer->last_seqnum = seqnum;
305 }
306 return 1;
307 }
308
309 const void *
310 raop_buffer_dequeue(raop_buffer_t *raop_buffer, int *length, int no_resend)
311 {
312 short buflen;
313 raop_buffer_entry_t *entry;
314
315 /* Calculate number of entries in the current buffer */
316 buflen = seqnum_cmp(raop_buffer->last_seqnum, raop_buffer->first_seqnum)+1;
317
318 /* Cannot dequeue from empty buffer */
319 if (raop_buffer->is_empty || buflen <= 0) {
320 return NULL;
321 }
322
323 /* Get the first buffer entry for inspection */
324 entry = &raop_buffer->entries[raop_buffer->first_seqnum % RAOP_BUFFER_LENGTH];
325 if (no_resend) {
326 /* If we do no resends, always return the first entry */
327 } else if (!entry->available) {
328 /* Check how much we have space left in the buffer */
329 if (buflen < RAOP_BUFFER_LENGTH) {
330 /* Return nothing and hope resend gets on time */
331 return NULL;
332 }
333 /* Risk of buffer overrun, return empty buffer */
334 }
335
336 /* Update buffer and validate entry */
337 raop_buffer->first_seqnum += 1;
338 if (!entry->available) {
339 /* Return an empty audio buffer to skip audio */
340 *length = entry->audio_buffer_size;
341 memset(entry->audio_buffer, 0, *length);
342 return entry->audio_buffer;
343 }
344 entry->available = 0;
345
346 /* Return entry audio buffer */
347 *length = entry->audio_buffer_len;
348 entry->audio_buffer_len = 0;
349 return entry->audio_buffer;
350 }
351
352 void
353 raop_buffer_handle_resends(raop_buffer_t *raop_buffer, raop_resend_cb_t resend_cb, void *opaque)
354 {
355 raop_buffer_entry_t *entry;
356
357 assert(raop_buffer);
358 assert(resend_cb);
359
360 if (seqnum_cmp(raop_buffer->first_seqnum, raop_buffer->last_seqnum) < 0) {
361 int seqnum, count;
362
363 for (seqnum=raop_buffer->first_seqnum; seqnum_cmp(seqnum, raop_buffer->last_seqnum)<0; seqnum++) {
364 entry = &raop_buffer->entries[seqnum % RAOP_BUFFER_LENGTH];
365 if (entry->available) {
366 break;
367 }
368 }
369 if (seqnum_cmp(seqnum, raop_buffer->first_seqnum) == 0) {
370 return;
371 }
372 count = seqnum_cmp(seqnum, raop_buffer->first_seqnum);
373 resend_cb(opaque, raop_buffer->first_seqnum, count);
374 }
375 }
376
377 void
378 raop_buffer_flush(raop_buffer_t *raop_buffer, int next_seq)
379 {
380 int i;
381
382 assert(raop_buffer);
383
384 for (i=0; i<RAOP_BUFFER_LENGTH; i++) {
385 raop_buffer->entries[i].available = 0;
386 raop_buffer->entries[i].audio_buffer_len = 0;
387 }
388 if (next_seq < 0 || next_seq > 0xffff) {
389 raop_buffer->is_empty = 1;
390 } else {
391 raop_buffer->first_seqnum = next_seq;
392 raop_buffer->last_seqnum = next_seq-1;
393 }
394 }