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.

515 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 a seektable with one frame
  173. if (avctx->extradata_size < 30)
  174. return AVERROR_INVALIDDATA;
  175. init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);
  176. if (show_bits_long(&s->gb, 32) == AV_RL32("TTA1"))
  177. {
  178. if (avctx->err_recognition & AV_EF_CRCCHECK) {
  179. s->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);
  180. tta_check_crc(s, avctx->extradata, 18);
  181. }
  182. /* signature */
  183. skip_bits_long(&s->gb, 32);
  184. s->format = get_bits(&s->gb, 16);
  185. if (s->format > 2) {
  186. av_log(avctx, AV_LOG_ERROR, "Invalid format\n");
  187. return AVERROR_INVALIDDATA;
  188. }
  189. if (s->format == FORMAT_ENCRYPTED) {
  190. if (!s->pass) {
  191. av_log(avctx, AV_LOG_ERROR, "Missing password for encrypted stream. Please use the -password option\n");
  192. return AVERROR(EINVAL);
  193. }
  194. AV_WL64(s->crc_pass, tta_check_crc64(s->pass));
  195. }
  196. avctx->channels = s->channels = get_bits(&s->gb, 16);
  197. if (s->channels > 1 && s->channels < 9)
  198. avctx->channel_layout = tta_channel_layouts[s->channels-2];
  199. avctx->bits_per_raw_sample = get_bits(&s->gb, 16);
  200. s->bps = (avctx->bits_per_raw_sample + 7) / 8;
  201. avctx->sample_rate = get_bits_long(&s->gb, 32);
  202. s->data_length = get_bits_long(&s->gb, 32);
  203. skip_bits_long(&s->gb, 32); // CRC32 of header
  204. if (s->channels == 0) {
  205. av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
  206. return AVERROR_INVALIDDATA;
  207. } else if (avctx->sample_rate == 0) {
  208. av_log(avctx, AV_LOG_ERROR, "Invalid samplerate\n");
  209. return AVERROR_INVALIDDATA;
  210. }
  211. switch(s->bps) {
  212. case 1: avctx->sample_fmt = AV_SAMPLE_FMT_U8; break;
  213. case 2:
  214. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  215. break;
  216. case 3:
  217. avctx->sample_fmt = AV_SAMPLE_FMT_S32;
  218. break;
  219. //case 4: avctx->sample_fmt = AV_SAMPLE_FMT_S32; break;
  220. default:
  221. av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported sample format.\n");
  222. return AVERROR_INVALIDDATA;
  223. }
  224. // prevent overflow
  225. if (avctx->sample_rate > 0x7FFFFFu) {
  226. av_log(avctx, AV_LOG_ERROR, "sample_rate too large\n");
  227. return AVERROR(EINVAL);
  228. }
  229. s->frame_length = 256 * avctx->sample_rate / 245;
  230. s->last_frame_length = s->data_length % s->frame_length;
  231. total_frames = s->data_length / s->frame_length +
  232. (s->last_frame_length ? 1 : 0);
  233. av_log(avctx, AV_LOG_DEBUG, "format: %d chans: %d bps: %d rate: %d block: %d\n",
  234. s->format, avctx->channels, avctx->bits_per_coded_sample, avctx->sample_rate,
  235. avctx->block_align);
  236. av_log(avctx, AV_LOG_DEBUG, "data_length: %d frame_length: %d last: %d total: %d\n",
  237. s->data_length, s->frame_length, s->last_frame_length, total_frames);
  238. // FIXME: seek table
  239. if (avctx->extradata_size <= 26 || total_frames > INT_MAX / 4 ||
  240. avctx->extradata_size - 26 < total_frames * 4)
  241. av_log(avctx, AV_LOG_WARNING, "Seek table missing or too small\n");
  242. else if (avctx->err_recognition & AV_EF_CRCCHECK) {
  243. if (tta_check_crc(s, avctx->extradata + 22, total_frames * 4))
  244. return AVERROR_INVALIDDATA;
  245. }
  246. skip_bits_long(&s->gb, 32 * total_frames);
  247. skip_bits_long(&s->gb, 32); // CRC32 of seektable
  248. if(s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))){
  249. av_log(avctx, AV_LOG_ERROR, "frame_length too large\n");
  250. return AVERROR_INVALIDDATA;
  251. }
  252. if (s->bps < 3) {
  253. s->decode_buffer = av_mallocz(sizeof(int32_t)*s->frame_length*s->channels);
  254. if (!s->decode_buffer)
  255. return AVERROR(ENOMEM);
  256. } else
  257. s->decode_buffer = NULL;
  258. s->ch_ctx = av_malloc(avctx->channels * sizeof(*s->ch_ctx));
  259. if (!s->ch_ctx) {
  260. av_freep(&s->decode_buffer);
  261. return AVERROR(ENOMEM);
  262. }
  263. } else {
  264. av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");
  265. return AVERROR_INVALIDDATA;
  266. }
  267. return 0;
  268. }
  269. static int tta_decode_frame(AVCodecContext *avctx, void *data,
  270. int *got_frame_ptr, AVPacket *avpkt)
  271. {
  272. AVFrame *frame = data;
  273. const uint8_t *buf = avpkt->data;
  274. int buf_size = avpkt->size;
  275. TTAContext *s = avctx->priv_data;
  276. int i, ret;
  277. int cur_chan = 0, framelen = s->frame_length;
  278. int32_t *p;
  279. if (avctx->err_recognition & AV_EF_CRCCHECK) {
  280. if (buf_size < 4 || tta_check_crc(s, buf, buf_size - 4))
  281. return AVERROR_INVALIDDATA;
  282. }
  283. init_get_bits(&s->gb, buf, buf_size*8);
  284. /* get output buffer */
  285. frame->nb_samples = framelen;
  286. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
  287. return ret;
  288. // decode directly to output buffer for 24-bit sample format
  289. if (s->bps == 3)
  290. s->decode_buffer = (int32_t *)frame->data[0];
  291. // init per channel states
  292. for (i = 0; i < s->channels; i++) {
  293. s->ch_ctx[i].predictor = 0;
  294. ttafilter_init(s, &s->ch_ctx[i].filter, ttafilter_configs[s->bps-1]);
  295. rice_init(&s->ch_ctx[i].rice, 10, 10);
  296. }
  297. i = 0;
  298. for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++) {
  299. int32_t *predictor = &s->ch_ctx[cur_chan].predictor;
  300. TTAFilter *filter = &s->ch_ctx[cur_chan].filter;
  301. TTARice *rice = &s->ch_ctx[cur_chan].rice;
  302. uint32_t unary, depth, k;
  303. int32_t value;
  304. unary = tta_get_unary(&s->gb);
  305. if (unary == 0) {
  306. depth = 0;
  307. k = rice->k0;
  308. } else {
  309. depth = 1;
  310. k = rice->k1;
  311. unary--;
  312. }
  313. if (get_bits_left(&s->gb) < k) {
  314. ret = AVERROR_INVALIDDATA;
  315. goto error;
  316. }
  317. if (k) {
  318. if (k > MIN_CACHE_BITS) {
  319. ret = AVERROR_INVALIDDATA;
  320. goto error;
  321. }
  322. value = (unary << k) + get_bits(&s->gb, k);
  323. } else
  324. value = unary;
  325. // FIXME: copy paste from original
  326. switch (depth) {
  327. case 1:
  328. rice->sum1 += value - (rice->sum1 >> 4);
  329. if (rice->k1 > 0 && rice->sum1 < shift_16[rice->k1])
  330. rice->k1--;
  331. else if(rice->sum1 > shift_16[rice->k1 + 1])
  332. rice->k1++;
  333. value += shift_1[rice->k0];
  334. default:
  335. rice->sum0 += value - (rice->sum0 >> 4);
  336. if (rice->k0 > 0 && rice->sum0 < shift_16[rice->k0])
  337. rice->k0--;
  338. else if(rice->sum0 > shift_16[rice->k0 + 1])
  339. rice->k0++;
  340. }
  341. // extract coded value
  342. *p = 1 + ((value >> 1) ^ ((value & 1) - 1));
  343. // run hybrid filter
  344. ttafilter_process(filter, p);
  345. // fixed order prediction
  346. #define PRED(x, k) (int32_t)((((uint64_t)x << k) - x) >> k)
  347. switch (s->bps) {
  348. case 1: *p += PRED(*predictor, 4); break;
  349. case 2:
  350. case 3: *p += PRED(*predictor, 5); break;
  351. case 4: *p += *predictor; break;
  352. }
  353. *predictor = *p;
  354. // flip channels
  355. if (cur_chan < (s->channels-1))
  356. cur_chan++;
  357. else {
  358. // decorrelate in case of multiple channels
  359. if (s->channels > 1) {
  360. int32_t *r = p - 1;
  361. for (*p += *r / 2; r > p - s->channels; r--)
  362. *r = *(r + 1) - *r;
  363. }
  364. cur_chan = 0;
  365. i++;
  366. // check for last frame
  367. if (i == s->last_frame_length && get_bits_left(&s->gb) / 8 == 4) {
  368. frame->nb_samples = framelen = s->last_frame_length;
  369. break;
  370. }
  371. }
  372. }
  373. align_get_bits(&s->gb);
  374. if (get_bits_left(&s->gb) < 32) {
  375. ret = AVERROR_INVALIDDATA;
  376. goto error;
  377. }
  378. skip_bits_long(&s->gb, 32); // frame crc
  379. // convert to output buffer
  380. switch (s->bps) {
  381. case 1: {
  382. uint8_t *samples = (uint8_t *)frame->data[0];
  383. for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
  384. *samples++ = *p + 0x80;
  385. break;
  386. }
  387. case 2: {
  388. int16_t *samples = (int16_t *)frame->data[0];
  389. for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
  390. *samples++ = *p;
  391. break;
  392. }
  393. case 3: {
  394. // shift samples for 24-bit sample format
  395. int32_t *samples = (int32_t *)frame->data[0];
  396. for (p = s->decode_buffer; p < s->decode_buffer + (framelen * s->channels); p++)
  397. *samples++ <<= 8;
  398. // reset decode buffer
  399. s->decode_buffer = NULL;
  400. break;
  401. }
  402. }
  403. *got_frame_ptr = 1;
  404. return buf_size;
  405. error:
  406. // reset decode buffer
  407. if (s->bps == 3)
  408. s->decode_buffer = NULL;
  409. return ret;
  410. }
  411. static av_cold int tta_decode_close(AVCodecContext *avctx) {
  412. TTAContext *s = avctx->priv_data;
  413. if (s->bps < 3)
  414. av_free(s->decode_buffer);
  415. s->decode_buffer = NULL;
  416. av_freep(&s->ch_ctx);
  417. return 0;
  418. }
  419. #define OFFSET(x) offsetof(TTAContext, x)
  420. #define DEC (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
  421. static const AVOption options[] = {
  422. { "password", "Set decoding password", OFFSET(pass), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, DEC },
  423. { NULL },
  424. };
  425. static const AVClass tta_decoder_class = {
  426. .class_name = "TTA Decoder",
  427. .item_name = av_default_item_name,
  428. .option = options,
  429. .version = LIBAVUTIL_VERSION_INT,
  430. };
  431. AVCodec ff_tta_decoder = {
  432. .name = "tta",
  433. .type = AVMEDIA_TYPE_AUDIO,
  434. .id = AV_CODEC_ID_TTA,
  435. .priv_data_size = sizeof(TTAContext),
  436. .init = tta_decode_init,
  437. .close = tta_decode_close,
  438. .decode = tta_decode_frame,
  439. .capabilities = CODEC_CAP_DR1,
  440. .long_name = NULL_IF_CONFIG_SMALL("TTA (True Audio)"),
  441. .priv_class = &tta_decoder_class,
  442. };