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.

518 lines
16KB

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