alac.c 15 KB

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