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 32
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
get_fmtp_info(ALACSpecificConfig * config,const char * fmtp)72 get_fmtp_info(ALACSpecificConfig *config, const char *fmtp)
73 {
74 	int intarr[12];
75 	char *original;
76 	char *strptr;
77 	int i;
78 
79 	/* Parse fmtp string to integers */
80 	original = strptr = strdup(fmtp);
81 	for (i=0; i<12; i++) {
82 		if (strptr == NULL) {
83 			free(original);
84 			return -1;
85 		}
86 		intarr[i] = atoi(utils_strsep(&strptr, " "));
87 	}
88 	free(original);
89 	original = strptr = NULL;
90 
91 	/* Fill the config struct */
92 	config->frameLength = intarr[1];
93 	config->compatibleVersion = intarr[2];
94 	config->bitDepth = intarr[3];
95 	config->pb = intarr[4];
96 	config->mb = intarr[5];
97 	config->kb = intarr[6];
98 	config->numChannels = intarr[7];
99 	config->maxRun = intarr[8];
100 	config->maxFrameBytes = intarr[9];
101 	config->avgBitRate = intarr[10];
102 	config->sampleRate = intarr[11];
103 
104 	/* Validate supported audio types */
105 	if (config->bitDepth != 16) {
106 		return -2;
107 	}
108 	if (config->numChannels != 2) {
109 		return -3;
110 	}
111 
112 	return 0;
113 }
114 
115 static void
set_decoder_info(alac_file * alac,ALACSpecificConfig * config)116 set_decoder_info(alac_file *alac, ALACSpecificConfig *config)
117 {
118 	unsigned char decoder_info[48];
119 	memset(decoder_info, 0, sizeof(decoder_info));
120 
121 #define SET_UINT16(buf, value)do{\
122 	(buf)[0] = (unsigned char)((value) >> 8);\
123 	(buf)[1] = (unsigned char)(value);\
124 	}while(0)
125 
126 #define SET_UINT32(buf, value)do{\
127 	(buf)[0] = (unsigned char)((value) >> 24);\
128 	(buf)[1] = (unsigned char)((value) >> 16);\
129 	(buf)[2] = (unsigned char)((value) >> 8);\
130 	(buf)[3] = (unsigned char)(value);\
131 	}while(0)
132 
133 	/* Construct decoder info buffer */
134 	SET_UINT32(&decoder_info[24], config->frameLength);
135 	decoder_info[28] = config->compatibleVersion;
136 	decoder_info[29] = config->bitDepth;
137 	decoder_info[30] = config->pb;
138 	decoder_info[31] = config->mb;
139 	decoder_info[32] = config->kb;
140 	decoder_info[33] = config->numChannels;
141 	SET_UINT16(&decoder_info[34], config->maxRun);
142 	SET_UINT32(&decoder_info[36], config->maxFrameBytes);
143 	SET_UINT32(&decoder_info[40], config->avgBitRate);
144 	SET_UINT32(&decoder_info[44], config->sampleRate);
145 	alac_set_info(alac, (char *) decoder_info);
146 }
147 
148 raop_buffer_t *
raop_buffer_init(const char * rtpmap,const char * fmtp,const unsigned char * aeskey,const unsigned char * aesiv)149 raop_buffer_init(const char *rtpmap,
150                  const char *fmtp,
151                  const unsigned char *aeskey,
152                  const unsigned char *aesiv)
153 {
154 	raop_buffer_t *raop_buffer;
155 	int audio_buffer_size;
156 	ALACSpecificConfig *alacConfig;
157 	int i;
158 
159         assert(rtpmap);
160 	assert(fmtp);
161 	assert(aeskey);
162 	assert(aesiv);
163 
164 	raop_buffer = calloc(1, sizeof(raop_buffer_t));
165 	if (!raop_buffer) {
166 		return NULL;
167 	}
168 
169 	/* Parse fmtp information */
170 	alacConfig = &raop_buffer->alacConfig;
171 	if (get_fmtp_info(alacConfig, fmtp) < 0) {
172 		free(raop_buffer);
173 		return NULL;
174 	}
175 
176 	/* Allocate the output audio buffers */
177 	audio_buffer_size = alacConfig->frameLength *
178 	                    alacConfig->numChannels *
179 	                    alacConfig->bitDepth/8;
180 	raop_buffer->buffer_size = audio_buffer_size *
181 	                           RAOP_BUFFER_LENGTH;
182 	raop_buffer->buffer = malloc(raop_buffer->buffer_size);
183 	if (!raop_buffer->buffer) {
184 		free(raop_buffer);
185 		return NULL;
186 	}
187 	for (i=0; i<RAOP_BUFFER_LENGTH; i++) {
188 		raop_buffer_entry_t *entry = &raop_buffer->entries[i];
189 		entry->audio_buffer_size = audio_buffer_size;
190 		entry->audio_buffer_len = 0;
191 		entry->audio_buffer = (char *)raop_buffer->buffer+i*audio_buffer_size;
192 	}
193 
194 	/* Initialize ALAC decoder */
195 	raop_buffer->alac = alac_create(alacConfig->bitDepth,
196 	                                alacConfig->numChannels);
197 	if (!raop_buffer->alac) {
198 		free(raop_buffer->buffer);
199 		free(raop_buffer);
200 		return NULL;
201 	}
202 	set_decoder_info(raop_buffer->alac, alacConfig);
203 
204 	/* Initialize AES keys */
205 	memcpy(raop_buffer->aeskey, aeskey, RAOP_AESKEY_LEN);
206 	memcpy(raop_buffer->aesiv, aesiv, RAOP_AESIV_LEN);
207 
208 	/* Mark buffer as empty */
209 	raop_buffer->is_empty = 1;
210 	return raop_buffer;
211 }
212 
213 void
raop_buffer_destroy(raop_buffer_t * raop_buffer)214 raop_buffer_destroy(raop_buffer_t *raop_buffer)
215 {
216 	if (raop_buffer) {
217 		alac_free(raop_buffer->alac);
218 		free(raop_buffer->buffer);
219 		free(raop_buffer);
220 	}
221 }
222 
223 const ALACSpecificConfig *
raop_buffer_get_config(raop_buffer_t * raop_buffer)224 raop_buffer_get_config(raop_buffer_t *raop_buffer)
225 {
226 	assert(raop_buffer);
227 
228 	return &raop_buffer->alacConfig;
229 }
230 
231 static short
seqnum_cmp(unsigned short s1,unsigned short s2)232 seqnum_cmp(unsigned short s1, unsigned short s2)
233 {
234 	return (s1 - s2);
235 }
236 
237 int
raop_buffer_queue(raop_buffer_t * raop_buffer,unsigned char * data,unsigned short datalen,int use_seqnum)238 raop_buffer_queue(raop_buffer_t *raop_buffer, unsigned char *data, unsigned short datalen, int use_seqnum)
239 {
240 	unsigned char packetbuf[RAOP_PACKET_LEN];
241 	unsigned short seqnum;
242 	raop_buffer_entry_t *entry;
243 	int encryptedlen;
244 	AES_CTX aes_ctx;
245 	int outputlen;
246 
247 	assert(raop_buffer);
248 
249 	/* Check packet data length is valid */
250 	if (datalen < 12 || datalen > RAOP_PACKET_LEN) {
251 		return -1;
252 	}
253 
254 	/* Get correct seqnum for the packet */
255 	if (use_seqnum) {
256 		seqnum = (data[2] << 8) | data[3];
257 	} else {
258 		seqnum = raop_buffer->first_seqnum;
259 	}
260 
261 	/* If this packet is too late, just skip it */
262 	if (!raop_buffer->is_empty && seqnum_cmp(seqnum, raop_buffer->first_seqnum) < 0) {
263 		return 0;
264 	}
265 
266 	/* Check that there is always space in the buffer, otherwise flush */
267 	if (seqnum_cmp(seqnum, raop_buffer->first_seqnum+RAOP_BUFFER_LENGTH) >= 0) {
268 		raop_buffer_flush(raop_buffer, seqnum);
269 	}
270 
271 	/* Get entry corresponding our seqnum */
272 	entry = &raop_buffer->entries[seqnum % RAOP_BUFFER_LENGTH];
273 	if (entry->available && seqnum_cmp(entry->seqnum, seqnum) == 0) {
274 		/* Packet resend, we can safely ignore */
275 		return 0;
276 	}
277 
278 	/* Update the raop_buffer entry header */
279 	entry->flags = data[0];
280 	entry->type = data[1];
281 	entry->seqnum = seqnum;
282 	entry->timestamp = (data[4] << 24) | (data[5] << 16) |
283 	                   (data[6] << 8) | data[7];
284 	entry->ssrc = (data[8] << 24) | (data[9] << 16) |
285 	              (data[10] << 8) | data[11];
286 	entry->available = 1;
287 
288 	/* Decrypt audio data */
289 	encryptedlen = (datalen-12)/16*16;
290 	AES_set_key(&aes_ctx, raop_buffer->aeskey, raop_buffer->aesiv, AES_MODE_128);
291 	AES_convert_key(&aes_ctx);
292 	AES_cbc_decrypt(&aes_ctx, &data[12], packetbuf, encryptedlen);
293 	memcpy(packetbuf+encryptedlen, &data[12+encryptedlen], datalen-12-encryptedlen);
294 
295 	/* Decode ALAC audio data */
296 	outputlen = entry->audio_buffer_size;
297 	alac_decode_frame(raop_buffer->alac, packetbuf,
298 	                  entry->audio_buffer, &outputlen);
299 	entry->audio_buffer_len = outputlen;
300 
301 	/* Update the raop_buffer seqnums */
302 	if (raop_buffer->is_empty) {
303 		raop_buffer->first_seqnum = seqnum;
304 		raop_buffer->last_seqnum = seqnum;
305 		raop_buffer->is_empty = 0;
306 	}
307 	if (seqnum_cmp(seqnum, raop_buffer->last_seqnum) > 0) {
308 		raop_buffer->last_seqnum = seqnum;
309 	}
310 	return 1;
311 }
312 
313 const void *
raop_buffer_dequeue(raop_buffer_t * raop_buffer,int * length,int no_resend)314 raop_buffer_dequeue(raop_buffer_t *raop_buffer, int *length, int no_resend)
315 {
316 	short buflen;
317 	raop_buffer_entry_t *entry;
318 
319 	/* Calculate number of entries in the current buffer */
320 	buflen = seqnum_cmp(raop_buffer->last_seqnum, raop_buffer->first_seqnum)+1;
321 
322 	/* Cannot dequeue from empty buffer */
323 	if (raop_buffer->is_empty || buflen <= 0) {
324 		return NULL;
325 	}
326 
327 	/* Get the first buffer entry for inspection */
328 	entry = &raop_buffer->entries[raop_buffer->first_seqnum % RAOP_BUFFER_LENGTH];
329 	if (no_resend) {
330 		/* If we do no resends, always return the first entry */
331 	} else if (!entry->available) {
332 		/* Check how much we have space left in the buffer */
333 		if (buflen < RAOP_BUFFER_LENGTH) {
334 			/* Return nothing and hope resend gets on time */
335 			return NULL;
336 		}
337 		/* Risk of buffer overrun, return empty buffer */
338 	}
339 
340 	/* Update buffer and validate entry */
341 	raop_buffer->first_seqnum += 1;
342 	if (!entry->available) {
343 		/* Return an empty audio buffer to skip audio */
344 		*length = entry->audio_buffer_size;
345 		memset(entry->audio_buffer, 0, *length);
346 		return entry->audio_buffer;
347 	}
348 	entry->available = 0;
349 
350 	/* Return entry audio buffer */
351 	*length = entry->audio_buffer_len;
352 	entry->audio_buffer_len = 0;
353 	return entry->audio_buffer;
354 }
355 
356 void
raop_buffer_handle_resends(raop_buffer_t * raop_buffer,raop_resend_cb_t resend_cb,void * opaque)357 raop_buffer_handle_resends(raop_buffer_t *raop_buffer, raop_resend_cb_t resend_cb, void *opaque)
358 {
359 	raop_buffer_entry_t *entry;
360 
361 	assert(raop_buffer);
362 	assert(resend_cb);
363 
364 	if (seqnum_cmp(raop_buffer->first_seqnum, raop_buffer->last_seqnum) < 0) {
365 		int seqnum, count;
366 
367 		for (seqnum=raop_buffer->first_seqnum; seqnum_cmp(seqnum, raop_buffer->last_seqnum)<0; seqnum++) {
368 			entry = &raop_buffer->entries[seqnum % RAOP_BUFFER_LENGTH];
369 			if (entry->available) {
370 				break;
371 			}
372 		}
373 		if (seqnum_cmp(seqnum, raop_buffer->first_seqnum) == 0) {
374 			return;
375 		}
376 		count = seqnum_cmp(seqnum, raop_buffer->first_seqnum);
377 		resend_cb(opaque, raop_buffer->first_seqnum, count);
378 	}
379 }
380 
381 void
raop_buffer_flush(raop_buffer_t * raop_buffer,int next_seq)382 raop_buffer_flush(raop_buffer_t *raop_buffer, int next_seq)
383 {
384 	int i;
385 
386 	assert(raop_buffer);
387 
388 	for (i=0; i<RAOP_BUFFER_LENGTH; i++) {
389 		raop_buffer->entries[i].available = 0;
390 		raop_buffer->entries[i].audio_buffer_len = 0;
391 	}
392 	if (next_seq < 0 || next_seq > 0xffff) {
393 		raop_buffer->is_empty = 1;
394 	} else {
395 		raop_buffer->first_seqnum = next_seq;
396 		raop_buffer->last_seqnum = next_seq-1;
397 	}
398 }
399