1 /*
2 * HairTunes - RAOP packet handler and slave-clocked replay engine
3 * Copyright (c) James Laird 2011
4 * All rights reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person
7 * obtaining a copy of this software and associated documentation
8 * files (the "Software"), to deal in the Software without
9 * restriction, including without limitation the rights to use,
10 * copy, modify, merge, publish, distribute, sublicense, and/or
11 * sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 * OTHER DEALINGS IN THE SOFTWARE.
25 */
26
27 #define XBMC
28 #define HAS_AO
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <sys/select.h>
37 #include <netinet/in.h>
38 #include <arpa/inet.h>
39 #include <pthread.h>
40 #include <openssl/aes.h>
41 #include <math.h>
42 #include <sys/stat.h>
43
44 #include "hairtunes.h"
45 #include <sys/signal.h>
46 #include <fcntl.h>
47 #ifdef HAS_AO
48 #include "ao.h"
49 #endif
50
51 #ifdef FANCY_RESAMPLING
52 #include <samplerate.h>
53 #endif
54
55 #include <assert.h>
56 int debug = 0;
57
58 #include "alac.h"
59
60 // default buffer size
61 #define BUFFER_FRAMES 320
62 // and how full it needs to be to begin (must be <BUFFER_FRAMES)
63 #define START_FILL 282
64
65 #define MAX_PACKET 2048
66
67 typedef unsigned short seq_t;
68
69 // global options (constant after init)
70 unsigned char aeskey[16], aesiv[16];
71 AES_KEY aes;
72 char *rtphost = 0;
73 int dataport = 0, controlport = 0, timingport = 0;
74 int fmtp[32];
75 int sampling_rate;
76 int frame_size;
77
78 int buffer_start_fill = START_FILL;
79
80 char *libao_driver = NULL;
81 char *libao_devicename = NULL;
82 char *libao_deviceid = NULL; // ao_options expects "char*"
83
84 // FIFO name and file handle
85 char *pipename = NULL;
86 int pipe_handle = -1;
87
88 #define FRAME_BYTES (4*frame_size)
89 // maximal resampling shift - conservative
90 #define OUTFRAME_BYTES (4*(frame_size+3))
91
92 alac_file *decoder_info;
93
94 #ifdef FANCY_RESAMPLING
95 int fancy_resampling = 1;
96 SRC_STATE *src;
97 #endif
98
99 static int init_rtp(void);
100 static void init_buffer(void);
101 static int init_output(void);
102 static void rtp_request_resend(seq_t first, seq_t last);
103 static void ab_resync(void);
104
105 // interthread variables
106 // stdin->decoder
107 volatile double volume = 1.0;
108 volatile long fix_volume = 0x10000;
109
110 typedef struct audio_buffer_entry { // decoded audio packets
111 int ready;
112 signed short *data;
113 } abuf_t;
114 volatile abuf_t audio_buffer[BUFFER_FRAMES];
115 #define BUFIDX(seqno) ((seq_t)(seqno) % BUFFER_FRAMES)
116
117 // mutex-protected variables
118 volatile seq_t ab_read, ab_write;
119 int ab_buffering = 1, ab_synced = 0;
120 pthread_mutex_t ab_mutex;
121 pthread_cond_t ab_buffer_ready;
122
die(char * why)123 static void die(char *why) {
124 xprintf("FATAL: %s\n", why);
125 //exit(1);
126 }
127
hex2bin(unsigned char * buf,char * hex)128 static int hex2bin(unsigned char *buf, char *hex) {
129 int i, j;
130 if (strlen(hex) != 0x20)
131 return 1;
132 for (i=0; i<0x10; i++) {
133 if (!sscanf(hex, "%2X", &j))
134 return 1;
135 hex += 2;
136 *buf++ = j;
137 }
138 return 0;
139 }
140
141 alac_file *alac;
142
init_decoder(void)143 static int init_decoder(void) {
144 frame_size = fmtp[1]; // stereo samples
145 sampling_rate = fmtp[11];
146
147 int sample_size = fmtp[3];
148 if (sample_size != 16)
149 die("only 16-bit samples supported!");
150
151 alac = create_alac(sample_size, 2);
152 if (!alac)
153 return 1;
154 decoder_info = alac;
155
156 alac->setinfo_max_samples_per_frame = frame_size;
157 alac->setinfo_7a = fmtp[2];
158 alac->setinfo_sample_size = sample_size;
159 alac->setinfo_rice_historymult = fmtp[4];
160 alac->setinfo_rice_initialhistory = fmtp[5];
161 alac->setinfo_rice_kmodifier = fmtp[6];
162 alac->setinfo_7f = fmtp[7];
163 alac->setinfo_80 = fmtp[8];
164 alac->setinfo_82 = fmtp[9];
165 alac->setinfo_86 = fmtp[10];
166 alac->setinfo_8a_rate = fmtp[11];
167 allocate_buffers(alac);
168 return 0;
169 }
170
clean_decoder(void)171 static void clean_decoder(void)
172 {
173 deallocate_buffers(alac);
174 delete_alac(alac);
175 }
176
hairtunes_init(char * pAeskey,char * pAesiv,char * fmtpstr,int pCtrlPort,int pTimingPort,int pDataPort,char * pRtpHost,char * pPipeName,char * pLibaoDriver,char * pLibaoDeviceName,char * pLibaoDeviceId)177 int hairtunes_init(char *pAeskey, char *pAesiv, char *fmtpstr, int pCtrlPort, int pTimingPort,
178 int pDataPort, char *pRtpHost, char*pPipeName, char *pLibaoDriver, char *pLibaoDeviceName, char *pLibaoDeviceId)
179 {
180 volume = 1.0;
181 fix_volume = 0x10000;
182 rtphost = 0;
183 dataport = 0;
184 controlport = 0;
185 timingport = 0;
186 buffer_start_fill = START_FILL;
187 libao_driver = NULL;
188 libao_devicename = NULL;
189 libao_deviceid = NULL;
190 pipename = NULL;
191 pipe_handle = -1;
192 ab_buffering = 1;
193 ab_synced = 0;
194 pthread_mutex_init(&ab_mutex, NULL);
195 pthread_cond_init(&ab_buffer_ready, NULL);
196
197 if(pAeskey != NULL)
198 memcpy(aeskey, pAeskey, sizeof(aeskey));
199 if(pAesiv != NULL)
200 memcpy(aesiv, pAesiv, sizeof(aesiv));
201 if(pRtpHost != NULL)
202 rtphost = pRtpHost;
203 if(pPipeName != NULL)
204 pipename = pPipeName;
205 if(pLibaoDriver != NULL)
206 libao_driver = pLibaoDriver;
207 if(pLibaoDeviceName != NULL)
208 libao_devicename = pLibaoDeviceName;
209 if(pLibaoDeviceId != NULL)
210 libao_deviceid = pLibaoDeviceId;
211
212 controlport = pCtrlPort;
213 timingport = pTimingPort;
214 dataport = pDataPort;
215
216 AES_set_decrypt_key(aeskey, 128, &aes);
217
218 memset(fmtp, 0, sizeof(fmtp));
219 int i = 0;
220 char *arg;
221 while ( (arg = strsep(&fmtpstr, " \t")) )
222 fmtp[i++] = atoi(arg);
223
224 init_decoder();
225 init_buffer();
226 init_rtp(); // open a UDP listen port and start a listener; decode into ring buffer
227 fflush(stdout);
228 init_output(); // resample and output from ring buffer
229
230 #ifndef XBMC
231 char line[128];
232 int in_line = 0;
233 int n;
234 double f;
235 while (fgets(line + in_line, sizeof(line) - in_line, stdin)) {
236 n = strlen(line);
237 if (line[n-1] != '\n') {
238 in_line = strlen(line) - 1;
239 if (n == sizeof(line)-1)
240 in_line = 0;
241 continue;
242 }
243 if (sscanf(line, "vol: %lf\n", &f)) {
244 hairtunes_setvolume(f);
245 continue;
246 }
247 if (!strcmp(line, "exit\n")) {
248 ;//exit(0);
249 }
250 if (!strcmp(line, "flush\n")) {
251 hairtunes_flush();
252 }
253 }
254 xprintf("bye!\n");
255 fflush(stderr);
256 #endif
257
258 return EXIT_SUCCESS;
259 }
260
hairtunes_setvolume(float f)261 void hairtunes_setvolume(float f)
262 {
263 assert(f<=0);
264 if (debug)
265 xprintf("VOL: %lf\n", f);
266 volume = pow(10.0,0.05*f);
267 fix_volume = 65536.0 * volume;
268 }
269
hairtunes_set_metadata(const char * buffer,unsigned int size)270 void hairtunes_set_metadata(const char *buffer, unsigned int size)
271 {
272 g_ao.ao_set_metadata(buffer, size);
273 }
274
hairtunes_set_metadata_coverart(const char * buffer,unsigned int size)275 void hairtunes_set_metadata_coverart(const char *buffer, unsigned int size)
276 {
277 g_ao.ao_set_metadata_coverart(buffer, size);
278 }
279
hairtunes_flush(void)280 void hairtunes_flush(void)
281 {
282 pthread_mutex_lock(&ab_mutex);
283 ab_resync();
284 pthread_mutex_unlock(&ab_mutex);
285 if (debug)
286 xprintf("FLUSH\n");
287 }
288
289 #ifdef HAIRTUNES_STANDALONE
main(int argc,char ** argv)290 int main(int argc, char **argv) {
291 char *hexaeskey = 0, *hexaesiv = 0;
292 char *fmtpstr = 0;
293 char *arg;
294 assert(RAND_MAX >= 0x10000); // XXX move this to compile time
295 while ( (arg = *++argv) ) {
296 if (!strcasecmp(arg, "iv")) {
297 hexaesiv = *++argv;
298 argc--;
299 } else
300 if (!strcasecmp(arg, "key")) {
301 hexaeskey = *++argv;
302 argc--;
303 } else
304 if (!strcasecmp(arg, "fmtp")) {
305 fmtpstr = *++argv;
306 } else
307 if (!strcasecmp(arg, "cport")) {
308 controlport = atoi(*++argv);
309 } else
310 if (!strcasecmp(arg, "tport")) {
311 timingport = atoi(*++argv);
312 } else
313 if (!strcasecmp(arg, "dport")) {
314 dataport = atoi(*++argv);
315 } else
316 if (!strcasecmp(arg, "host")) {
317 rtphost = *++argv;
318 } else
319 if (!strcasecmp(arg, "pipe")) {
320 if (libao_driver || libao_devicename || libao_deviceid ) {
321 die("Option 'pipe' may not be combined with 'ao_driver', 'ao_devicename' or 'ao_deviceid'");
322 }
323
324 pipename = *++argv;
325 } else
326 if (!strcasecmp(arg, "ao_driver")) {
327 if (pipename) {
328 die("Option 'ao_driver' may not be combined with 'pipe'");
329 }
330
331 libao_driver = *++argv;
332 } else
333 if (!strcasecmp(arg, "ao_devicename")) {
334 if (pipename || libao_deviceid ) {
335 die("Option 'ao_devicename' may not be combined with 'pipe' or 'ao_deviceid'");
336 }
337
338 libao_devicename = *++argv;
339 } else
340 if (!strcasecmp(arg, "ao_deviceid")) {
341 if (pipename || libao_devicename) {
342 die("Option 'ao_deviceid' may not be combined with 'pipe' or 'ao_devicename'");
343 }
344
345 libao_deviceid = *++argv;
346 }
347 #ifdef FANCY_RESAMPLING
348 else
349 if (!strcasecmp(arg, "resamp")) {
350 fancy_resampling = atoi(*++argv);
351 }
352 #endif
353 }
354
355 if (!hexaeskey || !hexaesiv)
356 die("Must supply AES key and IV!");
357
358 if (hex2bin(aesiv, hexaesiv))
359 die("can't understand IV");
360 if (hex2bin(aeskey, hexaeskey))
361 die("can't understand key");
362 return hairtunes_init(NULL, NULL, fmtpstr, controlport, timingport, dataport,
363 NULL, NULL, NULL, NULL, NULL);
364 }
365 #endif
366
init_buffer(void)367 static void init_buffer(void) {
368 int i;
369 for (i=0; i<BUFFER_FRAMES; i++)
370 audio_buffer[i].data = malloc(OUTFRAME_BYTES);
371 ab_resync();
372 }
373
clean_buffer(void)374 static void clean_buffer(void)
375 {
376 int i;
377 for (i=0; i<BUFFER_FRAMES; i++)
378 free(audio_buffer[i].data);
379 }
380
ab_resync(void)381 static void ab_resync(void) {
382 int i;
383 for (i=0; i<BUFFER_FRAMES; i++)
384 audio_buffer[i].ready = 0;
385 ab_synced = 0;
386 ab_buffering = 1;
387 }
388
389 // the sequence numbers will wrap pretty often.
390 // this returns true if the second arg is after the first
seq_order(seq_t a,seq_t b)391 static inline int seq_order(seq_t a, seq_t b) {
392 signed short d = b - a;
393 return d > 0;
394 }
395
alac_decode(short * dest,char * buf,int len)396 static void alac_decode(short *dest, char *buf, int len) {
397 unsigned char packet[MAX_PACKET];
398 assert(len<=MAX_PACKET);
399
400 unsigned char iv[16];
401 int i;
402 memcpy(iv, aesiv, sizeof(iv));
403 for (i=0; i+16<=len; i += 16)
404 AES_cbc_encrypt((unsigned char*)buf+i, packet+i, 0x10, &aes, iv, AES_DECRYPT);
405 if (len & 0xf)
406 memcpy(packet+i, buf+i, len & 0xf);
407
408 int outsize;
409
410 decode_frame(decoder_info, packet, dest, &outsize);
411
412 assert(outsize == FRAME_BYTES);
413 }
414
buffer_put_packet(seq_t seqno,char * data,int len)415 static void buffer_put_packet(seq_t seqno, char *data, int len) {
416 volatile abuf_t *abuf = 0;
417 short read;
418 short buf_fill;
419
420 pthread_mutex_lock(&ab_mutex);
421 if (!ab_synced) {
422 ab_write = seqno;
423 ab_read = seqno-1;
424 ab_synced = 1;
425 }
426 if (seqno == ab_write+1) { // expected packet
427 abuf = audio_buffer + BUFIDX(seqno);
428 ab_write = seqno;
429 } else if (seq_order(ab_write, seqno)) { // newer than expected
430 rtp_request_resend(ab_write, seqno-1);
431 abuf = audio_buffer + BUFIDX(seqno);
432 ab_write = seqno;
433 } else if (seq_order(ab_read, seqno)) { // late but not yet played
434 abuf = audio_buffer + BUFIDX(seqno);
435 } else { // too late.
436 xprintf("\nlate packet %04X (%04X:%04X)\n", seqno, ab_read, ab_write);
437 }
438 buf_fill = ab_write - ab_read;
439 pthread_mutex_unlock(&ab_mutex);
440
441 if (abuf) {
442 alac_decode(abuf->data, data, len);
443 abuf->ready = 1;
444 }
445
446 if (ab_buffering && buf_fill >= buffer_start_fill) {
447 ab_buffering = 0;
448 pthread_cond_signal(&ab_buffer_ready);
449 }
450 #ifndef XBMC
451 if (!ab_buffering) {
452 // check if the t+10th packet has arrived... last-chance resend
453 read = ab_read + 10;
454 abuf = audio_buffer + BUFIDX(read);
455 if (!abuf->ready)
456 rtp_request_resend(read, read);
457 }
458 #endif
459 }
460
461 static int rtp_sockets[2]; // data, control
462 #ifdef AF_INET6
463 struct sockaddr_in6 rtp_client;
464 #else
465 struct sockaddr_in rtp_client;
466 #endif
467
468 int rtp_running = 0;
469
rtp_thread_func(void * arg)470 void *rtp_thread_func(void *arg) {
471 socklen_t si_len = sizeof(rtp_client);
472 char packet[MAX_PACKET];
473 char *pktp;
474 seq_t seqno;
475 ssize_t plen;
476 int sock = rtp_sockets[0], csock = rtp_sockets[1];
477 int readsock;
478 char type;
479
480 fd_set fds;
481 FD_ZERO(&fds);
482 FD_SET(sock, &fds);
483 FD_SET(csock, &fds);
484
485 struct timeval timeout;
486 timeout.tv_sec = 1;
487 timeout.tv_usec = 0;
488
489 rtp_running = 1;
490 while (select(csock>sock ? csock+1 : sock+1, &fds, 0, 0, &timeout)!=-1 && rtp_running) {
491
492 if (FD_ISSET(sock, &fds)) {
493 readsock = sock;
494 } else if (FD_ISSET(csock, &fds)) {
495 readsock = csock;
496 } else {
497 readsock = -1;
498 }
499
500 FD_ZERO(&fds);
501 FD_SET(sock, &fds);
502 FD_SET(csock, &fds);
503 timeout.tv_sec = 1;
504 timeout.tv_usec = 0;
505
506 if (readsock == -1)
507 continue;
508
509 plen = recvfrom(readsock, packet, sizeof(packet), 0, (struct sockaddr*)&rtp_client, &si_len);
510 if (plen < 0)
511 continue;
512 assert(plen<=MAX_PACKET);
513
514 type = packet[1] & ~0x80;
515 if (type == 0x60 || type == 0x56) { // audio data / resend
516 pktp = packet;
517 if (type==0x56) {
518 pktp += 4;
519 plen -= 4;
520 }
521 seqno = ntohs(*(unsigned short *)(pktp+2));
522 buffer_put_packet(seqno, pktp+12, plen-12);
523 }
524 }
525
526 return 0;
527 }
528
rtp_request_resend(seq_t first,seq_t last)529 static void rtp_request_resend(seq_t first, seq_t last) {
530 if (seq_order(last, first))
531 return;
532
533 xprintf("requesting resend on %d packets (port %d)\n", last-first+1, controlport);
534
535 char req[8]; // *not* a standard RTCP NACK
536 req[0] = 0x80;
537 req[1] = 0x55|0x80; // Apple 'resend'
538 *(unsigned short *)(req+2) = htons(1); // our seqnum
539 *(unsigned short *)(req+4) = htons(first); // missed seqnum
540 *(unsigned short *)(req+6) = htons(last-first+1); // count
541
542 #ifdef AF_INET6
543 rtp_client.sin6_port = htons(controlport);
544 #else
545 rtp_client.sin_port = htons(controlport);
546 #endif
547 sendto(rtp_sockets[1], req, sizeof(req), 0, (struct sockaddr *)&rtp_client, sizeof(rtp_client));
548 }
549
550 pthread_t rtp_thread;
551
init_rtp(void)552 static int init_rtp(void) {
553 struct sockaddr_in si;
554 int type = AF_INET;
555 struct sockaddr* si_p = (struct sockaddr*)&si;
556 socklen_t si_len = sizeof(si);
557 unsigned short *sin_port = &si.sin_port;
558 memset(&si, 0, sizeof(si));
559 #ifdef AF_INET6
560 struct sockaddr_in6 si6;
561 type = AF_INET6;
562 si_p = (struct sockaddr*)&si6;
563 si_len = sizeof(si6);
564 sin_port = &si6.sin6_port;
565 memset(&si6, 0, sizeof(si6));
566 #endif
567
568 si.sin_family = AF_INET;
569 #ifdef SIN_LEN
570 si.sin_len = sizeof(si);
571 #endif
572 si.sin_addr.s_addr = htonl(INADDR_ANY);
573 #ifdef AF_INET6
574 si6.sin6_family = AF_INET6;
575 #ifdef SIN6_LEN
576 si6.sin6_len = sizeof(si);
577 #endif
578 si6.sin6_addr = in6addr_any;
579 si6.sin6_flowinfo = 0;
580 #endif
581
582 int sock = -1, csock = -1; // data and control (we treat the streams the same here)
583 unsigned short port = 6000;
584 while(1) {
585 if(sock < 0)
586 sock = socket(type, SOCK_DGRAM, IPPROTO_UDP);
587 #ifdef AF_INET6
588 if(sock==-1 && type == AF_INET6) {
589 // try fallback to IPv4
590 type = AF_INET;
591 si_p = (struct sockaddr*)&si;
592 si_len = sizeof(si);
593 sin_port = &si.sin_port;
594 continue;
595 }
596 #endif
597 if (sock==-1)
598 die("Can't create data socket!");
599
600 if(csock < 0)
601 csock = socket(type, SOCK_DGRAM, IPPROTO_UDP);
602 if (csock==-1)
603 die("Can't create control socket!");
604
605 *sin_port = htons(port);
606 int bind1 = bind(sock, si_p, si_len);
607 *sin_port = htons(port + 1);
608 int bind2 = bind(csock, si_p, si_len);
609
610 if(bind1 != -1 && bind2 != -1) break;
611 if(bind1 != -1) { close(sock); sock = -1; }
612 if(bind2 != -1) { close(csock); csock = -1; }
613
614 port += 3;
615 }
616
617 xprintf("port: %d\n", port); // let our handler know where we end up listening
618 xprintf("cport: %d\n", port+1);
619
620 rtp_sockets[0] = sock;
621 rtp_sockets[1] = csock;
622 pthread_create(&rtp_thread, NULL, rtp_thread_func, (void *)rtp_sockets);
623
624 return port;
625 }
626
clean_rtp()627 void clean_rtp()
628 {
629 rtp_running = 0;
630 pthread_join(rtp_thread, NULL);
631 int sock = rtp_sockets[0], csock = rtp_sockets[1];
632 close(sock);
633 close(csock);
634 }
635
dithered_vol(short sample)636 static inline short dithered_vol(short sample) {
637 static short rand_a, rand_b;
638 long out;
639 rand_b = rand_a;
640 rand_a = rand() & 0xffff;
641
642 out = (long)sample * fix_volume;
643 if (fix_volume < 0x10000) {
644 out += rand_a;
645 out -= rand_b;
646 }
647 return out>>16;
648 }
649
650 typedef struct {
651 double hist[2];
652 double a[2];
653 double b[3];
654 } biquad_t;
655
biquad_init(biquad_t * bq,double a[],double b[])656 static void biquad_init(biquad_t *bq, double a[], double b[]) {
657 bq->hist[0] = bq->hist[1] = 0.0;
658 memcpy(bq->a, a, 2*sizeof(double));
659 memcpy(bq->b, b, 3*sizeof(double));
660 }
661
biquad_lpf(biquad_t * bq,double freq,double Q)662 static void biquad_lpf(biquad_t *bq, double freq, double Q) {
663 double w0 = 2*M_PI*freq/((float)sampling_rate/(float)frame_size);
664 double alpha = sin(w0)/(2.0*Q);
665
666 double a_0 = 1.0 + alpha;
667 double b[3], a[2];
668 b[0] = (1.0-cos(w0))/(2.0*a_0);
669 b[1] = (1.0-cos(w0))/a_0;
670 b[2] = b[0];
671 a[0] = -2.0*cos(w0)/a_0;
672 a[1] = (1-alpha)/a_0;
673
674 biquad_init(bq, a, b);
675 }
676
biquad_filt(biquad_t * bq,double in)677 static double biquad_filt(biquad_t *bq, double in) {
678 double w = in - bq->a[0]*bq->hist[0] - bq->a[1]*bq->hist[1];
679 double out __attribute__((unused)) = bq->b[1]*bq->hist[0] + bq->b[2]*bq->hist[1] + bq->b[0]*w;
680 bq->hist[1] = bq->hist[0];
681 bq->hist[0] = w;
682
683 return w;
684 }
685
686 double bf_playback_rate = 1.0;
687
688 static double bf_est_drift = 0.0; // local clock is slower by
689 static biquad_t bf_drift_lpf;
690 static double bf_est_err = 0.0, bf_last_err;
691 static biquad_t bf_err_lpf, bf_err_deriv_lpf;
692 static double desired_fill;
693 static int fill_count;
694
bf_est_reset(short fill)695 void bf_est_reset(short fill) {
696 biquad_lpf(&bf_drift_lpf, 1.0/180.0, 0.3);
697 biquad_lpf(&bf_err_lpf, 1.0/10.0, 0.25);
698 biquad_lpf(&bf_err_deriv_lpf, 1.0/2.0, 0.2);
699 fill_count = 0;
700 bf_playback_rate = 1.0;
701 bf_est_err = bf_last_err = 0;
702 desired_fill = fill_count = 0;
703 }
bf_est_update(short fill)704 void bf_est_update(short fill) {
705 if (fill_count < 1000) {
706 desired_fill += (double)fill/1000.0;
707 fill_count++;
708 return;
709 }
710
711 #define CONTROL_A (1e-4)
712 #define CONTROL_B (1e-1)
713
714 double buf_delta = fill - desired_fill;
715 bf_est_err = biquad_filt(&bf_err_lpf, buf_delta);
716 double err_deriv = biquad_filt(&bf_err_deriv_lpf, bf_est_err - bf_last_err);
717
718 bf_est_drift = biquad_filt(&bf_drift_lpf, CONTROL_B*(bf_est_err*CONTROL_A + err_deriv) + bf_est_drift);
719
720 if (debug)
721 xprintf("bf %d err %f drift %f desiring %f ed %f estd %f\r", fill, bf_est_err, bf_est_drift, desired_fill, err_deriv, err_deriv + CONTROL_A*bf_est_err);
722 bf_playback_rate = 1.0 + CONTROL_A*bf_est_err + bf_est_drift;
723
724 bf_last_err = bf_est_err;
725 }
726
727 // get the next frame, when available. return 0 if underrun/stream reset.
buffer_get_frame(void)728 short *buffer_get_frame(void) {
729 short buf_fill;
730 seq_t read;
731
732 pthread_mutex_lock(&ab_mutex);
733
734 buf_fill = ab_write - ab_read;
735 if (buf_fill < 1 || !ab_synced || ab_buffering) { // init or underrun. stop and wait
736 if (ab_synced)
737 xprintf("\nunderrun\n");
738
739 ab_buffering = 1;
740 pthread_cond_wait(&ab_buffer_ready, &ab_mutex);
741 ab_read++;
742 buf_fill = ab_write - ab_read;
743 pthread_mutex_unlock(&ab_mutex);
744
745 bf_est_reset(buf_fill);
746 return 0;
747 }
748 if (buf_fill >= BUFFER_FRAMES) { // overrunning! uh-oh. restart at a sane distance
749 xprintf("\noverrun.\n");
750 ab_read = ab_write - START_FILL;
751 }
752 read = ab_read;
753 ab_read++;
754 pthread_mutex_unlock(&ab_mutex);
755
756 buf_fill = ab_write - ab_read;
757 bf_est_update(buf_fill);
758
759 volatile abuf_t *curframe = audio_buffer + BUFIDX(read);
760 if (!curframe->ready) {
761 xprintf("\nmissing frame.\n");
762 memset(curframe->data, 0, FRAME_BYTES);
763 }
764 curframe->ready = 0;
765 return curframe->data;
766 }
767
stuff_buffer(double playback_rate,short * inptr,short * outptr)768 int stuff_buffer(double playback_rate, short *inptr, short *outptr) {
769 int i;
770 int stuffsamp = frame_size;
771 int stuff = 0;
772 double p_stuff;
773
774 p_stuff = 1.0 - pow(1.0 - fabs(playback_rate-1.0), frame_size);
775
776 if ((float)rand()/((float)RAND_MAX) < p_stuff) {
777 stuff = playback_rate > 1.0 ? -1 : 1;
778 stuffsamp = rand() % (frame_size - 1);
779 }
780
781 for (i=0; i<stuffsamp; i++) { // the whole frame, if no stuffing
782 *outptr++ = dithered_vol(*inptr++);
783 *outptr++ = dithered_vol(*inptr++);
784 };
785 if (stuff) {
786 if (stuff==1) {
787 if (debug)
788 xprintf("+++++++++\n");
789 // interpolate one sample
790 *outptr++ = dithered_vol(((long)inptr[-2] + (long)inptr[0]) >> 1);
791 *outptr++ = dithered_vol(((long)inptr[-1] + (long)inptr[1]) >> 1);
792 } else if (stuff==-1) {
793 if (debug)
794 xprintf("---------\n");
795 inptr++;
796 inptr++;
797 }
798 for (i=stuffsamp; i<frame_size + stuff; i++) {
799 *outptr++ = dithered_vol(*inptr++);
800 *outptr++ = dithered_vol(*inptr++);
801 }
802 }
803
804 return frame_size + stuff;
805 }
806
807 int audio_running = 0;
808
audio_thread_func(void * arg)809 void *audio_thread_func(void *arg) {
810 #ifdef HAS_AO
811 ao_device* dev = arg;
812 #endif
813 int play_samples;
814
815 signed short buf_fill __attribute__((unused));
816 signed short *inbuf, *outbuf;
817 outbuf = malloc(OUTFRAME_BYTES);
818
819 #ifdef FANCY_RESAMPLING
820 float *frame, *outframe;
821 SRC_DATA srcdat;
822 if (fancy_resampling) {
823 frame = malloc(frame_size*2*sizeof(float));
824 outframe = malloc(2*frame_size*2*sizeof(float));
825
826 srcdat.data_in = frame;
827 srcdat.data_out = outframe;
828 srcdat.input_frames = FRAME_BYTES;
829 srcdat.output_frames = 2*FRAME_BYTES;
830 srcdat.src_ratio = 1.0;
831 srcdat.end_of_input = 0;
832 }
833 #endif
834
835 audio_running = 1;
836
837 while (audio_running) {
838 do {
839 int buf_fill;
840 do {
841 pthread_mutex_lock(&ab_mutex);
842 buf_fill = ab_write - ab_read;
843 pthread_mutex_unlock(&ab_mutex);
844 if (buf_fill == 0) /* underrun */
845 {
846 //fprintf(stderr, "sleeping\n");
847 usleep(30000);
848 }
849
850 if (!audio_running)
851 return 0;
852
853 } while (buf_fill == 0 && audio_running);
854
855 if (!audio_running)
856 return 0;
857
858 inbuf = buffer_get_frame();
859 } while (!inbuf && audio_running);
860
861 if(!audio_running)
862 {
863 return 0; //don't access inbuf if audio stopped
864 }
865
866 #ifdef FANCY_RESAMPLING
867 if (fancy_resampling) {
868 int i;
869 for (i=0; i<2*FRAME_BYTES; i++) {
870 frame[i] = (float)inbuf[i] / 32768.0;
871 frame[i] *= volume;
872 }
873 srcdat.src_ratio = bf_playback_rate;
874 src_process(src, &srcdat);
875 assert(srcdat.input_frames_used == FRAME_BYTES);
876 src_float_to_short_array(outframe, outbuf, FRAME_BYTES*2);
877 play_samples = srcdat.output_frames_gen;
878 } else
879 #endif
880
881 play_samples = stuff_buffer(bf_playback_rate, inbuf, outbuf);
882
883 if (pipename) {
884 if (pipe_handle == -1) {
885 // attempt to open pipe - block if there are no readers
886 pipe_handle = open(pipename, O_WRONLY);
887 }
888
889 // only write if pipe open (there's a reader)
890 if (pipe_handle != -1) {
891 if (write(pipe_handle, outbuf, play_samples*4) == -1) {
892 // write failed - do anything here?
893 // SIGPIPE is handled elsewhere...
894 }
895 }
896 #ifdef HAS_AO
897 } else {
898 g_ao.ao_play(dev, (char *)outbuf, play_samples*4);
899 #endif
900 }
901 }
902
903 return 0;
904 }
905
906 #define NUM_CHANNELS 2
907
handle_broken_fifo()908 void handle_broken_fifo() {
909 close(pipe_handle);
910 pipe_handle = -1;
911 }
912
init_pipe(char * pipe)913 void init_pipe(char* pipe) {
914 // make the FIFO and catch the broken pipe signal
915 mknod(pipe, S_IFIFO | 0644, 0);
916 signal(SIGPIPE, handle_broken_fifo);
917 }
918
919 #ifdef HAS_AO
920 ao_device *dev;
921
init_ao()922 void* init_ao() {
923 g_ao.ao_initialize();
924
925 int driver;
926 #ifndef XBMC
927 if (libao_driver) {
928 // if a libao driver is specified on the command line, use that
929 driver = ao_driver_id(libao_driver);
930 if (driver == -1) {
931 die("Could not find requested ao driver");
932 }
933 }
934 else
935 #endif
936 {
937 // otherwise choose the default
938 driver = g_ao.ao_default_driver_id();
939 }
940
941 ao_sample_format fmt;
942 memset(&fmt, 0, sizeof(fmt));
943
944 fmt.bits = 16;
945 fmt.rate = sampling_rate;
946 fmt.channels = NUM_CHANNELS;
947 fmt.byte_format = AO_FMT_NATIVE;
948
949 ao_option* ao_opts = NULL;
950 #ifndef XBMC
951 if(libao_deviceid) {
952 ao_append_option(&ao_opts, "id", libao_deviceid);
953 } else if(libao_devicename){
954 ao_append_option(&ao_opts, "dev", libao_devicename);
955 // Old libao versions (for example, 0.8.8) only support
956 // "dsp" instead of "dev".
957 ao_append_option(&ao_opts, "dsp", libao_devicename);
958 }
959 #endif
960
961 g_ao.ao_append_option(&ao_opts, "name", "Streaming...");
962
963 dev = g_ao.ao_open_live(driver, &fmt, ao_opts);
964 if (dev == NULL) {
965 die("Could not open ao device");
966 }
967
968 return dev;
969 }
970 #endif
971
972 pthread_t audio_thread;
973
init_output(void)974 int init_output(void) {
975 void* arg = 0;
976
977 if (pipename) {
978 init_pipe(pipename);
979 #ifdef HAS_AO
980 } else {
981 arg = init_ao();
982 #endif
983 }
984
985 #ifdef FANCY_RESAMPLING
986 int err;
987 if (fancy_resampling)
988 src = src_new(SRC_SINC_MEDIUM_QUALITY, 2, &err);
989 else
990 src = 0;
991 #endif
992 pthread_create(&audio_thread, NULL, audio_thread_func, arg);
993
994 return 0;
995 }
996
clean_output(void)997 void clean_output(void)
998 {
999 audio_running = 0;
1000 pthread_join(audio_thread, NULL);
1001 #ifdef HAS_AO
1002 g_ao.ao_close(dev);
1003 #endif
1004 }
1005
hairtunes_cleanup(void)1006 void hairtunes_cleanup(void)
1007 {
1008 pthread_cond_signal(&ab_buffer_ready);
1009 clean_output();
1010 clean_rtp();
1011 clean_buffer();
1012 clean_decoder();
1013
1014 pthread_mutex_destroy(&ab_mutex);
1015 pthread_cond_destroy(&ab_buffer_ready);
1016 }
1017