alac.c 15 KB

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