2
0

alac.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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->decoder = alac_create_decoder(len - 36, ptr, &l->sample_size, &l->sample_rate, &l->channels, &block_size);
  109. l->play = l->trak;
  110. l->writebuf = malloc(block_size + 256);
  111. if (!l->writebuf) {
  112. LOG_ERROR("cannot allocate write buffer for %u bytes", block_size);
  113. return -1;
  114. } else {
  115. LOG_INFO("write buffer of %u bytes", block_size);
  116. }
  117. }
  118. // extract the total number of samples from stts
  119. if (!strcmp(type, "stsz") && bytes > len) {
  120. u32_t i;
  121. u8_t *ptr = streambuf->readp + 12;
  122. l->default_block_size = unpackN((u32_t *) ptr); ptr += 4;
  123. if (!l->default_block_size) {
  124. u32_t entries = unpackN((u32_t *)ptr); ptr += 4;
  125. l->block_size = malloc((entries + 1)* 4);
  126. for (i = 0; i < entries; i++) {
  127. l->block_size[i] = unpackN((u32_t *)ptr); ptr += 4;
  128. }
  129. l->block_size[entries] = 0;
  130. LOG_DEBUG("total blocksize contained in stsz %u", entries);
  131. } else {
  132. LOG_DEBUG("fixed blocksize in stsz %u", l->default_block_size);
  133. }
  134. }
  135. // extract the total number of samples from stts
  136. if (!strcmp(type, "stts") && bytes > len) {
  137. u32_t i;
  138. u8_t *ptr = streambuf->readp + 12;
  139. u32_t entries = unpackN((u32_t *)ptr);
  140. ptr += 4;
  141. for (i = 0; i < entries; ++i) {
  142. u32_t count = unpackN((u32_t *)ptr);
  143. u32_t size = unpackN((u32_t *)(ptr + 4));
  144. l->sttssamples += count * size;
  145. ptr += 8;
  146. }
  147. LOG_DEBUG("total number of samples contained in stts: " FMT_u64, l->sttssamples);
  148. }
  149. // stash sample to chunk info, assume it comes before stco
  150. if (!strcmp(type, "stsc") && bytes > len && !l->chunkinfo) {
  151. l->stsc = malloc(len - 12);
  152. if (l->stsc == NULL) {
  153. LOG_WARN("malloc fail");
  154. return -1;
  155. }
  156. memcpy(l->stsc, streambuf->readp + 12, len - 12);
  157. }
  158. // build offsets table from stco and stored stsc
  159. if (!strcmp(type, "stco") && bytes > len && l->play == l->trak) {
  160. u32_t i;
  161. // extract chunk offsets
  162. u8_t *ptr = streambuf->readp + 12;
  163. u32_t entries = unpackN((u32_t *)ptr);
  164. ptr += 4;
  165. l->chunkinfo = malloc(sizeof(struct chunk_table) * (entries + 1));
  166. if (l->chunkinfo == NULL) {
  167. LOG_WARN("malloc fail");
  168. return -1;
  169. }
  170. for (i = 0; i < entries; ++i) {
  171. l->chunkinfo[i].offset = unpackN((u32_t *)ptr);
  172. l->chunkinfo[i].sample = 0;
  173. ptr += 4;
  174. }
  175. l->chunkinfo[i].sample = 0;
  176. l->chunkinfo[i].offset = 0;
  177. // fill in first sample id for each chunk from stored stsc
  178. if (l->stsc) {
  179. u32_t stsc_entries = unpackN((u32_t *)l->stsc);
  180. u32_t sample = 0;
  181. u32_t last = 0, last_samples = 0;
  182. u8_t *ptr = (u8_t *)l->stsc + 4;
  183. while (stsc_entries--) {
  184. u32_t first = unpackN((u32_t *)ptr);
  185. u32_t samples = unpackN((u32_t *)(ptr + 4));
  186. if (last) {
  187. for (i = last - 1; i < first - 1; ++i) {
  188. l->chunkinfo[i].sample = sample;
  189. sample += last_samples;
  190. }
  191. }
  192. if (stsc_entries == 0) {
  193. for (i = first - 1; i < entries; ++i) {
  194. l->chunkinfo[i].sample = sample;
  195. sample += samples;
  196. }
  197. }
  198. last = first;
  199. last_samples = samples;
  200. ptr += 12;
  201. }
  202. free(l->stsc);
  203. l->stsc = NULL;
  204. }
  205. }
  206. // found media data, advance to start of first chunk and return
  207. if (!strcmp(type, "mdat")) {
  208. _buf_inc_readp(streambuf, 8);
  209. l->pos += 8;
  210. bytes -= 8;
  211. if (l->play) {
  212. LOG_DEBUG("type: mdat len: %u pos: %u", len, l->pos);
  213. if (l->chunkinfo && l->chunkinfo[0].offset > l->pos) {
  214. u32_t skip = l->chunkinfo[0].offset - l->pos;
  215. LOG_DEBUG("skipping: %u", skip);
  216. if (skip <= bytes) {
  217. _buf_inc_readp(streambuf, skip);
  218. l->pos += skip;
  219. } else {
  220. l->consume = skip;
  221. }
  222. }
  223. l->sample = l->nextchunk = 1;
  224. l->block_index = 0;
  225. return 1;
  226. } else {
  227. LOG_DEBUG("type: mdat len: %u, no playable track found", len);
  228. return -1;
  229. }
  230. }
  231. // parse key-value atoms within ilst ---- entries to get encoder padding within iTunSMPB entry for gapless
  232. if (!strcmp(type, "----") && bytes > len) {
  233. u8_t *ptr = streambuf->readp + 8;
  234. u32_t remain = len - 8, size;
  235. if (!memcmp(ptr + 4, "mean", 4) && (size = unpackN((u32_t *)ptr)) < remain) {
  236. ptr += size; remain -= size;
  237. }
  238. if (!memcmp(ptr + 4, "name", 4) && (size = unpackN((u32_t *)ptr)) < remain && !memcmp(ptr + 12, "iTunSMPB", 8)) {
  239. ptr += size; remain -= size;
  240. }
  241. if (!memcmp(ptr + 4, "data", 4) && remain > 16 + 48) {
  242. // data is stored as hex strings: 0 start end samples
  243. u32_t b, c; u64_t d;
  244. if (sscanf((const char *)(ptr + 16), "%x %x %x " FMT_x64, &b, &b, &c, &d) == 4) {
  245. LOG_DEBUG("iTunSMPB start: %u end: %u samples: " FMT_u64, b, c, d);
  246. if (l->sttssamples && l->sttssamples < b + c + d) {
  247. LOG_DEBUG("reducing samples as stts count is less");
  248. d = l->sttssamples - (b + c);
  249. }
  250. l->skip = b;
  251. l->samples = d;
  252. }
  253. }
  254. }
  255. // default to consuming entire box
  256. consume = len;
  257. // read into these boxes so reduce consume
  258. if (!strcmp(type, "moov") || !strcmp(type, "trak") || !strcmp(type, "mdia") || !strcmp(type, "minf") || !strcmp(type, "stbl") ||
  259. !strcmp(type, "udta") || !strcmp(type, "ilst")) {
  260. consume = 8;
  261. }
  262. // special cases which mix mix data in the enclosing box which we want to read into
  263. if (!strcmp(type, "stsd")) consume = 16;
  264. if (!strcmp(type, "mp4a")) consume = 36;
  265. if (!strcmp(type, "meta")) consume = 12;
  266. // consume rest of box if it has been parsed (all in the buffer) or is not one we want to parse
  267. if (bytes >= consume) {
  268. LOG_DEBUG("type: %s len: %u consume: %u", type, len, consume);
  269. _buf_inc_readp(streambuf, consume);
  270. l->pos += consume;
  271. bytes -= consume;
  272. } else if ( !(!strcmp(type, "esds") || !strcmp(type, "stts") || !strcmp(type, "stsc") ||
  273. !strcmp(type, "stsz") || !strcmp(type, "stco") || !strcmp(type, "----")) ) {
  274. LOG_DEBUG("type: %s len: %u consume: %u - partial consume: %u", type, len, consume, bytes);
  275. _buf_inc_readp(streambuf, bytes);
  276. l->pos += bytes;
  277. l->consume = consume - bytes;
  278. break;
  279. } else if (len > streambuf->size) {
  280. // can't process an atom larger than streambuf!
  281. LOG_ERROR("atom %s too large for buffer %u %u", type, len, streambuf->size);
  282. return -1;
  283. } else {
  284. // make sure there is 'len' contiguous space
  285. _buf_unwrap(streambuf, len);
  286. break;
  287. }
  288. }
  289. return 0;
  290. }
  291. static decode_state alac_decode(void) {
  292. size_t bytes;
  293. bool endstream;
  294. u8_t *iptr;
  295. u32_t frames, block_size;
  296. LOCK_S;
  297. // data not reached yet
  298. if (l->consume) {
  299. u32_t consume = min(l->consume, _buf_used(streambuf));
  300. LOG_DEBUG("consume: %u of %u", consume, l->consume);
  301. _buf_inc_readp(streambuf, consume);
  302. l->pos += consume;
  303. l->consume -= consume;
  304. UNLOCK_S;
  305. return DECODE_RUNNING;
  306. }
  307. if (decode.new_stream) {
  308. int found = 0;
  309. // mp4 - read header
  310. found = read_mp4_header();
  311. if (found == 1) {
  312. bytes = min(_buf_used(streambuf), _buf_cont_read(streambuf));
  313. LOG_INFO("setting track_start");
  314. LOCK_O;
  315. output.next_sample_rate = decode_newstream(l->sample_rate, output.supported_rates);
  316. output.track_start = outputbuf->writep;
  317. if (output.fade_mode) _checkfade(true);
  318. decode.new_stream = false;
  319. UNLOCK_O;
  320. } else if (found == -1) {
  321. LOG_WARN("[%p]: error reading stream header");
  322. UNLOCK_S;
  323. return DECODE_ERROR;
  324. } else {
  325. // not finished header parsing come back next time
  326. UNLOCK_S;
  327. return DECODE_RUNNING;
  328. }
  329. }
  330. bytes = _buf_used(streambuf);
  331. block_size = l->default_block_size ? l->default_block_size : l->block_size[l->block_index];
  332. // stream terminated
  333. if (stream.state <= DISCONNECT && (bytes == 0 || block_size == 0)) {
  334. UNLOCK_S;
  335. LOG_DEBUG("end of stream");
  336. return DECODE_COMPLETE;
  337. }
  338. // is there enough data for decoding
  339. if (bytes < block_size) {
  340. UNLOCK_S;
  341. return DECODE_RUNNING;
  342. } else if (block_size != l->default_block_size) l->block_index++;
  343. bytes = min(bytes, _buf_cont_read(streambuf));
  344. // need to create a buffer with contiguous data
  345. if (bytes < block_size) {
  346. iptr = malloc(block_size);
  347. memcpy(iptr, streambuf->readp, bytes);
  348. memcpy(iptr + bytes, streambuf->buf, block_size - bytes);
  349. } else iptr = streambuf->readp;
  350. if (!alac_to_pcm(l->decoder, iptr, l->writebuf, 2, &frames)) {
  351. LOG_ERROR("decode error");
  352. UNLOCK_S;
  353. return DECODE_ERROR;
  354. }
  355. // and free it
  356. if (bytes < block_size) free(iptr);
  357. LOG_SDEBUG("block of %u bytes (%u frames)", block_size, frames);
  358. endstream = false;
  359. // mp4 end of chunk - skip to next offset
  360. if (l->chunkinfo && l->chunkinfo[l->nextchunk].offset && l->sample++ == l->chunkinfo[l->nextchunk].sample) {
  361. if (l->chunkinfo[l->nextchunk].offset > l->pos) {
  362. u32_t skip = l->chunkinfo[l->nextchunk].offset - l->pos;
  363. if (_buf_used(streambuf) >= skip) {
  364. _buf_inc_readp(streambuf, skip);
  365. l->pos += skip;
  366. } else {
  367. l->consume = skip;
  368. }
  369. l->nextchunk++;
  370. } else {
  371. LOG_ERROR("error: need to skip backwards!");
  372. endstream = true;
  373. }
  374. // mp4 when not at end of chunk
  375. } else if (frames) {
  376. _buf_inc_readp(streambuf, block_size);
  377. l->pos += block_size;
  378. } else {
  379. endstream = true;
  380. }
  381. UNLOCK_S;
  382. if (endstream) {
  383. LOG_WARN("unable to decode further");
  384. return DECODE_ERROR;
  385. }
  386. // now point at the beginning of decoded samples
  387. iptr = l->writebuf;
  388. if (l->skip) {
  389. u32_t skip;
  390. if (l->empty) {
  391. l->empty = false;
  392. l->skip -= frames;
  393. LOG_DEBUG("gapless: first frame empty, skipped %u frames at start", frames);
  394. }
  395. skip = min(frames, l->skip);
  396. LOG_DEBUG("gapless: skipping %u frames at start", skip);
  397. frames -= skip;
  398. l->skip -= skip;
  399. iptr += skip * l->channels * l->sample_size;
  400. }
  401. if (l->samples) {
  402. if (l->samples < frames) {
  403. LOG_DEBUG("gapless: trimming %u frames from end", frames - l->samples);
  404. frames = (u32_t) l->samples;
  405. }
  406. l->samples -= frames;
  407. }
  408. LOCK_O_direct;
  409. while (frames > 0) {
  410. size_t f, count;
  411. ISAMPLE_T *optr;
  412. IF_DIRECT(
  413. f = min(frames, _buf_cont_write(outputbuf) / BYTES_PER_FRAME);
  414. optr = (ISAMPLE_T *)outputbuf->writep;
  415. );
  416. IF_PROCESS(
  417. f = min(frames, process.max_in_frames - process.in_frames);
  418. optr = (ISAMPLE_T *)((u8_t *) process.inbuf + process.in_frames * BYTES_PER_FRAME);
  419. );
  420. f = min(f, frames);
  421. count = f;
  422. if (l->sample_size == 8) {
  423. while (count--) {
  424. *optr++ = ALIGN8(*iptr++);
  425. *optr++ = ALIGN8(*iptr++);
  426. }
  427. } else if (l->sample_size == 16) {
  428. u16_t *_iptr = (u16_t*) iptr;
  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. while (count--) {
  442. *optr++ = ALIGN32(*_iptr++);
  443. *optr++ = ALIGN32(*_iptr++);
  444. }
  445. } else {
  446. LOG_ERROR("unsupported bits per sample: %u", l->sample_size);
  447. }
  448. frames -= f;
  449. IF_DIRECT(
  450. _buf_inc_writep(outputbuf, f * BYTES_PER_FRAME);
  451. );
  452. IF_PROCESS(
  453. process.in_frames = f;
  454. // called only if there is enough space in process buffer
  455. if (frames) LOG_ERROR("unhandled case");
  456. );
  457. }
  458. UNLOCK_O_direct;
  459. return DECODE_RUNNING;
  460. }
  461. static void alac_close(void) {
  462. if (l->decoder) alac_delete_decoder(l->decoder);
  463. if (l->writebuf) free(l->writebuf);
  464. if (l->chunkinfo) free(l->chunkinfo);
  465. if (l->block_size) free(l->block_size);
  466. if (l->stsc) free(l->stsc);
  467. memset(l, 0, sizeof(struct alac));
  468. }
  469. static void alac_open(u8_t size, u8_t rate, u8_t chan, u8_t endianness) {
  470. alac_close();
  471. }
  472. struct codec *register_alac(void) {
  473. static struct codec ret = {
  474. 'l', // id
  475. "alc", // types
  476. MIN_READ, // min read
  477. MIN_SPACE, // min space assuming a ratio of 2
  478. alac_open, // open
  479. alac_close, // close
  480. alac_decode, // decode
  481. };
  482. l = calloc(1, sizeof(struct alac));
  483. if (!l) return NULL;
  484. LOG_INFO("using alac to decode alc");
  485. return &ret;
  486. }