alac.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. * Squeezelite - lightweight headless squeezebox emulator
  3. *
  4. * (c) Adrian Smith 2012-2015, triode1@btinternet.com
  5. * (c) Philippe, philippe_44@outlook.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. #include "squeezelite.h"
  22. #include "alac_wrapper.h"
  23. #if BYTES_PER_FRAME == 4
  24. #define ALIGN8(n) (n << 8)
  25. #define ALIGN16(n) (n)
  26. #define ALIGN24(n) (n >> 8)
  27. #define ALIGN32(n) (n >> 16)
  28. #else
  29. #define ALIGN8(n) (n << 24)
  30. #define ALIGN16(n) (n << 16)
  31. #define ALIGN24(n) (n << 8)
  32. #define ALIGN32(n) (n)
  33. #endif
  34. #define BLOCK_SIZE (4096 * BYTES_PER_FRAME)
  35. #define MIN_READ BLOCK_SIZE
  36. #define MIN_SPACE (MIN_READ * 4)
  37. struct chunk_table {
  38. u32_t sample, offset;
  39. };
  40. struct alac {
  41. void *decoder;
  42. u8_t *writebuf;
  43. // following used for mp4 only
  44. u32_t consume;
  45. u32_t pos;
  46. u32_t sample;
  47. u32_t nextchunk;
  48. void *stsc;
  49. u32_t skip;
  50. u64_t samples;
  51. u64_t sttssamples;
  52. bool empty;
  53. struct chunk_table *chunkinfo;
  54. u32_t *block_size, default_block_size, block_index;
  55. unsigned sample_rate;
  56. unsigned char channels, sample_size;
  57. unsigned trak, play;
  58. };
  59. static struct alac *l;
  60. extern log_level loglevel;
  61. extern struct buffer *streambuf;
  62. extern struct buffer *outputbuf;
  63. extern struct streamstate stream;
  64. extern struct outputstate output;
  65. extern struct decodestate decode;
  66. extern struct processstate process;
  67. #define LOCK_S mutex_lock(streambuf->mutex)
  68. #define UNLOCK_S mutex_unlock(streambuf->mutex)
  69. #define LOCK_O mutex_lock(outputbuf->mutex)
  70. #define UNLOCK_O mutex_unlock(outputbuf->mutex)
  71. #if PROCESS
  72. #define LOCK_O_direct if (decode.direct) mutex_lock(outputbuf->mutex)
  73. #define UNLOCK_O_direct if (decode.direct) mutex_unlock(outputbuf->mutex)
  74. #define LOCK_O_not_direct if (!decode.direct) mutex_lock(outputbuf->mutex)
  75. #define UNLOCK_O_not_direct if (!decode.direct) mutex_unlock(outputbuf->mutex)
  76. #define IF_DIRECT(x) if (decode.direct) { x }
  77. #define IF_PROCESS(x) if (!decode.direct) { x }
  78. #else
  79. #define LOCK_O_direct mutex_lock(outputbuf->mutex)
  80. #define UNLOCK_O_direct mutex_unlock(outputbuf->mutex)
  81. #define LOCK_O_not_direct
  82. #define UNLOCK_O_not_direct
  83. #define IF_DIRECT(x) { x }
  84. #define IF_PROCESS(x)
  85. #endif
  86. // read mp4 header to extract config data
  87. static int read_mp4_header(void) {
  88. size_t bytes = min(_buf_used(streambuf), _buf_cont_read(streambuf));
  89. char type[5];
  90. u32_t len;
  91. while (bytes >= 8) {
  92. // count trak to find the first playable one
  93. u32_t consume;
  94. len = unpackN((u32_t *)streambuf->readp);
  95. memcpy(type, streambuf->readp + 4, 4);
  96. type[4] = '\0';
  97. if (!strcmp(type, "moov")) {
  98. l->trak = 0;
  99. l->play = 0;
  100. }
  101. if (!strcmp(type, "trak")) {
  102. l->trak++;
  103. }
  104. // extract audio config from within alac
  105. if (!strcmp(type, "alac") && bytes > len) {
  106. u8_t *ptr = streambuf->readp + 36;
  107. unsigned int block_size;
  108. l->play = l->trak;
  109. l->decoder = alac_create_decoder(len - 36, ptr, &l->sample_size, &l->sample_rate, &l->channels, &block_size);
  110. l->writebuf = malloc(block_size + 256);
  111. LOG_INFO("allocated write buffer of %u bytes", block_size);
  112. if (!l->writebuf) {
  113. LOG_ERROR("allocation failed");
  114. return -1;
  115. }
  116. }
  117. // extract the total number of samples from stts
  118. if (!strcmp(type, "stsz") && bytes > len) {
  119. u32_t i;
  120. u8_t *ptr = streambuf->readp + 12;
  121. l->default_block_size = unpackN((u32_t *) ptr); ptr += 4;
  122. if (!l->default_block_size) {
  123. u32_t entries = unpackN((u32_t *)ptr); ptr += 4;
  124. l->block_size = malloc((entries + 1)* 4);
  125. for (i = 0; i < entries; i++) {
  126. l->block_size[i] = unpackN((u32_t *)ptr); ptr += 4;
  127. }
  128. l->block_size[entries] = 0;
  129. LOG_DEBUG("total blocksize contained in stsz %u", entries);
  130. } else {
  131. LOG_DEBUG("fixed blocksize in stsz %u", l->default_block_size);
  132. }
  133. }
  134. // extract the total number of samples from stts
  135. if (!strcmp(type, "stts") && bytes > len) {
  136. u32_t i;
  137. u8_t *ptr = streambuf->readp + 12;
  138. u32_t entries = unpackN((u32_t *)ptr);
  139. ptr += 4;
  140. for (i = 0; i < entries; ++i) {
  141. u32_t count = unpackN((u32_t *)ptr);
  142. u32_t size = unpackN((u32_t *)(ptr + 4));
  143. l->sttssamples += count * size;
  144. ptr += 8;
  145. }
  146. LOG_DEBUG("total number of samples contained in stts: " FMT_u64, l->sttssamples);
  147. }
  148. // stash sample to chunk info, assume it comes before stco
  149. if (!strcmp(type, "stsc") && bytes > len && !l->chunkinfo) {
  150. l->stsc = malloc(len - 12);
  151. if (l->stsc == NULL) {
  152. LOG_WARN("malloc fail");
  153. return -1;
  154. }
  155. memcpy(l->stsc, streambuf->readp + 12, len - 12);
  156. }
  157. // build offsets table from stco and stored stsc
  158. if (!strcmp(type, "stco") && bytes > len && l->play == l->trak) {
  159. u32_t i;
  160. // extract chunk offsets
  161. u8_t *ptr = streambuf->readp + 12;
  162. u32_t entries = unpackN((u32_t *)ptr);
  163. ptr += 4;
  164. l->chunkinfo = malloc(sizeof(struct chunk_table) * (entries + 1));
  165. if (l->chunkinfo == NULL) {
  166. LOG_WARN("malloc fail");
  167. return -1;
  168. }
  169. for (i = 0; i < entries; ++i) {
  170. l->chunkinfo[i].offset = unpackN((u32_t *)ptr);
  171. l->chunkinfo[i].sample = 0;
  172. ptr += 4;
  173. }
  174. l->chunkinfo[i].sample = 0;
  175. l->chunkinfo[i].offset = 0;
  176. // fill in first sample id for each chunk from stored stsc
  177. if (l->stsc) {
  178. u32_t stsc_entries = unpackN((u32_t *)l->stsc);
  179. u32_t sample = 0;
  180. u32_t last = 0, last_samples = 0;
  181. u8_t *ptr = (u8_t *)l->stsc + 4;
  182. while (stsc_entries--) {
  183. u32_t first = unpackN((u32_t *)ptr);
  184. u32_t samples = unpackN((u32_t *)(ptr + 4));
  185. if (last) {
  186. for (i = last - 1; i < first - 1; ++i) {
  187. l->chunkinfo[i].sample = sample;
  188. sample += last_samples;
  189. }
  190. }
  191. if (stsc_entries == 0) {
  192. for (i = first - 1; i < entries; ++i) {
  193. l->chunkinfo[i].sample = sample;
  194. sample += samples;
  195. }
  196. }
  197. last = first;
  198. last_samples = samples;
  199. ptr += 12;
  200. }
  201. free(l->stsc);
  202. l->stsc = NULL;
  203. }
  204. }
  205. // found media data, advance to start of first chunk and return
  206. if (!strcmp(type, "mdat")) {
  207. _buf_inc_readp(streambuf, 8);
  208. l->pos += 8;
  209. bytes -= 8;
  210. if (l->play) {
  211. LOG_DEBUG("type: mdat len: %u pos: %u", len, l->pos);
  212. if (l->chunkinfo && l->chunkinfo[0].offset > l->pos) {
  213. u32_t skip = l->chunkinfo[0].offset - l->pos;
  214. LOG_DEBUG("skipping: %u", skip);
  215. if (skip <= bytes) {
  216. _buf_inc_readp(streambuf, skip);
  217. l->pos += skip;
  218. } else {
  219. l->consume = skip;
  220. }
  221. }
  222. l->sample = l->nextchunk = 1;
  223. l->block_index = 0;
  224. return 1;
  225. } else {
  226. LOG_DEBUG("type: mdat len: %u, no playable track found", len);
  227. return -1;
  228. }
  229. }
  230. // parse key-value atoms within ilst ---- entries to get encoder padding within iTunSMPB entry for gapless
  231. if (!strcmp(type, "----") && bytes > len) {
  232. u8_t *ptr = streambuf->readp + 8;
  233. u32_t remain = len - 8, size;
  234. if (!memcmp(ptr + 4, "mean", 4) && (size = unpackN((u32_t *)ptr)) < remain) {
  235. ptr += size; remain -= size;
  236. }
  237. if (!memcmp(ptr + 4, "name", 4) && (size = unpackN((u32_t *)ptr)) < remain && !memcmp(ptr + 12, "iTunSMPB", 8)) {
  238. ptr += size; remain -= size;
  239. }
  240. if (!memcmp(ptr + 4, "data", 4) && remain > 16 + 48) {
  241. // data is stored as hex strings: 0 start end samples
  242. u32_t b, c; u64_t d;
  243. if (sscanf((const char *)(ptr + 16), "%x %x %x " FMT_x64, &b, &b, &c, &d) == 4) {
  244. LOG_DEBUG("iTunSMPB start: %u end: %u samples: " FMT_u64, b, c, d);
  245. if (l->sttssamples && l->sttssamples < b + c + d) {
  246. LOG_DEBUG("reducing samples as stts count is less");
  247. d = l->sttssamples - (b + c);
  248. }
  249. l->skip = b;
  250. l->samples = d;
  251. }
  252. }
  253. }
  254. // default to consuming entire box
  255. consume = len;
  256. // read into these boxes so reduce consume
  257. if (!strcmp(type, "moov") || !strcmp(type, "trak") || !strcmp(type, "mdia") || !strcmp(type, "minf") || !strcmp(type, "stbl") ||
  258. !strcmp(type, "udta") || !strcmp(type, "ilst")) {
  259. consume = 8;
  260. }
  261. // special cases which mix mix data in the enclosing box which we want to read into
  262. if (!strcmp(type, "stsd")) consume = 16;
  263. if (!strcmp(type, "mp4a")) consume = 36;
  264. if (!strcmp(type, "meta")) consume = 12;
  265. // consume rest of box if it has been parsed (all in the buffer) or is not one we want to parse
  266. if (bytes >= consume) {
  267. LOG_DEBUG("type: %s len: %u consume: %u", type, len, consume);
  268. _buf_inc_readp(streambuf, consume);
  269. l->pos += consume;
  270. bytes -= consume;
  271. } else if ( !(!strcmp(type, "esds") || !strcmp(type, "stts") || !strcmp(type, "stsc") ||
  272. !strcmp(type, "stsz") || !strcmp(type, "stco") || !strcmp(type, "----")) ) {
  273. LOG_DEBUG("type: %s len: %u consume: %u - partial consume: %u", type, len, consume, bytes);
  274. _buf_inc_readp(streambuf, bytes);
  275. l->pos += bytes;
  276. l->consume = consume - bytes;
  277. break;
  278. } else if (len > streambuf->size) {
  279. // can't process an atom larger than streambuf!
  280. LOG_ERROR("atom %s too large for buffer %u %u", type, len, streambuf->size);
  281. return -1;
  282. } else {
  283. // make sure there is 'len' contiguous space
  284. _buf_unwrap(streambuf, len);
  285. break;
  286. }
  287. }
  288. return 0;
  289. }
  290. static decode_state alac_decode(void) {
  291. size_t bytes;
  292. bool endstream;
  293. u8_t *iptr;
  294. u32_t frames, block_size;
  295. LOCK_S;
  296. // data not reached yet
  297. if (l->consume) {
  298. u32_t consume = min(l->consume, _buf_used(streambuf));
  299. LOG_DEBUG("consume: %u of %u", consume, l->consume);
  300. _buf_inc_readp(streambuf, consume);
  301. l->pos += consume;
  302. l->consume -= consume;
  303. UNLOCK_S;
  304. return DECODE_RUNNING;
  305. }
  306. if (decode.new_stream) {
  307. int found = 0;
  308. // mp4 - read header
  309. found = read_mp4_header();
  310. if (found == 1) {
  311. bytes = min(_buf_used(streambuf), _buf_cont_read(streambuf));
  312. LOG_INFO("setting track_start");
  313. LOCK_O;
  314. output.next_sample_rate = decode_newstream(l->sample_rate, output.supported_rates);
  315. output.track_start = outputbuf->writep;
  316. if (output.fade_mode) _checkfade(true);
  317. decode.new_stream = false;
  318. UNLOCK_O;
  319. } else if (found == -1) {
  320. LOG_WARN("[%p]: error reading stream header");
  321. UNLOCK_S;
  322. return DECODE_ERROR;
  323. } else {
  324. // not finished header parsing come back next time
  325. UNLOCK_S;
  326. return DECODE_RUNNING;
  327. }
  328. }
  329. bytes = _buf_used(streambuf);
  330. block_size = l->default_block_size ? l->default_block_size : l->block_size[l->block_index];
  331. // stream terminated
  332. if (stream.state <= DISCONNECT && (bytes == 0 || block_size == 0)) {
  333. UNLOCK_S;
  334. LOG_DEBUG("end of stream");
  335. return DECODE_COMPLETE;
  336. }
  337. // is there enough data for decoding
  338. if (bytes < block_size) {
  339. UNLOCK_S;
  340. return DECODE_RUNNING;
  341. } else if (block_size != l->default_block_size) l->block_index++;
  342. bytes = min(bytes, _buf_cont_read(streambuf));
  343. // need to create a buffer with contiguous data
  344. if (bytes < block_size) {
  345. iptr = malloc(block_size);
  346. memcpy(iptr, streambuf->readp, bytes);
  347. memcpy(iptr + bytes, streambuf->buf, block_size - bytes);
  348. } else iptr = streambuf->readp;
  349. if (!alac_to_pcm(l->decoder, iptr, l->writebuf, 2, &frames)) {
  350. LOG_ERROR("decode error");
  351. UNLOCK_S;
  352. return DECODE_ERROR;
  353. }
  354. // and free it
  355. if (bytes < block_size) free(iptr);
  356. LOG_SDEBUG("block of %u bytes (%u frames)", block_size, frames);
  357. endstream = false;
  358. // mp4 end of chunk - skip to next offset
  359. if (l->chunkinfo && l->chunkinfo[l->nextchunk].offset && l->sample++ == l->chunkinfo[l->nextchunk].sample) {
  360. if (l->chunkinfo[l->nextchunk].offset > l->pos) {
  361. u32_t skip = l->chunkinfo[l->nextchunk].offset - l->pos;
  362. if (_buf_used(streambuf) >= skip) {
  363. _buf_inc_readp(streambuf, skip);
  364. l->pos += skip;
  365. } else {
  366. l->consume = skip;
  367. }
  368. l->nextchunk++;
  369. } else {
  370. LOG_ERROR("error: need to skip backwards!");
  371. endstream = true;
  372. }
  373. // mp4 when not at end of chunk
  374. } else if (frames) {
  375. _buf_inc_readp(streambuf, block_size);
  376. l->pos += block_size;
  377. } else {
  378. endstream = true;
  379. }
  380. UNLOCK_S;
  381. if (endstream) {
  382. LOG_WARN("unable to decode further");
  383. return DECODE_ERROR;
  384. }
  385. // now point at the beginning of decoded samples
  386. iptr = l->writebuf;
  387. if (l->skip) {
  388. u32_t skip;
  389. if (l->empty) {
  390. l->empty = false;
  391. l->skip -= frames;
  392. LOG_DEBUG("gapless: first frame empty, skipped %u frames at start", frames);
  393. }
  394. skip = min(frames, l->skip);
  395. LOG_DEBUG("gapless: skipping %u frames at start", skip);
  396. frames -= skip;
  397. l->skip -= skip;
  398. iptr += skip * l->channels * l->sample_size;
  399. }
  400. if (l->samples) {
  401. if (l->samples < frames) {
  402. LOG_DEBUG("gapless: trimming %u frames from end", frames - l->samples);
  403. frames = (u32_t) l->samples;
  404. }
  405. l->samples -= frames;
  406. }
  407. LOCK_O_direct;
  408. while (frames > 0) {
  409. size_t f, count;
  410. ISAMPLE_T *optr;
  411. IF_DIRECT(
  412. f = min(frames, _buf_cont_write(outputbuf) / BYTES_PER_FRAME);
  413. optr = (ISAMPLE_T *)outputbuf->writep;
  414. );
  415. IF_PROCESS(
  416. f = min(frames, process.max_in_frames - process.in_frames);
  417. optr = (ISAMPLE_T *)((u8_t *) process.inbuf + process.in_frames * BYTES_PER_FRAME);
  418. );
  419. f = min(f, frames);
  420. count = f;
  421. if (l->sample_size == 8) {
  422. while (count--) {
  423. *optr++ = ALIGN8(*iptr++);
  424. *optr++ = ALIGN8(*iptr++);
  425. }
  426. } else if (l->sample_size == 16) {
  427. u16_t *_iptr = (u16_t*) iptr;
  428. iptr += count * 4;
  429. while (count--) {
  430. *optr++ = ALIGN16(*_iptr++);
  431. *optr++ = ALIGN16(*_iptr++);
  432. }
  433. } else if (l->sample_size == 24) {
  434. while (count--) {
  435. *optr++ = ALIGN24(*(u32_t*) iptr);
  436. *optr++ = ALIGN24(*(u32_t*) (iptr + 3));
  437. iptr += 6;
  438. }
  439. } else if (l->sample_size == 32) {
  440. u32_t *_iptr = (u32_t*) iptr;
  441. iptr += count * 8;
  442. while (count--) {
  443. *optr++ = ALIGN32(*_iptr++);
  444. *optr++ = ALIGN32(*_iptr++);
  445. }
  446. } else {
  447. LOG_ERROR("unsupported bits per sample: %u", l->sample_size);
  448. }
  449. frames -= f;
  450. IF_DIRECT(
  451. _buf_inc_writep(outputbuf, f * BYTES_PER_FRAME);
  452. );
  453. IF_PROCESS(
  454. process.in_frames = f;
  455. // called only if there is enough space in process buffer
  456. if (frames) LOG_ERROR("unhandled case");
  457. );
  458. }
  459. UNLOCK_O_direct;
  460. return DECODE_RUNNING;
  461. }
  462. static void alac_close(void) {
  463. if (l->decoder) alac_delete_decoder(l->decoder);
  464. if (l->writebuf) free(l->writebuf);
  465. if (l->chunkinfo) free(l->chunkinfo);
  466. if (l->block_size) free(l->block_size);
  467. if (l->stsc) free(l->stsc);
  468. memset(l, 0, sizeof(struct alac));
  469. }
  470. static void alac_open(u8_t size, u8_t rate, u8_t chan, u8_t endianness) {
  471. alac_close();
  472. }
  473. struct codec *register_alac(void) {
  474. static struct codec ret = {
  475. 'l', // id
  476. "alc", // types
  477. MIN_READ, // min read
  478. MIN_SPACE, // min space assuming a ratio of 2
  479. alac_open, // open
  480. alac_close, // close
  481. alac_decode, // decode
  482. };
  483. l = calloc(1, sizeof(struct alac));
  484. if (!l) return NULL;
  485. LOG_INFO("using alac to decode alc");
  486. return &ret;
  487. }