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.

501 lines
15KB

  1. /*
  2. * TTA (The Lossless True Audio) decoder
  3. * Copyright (c) 2006 Alex Beregszaszi
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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. * TTA (The Lossless True Audio) decoder
  24. * @see http://www.true-audio.com/
  25. * @see http://tta.corecodec.org/
  26. * @author Alex Beregszaszi
  27. */
  28. #define BITSTREAM_READER_LE
  29. #include <limits.h>
  30. #include "avcodec.h"
  31. #include "get_bits.h"
  32. #include "internal.h"
  33. #include "libavutil/crc.h"
  34. #include "libavutil/intreadwrite.h"
  35. #include "libavutil/opt.h"
  36. #define FORMAT_SIMPLE 1
  37. #define FORMAT_ENCRYPTED 2
  38. #define MAX_ORDER 16
  39. typedef struct TTAFilter {
  40. int32_t shift, round, error;
  41. int32_t qm[MAX_ORDER];
  42. int32_t dx[MAX_ORDER];
  43. int32_t dl[MAX_ORDER];
  44. } TTAFilter;
  45. typedef struct TTARice {
  46. uint32_t k0, k1, sum0, sum1;
  47. } TTARice;
  48. typedef struct TTAChannel {
  49. int32_t predictor;
  50. TTAFilter filter;
  51. TTARice rice;
  52. } TTAChannel;
  53. typedef struct TTAContext {
  54. AVClass *class;
  55. AVCodecContext *avctx;
  56. GetBitContext gb;
  57. const AVCRC *crc_table;
  58. int format, channels, bps;
  59. unsigned data_length;
  60. int frame_length, last_frame_length;
  61. int32_t *decode_buffer;
  62. uint8_t crc_pass[8];
  63. uint8_t *pass;
  64. TTAChannel *ch_ctx;
  65. } TTAContext;
  66. static const uint32_t shift_1[] = {
  67. 0x00000001, 0x00000002, 0x00000004, 0x00000008,
  68. 0x00000010, 0x00000020, 0x00000040, 0x00000080,
  69. 0x00000100, 0x00000200, 0x00000400, 0x00000800,
  70. 0x00001000, 0x00002000, 0x00004000, 0x00008000,
  71. 0x00010000, 0x00020000, 0x00040000, 0x00080000,
  72. 0x00100000, 0x00200000, 0x00400000, 0x00800000,
  73. 0x01000000, 0x02000000, 0x04000000, 0x08000000,
  74. 0x10000000, 0x20000000, 0x40000000, 0x80000000,
  75. 0x80000000, 0x80000000, 0x80000000, 0x80000000,
  76. 0x80000000, 0x80000000, 0x80000000, 0x80000000
  77. };
  78. static const uint32_t * const shift_16 = shift_1 + 4;
  79. static const int32_t ttafilter_configs[4] = {
  80. 10,
  81. 9,
  82. 10,
  83. 12
  84. };
  85. static void ttafilter_init(TTAContext *s, TTAFilter *c, int32_t shift) {
  86. memset(c, 0, sizeof(TTAFilter));
  87. if (s->format == FORMAT_ENCRYPTED) {
  88. int i;
  89. for (i = 0; i < 8; i++)
  90. c->qm[i] = sign_extend(s->crc_pass[i], 8);
  91. }
  92. c->shift = shift;
  93. c->round = shift_1[shift-1];
  94. // c->round = 1 << (shift - 1);
  95. }
  96. static inline void ttafilter_process(TTAFilter *c, int32_t *in)
  97. {
  98. register int32_t *dl = c->dl, *qm = c->qm, *dx = c->dx, sum = c->round;
  99. if (c->error < 0) {
  100. qm[0] -= dx[0]; qm[1] -= dx[1]; qm[2] -= dx[2]; qm[3] -= dx[3];
  101. qm[4] -= dx[4]; qm[5] -= dx[5]; qm[6] -= dx[6]; qm[7] -= dx[7];
  102. } else if (c->error > 0) {
  103. qm[0] += dx[0]; qm[1] += dx[1]; qm[2] += dx[2]; qm[3] += dx[3];
  104. qm[4] += dx[4]; qm[5] += dx[5]; qm[6] += dx[6]; qm[7] += dx[7];
  105. }
  106. sum += dl[0] * qm[0] + dl[1] * qm[1] + dl[2] * qm[2] + dl[3] * qm[3] +
  107. dl[4] * qm[4] + dl[5] * qm[5] + dl[6] * qm[6] + dl[7] * qm[7];
  108. dx[0] = dx[1]; dx[1] = dx[2]; dx[2] = dx[3]; dx[3] = dx[4];
  109. dl[0] = dl[1]; dl[1] = dl[2]; dl[2] = dl[3]; dl[3] = dl[4];
  110. dx[4] = ((dl[4] >> 30) | 1);
  111. dx[5] = ((dl[5] >> 30) | 2) & ~1;
  112. dx[6] = ((dl[6] >> 30) | 2) & ~1;
  113. dx[7] = ((dl[7] >> 30) | 4) & ~3;
  114. c->error = *in;
  115. *in += (sum >> c->shift);
  116. dl[4] = -dl[5]; dl[5] = -dl[6];
  117. dl[6] = *in - dl[7]; dl[7] = *in;
  118. dl[5] += dl[6]; dl[4] += dl[5];
  119. }
  120. static void rice_init(TTARice *c, uint32_t k0, uint32_t k1)
  121. {
  122. c->k0 = k0;
  123. c->k1 = k1;
  124. c->sum0 = shift_16[k0];
  125. c->sum1 = shift_16[k1];
  126. }
  127. static int tta_get_unary(GetBitContext *gb)
  128. {
  129. int ret = 0;
  130. // count ones
  131. while (get_bits_left(gb) > 0 && get_bits1(gb))
  132. ret++;
  133. return ret;
  134. }
  135. static const int64_t tta_channel_layouts[7] = {
  136. AV_CH_LAYOUT_STEREO,
  137. AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY,
  138. AV_CH_LAYOUT_QUAD,
  139. 0,
  140. AV_CH_LAYOUT_5POINT1_BACK,
  141. AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER,
  142. AV_CH_LAYOUT_7POINT1_WIDE
  143. };
  144. static int tta_check_crc(TTAContext *s, const uint8_t *buf, int buf_size)
  145. {
  146. uint32_t crc, CRC;
  147. CRC = AV_RL32(buf + buf_size);
  148. crc = av_crc(s->crc_table, 0xFFFFFFFFU, buf, buf_size);
  149. if (CRC != (crc ^ 0xFFFFFFFFU)) {
  150. av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
  151. return AVERROR_INVALIDDATA;
  152. }
  153. return 0;
  154. }
  155. static uint64_t tta_check_crc64(uint8_t *pass)
  156. {
  157. uint64_t crc = UINT64_MAX, poly = 0x42F0E1EBA9EA3693U;
  158. uint8_t *end = pass + strlen(pass);
  159. int i;
  160. while (pass < end) {
  161. crc ^= (uint64_t)*pass++ << 56;
  162. for (i = 0; i < 8; i++)
  163. crc = (crc << 1) ^ (poly & (((int64_t) crc) >> 63));
  164. }
  165. return crc ^ UINT64_MAX;
  166. }
  167. static av_cold int tta_decode_init(AVCodecContext * avctx)
  168. {
  169. TTAContext *s = avctx->priv_data;
  170. int total_frames;
  171. s->avctx = avctx;
  172. // 30bytes includes TTA1 header
  173. if (avctx->extradata_size < 22)
  174. return AVERROR_INVALIDDATA;
  175. s->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
  176. init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
  177. if (show_bits_long(&s->gb, 32) == AV_RL32("TTA1"))
  178. {
  179. /* signature */
  180. skip_bits_long(&s->gb, 32);
  181. s->format = get_bits(&s->gb, 16);
  182. if (s->format > 2) {
  183. av_log(avctx, AV_LOG_ERROR, "Invalid format\n");
  184. return AVERROR_INVALIDDATA;
  185. }
  186. if (s->format == FORMAT_ENCRYPTED) {
  187. if (!s->pass) {
  188. av_log(avctx, AV_LOG_ERROR, "Missing password for encrypted stream. Please use the -password option\n");
  189. return AVERROR(EINVAL);
  190. }
  191. AV_WL64(s->crc_pass, tta_check_crc64(s->pass));
  192. }
  193. avctx->channels = s->channels = get_bits(&s->gb, 16);
  194. if (s->channels > 1 && s->channels < 9)
  195. avctx->channel_layout = tta_channel_layouts[s->channels-2];
  196. avctx->bits_per_raw_sample = get_bits(&s->gb, 16);
  197. s->bps = (avctx->bits_per_raw_sample + 7) / 8;
  198. avctx->sample_rate = get_bits_long(&s->gb, 32);
  199. s->data_length = get_bits_long(&s->gb, 32);
  200. skip_bits_long(&s->gb, 32); // CRC32 of header
  201. if (s->channels == 0) {
  202. av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
  203. return AVERROR_INVALIDDATA;
  204. } else if (avctx->sample_rate == 0) {
  205. av_log(avctx, AV_LOG_ERROR, "Invalid samplerate\n");
  206. return AVERROR_INVALIDDATA;
  207. }
  208. switch(s->bps) {
  209. case 1: avctx->sample_fmt = AV_SAMPLE_FMT_U8; break;
  210. case 2:
  211. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  212. break;
  213. case 3:
  214. avctx->sample_fmt = AV_SAMPLE_FMT_S32;
  215. break;
  216. //case 4: avctx->sample_fmt = AV_SAMPLE_FMT_S32; break;
  217. default:
  218. av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported sample format.\n");
  219. return AVERROR_INVALIDDATA;
  220. }
  221. // prevent overflow
  222. if (avctx->sample_rate > 0x7FFFFFu) {
  223. av_log(avctx, AV_LOG_ERROR, "sample_rate too large\n");
  224. return AVERROR(EINVAL);
  225. }
  226. s->frame_length = 256 * avctx->sample_rate / 245;
  227. s->last_frame_length = s->data_length % s->frame_length;
  228. total_frames = s->data_length / s->frame_length +
  229. (s->last_frame_length ? 1 : 0);
  230. av_log(avctx, AV_LOG_DEBUG, "format: %d chans: %d bps: %d rate: %d block: %d\n",
  231. s->format, avctx->channels, avctx->bits_per_coded_sample, avctx->sample_rate,
  232. avctx->block_align);
  233. av_log(avctx, AV_LOG_DEBUG, "data_length: %d frame_length: %d last: %d total: %d\n",
  234. s->data_length, s->frame_length, s->last_frame_length, total_frames);
  235. if(s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))){
  236. av_log(avctx, AV_LOG_ERROR, "frame_length too large\n");
  237. return AVERROR_INVALIDDATA;
  238. }
  239. if (s->bps < 3) {
  240. s->decode_buffer = av_mallocz(sizeof(int32_t)*s->frame_length*s->channels);
  241. if (!s->decode_buffer)
  242. return AVERROR(ENOMEM);
  243. } else
  244. s->decode_buffer = NULL;
  245. s->ch_ctx = av_malloc(avctx->channels * sizeof(*s->ch_ctx));
  246. if (!s->ch_ctx) {
  247. av_freep(&s->decode_buffer);
  248. return AVERROR(ENOMEM);
  249. }
  250. } else {
  251. av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");
  252. return AVERROR_INVALIDDATA;
  253. }
  254. return 0;
  255. }
  256. static int tta_decode_frame(AVCodecContext *avctx, void *data,
  257. int *got_frame_ptr, AVPacket *avpkt)
  258. {
  259. AVFrame *frame = data;
  260. const uint8_t *buf = avpkt->data;
  261. int buf_size = avpkt->size;
  262. TTAContext *s = avctx->priv_data;
  263. int i, ret;
  264. int cur_chan = 0, framelen = s->frame_length;
  265. int32_t *p;
  266. if (avctx->err_recognition & AV_EF_CRCCHECK) {
  267. if (buf_size < 4 || tta_check_crc(s, buf, buf_size - 4))
  268. return AVERROR_INVALIDDATA;
  269. }
  270. if ((ret = init_get_bits8(&s->gb, avpkt->data, avpkt->size)) < 0)
  271. return ret;
  272. /* get output buffer */
  273. frame->nb_samples = framelen;
  274. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
  275. return ret;
  276. // decode directly to output buffer for 24-bit sample format
  277. if (s->bps == 3)
  278. s->decode_buffer = (int32_t *)frame->data[0];
  279. // init per channel states
  280. for (i = 0; i < s->channels; i++) {
  281. s->ch_ctx[i].predictor = 0;
  282. ttafilter_init(s, &s->ch_ctx[i].filter, ttafilter_configs[s->bps-1]);
  283. rice_init(&s->ch_ctx[i].rice, 10, 10);
  284. }
  285. i = 0;
  286. for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {
  287. int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
  288. TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
  289. TTARice *rice = &s->ch_ctx[cur_chan].rice;
  290. uint32_t unary, depth, k;
  291. int32_t value;
  292. unary = tta_get_unary(&s->gb);
  293. if (unary == 0) {
  294. depth = 0;
  295. k = rice->k0;
  296. } else {
  297. depth = 1;
  298. k = rice->k1;
  299. unary--;
  300. }
  301. if (get_bits_left(&s->gb) < k) {
  302. ret = AVERROR_INVALIDDATA;
  303. goto error;
  304. }
  305. if (k) {
  306. if (k > MIN_CACHE_BITS) {
  307. ret = AVERROR_INVALIDDATA;
  308. goto error;
  309. }
  310. value = (unary << k) + get_bits(&s->gb, k);
  311. } else
  312. value = unary;
  313. // FIXME: copy paste from original
  314. switch (depth) {
  315. case 1:
  316. rice->sum1 += value - (rice->sum1 >> 4);
  317. if (rice->k1 > 0 && rice->sum1 < shift_16[rice->k1])
  318. rice->k1--;
  319. else if(rice->sum1 > shift_16[rice->k1 + 1])
  320. rice->k1++;
  321. value += shift_1[rice->k0];
  322. default:
  323. rice->sum0 += value - (rice->sum0 >> 4);
  324. if (rice->k0 > 0 && rice->sum0 < shift_16[rice->k0])
  325. rice->k0--;
  326. else if(rice->sum0 > shift_16[rice->k0 + 1])
  327. rice->k0++;
  328. }
  329. // extract coded value
  330. *p = 1 + ((value >> 1) ^ ((value & 1) - 1));
  331. // run hybrid filter
  332. ttafilter_process(filter, p);
  333. // fixed order prediction
  334. #define PRED(x, k) (int32_t)((((uint64_t)x << k) - x) >> k)
  335. switch (s->bps) {
  336. case 1: *p += PRED(*predictor, 4); break;
  337. case 2:
  338. case 3: *p += PRED(*predictor, 5); break;
  339. case 4: *p += *predictor; break;
  340. }
  341. *predictor = *p;
  342. // flip channels
  343. if (cur_chan < (s->channels-1))
  344. cur_chan++;
  345. else {
  346. // decorrelate in case of multiple channels
  347. if (s->channels > 1) {
  348. int32_t *r = p - 1;
  349. for (*p += *r / 2; r > p - s->channels; r--)
  350. *r = *(r + 1) - *r;
  351. }
  352. cur_chan = 0;
  353. i++;
  354. // check for last frame
  355. if (i == s->last_frame_length && get_bits_left(&s->gb) / 8 == 4) {
  356. frame->nb_samples = framelen = s->last_frame_length;
  357. break;
  358. }
  359. }
  360. }
  361. align_get_bits(&s->gb);
  362. if (get_bits_left(&s->gb) < 32) {
  363. ret = AVERROR_INVALIDDATA;
  364. goto error;
  365. }
  366. skip_bits_long(&s->gb, 32); // frame crc
  367. // convert to output buffer
  368. switch (s->bps) {
  369. case 1: {
  370. uint8_t *samples = (uint8_t *)frame->data[0];
  371. for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
  372. *samples++ = *p + 0x80;
  373. break;
  374. }
  375. case 2: {
  376. int16_t *samples = (int16_t *)frame->data[0];
  377. for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
  378. *samples++ = *p;
  379. break;
  380. }
  381. case 3: {
  382. // shift samples for 24-bit sample format
  383. int32_t *samples = (int32_t *)frame->data[0];
  384. for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
  385. *samples++ <<= 8;
  386. // reset decode buffer
  387. s->decode_buffer = NULL;
  388. break;
  389. }
  390. }
  391. *got_frame_ptr = 1;
  392. return buf_size;
  393. error:
  394. // reset decode buffer
  395. if (s->bps == 3)
  396. s->decode_buffer = NULL;
  397. return ret;
  398. }
  399. static av_cold int tta_decode_close(AVCodecContext *avctx) {
  400. TTAContext *s = avctx->priv_data;
  401. if (s->bps < 3)
  402. av_free(s->decode_buffer);
  403. s->decode_buffer = NULL;
  404. av_freep(&s->ch_ctx);
  405. return 0;
  406. }
  407. #define OFFSET(x) offsetof(TTAContext, x)
  408. #define DEC (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
  409. static const AVOption options[] = {
  410. { "password", "Set decoding password", OFFSET(pass), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, DEC },
  411. { NULL },
  412. };
  413. static const AVClass tta_decoder_class = {
  414. .class_name = "TTA Decoder",
  415. .item_name = av_default_item_name,
  416. .option = options,
  417. .version = LIBAVUTIL_VERSION_INT,
  418. };
  419. AVCodec ff_tta_decoder = {
  420. .name = "tta",
  421. .type = AVMEDIA_TYPE_AUDIO,
  422. .id = AV_CODEC_ID_TTA,
  423. .priv_data_size = sizeof(TTAContext),
  424. .init = tta_decode_init,
  425. .close = tta_decode_close,
  426. .decode = tta_decode_frame,
  427. .capabilities = CODEC_CAP_DR1,
  428. .long_name = NULL_IF_CONFIG_SMALL("TTA (True Audio)"),
  429. .priv_class = &tta_decoder_class,
  430. };