├── INSTALL ├── Makefile ├── README ├── alac.c ├── alac.h ├── hairtunes.c └── shairport.pl /INSTALL: -------------------------------------------------------------------------------- 1 | Type 'make' to build the packet decoder, 'hairtunes'. 2 | 3 | You need the following installed: 4 | openssl 5 | libao 6 | avahi (avahi-daemon running and avahi-publish-service on path) 7 | Perl 8 | 9 | Debian/Ubuntu users need: 10 | libssl-dev libcrypt-openssl-rsa-perl libao2 libao-dev2 libio-socket-inet6-perl 11 | 12 | Perl modules (install from CPAN if needed): 13 | HTTP::Message 14 | Crypt::OpenSSL::RSA 15 | IO::Socket::INET6 16 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CFLAGS = `pkg-config --cflags --libs ao openssl` 2 | 3 | hairtunes: hairtunes.c alac.c 4 | gcc hairtunes.c alac.c -D__i386 -lm $(CFLAGS) -o hairtunes 5 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | Shairport v0.03 2 | ============== 3 | James Laird 4 | April 11, 2011 5 | 6 | What it is 7 | ---------- 8 | This program emulates an Airport Express for the purpose of streaming music from 9 | iTunes and compatible iPods. It implements a server for the Apple RAOP protocol. 10 | 11 | It probably supports multiple simultaneous streams, if your audio output chain 12 | (as detected by libao) does so. 13 | 14 | How to use it 15 | ------------- 16 | 1. Make sure avahi-daemon is running and the prerequisites are installed (see 17 | INSTALL). 18 | 2. Edit shairport.pl with your favourite text editor to set the access 19 | point name and/or password, if desired. 20 | 3. `perl shairport.pl` 21 | 22 | The triangle-in-rectangle Airtunes logo will appear in the iTunes status bar of 23 | any machine on the network, or on iPod play controls screen. Choose your access 24 | point name to start streaming to the Shairport instance. 25 | 26 | Thanks 27 | ------ 28 | Big thanks to David Hammerton for releasing an ALAC decoder, which is reproduced 29 | here in full. 30 | Thanks to everyone who has worked to reverse engineer the RAOP protocol - after 31 | finding the keys, everything else was pretty much trivial. 32 | Thanks also to Apple for obfuscating the private key in the ROM image, using a 33 | scheme that made the deobfuscation code itself stand out like a flare. 34 | Thanks to Ten Thousand Free Men and their Families for having a computer and stuff. 35 | Thanks to wtbw. 36 | 37 | Changelog 38 | --------- 39 | 0.01 April 5, 2011 40 | initial release 41 | 0.02 April 11, 2011 42 | bugfix: libao compatibility 43 | 0.03 April 11, 2011 44 | bugfix: ipv6 didn't work - 45 | IO::Socket::INET6 is required too 46 | 47 | -------------------------------------------------------------------------------- /alac.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ALAC (Apple Lossless Audio Codec) decoder 3 | * Copyright (c) 2005 David Hammerton 4 | * All rights reserved. 5 | * 6 | * This is the actual decoder. 7 | * 8 | * http://crazney.net/programs/itunes/alac.html 9 | * 10 | * Permission is hereby granted, free of charge, to any person 11 | * obtaining a copy of this software and associated documentation 12 | * files (the "Software"), to deal in the Software without 13 | * restriction, including without limitation the rights to use, 14 | * copy, modify, merge, publish, distribute, sublicense, and/or 15 | * sell copies of the Software, and to permit persons to whom the 16 | * Software is furnished to do so, subject to the following conditions: 17 | * 18 | * The above copyright notice and this permission notice shall be 19 | * included in all copies or substantial portions of the Software. 20 | * 21 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 22 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 23 | * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 24 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 25 | * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 26 | * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 27 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 28 | * OTHER DEALINGS IN THE SOFTWARE. 29 | * 30 | */ 31 | 32 | static const int host_bigendian = 0; 33 | 34 | #include 35 | #include 36 | #include 37 | #ifdef _WIN32 38 | #include "stdint_win.h" 39 | #else 40 | #include 41 | #endif 42 | 43 | #include "alac.h" 44 | 45 | #define _Swap32(v) do { \ 46 | v = (((v) & 0x000000FF) << 0x18) | \ 47 | (((v) & 0x0000FF00) << 0x08) | \ 48 | (((v) & 0x00FF0000) >> 0x08) | \ 49 | (((v) & 0xFF000000) >> 0x18); } while(0) 50 | 51 | #define _Swap16(v) do { \ 52 | v = (((v) & 0x00FF) << 0x08) | \ 53 | (((v) & 0xFF00) >> 0x08); } while (0) 54 | 55 | struct {signed int x:24;} se_struct_24; 56 | #define SignExtend24(val) (se_struct_24.x = val) 57 | 58 | void allocate_buffers(alac_file *alac) 59 | { 60 | alac->predicterror_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4); 61 | alac->predicterror_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4); 62 | 63 | alac->outputsamples_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4); 64 | alac->outputsamples_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4); 65 | 66 | alac->uncompressed_bytes_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4); 67 | alac->uncompressed_bytes_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4); 68 | } 69 | 70 | void alac_set_info(alac_file *alac, char *inputbuffer) 71 | { 72 | char *ptr = inputbuffer; 73 | ptr += 4; /* size */ 74 | ptr += 4; /* frma */ 75 | ptr += 4; /* alac */ 76 | ptr += 4; /* size */ 77 | ptr += 4; /* alac */ 78 | 79 | ptr += 4; /* 0 ? */ 80 | 81 | alac->setinfo_max_samples_per_frame = *(uint32_t*)ptr; /* buffer size / 2 ? */ 82 | if (!host_bigendian) 83 | _Swap32(alac->setinfo_max_samples_per_frame); 84 | ptr += 4; 85 | alac->setinfo_7a = *(uint8_t*)ptr; 86 | ptr += 1; 87 | alac->setinfo_sample_size = *(uint8_t*)ptr; 88 | ptr += 1; 89 | alac->setinfo_rice_historymult = *(uint8_t*)ptr; 90 | ptr += 1; 91 | alac->setinfo_rice_initialhistory = *(uint8_t*)ptr; 92 | ptr += 1; 93 | alac->setinfo_rice_kmodifier = *(uint8_t*)ptr; 94 | ptr += 1; 95 | alac->setinfo_7f = *(uint8_t*)ptr; 96 | ptr += 1; 97 | alac->setinfo_80 = *(uint16_t*)ptr; 98 | if (!host_bigendian) 99 | _Swap16(alac->setinfo_80); 100 | ptr += 2; 101 | alac->setinfo_82 = *(uint32_t*)ptr; 102 | if (!host_bigendian) 103 | _Swap32(alac->setinfo_82); 104 | ptr += 4; 105 | alac->setinfo_86 = *(uint32_t*)ptr; 106 | if (!host_bigendian) 107 | _Swap32(alac->setinfo_86); 108 | ptr += 4; 109 | alac->setinfo_8a_rate = *(uint32_t*)ptr; 110 | if (!host_bigendian) 111 | _Swap32(alac->setinfo_8a_rate); 112 | ptr += 4; 113 | 114 | allocate_buffers(alac); 115 | 116 | } 117 | 118 | /* stream reading */ 119 | 120 | /* supports reading 1 to 16 bits, in big endian format */ 121 | static uint32_t readbits_16(alac_file *alac, int bits) 122 | { 123 | uint32_t result; 124 | int new_accumulator; 125 | 126 | result = (alac->input_buffer[0] << 16) | 127 | (alac->input_buffer[1] << 8) | 128 | (alac->input_buffer[2]); 129 | 130 | /* shift left by the number of bits we've already read, 131 | * so that the top 'n' bits of the 24 bits we read will 132 | * be the return bits */ 133 | result = result << alac->input_buffer_bitaccumulator; 134 | 135 | result = result & 0x00ffffff; 136 | 137 | /* and then only want the top 'n' bits from that, where 138 | * n is 'bits' */ 139 | result = result >> (24 - bits); 140 | 141 | new_accumulator = (alac->input_buffer_bitaccumulator + bits); 142 | 143 | /* increase the buffer pointer if we've read over n bytes. */ 144 | alac->input_buffer += (new_accumulator >> 3); 145 | 146 | /* and the remainder goes back into the bit accumulator */ 147 | alac->input_buffer_bitaccumulator = (new_accumulator & 7); 148 | 149 | return result; 150 | } 151 | 152 | /* supports reading 1 to 32 bits, in big endian format */ 153 | static uint32_t readbits(alac_file *alac, int bits) 154 | { 155 | int32_t result = 0; 156 | 157 | if (bits > 16) 158 | { 159 | bits -= 16; 160 | result = readbits_16(alac, 16) << bits; 161 | } 162 | 163 | result |= readbits_16(alac, bits); 164 | 165 | return result; 166 | } 167 | 168 | /* reads a single bit */ 169 | static int readbit(alac_file *alac) 170 | { 171 | int result; 172 | int new_accumulator; 173 | 174 | result = alac->input_buffer[0]; 175 | 176 | result = result << alac->input_buffer_bitaccumulator; 177 | 178 | result = result >> 7 & 1; 179 | 180 | new_accumulator = (alac->input_buffer_bitaccumulator + 1); 181 | 182 | alac->input_buffer += (new_accumulator / 8); 183 | 184 | alac->input_buffer_bitaccumulator = (new_accumulator % 8); 185 | 186 | return result; 187 | } 188 | 189 | static void unreadbits(alac_file *alac, int bits) 190 | { 191 | int new_accumulator = (alac->input_buffer_bitaccumulator - bits); 192 | 193 | alac->input_buffer += (new_accumulator >> 3); 194 | 195 | alac->input_buffer_bitaccumulator = (new_accumulator & 7); 196 | if (alac->input_buffer_bitaccumulator < 0) 197 | alac->input_buffer_bitaccumulator *= -1; 198 | } 199 | 200 | /* various implementations of count_leading_zero: 201 | * the first one is the original one, the simplest and most 202 | * obvious for what it's doing. never use this. 203 | * then there are the asm ones. fill in as necessary 204 | * and finally an unrolled and optimised c version 205 | * to fall back to 206 | */ 207 | #if 0 208 | /* hideously inefficient. could use a bitmask search, 209 | * alternatively bsr on x86, 210 | */ 211 | static int count_leading_zeros(int32_t input) 212 | { 213 | int i = 0; 214 | while (!(0x80000000 & input) && i < 32) 215 | { 216 | i++; 217 | input = input << 1; 218 | } 219 | return i; 220 | } 221 | #elif defined(__GNUC__) && (defined(_X86) || defined(__i386) || defined(i386)) 222 | /* for some reason the unrolled version (below) is 223 | * actually faster than this. yay intel! 224 | */ 225 | static int count_leading_zeros(int input) 226 | { 227 | int output = 0; 228 | if (!input) return 32; 229 | __asm("bsr %1, %0\n" 230 | : "=r" (output) 231 | : "r" (input)); 232 | return (0x1f - output); 233 | } 234 | #elif defined(_MSC_VER) && defined(_M_IX86) 235 | static int count_leading_zeros(int input) 236 | { 237 | int output = 0; 238 | if (!input) return 32; 239 | __asm 240 | { 241 | mov eax, input; 242 | mov edx, 0x1f; 243 | bsr ecx, eax; 244 | sub edx, ecx; 245 | mov output, edx; 246 | } 247 | return output; 248 | } 249 | #else 250 | #warning using generic count leading zeroes. You may wish to write one for your CPU / compiler 251 | static int count_leading_zeros(int input) 252 | { 253 | int output = 0; 254 | int curbyte = 0; 255 | 256 | curbyte = input >> 24; 257 | if (curbyte) goto found; 258 | output += 8; 259 | 260 | curbyte = input >> 16; 261 | if (curbyte & 0xff) goto found; 262 | output += 8; 263 | 264 | curbyte = input >> 8; 265 | if (curbyte & 0xff) goto found; 266 | output += 8; 267 | 268 | curbyte = input; 269 | if (curbyte & 0xff) goto found; 270 | output += 8; 271 | 272 | return output; 273 | 274 | found: 275 | if (!(curbyte & 0xf0)) 276 | { 277 | output += 4; 278 | } 279 | else 280 | curbyte >>= 4; 281 | 282 | if (curbyte & 0x8) 283 | return output; 284 | if (curbyte & 0x4) 285 | return output + 1; 286 | if (curbyte & 0x2) 287 | return output + 2; 288 | if (curbyte & 0x1) 289 | return output + 3; 290 | 291 | /* shouldn't get here: */ 292 | return output + 4; 293 | } 294 | #endif 295 | 296 | #define RICE_THRESHOLD 8 // maximum number of bits for a rice prefix. 297 | 298 | int32_t entropy_decode_value(alac_file* alac, 299 | int readSampleSize, 300 | int k, 301 | int rice_kmodifier_mask) 302 | { 303 | int32_t x = 0; // decoded value 304 | 305 | // read x, number of 1s before 0 represent the rice value. 306 | while (x <= RICE_THRESHOLD && readbit(alac)) 307 | { 308 | x++; 309 | } 310 | 311 | if (x > RICE_THRESHOLD) 312 | { 313 | // read the number from the bit stream (raw value) 314 | int32_t value; 315 | 316 | value = readbits(alac, readSampleSize); 317 | 318 | // mask value 319 | value &= (((uint32_t)0xffffffff) >> (32 - readSampleSize)); 320 | 321 | x = value; 322 | } 323 | else 324 | { 325 | if (k != 1) 326 | { 327 | int extraBits = readbits(alac, k); 328 | 329 | // x = x * (2^k - 1) 330 | x *= (((1 << k) - 1) & rice_kmodifier_mask); 331 | 332 | if (extraBits > 1) 333 | x += extraBits - 1; 334 | else 335 | unreadbits(alac, 1); 336 | } 337 | } 338 | 339 | return x; 340 | } 341 | 342 | void entropy_rice_decode(alac_file* alac, 343 | int32_t* outputBuffer, 344 | int outputSize, 345 | int readSampleSize, 346 | int rice_initialhistory, 347 | int rice_kmodifier, 348 | int rice_historymult, 349 | int rice_kmodifier_mask) 350 | { 351 | int outputCount; 352 | int history = rice_initialhistory; 353 | int signModifier = 0; 354 | 355 | for (outputCount = 0; outputCount < outputSize; outputCount++) 356 | { 357 | int32_t decodedValue; 358 | int32_t finalValue; 359 | int32_t k; 360 | 361 | k = 31 - rice_kmodifier - count_leading_zeros((history >> 9) + 3); 362 | 363 | if (k < 0) k += rice_kmodifier; 364 | else k = rice_kmodifier; 365 | 366 | // note: don't use rice_kmodifier_mask here (set mask to 0xFFFFFFFF) 367 | decodedValue = entropy_decode_value(alac, readSampleSize, k, 0xFFFFFFFF); 368 | 369 | decodedValue += signModifier; 370 | finalValue = (decodedValue + 1) / 2; // inc by 1 and shift out sign bit 371 | if (decodedValue & 1) // the sign is stored in the low bit 372 | finalValue *= -1; 373 | 374 | outputBuffer[outputCount] = finalValue; 375 | 376 | signModifier = 0; 377 | 378 | // update history 379 | history += (decodedValue * rice_historymult) 380 | - ((history * rice_historymult) >> 9); 381 | 382 | if (decodedValue > 0xFFFF) 383 | history = 0xFFFF; 384 | 385 | // special case, for compressed blocks of 0 386 | if ((history < 128) && (outputCount + 1 < outputSize)) 387 | { 388 | int32_t blockSize; 389 | 390 | signModifier = 1; 391 | 392 | k = count_leading_zeros(history) + ((history + 16) / 64) - 24; 393 | 394 | // note: blockSize is always 16bit 395 | blockSize = entropy_decode_value(alac, 16, k, rice_kmodifier_mask); 396 | 397 | // got blockSize 0s 398 | if (blockSize > 0) 399 | { 400 | memset(&outputBuffer[outputCount + 1], 0, blockSize * sizeof(*outputBuffer)); 401 | outputCount += blockSize; 402 | } 403 | 404 | if (blockSize > 0xFFFF) 405 | signModifier = 0; 406 | 407 | history = 0; 408 | } 409 | } 410 | } 411 | 412 | #define SIGN_EXTENDED32(val, bits) ((val << (32 - bits)) >> (32 - bits)) 413 | 414 | #define SIGN_ONLY(v) \ 415 | ((v < 0) ? (-1) : \ 416 | ((v > 0) ? (1) : \ 417 | (0))) 418 | 419 | static void predictor_decompress_fir_adapt(int32_t *error_buffer, 420 | int32_t *buffer_out, 421 | int output_size, 422 | int readsamplesize, 423 | int16_t *predictor_coef_table, 424 | int predictor_coef_num, 425 | int predictor_quantitization) 426 | { 427 | int i; 428 | 429 | /* first sample always copies */ 430 | *buffer_out = *error_buffer; 431 | 432 | if (!predictor_coef_num) 433 | { 434 | if (output_size <= 1) return; 435 | memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4); 436 | return; 437 | } 438 | 439 | if (predictor_coef_num == 0x1f) /* 11111 - max value of predictor_coef_num */ 440 | { /* second-best case scenario for fir decompression, 441 | * error describes a small difference from the previous sample only 442 | */ 443 | if (output_size <= 1) return; 444 | for (i = 0; i < output_size - 1; i++) 445 | { 446 | int32_t prev_value; 447 | int32_t error_value; 448 | 449 | prev_value = buffer_out[i]; 450 | error_value = error_buffer[i+1]; 451 | buffer_out[i+1] = SIGN_EXTENDED32((prev_value + error_value), readsamplesize); 452 | } 453 | return; 454 | } 455 | 456 | /* read warm-up samples */ 457 | if (predictor_coef_num > 0) 458 | { 459 | int i; 460 | for (i = 0; i < predictor_coef_num; i++) 461 | { 462 | int32_t val; 463 | 464 | val = buffer_out[i] + error_buffer[i+1]; 465 | 466 | val = SIGN_EXTENDED32(val, readsamplesize); 467 | 468 | buffer_out[i+1] = val; 469 | } 470 | } 471 | 472 | #if 0 473 | /* 4 and 8 are very common cases (the only ones i've seen). these 474 | * should be unrolled and optimised 475 | */ 476 | if (predictor_coef_num == 4) 477 | { 478 | /* FIXME: optimised general case */ 479 | return; 480 | } 481 | 482 | if (predictor_coef_table == 8) 483 | { 484 | /* FIXME: optimised general case */ 485 | return; 486 | } 487 | #endif 488 | 489 | 490 | /* general case */ 491 | if (predictor_coef_num > 0) 492 | { 493 | for (i = predictor_coef_num + 1; 494 | i < output_size; 495 | i++) 496 | { 497 | int j; 498 | int sum = 0; 499 | int outval; 500 | int error_val = error_buffer[i]; 501 | 502 | for (j = 0; j < predictor_coef_num; j++) 503 | { 504 | sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) * 505 | predictor_coef_table[j]; 506 | } 507 | 508 | outval = (1 << (predictor_quantitization-1)) + sum; 509 | outval = outval >> predictor_quantitization; 510 | outval = outval + buffer_out[0] + error_val; 511 | outval = SIGN_EXTENDED32(outval, readsamplesize); 512 | 513 | buffer_out[predictor_coef_num+1] = outval; 514 | 515 | if (error_val > 0) 516 | { 517 | int predictor_num = predictor_coef_num - 1; 518 | 519 | while (predictor_num >= 0 && error_val > 0) 520 | { 521 | int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num]; 522 | int sign = SIGN_ONLY(val); 523 | 524 | predictor_coef_table[predictor_num] -= sign; 525 | 526 | val *= sign; /* absolute value */ 527 | 528 | error_val -= ((val >> predictor_quantitization) * 529 | (predictor_coef_num - predictor_num)); 530 | 531 | predictor_num--; 532 | } 533 | } 534 | else if (error_val < 0) 535 | { 536 | int predictor_num = predictor_coef_num - 1; 537 | 538 | while (predictor_num >= 0 && error_val < 0) 539 | { 540 | int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num]; 541 | int sign = - SIGN_ONLY(val); 542 | 543 | predictor_coef_table[predictor_num] -= sign; 544 | 545 | val *= sign; /* neg value */ 546 | 547 | error_val -= ((val >> predictor_quantitization) * 548 | (predictor_coef_num - predictor_num)); 549 | 550 | predictor_num--; 551 | } 552 | } 553 | 554 | buffer_out++; 555 | } 556 | } 557 | } 558 | 559 | void deinterlace_16(int32_t *buffer_a, int32_t *buffer_b, 560 | int16_t *buffer_out, 561 | int numchannels, int numsamples, 562 | uint8_t interlacing_shift, 563 | uint8_t interlacing_leftweight) 564 | { 565 | int i; 566 | if (numsamples <= 0) return; 567 | 568 | /* weighted interlacing */ 569 | if (interlacing_leftweight) 570 | { 571 | for (i = 0; i < numsamples; i++) 572 | { 573 | int32_t difference, midright; 574 | int16_t left; 575 | int16_t right; 576 | 577 | midright = buffer_a[i]; 578 | difference = buffer_b[i]; 579 | 580 | 581 | right = midright - ((difference * interlacing_leftweight) >> interlacing_shift); 582 | left = right + difference; 583 | 584 | /* output is always little endian */ 585 | if (host_bigendian) 586 | { 587 | _Swap16(left); 588 | _Swap16(right); 589 | } 590 | 591 | buffer_out[i*numchannels] = left; 592 | buffer_out[i*numchannels + 1] = right; 593 | } 594 | 595 | return; 596 | } 597 | 598 | /* otherwise basic interlacing took place */ 599 | for (i = 0; i < numsamples; i++) 600 | { 601 | int16_t left, right; 602 | 603 | left = buffer_a[i]; 604 | right = buffer_b[i]; 605 | 606 | /* output is always little endian */ 607 | if (host_bigendian) 608 | { 609 | _Swap16(left); 610 | _Swap16(right); 611 | } 612 | 613 | buffer_out[i*numchannels] = left; 614 | buffer_out[i*numchannels + 1] = right; 615 | } 616 | } 617 | 618 | void deinterlace_24(int32_t *buffer_a, int32_t *buffer_b, 619 | int uncompressed_bytes, 620 | int32_t *uncompressed_bytes_buffer_a, int32_t *uncompressed_bytes_buffer_b, 621 | void *buffer_out, 622 | int numchannels, int numsamples, 623 | uint8_t interlacing_shift, 624 | uint8_t interlacing_leftweight) 625 | { 626 | int i; 627 | if (numsamples <= 0) return; 628 | 629 | /* weighted interlacing */ 630 | if (interlacing_leftweight) 631 | { 632 | for (i = 0; i < numsamples; i++) 633 | { 634 | int32_t difference, midright; 635 | int32_t left; 636 | int32_t right; 637 | 638 | midright = buffer_a[i]; 639 | difference = buffer_b[i]; 640 | 641 | right = midright - ((difference * interlacing_leftweight) >> interlacing_shift); 642 | left = right + difference; 643 | 644 | if (uncompressed_bytes) 645 | { 646 | uint32_t mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8)); 647 | left <<= (uncompressed_bytes * 8); 648 | right <<= (uncompressed_bytes * 8); 649 | 650 | left |= uncompressed_bytes_buffer_a[i] & mask; 651 | right |= uncompressed_bytes_buffer_b[i] & mask; 652 | } 653 | 654 | ((uint8_t*)buffer_out)[i * numchannels * 3] = (left) & 0xFF; 655 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF; 656 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF; 657 | 658 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF; 659 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF; 660 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF; 661 | } 662 | 663 | return; 664 | } 665 | 666 | /* otherwise basic interlacing took place */ 667 | for (i = 0; i < numsamples; i++) 668 | { 669 | int32_t left, right; 670 | 671 | left = buffer_a[i]; 672 | right = buffer_b[i]; 673 | 674 | if (uncompressed_bytes) 675 | { 676 | uint32_t mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8)); 677 | left <<= (uncompressed_bytes * 8); 678 | right <<= (uncompressed_bytes * 8); 679 | 680 | left |= uncompressed_bytes_buffer_a[i] & mask; 681 | right |= uncompressed_bytes_buffer_b[i] & mask; 682 | } 683 | 684 | ((uint8_t*)buffer_out)[i * numchannels * 3] = (left) & 0xFF; 685 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF; 686 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF; 687 | 688 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF; 689 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF; 690 | ((uint8_t*)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF; 691 | 692 | } 693 | 694 | } 695 | 696 | void decode_frame(alac_file *alac, 697 | unsigned char *inbuffer, 698 | void *outbuffer, int *outputsize) 699 | { 700 | int channels; 701 | int32_t outputsamples = alac->setinfo_max_samples_per_frame; 702 | 703 | /* setup the stream */ 704 | alac->input_buffer = inbuffer; 705 | alac->input_buffer_bitaccumulator = 0; 706 | 707 | channels = readbits(alac, 3); 708 | 709 | *outputsize = outputsamples * alac->bytespersample; 710 | 711 | switch(channels) 712 | { 713 | case 0: /* 1 channel */ 714 | { 715 | int hassize; 716 | int isnotcompressed; 717 | int readsamplesize; 718 | 719 | int uncompressed_bytes; 720 | int ricemodifier; 721 | 722 | /* 2^result = something to do with output waiting. 723 | * perhaps matters if we read > 1 frame in a pass? 724 | */ 725 | readbits(alac, 4); 726 | 727 | readbits(alac, 12); /* unknown, skip 12 bits */ 728 | 729 | hassize = readbits(alac, 1); /* the output sample size is stored soon */ 730 | 731 | uncompressed_bytes = readbits(alac, 2); /* number of bytes in the (compressed) stream that are not compressed */ 732 | 733 | isnotcompressed = readbits(alac, 1); /* whether the frame is compressed */ 734 | 735 | if (hassize) 736 | { 737 | /* now read the number of samples, 738 | * as a 32bit integer */ 739 | outputsamples = readbits(alac, 32); 740 | *outputsize = outputsamples * alac->bytespersample; 741 | } 742 | 743 | readsamplesize = alac->setinfo_sample_size - (uncompressed_bytes * 8); 744 | 745 | if (!isnotcompressed) 746 | { /* so it is compressed */ 747 | int16_t predictor_coef_table[32]; 748 | int predictor_coef_num; 749 | int prediction_type; 750 | int prediction_quantitization; 751 | int i; 752 | 753 | /* skip 16 bits, not sure what they are. seem to be used in 754 | * two channel case */ 755 | readbits(alac, 8); 756 | readbits(alac, 8); 757 | 758 | prediction_type = readbits(alac, 4); 759 | prediction_quantitization = readbits(alac, 4); 760 | 761 | ricemodifier = readbits(alac, 3); 762 | predictor_coef_num = readbits(alac, 5); 763 | 764 | /* read the predictor table */ 765 | for (i = 0; i < predictor_coef_num; i++) 766 | { 767 | predictor_coef_table[i] = (int16_t)readbits(alac, 16); 768 | } 769 | 770 | if (uncompressed_bytes) 771 | { 772 | int i; 773 | for (i = 0; i < outputsamples; i++) 774 | { 775 | alac->uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8); 776 | } 777 | } 778 | 779 | entropy_rice_decode(alac, 780 | alac->predicterror_buffer_a, 781 | outputsamples, 782 | readsamplesize, 783 | alac->setinfo_rice_initialhistory, 784 | alac->setinfo_rice_kmodifier, 785 | ricemodifier * alac->setinfo_rice_historymult / 4, 786 | (1 << alac->setinfo_rice_kmodifier) - 1); 787 | 788 | if (prediction_type == 0) 789 | { /* adaptive fir */ 790 | predictor_decompress_fir_adapt(alac->predicterror_buffer_a, 791 | alac->outputsamples_buffer_a, 792 | outputsamples, 793 | readsamplesize, 794 | predictor_coef_table, 795 | predictor_coef_num, 796 | prediction_quantitization); 797 | } 798 | else 799 | { 800 | fprintf(stderr, "FIXME: unhandled predicition type: %i\n", prediction_type); 801 | /* i think the only other prediction type (or perhaps this is just a 802 | * boolean?) runs adaptive fir twice.. like: 803 | * predictor_decompress_fir_adapt(predictor_error, tempout, ...) 804 | * predictor_decompress_fir_adapt(predictor_error, outputsamples ...) 805 | * little strange.. 806 | */ 807 | } 808 | 809 | } 810 | else 811 | { /* not compressed, easy case */ 812 | if (alac->setinfo_sample_size <= 16) 813 | { 814 | int i; 815 | for (i = 0; i < outputsamples; i++) 816 | { 817 | int32_t audiobits = readbits(alac, alac->setinfo_sample_size); 818 | 819 | audiobits = SIGN_EXTENDED32(audiobits, alac->setinfo_sample_size); 820 | 821 | alac->outputsamples_buffer_a[i] = audiobits; 822 | } 823 | } 824 | else 825 | { 826 | int i; 827 | for (i = 0; i < outputsamples; i++) 828 | { 829 | int32_t audiobits; 830 | 831 | audiobits = readbits(alac, 16); 832 | /* special case of sign extension.. 833 | * as we'll be ORing the low 16bits into this */ 834 | audiobits = audiobits << (alac->setinfo_sample_size - 16); 835 | audiobits |= readbits(alac, alac->setinfo_sample_size - 16); 836 | audiobits = SignExtend24(audiobits); 837 | 838 | alac->outputsamples_buffer_a[i] = audiobits; 839 | } 840 | } 841 | uncompressed_bytes = 0; // always 0 for uncompressed 842 | } 843 | 844 | switch(alac->setinfo_sample_size) 845 | { 846 | case 16: 847 | { 848 | int i; 849 | for (i = 0; i < outputsamples; i++) 850 | { 851 | int16_t sample = alac->outputsamples_buffer_a[i]; 852 | if (host_bigendian) 853 | _Swap16(sample); 854 | ((int16_t*)outbuffer)[i * alac->numchannels] = sample; 855 | } 856 | break; 857 | } 858 | case 24: 859 | { 860 | int i; 861 | for (i = 0; i < outputsamples; i++) 862 | { 863 | int32_t sample = alac->outputsamples_buffer_a[i]; 864 | 865 | if (uncompressed_bytes) 866 | { 867 | uint32_t mask; 868 | sample = sample << (uncompressed_bytes * 8); 869 | mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8)); 870 | sample |= alac->uncompressed_bytes_buffer_a[i] & mask; 871 | } 872 | 873 | ((uint8_t*)outbuffer)[i * alac->numchannels * 3] = (sample) & 0xFF; 874 | ((uint8_t*)outbuffer)[i * alac->numchannels * 3 + 1] = (sample >> 8) & 0xFF; 875 | ((uint8_t*)outbuffer)[i * alac->numchannels * 3 + 2] = (sample >> 16) & 0xFF; 876 | } 877 | break; 878 | } 879 | case 20: 880 | case 32: 881 | fprintf(stderr, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size); 882 | break; 883 | default: 884 | break; 885 | } 886 | break; 887 | } 888 | case 1: /* 2 channels */ 889 | { 890 | int hassize; 891 | int isnotcompressed; 892 | int readsamplesize; 893 | 894 | int uncompressed_bytes; 895 | 896 | uint8_t interlacing_shift; 897 | uint8_t interlacing_leftweight; 898 | 899 | /* 2^result = something to do with output waiting. 900 | * perhaps matters if we read > 1 frame in a pass? 901 | */ 902 | readbits(alac, 4); 903 | 904 | readbits(alac, 12); /* unknown, skip 12 bits */ 905 | 906 | hassize = readbits(alac, 1); /* the output sample size is stored soon */ 907 | 908 | uncompressed_bytes = readbits(alac, 2); /* the number of bytes in the (compressed) stream that are not compressed */ 909 | 910 | isnotcompressed = readbits(alac, 1); /* whether the frame is compressed */ 911 | 912 | if (hassize) 913 | { 914 | /* now read the number of samples, 915 | * as a 32bit integer */ 916 | outputsamples = readbits(alac, 32); 917 | *outputsize = outputsamples * alac->bytespersample; 918 | } 919 | 920 | readsamplesize = alac->setinfo_sample_size - (uncompressed_bytes * 8) + 1; 921 | 922 | if (!isnotcompressed) 923 | { /* compressed */ 924 | int16_t predictor_coef_table_a[32]; 925 | int predictor_coef_num_a; 926 | int prediction_type_a; 927 | int prediction_quantitization_a; 928 | int ricemodifier_a; 929 | 930 | int16_t predictor_coef_table_b[32]; 931 | int predictor_coef_num_b; 932 | int prediction_type_b; 933 | int prediction_quantitization_b; 934 | int ricemodifier_b; 935 | 936 | int i; 937 | 938 | interlacing_shift = readbits(alac, 8); 939 | interlacing_leftweight = readbits(alac, 8); 940 | 941 | /******** channel 1 ***********/ 942 | prediction_type_a = readbits(alac, 4); 943 | prediction_quantitization_a = readbits(alac, 4); 944 | 945 | ricemodifier_a = readbits(alac, 3); 946 | predictor_coef_num_a = readbits(alac, 5); 947 | 948 | /* read the predictor table */ 949 | for (i = 0; i < predictor_coef_num_a; i++) 950 | { 951 | predictor_coef_table_a[i] = (int16_t)readbits(alac, 16); 952 | } 953 | 954 | /******** channel 2 *********/ 955 | prediction_type_b = readbits(alac, 4); 956 | prediction_quantitization_b = readbits(alac, 4); 957 | 958 | ricemodifier_b = readbits(alac, 3); 959 | predictor_coef_num_b = readbits(alac, 5); 960 | 961 | /* read the predictor table */ 962 | for (i = 0; i < predictor_coef_num_b; i++) 963 | { 964 | predictor_coef_table_b[i] = (int16_t)readbits(alac, 16); 965 | } 966 | 967 | /*********************/ 968 | if (uncompressed_bytes) 969 | { /* see mono case */ 970 | int i; 971 | for (i = 0; i < outputsamples; i++) 972 | { 973 | alac->uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8); 974 | alac->uncompressed_bytes_buffer_b[i] = readbits(alac, uncompressed_bytes * 8); 975 | } 976 | } 977 | 978 | /* channel 1 */ 979 | entropy_rice_decode(alac, 980 | alac->predicterror_buffer_a, 981 | outputsamples, 982 | readsamplesize, 983 | alac->setinfo_rice_initialhistory, 984 | alac->setinfo_rice_kmodifier, 985 | ricemodifier_a * alac->setinfo_rice_historymult / 4, 986 | (1 << alac->setinfo_rice_kmodifier) - 1); 987 | 988 | if (prediction_type_a == 0) 989 | { /* adaptive fir */ 990 | predictor_decompress_fir_adapt(alac->predicterror_buffer_a, 991 | alac->outputsamples_buffer_a, 992 | outputsamples, 993 | readsamplesize, 994 | predictor_coef_table_a, 995 | predictor_coef_num_a, 996 | prediction_quantitization_a); 997 | } 998 | else 999 | { /* see mono case */ 1000 | fprintf(stderr, "FIXME: unhandled predicition type: %i\n", prediction_type_a); 1001 | } 1002 | 1003 | /* channel 2 */ 1004 | entropy_rice_decode(alac, 1005 | alac->predicterror_buffer_b, 1006 | outputsamples, 1007 | readsamplesize, 1008 | alac->setinfo_rice_initialhistory, 1009 | alac->setinfo_rice_kmodifier, 1010 | ricemodifier_b * alac->setinfo_rice_historymult / 4, 1011 | (1 << alac->setinfo_rice_kmodifier) - 1); 1012 | 1013 | if (prediction_type_b == 0) 1014 | { /* adaptive fir */ 1015 | predictor_decompress_fir_adapt(alac->predicterror_buffer_b, 1016 | alac->outputsamples_buffer_b, 1017 | outputsamples, 1018 | readsamplesize, 1019 | predictor_coef_table_b, 1020 | predictor_coef_num_b, 1021 | prediction_quantitization_b); 1022 | } 1023 | else 1024 | { 1025 | fprintf(stderr, "FIXME: unhandled predicition type: %i\n", prediction_type_b); 1026 | } 1027 | } 1028 | else 1029 | { /* not compressed, easy case */ 1030 | if (alac->setinfo_sample_size <= 16) 1031 | { 1032 | int i; 1033 | for (i = 0; i < outputsamples; i++) 1034 | { 1035 | int32_t audiobits_a, audiobits_b; 1036 | 1037 | audiobits_a = readbits(alac, alac->setinfo_sample_size); 1038 | audiobits_b = readbits(alac, alac->setinfo_sample_size); 1039 | 1040 | audiobits_a = SIGN_EXTENDED32(audiobits_a, alac->setinfo_sample_size); 1041 | audiobits_b = SIGN_EXTENDED32(audiobits_b, alac->setinfo_sample_size); 1042 | 1043 | alac->outputsamples_buffer_a[i] = audiobits_a; 1044 | alac->outputsamples_buffer_b[i] = audiobits_b; 1045 | } 1046 | } 1047 | else 1048 | { 1049 | int i; 1050 | for (i = 0; i < outputsamples; i++) 1051 | { 1052 | int32_t audiobits_a, audiobits_b; 1053 | 1054 | audiobits_a = readbits(alac, 16); 1055 | audiobits_a = audiobits_a << (alac->setinfo_sample_size - 16); 1056 | audiobits_a |= readbits(alac, alac->setinfo_sample_size - 16); 1057 | audiobits_a = SignExtend24(audiobits_a); 1058 | 1059 | audiobits_b = readbits(alac, 16); 1060 | audiobits_b = audiobits_b << (alac->setinfo_sample_size - 16); 1061 | audiobits_b |= readbits(alac, alac->setinfo_sample_size - 16); 1062 | audiobits_b = SignExtend24(audiobits_b); 1063 | 1064 | alac->outputsamples_buffer_a[i] = audiobits_a; 1065 | alac->outputsamples_buffer_b[i] = audiobits_b; 1066 | } 1067 | } 1068 | uncompressed_bytes = 0; // always 0 for uncompressed 1069 | interlacing_shift = 0; 1070 | interlacing_leftweight = 0; 1071 | } 1072 | 1073 | switch(alac->setinfo_sample_size) 1074 | { 1075 | case 16: 1076 | { 1077 | deinterlace_16(alac->outputsamples_buffer_a, 1078 | alac->outputsamples_buffer_b, 1079 | (int16_t*)outbuffer, 1080 | alac->numchannels, 1081 | outputsamples, 1082 | interlacing_shift, 1083 | interlacing_leftweight); 1084 | break; 1085 | } 1086 | case 24: 1087 | { 1088 | deinterlace_24(alac->outputsamples_buffer_a, 1089 | alac->outputsamples_buffer_b, 1090 | uncompressed_bytes, 1091 | alac->uncompressed_bytes_buffer_a, 1092 | alac->uncompressed_bytes_buffer_b, 1093 | (int16_t*)outbuffer, 1094 | alac->numchannels, 1095 | outputsamples, 1096 | interlacing_shift, 1097 | interlacing_leftweight); 1098 | break; 1099 | } 1100 | case 20: 1101 | case 32: 1102 | fprintf(stderr, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size); 1103 | break; 1104 | default: 1105 | break; 1106 | } 1107 | 1108 | break; 1109 | } 1110 | } 1111 | } 1112 | 1113 | alac_file *create_alac(int samplesize, int numchannels) 1114 | { 1115 | alac_file *newfile = malloc(sizeof(alac_file)); 1116 | 1117 | newfile->samplesize = samplesize; 1118 | newfile->numchannels = numchannels; 1119 | newfile->bytespersample = (samplesize / 8) * numchannels; 1120 | 1121 | return newfile; 1122 | } 1123 | -------------------------------------------------------------------------------- /alac.h: -------------------------------------------------------------------------------- 1 | #ifndef __ALAC__DECOMP_H 2 | #define __ALAC__DECOMP_H 3 | 4 | typedef struct alac_file alac_file; 5 | 6 | alac_file *create_alac(int samplesize, int numchannels); 7 | void decode_frame(alac_file *alac, 8 | unsigned char *inbuffer, 9 | void *outbuffer, int *outputsize); 10 | void alac_set_info(alac_file *alac, char *inputbuffer); 11 | void allocate_buffers(alac_file *alac); 12 | 13 | struct alac_file 14 | { 15 | unsigned char *input_buffer; 16 | int input_buffer_bitaccumulator; /* used so we can do arbitary 17 | bit reads */ 18 | 19 | int samplesize; 20 | int numchannels; 21 | int bytespersample; 22 | 23 | 24 | /* buffers */ 25 | int32_t *predicterror_buffer_a; 26 | int32_t *predicterror_buffer_b; 27 | 28 | int32_t *outputsamples_buffer_a; 29 | int32_t *outputsamples_buffer_b; 30 | 31 | int32_t *uncompressed_bytes_buffer_a; 32 | int32_t *uncompressed_bytes_buffer_b; 33 | 34 | 35 | 36 | /* stuff from setinfo */ 37 | uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */ 38 | uint8_t setinfo_7a; /* 0x00 */ 39 | uint8_t setinfo_sample_size; /* 0x10 */ 40 | uint8_t setinfo_rice_historymult; /* 0x28 */ 41 | uint8_t setinfo_rice_initialhistory; /* 0x0a */ 42 | uint8_t setinfo_rice_kmodifier; /* 0x0e */ 43 | uint8_t setinfo_7f; /* 0x02 */ 44 | uint16_t setinfo_80; /* 0x00ff */ 45 | uint32_t setinfo_82; /* 0x000020e7 */ /* max sample size?? */ 46 | uint32_t setinfo_86; /* 0x00069fe4 */ /* bit rate (avarge)?? */ 47 | uint32_t setinfo_8a_rate; /* 0x0000ac44 */ 48 | /* end setinfo stuff */ 49 | 50 | }; 51 | 52 | 53 | #endif /* __ALAC__DECOMP_H */ 54 | 55 | -------------------------------------------------------------------------------- /hairtunes.c: -------------------------------------------------------------------------------- 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 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | #ifdef FANCY_RESAMPLING 40 | #include 41 | #endif 42 | 43 | #include 44 | int debug = 0; 45 | 46 | #include "alac.h" 47 | 48 | // default buffer - about half a second 49 | #define BUFFER_FRAMES 64 50 | #define START_FILL 55 51 | #define MAX_PACKET 2048 52 | 53 | typedef unsigned short seq_t; 54 | 55 | // global options (constant after init) 56 | unsigned char aeskey[16], aesiv[16]; 57 | AES_KEY aes; 58 | char *rtphost = 0; 59 | int dataport = 0, controlport = 0, timingport = 0; 60 | int fmtp[32]; 61 | int sampling_rate; 62 | int frame_size; 63 | #define FRAME_BYTES (4*frame_size) 64 | // maximal resampling shift - conservative 65 | #define OUTFRAME_BYTES (4*(frame_size+3)) 66 | 67 | 68 | alac_file *decoder_info; 69 | 70 | #ifdef FANCY_RESAMPLING 71 | int fancy_resampling = 1; 72 | SRC_STATE *src; 73 | #endif 74 | 75 | void rtp_request_resend(seq_t first, seq_t last); 76 | void init_buffer(void); 77 | void ab_resync(void); 78 | 79 | // interthread variables 80 | // stdin->decoder 81 | volatile double volume = 1.0; 82 | volatile long fix_volume = 0x10000; 83 | 84 | typedef struct audio_buffer_entry { // decoded audio packets 85 | int ready; 86 | signed short *data; 87 | } abuf_t; 88 | volatile abuf_t audio_buffer[BUFFER_FRAMES]; 89 | #define BUFIDX(seqno) ((seq_t)(seqno) % BUFFER_FRAMES) 90 | 91 | // mutex-protected variables 92 | volatile seq_t ab_read, ab_write; 93 | int ab_buffering = 1, ab_synced = 0; 94 | pthread_mutex_t ab_mutex = PTHREAD_MUTEX_INITIALIZER; 95 | pthread_cond_t ab_buffer_ready = PTHREAD_COND_INITIALIZER; 96 | 97 | void die(char *why) { 98 | fprintf(stderr, "FATAL: %s\n", why); 99 | exit(1); 100 | } 101 | 102 | int hex2bin(unsigned char *buf, char *hex) { 103 | int i, j; 104 | if (strlen(hex) != 0x20) 105 | return 1; 106 | for (i=0; i<0x10; i++) { 107 | if (!sscanf(hex, "%2X", &j)) 108 | return 1; 109 | hex += 2; 110 | *buf++ = j; 111 | } 112 | return 0; 113 | } 114 | 115 | int init_decoder(void) { 116 | alac_file *alac; 117 | 118 | frame_size = fmtp[1]; // stereo samples 119 | sampling_rate = fmtp[11]; 120 | 121 | int sample_size = fmtp[3]; 122 | if (sample_size != 16) 123 | die("only 16-bit samples supported!"); 124 | 125 | alac = create_alac(sample_size, 2); 126 | if (!alac) 127 | return 1; 128 | decoder_info = alac; 129 | 130 | alac->setinfo_max_samples_per_frame = frame_size; 131 | alac->setinfo_7a = fmtp[2]; 132 | alac->setinfo_sample_size = sample_size; 133 | alac->setinfo_rice_historymult = fmtp[4]; 134 | alac->setinfo_rice_initialhistory = fmtp[5]; 135 | alac->setinfo_rice_kmodifier = fmtp[6]; 136 | alac->setinfo_7f = fmtp[7]; 137 | alac->setinfo_80 = fmtp[8]; 138 | alac->setinfo_82 = fmtp[9]; 139 | alac->setinfo_86 = fmtp[10]; 140 | alac->setinfo_8a_rate = fmtp[11]; 141 | allocate_buffers(alac); 142 | return 0; 143 | } 144 | 145 | int main(int argc, char **argv) { 146 | char *hexaeskey = 0, *hexaesiv = 0; 147 | char *fmtpstr = 0; 148 | char *arg; 149 | int i; 150 | assert(RAND_MAX >= 0x10000); // XXX move this to compile time 151 | while (arg = *++argv) { 152 | if (!strcasecmp(arg, "iv")) { 153 | hexaesiv = *++argv; 154 | argc--; 155 | } else 156 | if (!strcasecmp(arg, "key")) { 157 | hexaeskey = *++argv; 158 | argc--; 159 | } else 160 | if (!strcasecmp(arg, "fmtp")) { 161 | fmtpstr = *++argv; 162 | } else 163 | if (!strcasecmp(arg, "cport")) { 164 | controlport = atoi(*++argv); 165 | } else 166 | if (!strcasecmp(arg, "tport")) { 167 | timingport = atoi(*++argv); 168 | } else 169 | if (!strcasecmp(arg, "dport")) { 170 | dataport = atoi(*++argv); 171 | } else 172 | if (!strcasecmp(arg, "host")) { 173 | rtphost = *++argv; 174 | } 175 | #ifdef FANCY_RESAMPLING 176 | else 177 | if (!strcasecmp(arg, "resamp")) { 178 | fancy_resampling = atoi(*++argv); 179 | } 180 | #endif 181 | } 182 | 183 | if (!hexaeskey || !hexaesiv) 184 | die("Must supply AES key and IV!"); 185 | 186 | if (hex2bin(aesiv, hexaesiv)) 187 | die("can't understand IV"); 188 | if (hex2bin(aeskey, hexaeskey)) 189 | die("can't understand key"); 190 | AES_set_decrypt_key(aeskey, 128, &aes); 191 | 192 | memset(fmtp, 0, sizeof(fmtp)); 193 | i = 0; 194 | while (arg = strsep(&fmtpstr, " \t")) 195 | fmtp[i++] = atoi(arg); 196 | 197 | init_decoder(); 198 | init_buffer(); 199 | init_rtp(); // open a UDP listen port and start a listener; decode into ring buffer 200 | fflush(stdout); 201 | init_output(); // resample and output from ring buffer 202 | 203 | char line[128]; 204 | int in_line = 0; 205 | int n; 206 | double f; 207 | while (fgets(line + in_line, sizeof(line) - in_line, stdin)) { 208 | n = strlen(line); 209 | if (line[n-1] != '\n') { 210 | in_line = strlen(line) - 1; 211 | if (n == sizeof(line)-1) 212 | in_line = 0; 213 | continue; 214 | } 215 | if (sscanf(line, "vol: %lf\n", &f)) { 216 | assert(f<=0); 217 | if (debug) 218 | fprintf(stderr, "VOL: %lf\n", f); 219 | volume = pow(10.0,0.1*f); 220 | fix_volume = 65536.0 * volume; 221 | continue; 222 | } 223 | if (!strcmp(line, "exit\n")) { 224 | exit(0); 225 | } 226 | if (!strcmp(line, "flush\n")) { 227 | pthread_mutex_lock(&ab_mutex); 228 | ab_resync(); 229 | pthread_mutex_unlock(&ab_mutex); 230 | if (debug) 231 | fprintf(stderr, "FLUSH\n"); 232 | } 233 | } 234 | fprintf(stderr, "bye!\n"); 235 | fflush(stderr); 236 | } 237 | 238 | void init_buffer(void) { 239 | int i; 240 | for (i=0; i 0; 257 | } 258 | 259 | void alac_decode(short *dest, char *buf, int len) { 260 | char packet[MAX_PACKET]; 261 | assert(len<=MAX_PACKET); 262 | 263 | char iv[16]; 264 | int i; 265 | memcpy(iv, aesiv, sizeof(iv)); 266 | for (i=0; i+16<=len; i += 16) 267 | AES_cbc_encrypt(buf+i, packet+i, 0x10, &aes, iv, AES_DECRYPT); 268 | if (len & 0xf) 269 | memcpy(packet+i, buf+i, len & 0xf); 270 | 271 | int outsize; 272 | 273 | decode_frame(decoder_info, packet, dest, &outsize); 274 | 275 | assert(outsize == FRAME_BYTES); 276 | } 277 | 278 | void buffer_put_packet(seq_t seqno, char *data, int len) { 279 | volatile abuf_t *abuf = 0; 280 | short read; 281 | short buf_fill; 282 | 283 | pthread_mutex_lock(&ab_mutex); 284 | if (!ab_synced) { 285 | ab_write = seqno; 286 | ab_read = seqno-1; 287 | ab_synced = 1; 288 | } 289 | if (seqno == ab_write+1) { // expected packet 290 | abuf = audio_buffer + BUFIDX(seqno); 291 | ab_write = seqno; 292 | } else if (seq_order(ab_write, seqno)) { // newer than expected 293 | rtp_request_resend(ab_write, seqno-1); 294 | abuf = audio_buffer + BUFIDX(seqno); 295 | ab_write = seqno; 296 | } else if (seq_order(ab_read, seqno)) { // late but not yet played 297 | abuf = audio_buffer + BUFIDX(seqno); 298 | } else { // too late. 299 | fprintf(stderr, "\nlate packet %04X (%04X:%04X)\n", seqno, ab_read, ab_write); 300 | } 301 | buf_fill = ab_write - ab_read; 302 | pthread_mutex_unlock(&ab_mutex); 303 | 304 | if (abuf) { 305 | alac_decode(abuf->data, data, len); 306 | abuf->ready = 1; 307 | } 308 | 309 | if (ab_buffering && buf_fill >= START_FILL) 310 | pthread_cond_signal(&ab_buffer_ready); 311 | if (!ab_buffering) { 312 | // check if the t+10th packet has arrived... last-chance resend 313 | read = ab_read + 10; 314 | abuf = audio_buffer + BUFIDX(read); 315 | if (!abuf->ready) 316 | rtp_request_resend(read, read); 317 | } 318 | } 319 | 320 | static int rtp_sockets[2]; // data, control 321 | #ifdef AF_INET6 322 | struct sockaddr_in6 rtp_client; 323 | #else 324 | struct sockaddr_in rtp_client; 325 | #endif 326 | 327 | void *rtp_thread_func(void *arg) { 328 | socklen_t si_len = sizeof(rtp_client); 329 | char packet[MAX_PACKET]; 330 | char *pktp; 331 | seq_t seqno; 332 | ssize_t plen; 333 | int sock = rtp_sockets[0], csock = rtp_sockets[1]; 334 | int readsock; 335 | char type; 336 | 337 | fd_set fds; 338 | FD_ZERO(&fds); 339 | FD_SET(sock, &fds); 340 | FD_SET(csock, &fds); 341 | 342 | while (select(csock>sock ? csock+1 : sock+1, &fds, 0, 0, 0)!=-1) { 343 | if (FD_ISSET(sock, &fds)) { 344 | readsock = sock; 345 | } else { 346 | readsock = csock; 347 | } 348 | FD_SET(sock, &fds); 349 | FD_SET(csock, &fds); 350 | 351 | plen = recvfrom(readsock, packet, sizeof(packet), 0, (struct sockaddr*)&rtp_client, &si_len); 352 | if (plen < 0) 353 | continue; 354 | assert(plen<=MAX_PACKET); 355 | 356 | type = packet[1] & ~0x80; 357 | if (type == 0x60 || type == 0x56) { // audio data / resend 358 | pktp = packet; 359 | if (type==0x56) { 360 | pktp += 4; 361 | plen -= 4; 362 | } 363 | seqno = ntohs(*(unsigned short *)(pktp+2)); 364 | buffer_put_packet(seqno, pktp+12, plen-12); 365 | } 366 | } 367 | } 368 | 369 | void rtp_request_resend(seq_t first, seq_t last) { 370 | if (seq_order(last, first)) 371 | return; 372 | 373 | fprintf(stderr, "requesting resend on %d packets (port %d)\n", last-first+1, controlport); 374 | 375 | char req[8]; // *not* a standard RTCP NACK 376 | req[0] = 0x80; 377 | req[1] = 0x55|0x80; // Apple 'resend' 378 | *(unsigned short *)(req+2) = htons(1); // our seqnum 379 | *(unsigned short *)(req+4) = htons(first); // missed seqnum 380 | *(unsigned short *)(req+6) = htons(last-first+1); // count 381 | 382 | #ifdef AF_INET6 383 | rtp_client.sin6_port = htons(controlport); 384 | #else 385 | rtp_client.sin_port = htons(controlport); 386 | #endif 387 | sendto(rtp_sockets[1], req, sizeof(req), 0, (struct sockaddr *)&rtp_client, sizeof(struct sockaddr_in)); 388 | } 389 | 390 | 391 | int init_rtp(void) { 392 | #ifdef AF_INET6 393 | struct sockaddr_in6 si; 394 | int type = AF_INET6; 395 | short *sin_port = &si.sin6_port; 396 | #else 397 | struct sockaddr_in si; 398 | int type = AF_INET; 399 | short *sin_port = &si.sin_port; 400 | #endif 401 | int sock, csock; // data and control (we treat the streams the same here) 402 | 403 | sock = socket(type, SOCK_DGRAM, IPPROTO_UDP); 404 | if (sock==-1) 405 | die("Can't create socket!"); 406 | 407 | memset(&si, 0, sizeof(si)); 408 | #ifdef AF_INET6 409 | si.sin6_family = AF_INET6; 410 | #ifdef SIN6_LEN 411 | si.sin6_len = sizeof(si); 412 | #endif 413 | si.sin6_addr = in6addr_any; 414 | si.sin6_flowinfo = 0; 415 | #else 416 | si.sin_family = AF_INET; 417 | si.sin_len = sizeof(si); 418 | si.sin_addr.s_addr = htonl(INADDR_ANY); 419 | #endif 420 | 421 | unsigned short port = 6000 - 3; 422 | do { 423 | port += 3; 424 | *sin_port = htons(port); 425 | } while (bind(sock, (struct sockaddr*)&si, sizeof(si))==-1); 426 | 427 | csock = socket(type, SOCK_DGRAM, IPPROTO_UDP); 428 | if (csock==-1) 429 | die("Can't create socket!"); 430 | *sin_port = htons(port + 1); 431 | if (bind(csock, (struct sockaddr*)&si, sizeof(si))==-1) 432 | die("can't bind control socket"); 433 | 434 | printf("port: %d\n", port); // let our handler know where we end up listening 435 | printf("cport: %d\n", port+1); 436 | 437 | pthread_t rtp_thread; 438 | rtp_sockets[0] = sock; 439 | rtp_sockets[1] = csock; 440 | pthread_create(&rtp_thread, NULL, rtp_thread_func, (void *)rtp_sockets); 441 | 442 | return port; 443 | } 444 | 445 | static inline short dithered_vol(short sample) { 446 | static short rand_a, rand_b; 447 | long out; 448 | rand_b = rand_a; 449 | rand_a = rand() & 0xffff; 450 | 451 | out = (long)sample * fix_volume; 452 | if (fix_volume < 0x10000) { 453 | out += rand_a; 454 | out -= rand_b; 455 | } 456 | return out>>16; 457 | } 458 | 459 | typedef struct { 460 | double hist[2]; 461 | double a[2]; 462 | double b[3]; 463 | } biquad_t; 464 | 465 | static void biquad_init(biquad_t *bq, double a[], double b[]) { 466 | bq->hist[0] = bq->hist[1] = 0.0; 467 | memcpy(bq->a, a, 2*sizeof(double)); 468 | memcpy(bq->b, b, 3*sizeof(double)); 469 | } 470 | 471 | static void biquad_lpf(biquad_t *bq, double freq, double Q) { 472 | double w0 = 2*M_PI*freq/((float)sampling_rate/(float)frame_size); 473 | double alpha = sin(w0)/(2.0*Q); 474 | 475 | double a_0 = 1.0 + alpha; 476 | double b[3], a[2]; 477 | b[0] = (1.0-cos(w0))/(2.0*a_0); 478 | b[1] = (1.0-cos(w0))/a_0; 479 | b[2] = b[0]; 480 | a[0] = -2.0*cos(w0)/a_0; 481 | a[1] = (1-alpha)/a_0; 482 | 483 | biquad_init(bq, a, b); 484 | } 485 | 486 | static double biquad_filt(biquad_t *bq, double in) { 487 | double w = in - bq->a[0]*bq->hist[0] - bq->a[1]*bq->hist[1]; 488 | double out = bq->b[1]*bq->hist[0] + bq->b[2]*bq->hist[1] + bq->b[0]*w; 489 | bq->hist[1] = bq->hist[0]; 490 | bq->hist[0] = w; 491 | } 492 | 493 | double bf_playback_rate = 1.0; 494 | 495 | static double bf_est_drift = 0.0; // local clock is slower by 496 | static biquad_t bf_drift_lpf; 497 | static double bf_est_err = 0.0, bf_last_err; 498 | static biquad_t bf_err_lpf, bf_err_deriv_lpf; 499 | static double desired_fill; 500 | static int fill_count; 501 | 502 | void bf_est_reset(short fill) { 503 | biquad_lpf(&bf_drift_lpf, 1.0/180.0, 0.3); 504 | biquad_lpf(&bf_err_lpf, 1.0/10.0, 0.25); 505 | biquad_lpf(&bf_err_deriv_lpf, 1.0/2.0, 0.2); 506 | fill_count = 0; 507 | bf_playback_rate = 1.0; 508 | bf_est_err = bf_last_err = 0; 509 | desired_fill = fill_count = 0; 510 | } 511 | void bf_est_update(short fill) { 512 | if (fill_count < 1000) { 513 | desired_fill += (double)fill/1000.0; 514 | fill_count++; 515 | return; 516 | } 517 | 518 | #define CONTROL_A (1e-4) 519 | #define CONTROL_B (1e-1) 520 | 521 | double buf_delta = fill - desired_fill; 522 | bf_est_err = biquad_filt(&bf_err_lpf, buf_delta); 523 | double err_deriv = biquad_filt(&bf_err_deriv_lpf, bf_est_err - bf_last_err); 524 | 525 | bf_est_drift = biquad_filt(&bf_drift_lpf, CONTROL_B*(bf_est_err*CONTROL_A + err_deriv) + bf_est_drift); 526 | 527 | if (debug) 528 | fprintf(stderr, "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); 529 | bf_playback_rate = 1.0 + CONTROL_A*bf_est_err + bf_est_drift; 530 | 531 | bf_last_err = bf_est_err; 532 | } 533 | 534 | // get the next frame, when available. return 0 if underrun/stream reset. 535 | short *buffer_get_frame(void) { 536 | short buf_fill; 537 | seq_t read; 538 | 539 | pthread_mutex_lock(&ab_mutex); 540 | 541 | buf_fill = ab_write - ab_read; 542 | if (buf_fill < 1 || !ab_synced) { // init or underrun. stop and wait 543 | if (ab_synced) 544 | fprintf(stderr, "\nunderrun.\n"); 545 | 546 | ab_buffering = 1; 547 | pthread_cond_wait(&ab_buffer_ready, &ab_mutex); 548 | ab_read++; 549 | buf_fill = ab_write - ab_read; 550 | pthread_mutex_unlock(&ab_mutex); 551 | 552 | bf_est_reset(buf_fill); 553 | return 0; 554 | } 555 | if (buf_fill >= BUFFER_FRAMES) { // overrunning! uh-oh. restart at a sane distance 556 | fprintf(stderr, "\noverrun.\n"); 557 | ab_read = ab_write - START_FILL; 558 | } 559 | read = ab_read; 560 | ab_read++; 561 | pthread_mutex_unlock(&ab_mutex); 562 | 563 | buf_fill = ab_write - ab_read; 564 | bf_est_update(buf_fill); 565 | 566 | volatile abuf_t *curframe = audio_buffer + BUFIDX(read); 567 | if (!curframe->ready) { 568 | fprintf(stderr, "\nmissing frame.\n"); 569 | memset(curframe->data, 0, FRAME_BYTES); 570 | } 571 | curframe->ready = 0; 572 | return curframe->data; 573 | } 574 | 575 | int stuff_buffer(double playback_rate, short *inptr, short *outptr) { 576 | int i; 577 | int stuffsamp = frame_size; 578 | int stuff = 0; 579 | double p_stuff; 580 | 581 | p_stuff = 1.0 - pow(1.0 - fabs(playback_rate-1.0), frame_size); 582 | 583 | if ((float)rand()/((float)RAND_MAX) < p_stuff) { 584 | stuff = playback_rate > 1.0 ? -1 : 1; 585 | stuffsamp = rand() % (frame_size - 1); 586 | } 587 | 588 | for (i=0; i> 1); 598 | *outptr++ = dithered_vol(((long)inptr[-1] + (long)inptr[1]) >> 1); 599 | } else if (stuff==-1) { 600 | if (debug) 601 | fprintf(stderr, "---------\n"); 602 | inptr++; 603 | inptr++; 604 | } 605 | for (i=stuffsamp; i{decoder_pid} } } keys %conns; 83 | kill 9, $avahi_publish; 84 | exit(0); 85 | }; 86 | 87 | my $airport_pem = join '', ; 88 | my $rsa = Crypt::OpenSSL::RSA->new_private_key($airport_pem) || die; 89 | 90 | my $listen; 91 | { 92 | eval { 93 | $listen = new IO::Socket::INET6(Listen => 1, 94 | Domain => AF_INET6, 95 | LocalPort => 5000, 96 | ReuseAddr => 1, 97 | Proto => 'tcp'); 98 | }; 99 | if ($@) { 100 | print "**************************************\n\n", 101 | "* IO::Socket::INET6 not present! *\n", 102 | "* Install this if iTunes won't play. *\n", 103 | "**************************************\n\n"; 104 | 105 | $listen = new IO::Socket::INET(Listen => 1, 106 | LocalPort => 5000, 107 | ReuseAddr => 1, 108 | Proto => 'tcp'); 109 | } 110 | } 111 | die "Can't listen on port 5000: $!" unless $listen; 112 | 113 | sub ip6bin { 114 | my $ip = shift; 115 | $ip =~ /((.*)::)?(.+)/; 116 | my @left = split /:/, $2; 117 | my @right = split /:/, $3; 118 | my @mid; 119 | my $pad = 8 - ($#left + $#right + 2); 120 | if ($pad > 0) { 121 | @mid = (0) x $pad; 122 | } 123 | 124 | pack('S>*', map { hex } (@left, @mid, @right)); 125 | } 126 | 127 | my $sel = new IO::Select($listen); 128 | 129 | print "listening...\n"; 130 | 131 | while (1) { 132 | my @waiting = $sel->can_read; 133 | foreach $fh (@waiting) { 134 | if ($fh==$listen) { 135 | my $new = $listen->accept; 136 | printf "new connection from %s\n", $new->sockhost; 137 | 138 | $sel->add($new); 139 | $new->blocking(0); 140 | $conns{$new} = {fh => $fh}; 141 | } else { 142 | if (eof($fh)) { 143 | print "closed: $fh\n"; 144 | $sel->remove($fh); 145 | close $fh; 146 | eval { kill $conns{$fh}{decoder_pid} }; 147 | delete $conns{$fh}; 148 | next; 149 | } 150 | if (exists $conns{$fh}) { 151 | conn_handle_data($fh); 152 | } 153 | } 154 | } 155 | } 156 | 157 | sub conn_handle_data { 158 | my $fh = shift; 159 | my $conn = $conns{$fh}; 160 | 161 | if ($conn->{req_need}) { 162 | if (length($conn->{data}) >= $conn->{req_need}) { 163 | $conn->{req}->content(substr($conn->{data}, 0, $conn->{req_need}, '')); 164 | conn_handle_request($fh, $conn); 165 | } 166 | undef $conn->{req_need}; 167 | return; 168 | } 169 | 170 | read $fh, my $data, 4096; 171 | $conn->{data} .= $data; 172 | 173 | if ($conn->{data} =~ /(\r\n\r\n|\n\n|\r\r)/) { 174 | my $req_data = substr($conn->{data}, 0, $+[0], ''); 175 | $conn->{req} = HTTP::Request->parse($req_data); 176 | printf "REQ: %s\n", $conn->{req}->method; 177 | conn_handle_request($fh, $conn); 178 | conn_handle_data($fh) if length($conn->{data}); 179 | } 180 | } 181 | 182 | sub digest_ok { 183 | my ($req, $conn) = @_; 184 | my $authz = $req->header('Authorization'); 185 | return 0 unless $authz =~ s/^Digest\s+//i; 186 | return 0 unless length $conn->{nonce}; 187 | my @authz = split /,\s*/, $authz; 188 | my %authz = map { /(.+)="(.+)"/; ($1, $2) } @authz; 189 | 190 | # not a standard digest - uses capital hex digits, in conflict with the RFC 191 | my $digest = uc md5_hex ( 192 | uc(md5_hex($authz{username} . ':' . $authz{realm} . ':' . $password)) 193 | . ':' . $authz{nonce} . ':' . 194 | uc(md5_hex($req->method . ':' . $authz{uri})) 195 | ); 196 | 197 | return $digest eq $authz{response}; 198 | } 199 | 200 | sub conn_handle_request { 201 | my ($fh, $conn) = @_; 202 | 203 | my $req = $conn->{req};; 204 | my $clen = $req->header('content-length') // 0; 205 | if ($clen > 0 && !length($req->content)) { 206 | $conn->{req_need} = $clen; 207 | return; # need more! 208 | } 209 | 210 | my $resp = HTTP::Response->new(200); 211 | $resp->request($req); 212 | $resp->protocol($req->protocol); 213 | 214 | $resp->header('CSeq', $req->header('CSeq')); 215 | $resp->header('Audio-Jack-Status', 'connected; type=analog'); 216 | 217 | if (my $chall = $req->header('Apple-Challenge')) { 218 | my $data = decode_base64($chall); 219 | my $ip = $fh->sockhost; 220 | if ($ip =~ /((\d+\.){3}\d+)$/) { # IPv4 221 | $data .= join '', map { chr } split(/\./, $1); 222 | } else { 223 | $data .= ip6bin($ip); 224 | } 225 | 226 | $data .= join '', map { chr } @hw_addr; 227 | $data .= chr(0) x (0x20-length($data)); 228 | 229 | $rsa->use_pkcs1_padding; # this isn't hashed before signing 230 | my $signature = encode_base64 $rsa->private_encrypt($data), ''; 231 | $signature =~ s/=*$//; 232 | $resp->header('Apple-Response', $signature); 233 | } 234 | 235 | if (length $password) { 236 | if (!digest_ok($req, $conn)) { 237 | my $nonce = md5_hex(map { rand } 1..20); 238 | $conn->{nonce} = $nonce; 239 | $resp->header('WWW-Authenticate', "Digest realm=\"$apname\", nonce=\"$nonce\""); 240 | $resp->code(401); 241 | $req->method('DENIED'); 242 | } 243 | } 244 | 245 | for ($req->method) { 246 | /^OPTIONS$/ && do { 247 | $resp->header('Public', 'ANNOUNCE, SETUP, RECORD, PAUSE, FLUSH, TEARDOWN, OPTIONS, GET_PARAMETER, SET_PARAMETER'); 248 | last; 249 | }; 250 | 251 | /^ANNOUNCE$/ && do { 252 | my $sdptext = $req->content; 253 | my @sdplines = split /[\r\n]+/, $sdptext; 254 | my %sdp = map { ($1, $2) if /^a=([^:]+):(.+)/ } @sdplines; 255 | die("no AESIV") unless my $aesiv = decode_base64($sdp{aesiv}); 256 | die("no AESKEY") unless my $rsaaeskey = decode_base64($sdp{rsaaeskey}); 257 | $rsa->use_pkcs1_oaep_padding; 258 | my $aeskey = $rsa->decrypt($rsaaeskey) || die; 259 | 260 | $conn->{aesiv} = $aesiv; 261 | $conn->{aeskey} = $aeskey; 262 | $conn->{fmtp} = $sdp{fmtp}; 263 | last; 264 | }; 265 | 266 | /^SETUP$/ && do { 267 | my $transport = $req->header('Transport'); 268 | $transport =~ s/;control_port=(\d+)//; 269 | my $cport = $1; 270 | $transport =~ s/;timing_port=(\d+)//; 271 | my $tport = $1; 272 | $transport =~ s/;server_port=(\d+)//; 273 | my $dport = $1; 274 | $resp->header('Session', 'DEADBEEF'); 275 | 276 | 277 | my $dec = sprintf("./hairtunes iv %s key %s fmtp %s cport %s tport %s dport %s host %s", 278 | map { "'$_'" } ( 279 | unpack('H*', $conn->{aesiv}), 280 | unpack('H*', $conn->{aeskey}), 281 | $conn->{fmtp}, 282 | $cport, $tport, $dport, 283 | 'unused' 284 | )); 285 | # print "decode command: $dec\n"; 286 | my $decoder = open2(my $dec_out, my $dec_in, $dec); 287 | 288 | $conn->{decoder_pid} = $decoder; 289 | $conn->{decoder_fh} = $dec_in; 290 | my $portdesc = <$dec_out>; 291 | die("Expected port number from decoder; got $portdesc") unless $portdesc =~ /^port: (\d+)/; 292 | my $port = $1; 293 | print "launched decoder: $decoder on port: $port\n"; 294 | $resp->header('Transport', $req->header('Transport') . ";server_port=$port"); 295 | last; 296 | }; 297 | 298 | /^RECORD$/ && last; 299 | /^FLUSH$/ && do { 300 | my $dfh = $conn->{decoder_fh}; 301 | print $dfh "flush\n"; 302 | last; 303 | }; 304 | /^TEARDOWN$/ && do { 305 | $resp->header('Connection', 'close'); 306 | close $conn->{decoder_fh}; 307 | last; 308 | }; 309 | /^SET_PARAMETER$/ && do { 310 | my @lines = split /[\r\n]+/, $req->content; 311 | my %content = map { /^(\S+): (.+)/; (lc $1, $2) } @lines; 312 | my $cfh = $conn->{decoder_fh}; 313 | if (exists $content{volume}) { 314 | printf $cfh "vol: %f\n", $content{volume}; 315 | } 316 | last; 317 | }; 318 | /^GET_PARAMETER$/ && last; 319 | /^DENIED$/ && last; 320 | die("Unknown method: $_"); 321 | } 322 | 323 | print $fh $resp->as_string("\r\n"); 324 | $fh->flush; 325 | } 326 | 327 | __DATA__ 328 | -----BEGIN RSA PRIVATE KEY----- 329 | MIIEpQIBAAKCAQEA59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUt 330 | wC5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDRKSKv6kDqnw4U 331 | wPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuBOitnZ/bDzPHrTOZz0Dew0uowxf 332 | /+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJQ+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/ 333 | UAaHqn9JdsBWLUEpVviYnhimNVvYFZeCXg/IdTQ+x4IRdiXNv5hEewIDAQABAoIBAQDl8Axy9XfW 334 | BLmkzkEiqoSwF0PsmVrPzH9KsnwLGH+QZlvjWd8SWYGN7u1507HvhF5N3drJoVU3O14nDY4TFQAa 335 | LlJ9VM35AApXaLyY1ERrN7u9ALKd2LUwYhM7Km539O4yUFYikE2nIPscEsA5ltpxOgUGCY7b7ez5 336 | NtD6nL1ZKauw7aNXmVAvmJTcuPxWmoktF3gDJKK2wxZuNGcJE0uFQEG4Z3BrWP7yoNuSK3dii2jm 337 | lpPHr0O/KnPQtzI3eguhe0TwUem/eYSdyzMyVx/YpwkzwtYL3sR5k0o9rKQLtvLzfAqdBxBurciz 338 | aaA/L0HIgAmOit1GJA2saMxTVPNhAoGBAPfgv1oeZxgxmotiCcMXFEQEWflzhWYTsXrhUIuz5jFu 339 | a39GLS99ZEErhLdrwj8rDDViRVJ5skOp9zFvlYAHs0xh92ji1E7V/ysnKBfsMrPkk5KSKPrnjndM 340 | oPdevWnVkgJ5jxFuNgxkOLMuG9i53B4yMvDTCRiIPMQ++N2iLDaRAoGBAO9v//mU8eVkQaoANf0Z 341 | oMjW8CN4xwWA2cSEIHkd9AfFkftuv8oyLDCG3ZAf0vrhrrtkrfa7ef+AUb69DNggq4mHQAYBp7L+ 342 | k5DKzJrKuO0r+R0YbY9pZD1+/g9dVt91d6LQNepUE/yY2PP5CNoFmjedpLHMOPFdVgqDzDFxU8hL 343 | AoGBANDrr7xAJbqBjHVwIzQ4To9pb4BNeqDndk5Qe7fT3+/H1njGaC0/rXE0Qb7q5ySgnsCb3DvA 344 | cJyRM9SJ7OKlGt0FMSdJD5KG0XPIpAVNwgpXXH5MDJg09KHeh0kXo+QA6viFBi21y340NonnEfdf 345 | 54PX4ZGS/Xac1UK+pLkBB+zRAoGAf0AY3H3qKS2lMEI4bzEFoHeK3G895pDaK3TFBVmD7fV0Zhov 346 | 17fegFPMwOII8MisYm9ZfT2Z0s5Ro3s5rkt+nvLAdfC/PYPKzTLalpGSwomSNYJcB9HNMlmhkGzc 347 | 1JnLYT4iyUyx6pcZBmCd8bD0iwY/FzcgNDaUmbX9+XDvRA0CgYEAkE7pIPlE71qvfJQgoA9em0gI 348 | LAuE4Pu13aKiJnfft7hIjbK+5kyb3TysZvoyDnb3HOKvInK7vXbKuU4ISgxB2bB3HcYzQMGsz1qJ 349 | 2gG0N5hvJpzwwhbhXqFKA4zaaSrw622wDniAK5MlIE0tIAKKP4yxNGjoD2QYjhBGuhvkWKaXTyY= 350 | -----END RSA PRIVATE KEY----- 351 | --------------------------------------------------------------------------------