mad.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /*
  2. * Squeezelite - lightweight headless squeezebox emulator
  3. *
  4. * (c) Adrian Smith 2012-2015, triode1@btinternet.com
  5. * Ralph Irving 2015-2017, ralph_irving@hotmail.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 <mad.h>
  23. #define MAD_DELAY 529
  24. #define READBUF_SIZE 2048 // local buffer used by decoder: FIXME merge with any other decoders needing one?
  25. struct mad {
  26. u8_t *readbuf;
  27. unsigned readbuf_len;
  28. struct mad_stream stream;
  29. struct mad_frame frame;
  30. struct mad_synth synth;
  31. enum mad_error last_error;
  32. // for lame gapless processing
  33. int checktags;
  34. u32_t consume;
  35. u32_t skip;
  36. u64_t samples;
  37. u32_t padding;
  38. #if !LINKALL
  39. // mad symbols to be dynamically loaded
  40. void (* mad_stream_init)(struct mad_stream *);
  41. void (* mad_frame_init)(struct mad_frame *);
  42. void (* mad_synth_init)(struct mad_synth *);
  43. void (* mad_frame_finish)(struct mad_frame *);
  44. void (* mad_stream_finish)(struct mad_stream *);
  45. void (* mad_stream_buffer)(struct mad_stream *, unsigned char const *, unsigned long);
  46. int (* mad_frame_decode)(struct mad_frame *, struct mad_stream *);
  47. void (* mad_synth_frame)(struct mad_synth *, struct mad_frame const *);
  48. char const *(* mad_stream_errorstr)(struct mad_stream const *);
  49. #endif
  50. };
  51. static struct mad *m;
  52. extern log_level loglevel;
  53. extern struct buffer *streambuf;
  54. extern struct buffer *outputbuf;
  55. extern struct streamstate stream;
  56. extern struct outputstate output;
  57. extern struct decodestate decode;
  58. extern struct processstate process;
  59. #define LOCK_S mutex_lock(streambuf->mutex)
  60. #define UNLOCK_S mutex_unlock(streambuf->mutex)
  61. #define LOCK_O mutex_lock(outputbuf->mutex)
  62. #define UNLOCK_O mutex_unlock(outputbuf->mutex)
  63. #if PROCESS
  64. #define LOCK_O_direct if (decode.direct) mutex_lock(outputbuf->mutex)
  65. #define UNLOCK_O_direct if (decode.direct) mutex_unlock(outputbuf->mutex)
  66. #define IF_DIRECT(x) if (decode.direct) { x }
  67. #define IF_PROCESS(x) if (!decode.direct) { x }
  68. #else
  69. #define LOCK_O_direct mutex_lock(outputbuf->mutex)
  70. #define UNLOCK_O_direct mutex_unlock(outputbuf->mutex)
  71. #define IF_DIRECT(x) { x }
  72. #define IF_PROCESS(x)
  73. #endif
  74. #if LINKALL
  75. #define MAD(h, fn, ...) (mad_ ## fn)(__VA_ARGS__)
  76. #else
  77. #define MAD(h, fn, ...) (h)->mad_##fn(__VA_ARGS__)
  78. #endif
  79. // based on libmad minimad.c scale
  80. static inline ISAMPLE_T scale(mad_fixed_t sample) {
  81. sample += (1L << (MAD_F_FRACBITS - 24));
  82. if (sample >= MAD_F_ONE)
  83. sample = MAD_F_ONE - 1;
  84. else if (sample < -MAD_F_ONE)
  85. sample = -MAD_F_ONE;
  86. #if BYTES_PER_FRAME == 4
  87. return (ISAMPLE_T)((sample >> (MAD_F_FRACBITS + 1 - 24)) >> 8);
  88. #else
  89. return (ISAMPLE_T)((sample >> (MAD_F_FRACBITS + 1 - 24)) << 8);
  90. #endif
  91. }
  92. // check for id3.2 tag at start of file - http://id3.org/id3v2.4.0-structure, return length
  93. static unsigned _check_id3_tag(size_t bytes) {
  94. u8_t *ptr = streambuf->readp;
  95. u32_t size = 0;
  96. if (bytes > 10 && *ptr == 'I' && *(ptr+1) == 'D' && *(ptr+2) == '3') {
  97. // size is encoded as syncsafe integer, add 10 if footer present
  98. if (*(ptr+6) < 0x80 && *(ptr+7) < 0x80 && *(ptr+8) < 0x80 && *(ptr+9) < 0x80) {
  99. size = 10 + (*(ptr+6) << 21) + (*(ptr+7) << 14) + (*(ptr+8) << 7) + *(ptr+9) + ((*(ptr+5) & 0x10) ? 10 : 0);
  100. LOG_DEBUG("id3.2 tag len: %u", size);
  101. }
  102. }
  103. return size;
  104. }
  105. // check for lame gapless params, don't advance streambuf
  106. static void _check_lame_header(size_t bytes) {
  107. u8_t *ptr = streambuf->readp;
  108. if (*ptr == 0xff && (*(ptr+1) & 0xf0) == 0xf0 && bytes > 180) {
  109. u32_t frame_count = 0, enc_delay = 0, enc_padding = 0;
  110. u8_t flags;
  111. // 2 channels
  112. if (!memcmp(ptr + 36, "Xing", 4) || !memcmp(ptr + 36, "Info", 4)) {
  113. ptr += 36 + 7;
  114. // mono
  115. } else if (!memcmp(ptr + 21, "Xing", 4) || !memcmp(ptr + 21, "Info", 4)) {
  116. ptr += 21 + 7;
  117. }
  118. flags = *ptr;
  119. if (flags & 0x01) {
  120. frame_count = unpackN((u32_t *)(ptr + 1));
  121. ptr += 4;
  122. }
  123. if (flags & 0x02) ptr += 4;
  124. if (flags & 0x04) ptr += 100;
  125. if (flags & 0x08) ptr += 4;
  126. if (!!memcmp(ptr+1, "LAME", 4)) {
  127. return;
  128. }
  129. ptr += 22;
  130. enc_delay = (*ptr << 4 | *(ptr + 1) >> 4) + MAD_DELAY;
  131. enc_padding = (*(ptr + 1) & 0xF) << 8 | *(ptr + 2);
  132. enc_padding = enc_padding > MAD_DELAY ? enc_padding - MAD_DELAY : 0;
  133. // add one frame to initial skip for this (empty) frame
  134. m->skip = enc_delay + 1152;
  135. m->samples = frame_count * 1152 - enc_delay - enc_padding;
  136. m->padding = enc_padding;
  137. LOG_INFO("gapless: skip: %u samples: " FMT_u64 " delay: %u padding: %u", m->skip, m->samples, enc_delay, enc_padding);
  138. }
  139. }
  140. static decode_state mad_decode(void) {
  141. size_t bytes;
  142. bool eos = false;
  143. LOCK_S;
  144. bytes = min(_buf_used(streambuf), _buf_cont_read(streambuf));
  145. if (m->checktags) {
  146. if (m->checktags == 1) {
  147. m->consume = _check_id3_tag(bytes);
  148. m->checktags = 2;
  149. }
  150. if (m->consume) {
  151. u32_t consume = min(m->consume, bytes);
  152. LOG_DEBUG("consume: %u of %u", consume, m->consume);
  153. _buf_inc_readp(streambuf, consume);
  154. m->consume -= consume;
  155. UNLOCK_S;
  156. return DECODE_RUNNING;
  157. }
  158. if (m->checktags == 2) {
  159. if (!stream.meta_interval) {
  160. _check_lame_header(bytes);
  161. }
  162. m->checktags = 0;
  163. }
  164. }
  165. if (m->stream.next_frame && m->readbuf_len) {
  166. m->readbuf_len -= m->stream.next_frame - m->readbuf;
  167. memmove(m->readbuf, m->stream.next_frame, m->readbuf_len);
  168. }
  169. bytes = min(bytes, READBUF_SIZE - m->readbuf_len);
  170. memcpy(m->readbuf + m->readbuf_len, streambuf->readp, bytes);
  171. m->readbuf_len += bytes;
  172. _buf_inc_readp(streambuf, bytes);
  173. if (stream.state <= DISCONNECT && _buf_used(streambuf) == 0) {
  174. eos = true;
  175. LOG_DEBUG("end of stream");
  176. memset(m->readbuf + m->readbuf_len, 0, MAD_BUFFER_GUARD);
  177. m->readbuf_len += MAD_BUFFER_GUARD;
  178. }
  179. UNLOCK_S;
  180. MAD(m, stream_buffer, &m->stream, m->readbuf, m->readbuf_len);
  181. while (true) {
  182. size_t frames;
  183. s32_t *iptrl;
  184. s32_t *iptrr;
  185. unsigned max_frames;
  186. if (MAD(m, frame_decode, &m->frame, &m->stream) == -1) {
  187. decode_state ret;
  188. if (!eos && m->stream.error == MAD_ERROR_BUFLEN) {
  189. ret = DECODE_RUNNING;
  190. } else if (eos && (m->stream.error == MAD_ERROR_BUFLEN || m->stream.error == MAD_ERROR_LOSTSYNC
  191. || m->stream.error == MAD_ERROR_BADBITRATE)) {
  192. ret = DECODE_COMPLETE;
  193. } else if (!MAD_RECOVERABLE(m->stream.error)) {
  194. LOG_INFO("mad_frame_decode error: %s - stopping decoder", MAD(m, stream_errorstr, &m->stream));
  195. ret = DECODE_COMPLETE;
  196. } else {
  197. if (m->stream.error != m->last_error) {
  198. // suppress repeat error messages
  199. LOG_DEBUG("mad_frame_decode error: %s", MAD(m, stream_errorstr, &m->stream));
  200. }
  201. ret = DECODE_RUNNING;
  202. }
  203. m->last_error = m->stream.error;
  204. return ret;
  205. };
  206. MAD(m, synth_frame, &m->synth, &m->frame);
  207. if (decode.new_stream) {
  208. LOCK_O;
  209. LOG_INFO("setting track_start");
  210. output.next_sample_rate = decode_newstream(m->synth.pcm.samplerate, output.supported_rates);
  211. IF_DSD( output.next_fmt = PCM; )
  212. output.track_start = outputbuf->writep;
  213. if (output.fade_mode) _checkfade(true);
  214. decode.new_stream = false;
  215. UNLOCK_O;
  216. }
  217. LOCK_O_direct;
  218. IF_DIRECT(
  219. max_frames = _buf_space(outputbuf) / BYTES_PER_FRAME;
  220. );
  221. IF_PROCESS(
  222. max_frames = process.max_in_frames - process.in_frames;
  223. );
  224. if (m->synth.pcm.length > max_frames) {
  225. LOG_WARN("too many samples - dropping samples");
  226. m->synth.pcm.length = max_frames;
  227. }
  228. frames = m->synth.pcm.length;
  229. iptrl = m->synth.pcm.samples[0];
  230. iptrr = m->synth.pcm.samples[ m->synth.pcm.channels - 1 ];
  231. if (m->skip) {
  232. u32_t skip = min(m->skip, frames);
  233. LOG_DEBUG("gapless: skipping %u frames at start", skip);
  234. frames -= skip;
  235. m->skip -= skip;
  236. iptrl += skip;
  237. iptrr += skip;
  238. }
  239. if (m->samples) {
  240. if (m->samples < frames) {
  241. LOG_DEBUG("gapless: trimming %u frames from end", frames - m->samples);
  242. frames = (size_t)m->samples;
  243. }
  244. m->samples -= frames;
  245. if (m->samples > 0 && eos && !(m->stream.next_frame[0] == 0xff && (m->stream.next_frame[1] & 0xf0) == 0xf0)) {
  246. // this is the last frame to be decoded, but more samples expected so we must have skipped, remove padding
  247. // note this only works if the padding is less than one frame of 1152 bytes otherswise some gap will remain
  248. LOG_DEBUG("gapless: early end - trimming padding from end");
  249. if (frames >= m->padding) {
  250. frames -= m->padding;
  251. } else {
  252. frames = 0;
  253. }
  254. m->samples = 0;
  255. }
  256. }
  257. LOG_SDEBUG("write %u frames", frames);
  258. while (frames > 0) {
  259. size_t f, count;
  260. ISAMPLE_T *optr;
  261. IF_DIRECT(
  262. f = min(frames, _buf_cont_write(outputbuf) / BYTES_PER_FRAME);
  263. optr = (ISAMPLE_T *)outputbuf->writep;
  264. );
  265. IF_PROCESS(
  266. f = min(frames, process.max_in_frames - process.in_frames);
  267. optr = (ISAMPLE_T *)((u8_t *)process.inbuf + process.in_frames * BYTES_PER_FRAME);
  268. );
  269. count = f;
  270. while (count--) {
  271. *optr++ = scale(*iptrl++);
  272. *optr++ = scale(*iptrr++);
  273. }
  274. frames -= f;
  275. IF_DIRECT(
  276. _buf_inc_writep(outputbuf, f * BYTES_PER_FRAME);
  277. );
  278. IF_PROCESS(
  279. process.in_frames += f;
  280. );
  281. }
  282. UNLOCK_O_direct;
  283. }
  284. return eos ? DECODE_COMPLETE : DECODE_RUNNING;
  285. }
  286. static void mad_open(u8_t size, u8_t rate, u8_t chan, u8_t endianness) {
  287. if (!m->readbuf) {
  288. m->readbuf = malloc(READBUF_SIZE + MAD_BUFFER_GUARD);
  289. }
  290. m->checktags = 1;
  291. m->consume = 0;
  292. m->skip = MAD_DELAY;
  293. m->samples = 0;
  294. m->readbuf_len = 0;
  295. m->last_error = MAD_ERROR_NONE;
  296. MAD(m, stream_init, &m->stream);
  297. MAD(m, frame_init, &m->frame);
  298. MAD(m, synth_init, &m->synth);
  299. }
  300. static void mad_close(void) {
  301. mad_synth_finish(&m->synth); // macro only in current version
  302. MAD(m, frame_finish, &m->frame);
  303. MAD(m, stream_finish, &m->stream);
  304. free(m->readbuf);
  305. m->readbuf = NULL;
  306. }
  307. static bool load_mad() {
  308. #if !LINKALL
  309. void *handle = dlopen(LIBMAD, RTLD_NOW);
  310. char *err;
  311. if (!handle) {
  312. LOG_INFO("dlerror: %s", dlerror());
  313. return false;
  314. }
  315. m->mad_stream_init = dlsym(handle, "mad_stream_init");
  316. m->mad_frame_init = dlsym(handle, "mad_frame_init");
  317. m->mad_synth_init = dlsym(handle, "mad_synth_init");
  318. m->mad_frame_finish = dlsym(handle, "mad_frame_finish");
  319. m->mad_stream_finish = dlsym(handle, "mad_stream_finish");
  320. m->mad_stream_buffer = dlsym(handle, "mad_stream_buffer");
  321. m->mad_frame_decode = dlsym(handle, "mad_frame_decode");
  322. m->mad_synth_frame = dlsym(handle, "mad_synth_frame");
  323. m->mad_stream_errorstr = dlsym(handle, "mad_stream_errorstr");
  324. if ((err = dlerror()) != NULL) {
  325. LOG_INFO("dlerror: %s", err);
  326. return false;
  327. }
  328. LOG_INFO("loaded "LIBMAD);
  329. #endif
  330. return true;
  331. }
  332. struct codec *register_mad(void) {
  333. static struct codec ret = {
  334. 'm', // id
  335. "mp3", // types
  336. READBUF_SIZE, // min read
  337. 206800, // min space
  338. mad_open, // open
  339. mad_close, // close
  340. mad_decode, // decode
  341. };
  342. m = malloc(sizeof(struct mad));
  343. if (!m) {
  344. return NULL;
  345. }
  346. m->readbuf = NULL;
  347. m->readbuf_len = 0;
  348. if (!load_mad()) {
  349. return NULL;
  350. }
  351. LOG_INFO("using mad to decode mp3");
  352. return &ret;
  353. }