You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

572 lines
17KB

  1. /*
  2. * FLAC (Free Lossless Audio Codec) decoder
  3. * Copyright (c) 2003 Alex Beregszaszi
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav 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 GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * FLAC (Free Lossless Audio Codec) decoder
  24. * @author Alex Beregszaszi
  25. * @see http://flac.sourceforge.net/
  26. *
  27. * This decoder can be used in 1 of 2 ways: Either raw FLAC data can be fed
  28. * through, starting from the initial 'fLaC' signature; or by passing the
  29. * 34-byte streaminfo structure through avctx->extradata[_size] followed
  30. * by data starting with the 0xFFF8 marker.
  31. */
  32. #include <limits.h>
  33. #include "avcodec.h"
  34. #include "internal.h"
  35. #include "get_bits.h"
  36. #include "bytestream.h"
  37. #include "golomb_legacy.h"
  38. #include "flac.h"
  39. #include "flacdata.h"
  40. #include "flacdsp.h"
  41. typedef struct FLACContext {
  42. FLACSTREAMINFO
  43. AVCodecContext *avctx; ///< parent AVCodecContext
  44. GetBitContext gb; ///< GetBitContext initialized to start at the current frame
  45. int blocksize; ///< number of samples in the current frame
  46. int sample_shift; ///< shift required to make output samples 16-bit or 32-bit
  47. int ch_mode; ///< channel decorrelation type in the current frame
  48. int got_streaminfo; ///< indicates if the STREAMINFO has been read
  49. int32_t *decoded[FLAC_MAX_CHANNELS]; ///< decoded samples
  50. uint8_t *decoded_buffer;
  51. unsigned int decoded_buffer_size;
  52. FLACDSPContext dsp;
  53. } FLACContext;
  54. static int allocate_buffers(FLACContext *s);
  55. static void flac_set_bps(FLACContext *s)
  56. {
  57. enum AVSampleFormat req = s->avctx->request_sample_fmt;
  58. int need32 = s->bps > 16;
  59. int want32 = av_get_bytes_per_sample(req) > 2;
  60. int planar = av_sample_fmt_is_planar(req);
  61. if (need32 || want32) {
  62. if (planar)
  63. s->avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
  64. else
  65. s->avctx->sample_fmt = AV_SAMPLE_FMT_S32;
  66. s->sample_shift = 32 - s->bps;
  67. } else {
  68. if (planar)
  69. s->avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
  70. else
  71. s->avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  72. s->sample_shift = 16 - s->bps;
  73. }
  74. }
  75. static av_cold int flac_decode_init(AVCodecContext *avctx)
  76. {
  77. enum FLACExtradataFormat format;
  78. uint8_t *streaminfo;
  79. int ret;
  80. FLACContext *s = avctx->priv_data;
  81. s->avctx = avctx;
  82. /* for now, the raw FLAC header is allowed to be passed to the decoder as
  83. frame data instead of extradata. */
  84. if (!avctx->extradata)
  85. return 0;
  86. if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
  87. return AVERROR_INVALIDDATA;
  88. /* initialize based on the demuxer-supplied streamdata header */
  89. ff_flac_parse_streaminfo(avctx, (FLACStreaminfo *)s, streaminfo);
  90. ret = allocate_buffers(s);
  91. if (ret < 0)
  92. return ret;
  93. flac_set_bps(s);
  94. ff_flacdsp_init(&s->dsp, avctx->sample_fmt, s->bps);
  95. s->got_streaminfo = 1;
  96. return 0;
  97. }
  98. static void dump_headers(AVCodecContext *avctx, FLACStreaminfo *s)
  99. {
  100. av_log(avctx, AV_LOG_DEBUG, " Max Blocksize: %d\n", s->max_blocksize);
  101. av_log(avctx, AV_LOG_DEBUG, " Max Framesize: %d\n", s->max_framesize);
  102. av_log(avctx, AV_LOG_DEBUG, " Samplerate: %d\n", s->samplerate);
  103. av_log(avctx, AV_LOG_DEBUG, " Channels: %d\n", s->channels);
  104. av_log(avctx, AV_LOG_DEBUG, " Bits: %d\n", s->bps);
  105. }
  106. static int allocate_buffers(FLACContext *s)
  107. {
  108. int buf_size;
  109. buf_size = av_samples_get_buffer_size(NULL, s->channels, s->max_blocksize,
  110. AV_SAMPLE_FMT_S32P, 0);
  111. if (buf_size < 0)
  112. return buf_size;
  113. av_fast_malloc(&s->decoded_buffer, &s->decoded_buffer_size, buf_size);
  114. if (!s->decoded_buffer)
  115. return AVERROR(ENOMEM);
  116. return av_samples_fill_arrays((uint8_t **)s->decoded, NULL,
  117. s->decoded_buffer, s->channels,
  118. s->max_blocksize, AV_SAMPLE_FMT_S32P, 0);
  119. }
  120. /**
  121. * Parse the STREAMINFO from an inline header.
  122. * @param s the flac decoding context
  123. * @param buf input buffer, starting with the "fLaC" marker
  124. * @param buf_size buffer size
  125. * @return non-zero if metadata is invalid
  126. */
  127. static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
  128. {
  129. int metadata_type, metadata_size, ret;
  130. if (buf_size < FLAC_STREAMINFO_SIZE+8) {
  131. /* need more data */
  132. return 0;
  133. }
  134. flac_parse_block_header(&buf[4], NULL, &metadata_type, &metadata_size);
  135. if (metadata_type != FLAC_METADATA_TYPE_STREAMINFO ||
  136. metadata_size != FLAC_STREAMINFO_SIZE) {
  137. return AVERROR_INVALIDDATA;
  138. }
  139. ff_flac_parse_streaminfo(s->avctx, (FLACStreaminfo *)s, &buf[8]);
  140. ret = allocate_buffers(s);
  141. if (ret < 0)
  142. return ret;
  143. flac_set_bps(s);
  144. ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt, s->bps);
  145. s->got_streaminfo = 1;
  146. return 0;
  147. }
  148. /**
  149. * Determine the size of an inline header.
  150. * @param buf input buffer, starting with the "fLaC" marker
  151. * @param buf_size buffer size
  152. * @return number of bytes in the header, or 0 if more data is needed
  153. */
  154. static int get_metadata_size(const uint8_t *buf, int buf_size)
  155. {
  156. int metadata_last, metadata_size;
  157. const uint8_t *buf_end = buf + buf_size;
  158. buf += 4;
  159. do {
  160. if (buf_end - buf < 4)
  161. return 0;
  162. flac_parse_block_header(buf, &metadata_last, NULL, &metadata_size);
  163. buf += 4;
  164. if (buf_end - buf < metadata_size) {
  165. /* need more data in order to read the complete header */
  166. return 0;
  167. }
  168. buf += metadata_size;
  169. } while (!metadata_last);
  170. return buf_size - (buf_end - buf);
  171. }
  172. static int decode_residuals(FLACContext *s, int32_t *decoded, int pred_order)
  173. {
  174. int i, tmp, partition, method_type, rice_order;
  175. int rice_bits, rice_esc;
  176. int samples;
  177. method_type = get_bits(&s->gb, 2);
  178. if (method_type > 1) {
  179. av_log(s->avctx, AV_LOG_ERROR, "illegal residual coding method %d\n",
  180. method_type);
  181. return AVERROR_INVALIDDATA;
  182. }
  183. rice_order = get_bits(&s->gb, 4);
  184. samples= s->blocksize >> rice_order;
  185. if (pred_order > samples) {
  186. av_log(s->avctx, AV_LOG_ERROR, "invalid predictor order: %i > %i\n",
  187. pred_order, samples);
  188. return AVERROR_INVALIDDATA;
  189. }
  190. rice_bits = 4 + method_type;
  191. rice_esc = (1 << rice_bits) - 1;
  192. decoded += pred_order;
  193. i= pred_order;
  194. for (partition = 0; partition < (1 << rice_order); partition++) {
  195. tmp = get_bits(&s->gb, rice_bits);
  196. if (tmp == rice_esc) {
  197. tmp = get_bits(&s->gb, 5);
  198. for (; i < samples; i++)
  199. *decoded++ = get_sbits_long(&s->gb, tmp);
  200. } else {
  201. for (; i < samples; i++) {
  202. *decoded++ = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);
  203. }
  204. }
  205. i= 0;
  206. }
  207. return 0;
  208. }
  209. static int decode_subframe_fixed(FLACContext *s, int32_t *decoded,
  210. int pred_order, int bps)
  211. {
  212. const int blocksize = s->blocksize;
  213. int a, b, c, d, i, ret;
  214. /* warm up samples */
  215. for (i = 0; i < pred_order; i++) {
  216. decoded[i] = get_sbits_long(&s->gb, bps);
  217. }
  218. if ((ret = decode_residuals(s, decoded, pred_order)) < 0)
  219. return ret;
  220. if (pred_order > 0)
  221. a = decoded[pred_order-1];
  222. if (pred_order > 1)
  223. b = a - decoded[pred_order-2];
  224. if (pred_order > 2)
  225. c = b - decoded[pred_order-2] + decoded[pred_order-3];
  226. if (pred_order > 3)
  227. d = c - decoded[pred_order-2] + 2*decoded[pred_order-3] - decoded[pred_order-4];
  228. switch (pred_order) {
  229. case 0:
  230. break;
  231. case 1:
  232. for (i = pred_order; i < blocksize; i++)
  233. decoded[i] = a += decoded[i];
  234. break;
  235. case 2:
  236. for (i = pred_order; i < blocksize; i++)
  237. decoded[i] = a += b += decoded[i];
  238. break;
  239. case 3:
  240. for (i = pred_order; i < blocksize; i++)
  241. decoded[i] = a += b += c += decoded[i];
  242. break;
  243. case 4:
  244. for (i = pred_order; i < blocksize; i++)
  245. decoded[i] = a += b += c += d += decoded[i];
  246. break;
  247. default:
  248. av_log(s->avctx, AV_LOG_ERROR, "illegal pred order %d\n", pred_order);
  249. return AVERROR_INVALIDDATA;
  250. }
  251. return 0;
  252. }
  253. static int decode_subframe_lpc(FLACContext *s, int32_t *decoded, int pred_order,
  254. int bps)
  255. {
  256. int i, ret;
  257. int coeff_prec, qlevel;
  258. int coeffs[32];
  259. /* warm up samples */
  260. for (i = 0; i < pred_order; i++) {
  261. decoded[i] = get_sbits_long(&s->gb, bps);
  262. }
  263. coeff_prec = get_bits(&s->gb, 4) + 1;
  264. if (coeff_prec == 16) {
  265. av_log(s->avctx, AV_LOG_ERROR, "invalid coeff precision\n");
  266. return AVERROR_INVALIDDATA;
  267. }
  268. qlevel = get_sbits(&s->gb, 5);
  269. if (qlevel < 0) {
  270. av_log(s->avctx, AV_LOG_ERROR, "qlevel %d not supported, maybe buggy stream\n",
  271. qlevel);
  272. return AVERROR_INVALIDDATA;
  273. }
  274. for (i = 0; i < pred_order; i++) {
  275. coeffs[pred_order - i - 1] = get_sbits(&s->gb, coeff_prec);
  276. }
  277. if ((ret = decode_residuals(s, decoded, pred_order)) < 0)
  278. return ret;
  279. s->dsp.lpc(decoded, coeffs, pred_order, qlevel, s->blocksize);
  280. return 0;
  281. }
  282. static inline int decode_subframe(FLACContext *s, int channel)
  283. {
  284. int32_t *decoded = s->decoded[channel];
  285. int type, wasted = 0;
  286. int bps = s->bps;
  287. int i, tmp, ret;
  288. if (channel == 0) {
  289. if (s->ch_mode == FLAC_CHMODE_RIGHT_SIDE)
  290. bps++;
  291. } else {
  292. if (s->ch_mode == FLAC_CHMODE_LEFT_SIDE || s->ch_mode == FLAC_CHMODE_MID_SIDE)
  293. bps++;
  294. }
  295. if (get_bits1(&s->gb)) {
  296. av_log(s->avctx, AV_LOG_ERROR, "invalid subframe padding\n");
  297. return AVERROR_INVALIDDATA;
  298. }
  299. type = get_bits(&s->gb, 6);
  300. if (get_bits1(&s->gb)) {
  301. int left = get_bits_left(&s->gb);
  302. wasted = 1;
  303. if ( left < 0 ||
  304. (left < bps && !show_bits_long(&s->gb, left)) ||
  305. !show_bits_long(&s->gb, bps)) {
  306. av_log(s->avctx, AV_LOG_ERROR,
  307. "Invalid number of wasted bits > available bits (%d) - left=%d\n",
  308. bps, left);
  309. return AVERROR_INVALIDDATA;
  310. }
  311. while (!get_bits1(&s->gb))
  312. wasted++;
  313. bps -= wasted;
  314. }
  315. if (bps > 32) {
  316. avpriv_report_missing_feature(s->avctx, "Decorrelated bit depth > 32");
  317. return AVERROR_PATCHWELCOME;
  318. }
  319. //FIXME use av_log2 for types
  320. if (type == 0) {
  321. tmp = get_sbits_long(&s->gb, bps);
  322. for (i = 0; i < s->blocksize; i++)
  323. decoded[i] = tmp;
  324. } else if (type == 1) {
  325. for (i = 0; i < s->blocksize; i++)
  326. decoded[i] = get_sbits_long(&s->gb, bps);
  327. } else if ((type >= 8) && (type <= 12)) {
  328. if ((ret = decode_subframe_fixed(s, decoded, type & ~0x8, bps)) < 0)
  329. return ret;
  330. } else if (type >= 32) {
  331. if ((ret = decode_subframe_lpc(s, decoded, (type & ~0x20)+1, bps)) < 0)
  332. return ret;
  333. } else {
  334. av_log(s->avctx, AV_LOG_ERROR, "invalid coding type\n");
  335. return AVERROR_INVALIDDATA;
  336. }
  337. if (wasted) {
  338. int i;
  339. for (i = 0; i < s->blocksize; i++)
  340. decoded[i] <<= wasted;
  341. }
  342. return 0;
  343. }
  344. static int decode_frame(FLACContext *s)
  345. {
  346. int i, ret;
  347. GetBitContext *gb = &s->gb;
  348. FLACFrameInfo fi;
  349. if ((ret = ff_flac_decode_frame_header(s->avctx, gb, &fi, 0)) < 0) {
  350. av_log(s->avctx, AV_LOG_ERROR, "invalid frame header\n");
  351. return ret;
  352. }
  353. if (s->channels && fi.channels != s->channels && s->got_streaminfo) {
  354. s->channels = s->avctx->channels = fi.channels;
  355. ff_flac_set_channel_layout(s->avctx);
  356. ret = allocate_buffers(s);
  357. if (ret < 0)
  358. return ret;
  359. }
  360. s->channels = s->avctx->channels = fi.channels;
  361. if (!s->avctx->channel_layout)
  362. ff_flac_set_channel_layout(s->avctx);
  363. s->ch_mode = fi.ch_mode;
  364. if (!s->bps && !fi.bps) {
  365. av_log(s->avctx, AV_LOG_ERROR, "bps not found in STREAMINFO or frame header\n");
  366. return AVERROR_INVALIDDATA;
  367. }
  368. if (!fi.bps) {
  369. fi.bps = s->bps;
  370. } else if (s->bps && fi.bps != s->bps) {
  371. av_log(s->avctx, AV_LOG_ERROR, "switching bps mid-stream is not "
  372. "supported\n");
  373. return AVERROR_INVALIDDATA;
  374. }
  375. if (!s->bps) {
  376. s->bps = s->avctx->bits_per_raw_sample = fi.bps;
  377. flac_set_bps(s);
  378. }
  379. if (!s->max_blocksize)
  380. s->max_blocksize = FLAC_MAX_BLOCKSIZE;
  381. if (fi.blocksize > s->max_blocksize) {
  382. av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", fi.blocksize,
  383. s->max_blocksize);
  384. return AVERROR_INVALIDDATA;
  385. }
  386. s->blocksize = fi.blocksize;
  387. if (!s->samplerate && !fi.samplerate) {
  388. av_log(s->avctx, AV_LOG_ERROR, "sample rate not found in STREAMINFO"
  389. " or frame header\n");
  390. return AVERROR_INVALIDDATA;
  391. }
  392. if (fi.samplerate == 0)
  393. fi.samplerate = s->samplerate;
  394. s->samplerate = s->avctx->sample_rate = fi.samplerate;
  395. if (!s->got_streaminfo) {
  396. ret = allocate_buffers(s);
  397. if (ret < 0)
  398. return ret;
  399. ff_flacdsp_init(&s->dsp, s->avctx->sample_fmt, s->bps);
  400. s->got_streaminfo = 1;
  401. dump_headers(s->avctx, (FLACStreaminfo *)s);
  402. }
  403. // dump_headers(s->avctx, (FLACStreaminfo *)s);
  404. /* subframes */
  405. for (i = 0; i < s->channels; i++) {
  406. if ((ret = decode_subframe(s, i)) < 0)
  407. return ret;
  408. }
  409. align_get_bits(gb);
  410. /* frame footer */
  411. skip_bits(gb, 16); /* data crc */
  412. return 0;
  413. }
  414. static int flac_decode_frame(AVCodecContext *avctx, void *data,
  415. int *got_frame_ptr, AVPacket *avpkt)
  416. {
  417. AVFrame *frame = data;
  418. const uint8_t *buf = avpkt->data;
  419. int buf_size = avpkt->size;
  420. FLACContext *s = avctx->priv_data;
  421. int bytes_read = 0;
  422. int ret;
  423. *got_frame_ptr = 0;
  424. if (s->max_framesize == 0) {
  425. s->max_framesize =
  426. ff_flac_get_max_frame_size(s->max_blocksize ? s->max_blocksize : FLAC_MAX_BLOCKSIZE,
  427. FLAC_MAX_CHANNELS, 32);
  428. }
  429. /* check that there is at least the smallest decodable amount of data.
  430. this amount corresponds to the smallest valid FLAC frame possible.
  431. FF F8 69 02 00 00 9A 00 00 34 46 */
  432. if (buf_size < FLAC_MIN_FRAME_SIZE)
  433. return buf_size;
  434. /* check for inline header */
  435. if (AV_RB32(buf) == MKBETAG('f','L','a','C')) {
  436. if (!s->got_streaminfo && (ret = parse_streaminfo(s, buf, buf_size))) {
  437. av_log(s->avctx, AV_LOG_ERROR, "invalid header\n");
  438. return ret;
  439. }
  440. return get_metadata_size(buf, buf_size);
  441. }
  442. /* decode frame */
  443. init_get_bits(&s->gb, buf, buf_size*8);
  444. if ((ret = decode_frame(s)) < 0) {
  445. av_log(s->avctx, AV_LOG_ERROR, "decode_frame() failed\n");
  446. return ret;
  447. }
  448. bytes_read = (get_bits_count(&s->gb)+7)/8;
  449. /* get output buffer */
  450. frame->nb_samples = s->blocksize;
  451. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
  452. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  453. return ret;
  454. }
  455. s->dsp.decorrelate[s->ch_mode](frame->data, s->decoded, s->channels,
  456. s->blocksize, s->sample_shift);
  457. if (bytes_read > buf_size) {
  458. av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", bytes_read - buf_size);
  459. return AVERROR_INVALIDDATA;
  460. }
  461. if (bytes_read < buf_size) {
  462. av_log(s->avctx, AV_LOG_DEBUG, "underread: %d orig size: %d\n",
  463. buf_size - bytes_read, buf_size);
  464. }
  465. *got_frame_ptr = 1;
  466. return bytes_read;
  467. }
  468. static av_cold int flac_decode_close(AVCodecContext *avctx)
  469. {
  470. FLACContext *s = avctx->priv_data;
  471. av_freep(&s->decoded_buffer);
  472. return 0;
  473. }
  474. AVCodec ff_flac_decoder = {
  475. .name = "flac",
  476. .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
  477. .type = AVMEDIA_TYPE_AUDIO,
  478. .id = AV_CODEC_ID_FLAC,
  479. .priv_data_size = sizeof(FLACContext),
  480. .init = flac_decode_init,
  481. .close = flac_decode_close,
  482. .decode = flac_decode_frame,
  483. .capabilities = AV_CODEC_CAP_DR1,
  484. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16,
  485. AV_SAMPLE_FMT_S16P,
  486. AV_SAMPLE_FMT_S32,
  487. AV_SAMPLE_FMT_S32P,
  488. -1 },
  489. };