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.

644 lines
19KB

  1. /*
  2. * Shorten decoder
  3. * Copyright (c) 2005 Jeff Muizelaar
  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. * Shorten decoder
  24. * @author Jeff Muizelaar
  25. *
  26. */
  27. #include <limits.h>
  28. #include "avcodec.h"
  29. #include "bytestream.h"
  30. #include "get_bits.h"
  31. #include "golomb.h"
  32. #include "internal.h"
  33. #define MAX_CHANNELS 8
  34. #define MAX_BLOCKSIZE 65535
  35. #define OUT_BUFFER_SIZE 16384
  36. #define ULONGSIZE 2
  37. #define WAVE_FORMAT_PCM 0x0001
  38. #define DEFAULT_BLOCK_SIZE 256
  39. #define TYPESIZE 4
  40. #define CHANSIZE 0
  41. #define LPCQSIZE 2
  42. #define ENERGYSIZE 3
  43. #define BITSHIFTSIZE 2
  44. #define TYPE_S16HL 3
  45. #define TYPE_S16LH 5
  46. #define NWRAP 3
  47. #define NSKIPSIZE 1
  48. #define LPCQUANT 5
  49. #define V2LPCQOFFSET (1 << LPCQUANT)
  50. #define FNSIZE 2
  51. #define FN_DIFF0 0
  52. #define FN_DIFF1 1
  53. #define FN_DIFF2 2
  54. #define FN_DIFF3 3
  55. #define FN_QUIT 4
  56. #define FN_BLOCKSIZE 5
  57. #define FN_BITSHIFT 6
  58. #define FN_QLPC 7
  59. #define FN_ZERO 8
  60. #define FN_VERBATIM 9
  61. /** indicates if the FN_* command is audio or non-audio */
  62. static const uint8_t is_audio_command[10] = { 1, 1, 1, 1, 0, 0, 0, 1, 1, 0 };
  63. #define VERBATIM_CKSIZE_SIZE 5
  64. #define VERBATIM_BYTE_SIZE 8
  65. #define CANONICAL_HEADER_SIZE 44
  66. typedef struct ShortenContext {
  67. AVCodecContext *avctx;
  68. GetBitContext gb;
  69. int min_framesize, max_framesize;
  70. int channels;
  71. int32_t *decoded[MAX_CHANNELS];
  72. int32_t *decoded_base[MAX_CHANNELS];
  73. int32_t *offset[MAX_CHANNELS];
  74. int *coeffs;
  75. uint8_t *bitstream;
  76. int bitstream_size;
  77. int bitstream_index;
  78. unsigned int allocated_bitstream_size;
  79. int header_size;
  80. uint8_t header[OUT_BUFFER_SIZE];
  81. int version;
  82. int cur_chan;
  83. int bitshift;
  84. int nmean;
  85. int internal_ftype;
  86. int nwrap;
  87. int blocksize;
  88. int bitindex;
  89. int32_t lpcqoffset;
  90. int got_header;
  91. int got_quit_command;
  92. } ShortenContext;
  93. static av_cold int shorten_decode_init(AVCodecContext * avctx)
  94. {
  95. ShortenContext *s = avctx->priv_data;
  96. s->avctx = avctx;
  97. avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
  98. return 0;
  99. }
  100. static int allocate_buffers(ShortenContext *s)
  101. {
  102. int i, chan;
  103. int *coeffs;
  104. void *tmp_ptr;
  105. for (chan=0; chan<s->channels; chan++) {
  106. if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
  107. av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
  108. return -1;
  109. }
  110. if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
  111. av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
  112. return -1;
  113. }
  114. tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
  115. if (!tmp_ptr)
  116. return AVERROR(ENOMEM);
  117. s->offset[chan] = tmp_ptr;
  118. tmp_ptr = av_realloc(s->decoded_base[chan], (s->blocksize + s->nwrap) *
  119. sizeof(s->decoded_base[0][0]));
  120. if (!tmp_ptr)
  121. return AVERROR(ENOMEM);
  122. s->decoded_base[chan] = tmp_ptr;
  123. for (i=0; i<s->nwrap; i++)
  124. s->decoded_base[chan][i] = 0;
  125. s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
  126. }
  127. coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
  128. if (!coeffs)
  129. return AVERROR(ENOMEM);
  130. s->coeffs = coeffs;
  131. return 0;
  132. }
  133. static inline unsigned int get_uint(ShortenContext *s, int k)
  134. {
  135. if (s->version != 0)
  136. k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
  137. return get_ur_golomb_shorten(&s->gb, k);
  138. }
  139. static void fix_bitshift(ShortenContext *s, int32_t *buffer)
  140. {
  141. int i;
  142. if (s->bitshift != 0)
  143. for (i = 0; i < s->blocksize; i++)
  144. buffer[i] <<= s->bitshift;
  145. }
  146. static int init_offset(ShortenContext *s)
  147. {
  148. int32_t mean = 0;
  149. int chan, i;
  150. int nblock = FFMAX(1, s->nmean);
  151. /* initialise offset */
  152. switch (s->internal_ftype)
  153. {
  154. case TYPE_S16HL:
  155. case TYPE_S16LH:
  156. mean = 0;
  157. break;
  158. default:
  159. av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
  160. return AVERROR_INVALIDDATA;
  161. }
  162. for (chan = 0; chan < s->channels; chan++)
  163. for (i = 0; i < nblock; i++)
  164. s->offset[chan][i] = mean;
  165. return 0;
  166. }
  167. static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
  168. int header_size)
  169. {
  170. int len;
  171. short wave_format;
  172. if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
  173. av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
  174. return -1;
  175. }
  176. header += 4; /* chunk size */;
  177. if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
  178. av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
  179. return -1;
  180. }
  181. while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
  182. len = bytestream_get_le32(&header);
  183. header += len;
  184. }
  185. len = bytestream_get_le32(&header);
  186. if (len < 16) {
  187. av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
  188. return -1;
  189. }
  190. wave_format = bytestream_get_le16(&header);
  191. switch (wave_format) {
  192. case WAVE_FORMAT_PCM:
  193. break;
  194. default:
  195. av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
  196. return -1;
  197. }
  198. header += 2; // skip channels (already got from shorten header)
  199. avctx->sample_rate = bytestream_get_le32(&header);
  200. header += 4; // skip bit rate (represents original uncompressed bit rate)
  201. header += 2; // skip block align (not needed)
  202. avctx->bits_per_coded_sample = bytestream_get_le16(&header);
  203. if (avctx->bits_per_coded_sample != 16) {
  204. av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
  205. return -1;
  206. }
  207. len -= 16;
  208. if (len > 0)
  209. av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
  210. return 0;
  211. }
  212. static void output_buffer(int16_t **samples, int nchan, int blocksize,
  213. int32_t **buffer)
  214. {
  215. int i, ch;
  216. for (ch = 0; ch < nchan; ch++) {
  217. int32_t *in = buffer[ch];
  218. int16_t *out = samples[ch];
  219. for (i = 0; i < blocksize; i++)
  220. out[i] = av_clip_int16(in[i]);
  221. }
  222. }
  223. static const int fixed_coeffs[3][3] = {
  224. { 1, 0, 0 },
  225. { 2, -1, 0 },
  226. { 3, -3, 1 }
  227. };
  228. static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
  229. int residual_size, int32_t coffset)
  230. {
  231. int pred_order, sum, qshift, init_sum, i, j;
  232. const int *coeffs;
  233. if (command == FN_QLPC) {
  234. /* read/validate prediction order */
  235. pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
  236. if (pred_order > s->nwrap) {
  237. av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
  238. return AVERROR(EINVAL);
  239. }
  240. /* read LPC coefficients */
  241. for (i=0; i<pred_order; i++)
  242. s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
  243. coeffs = s->coeffs;
  244. qshift = LPCQUANT;
  245. } else {
  246. /* fixed LPC coeffs */
  247. pred_order = command;
  248. coeffs = fixed_coeffs[pred_order-1];
  249. qshift = 0;
  250. }
  251. /* subtract offset from previous samples to use in prediction */
  252. if (command == FN_QLPC && coffset)
  253. for (i = -pred_order; i < 0; i++)
  254. s->decoded[channel][i] -= coffset;
  255. /* decode residual and do LPC prediction */
  256. init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
  257. for (i=0; i < s->blocksize; i++) {
  258. sum = init_sum;
  259. for (j=0; j<pred_order; j++)
  260. sum += coeffs[j] * s->decoded[channel][i-j-1];
  261. s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
  262. }
  263. /* add offset to current samples */
  264. if (command == FN_QLPC && coffset)
  265. for (i = 0; i < s->blocksize; i++)
  266. s->decoded[channel][i] += coffset;
  267. return 0;
  268. }
  269. static int read_header(ShortenContext *s)
  270. {
  271. int i, ret;
  272. int maxnlpc = 0;
  273. /* shorten signature */
  274. if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
  275. av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
  276. return -1;
  277. }
  278. s->lpcqoffset = 0;
  279. s->blocksize = DEFAULT_BLOCK_SIZE;
  280. s->nmean = -1;
  281. s->version = get_bits(&s->gb, 8);
  282. s->internal_ftype = get_uint(s, TYPESIZE);
  283. s->channels = get_uint(s, CHANSIZE);
  284. if (s->channels <= 0 || s->channels > MAX_CHANNELS) {
  285. av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
  286. return -1;
  287. }
  288. s->avctx->channels = s->channels;
  289. /* get blocksize if version > 0 */
  290. if (s->version > 0) {
  291. int skip_bytes, blocksize;
  292. blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
  293. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  294. av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
  295. blocksize);
  296. return AVERROR(EINVAL);
  297. }
  298. s->blocksize = blocksize;
  299. maxnlpc = get_uint(s, LPCQSIZE);
  300. s->nmean = get_uint(s, 0);
  301. skip_bytes = get_uint(s, NSKIPSIZE);
  302. for (i=0; i<skip_bytes; i++) {
  303. skip_bits(&s->gb, 8);
  304. }
  305. }
  306. s->nwrap = FFMAX(NWRAP, maxnlpc);
  307. if ((ret = allocate_buffers(s)) < 0)
  308. return ret;
  309. if ((ret = init_offset(s)) < 0)
  310. return ret;
  311. if (s->version > 1)
  312. s->lpcqoffset = V2LPCQOFFSET;
  313. if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
  314. av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
  315. return -1;
  316. }
  317. s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  318. if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
  319. av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
  320. return -1;
  321. }
  322. for (i=0; i<s->header_size; i++)
  323. s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  324. if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
  325. return -1;
  326. s->cur_chan = 0;
  327. s->bitshift = 0;
  328. s->got_header = 1;
  329. return 0;
  330. }
  331. static int shorten_decode_frame(AVCodecContext *avctx, void *data,
  332. int *got_frame_ptr, AVPacket *avpkt)
  333. {
  334. AVFrame *frame = data;
  335. const uint8_t *buf = avpkt->data;
  336. int buf_size = avpkt->size;
  337. ShortenContext *s = avctx->priv_data;
  338. int i, input_buf_size = 0;
  339. int ret;
  340. /* allocate internal bitstream buffer */
  341. if(s->max_framesize == 0){
  342. void *tmp_ptr;
  343. s->max_framesize= 1024; // should hopefully be enough for the first header
  344. tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
  345. s->max_framesize);
  346. if (!tmp_ptr) {
  347. av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
  348. return AVERROR(ENOMEM);
  349. }
  350. s->bitstream = tmp_ptr;
  351. }
  352. /* append current packet data to bitstream buffer */
  353. if(1 && s->max_framesize){//FIXME truncated
  354. buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
  355. input_buf_size= buf_size;
  356. if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
  357. memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
  358. s->bitstream_index=0;
  359. }
  360. if (buf)
  361. memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
  362. buf= &s->bitstream[s->bitstream_index];
  363. buf_size += s->bitstream_size;
  364. s->bitstream_size= buf_size;
  365. /* do not decode until buffer has at least max_framesize bytes or
  366. the end of the file has been reached */
  367. if (buf_size < s->max_framesize && avpkt->data) {
  368. *got_frame_ptr = 0;
  369. return input_buf_size;
  370. }
  371. }
  372. /* init and position bitstream reader */
  373. init_get_bits(&s->gb, buf, buf_size*8);
  374. skip_bits(&s->gb, s->bitindex);
  375. /* process header or next subblock */
  376. if (!s->got_header) {
  377. if ((ret = read_header(s)) < 0)
  378. return ret;
  379. *got_frame_ptr = 0;
  380. goto finish_frame;
  381. }
  382. /* if quit command was read previously, don't decode anything */
  383. if (s->got_quit_command) {
  384. *got_frame_ptr = 0;
  385. return avpkt->size;
  386. }
  387. s->cur_chan = 0;
  388. while (s->cur_chan < s->channels) {
  389. unsigned cmd;
  390. int len;
  391. if (get_bits_left(&s->gb) < 3+FNSIZE) {
  392. *got_frame_ptr = 0;
  393. break;
  394. }
  395. cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
  396. if (cmd > FN_VERBATIM) {
  397. av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
  398. *got_frame_ptr = 0;
  399. break;
  400. }
  401. if (!is_audio_command[cmd]) {
  402. /* process non-audio command */
  403. switch (cmd) {
  404. case FN_VERBATIM:
  405. len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  406. while (len--) {
  407. get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  408. }
  409. break;
  410. case FN_BITSHIFT:
  411. s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
  412. break;
  413. case FN_BLOCKSIZE: {
  414. int blocksize = get_uint(s, av_log2(s->blocksize));
  415. if (blocksize > s->blocksize) {
  416. av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
  417. return AVERROR_PATCHWELCOME;
  418. }
  419. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  420. av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
  421. "block size: %d\n", blocksize);
  422. return AVERROR(EINVAL);
  423. }
  424. s->blocksize = blocksize;
  425. break;
  426. }
  427. case FN_QUIT:
  428. s->got_quit_command = 1;
  429. break;
  430. }
  431. if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
  432. *got_frame_ptr = 0;
  433. break;
  434. }
  435. } else {
  436. /* process audio command */
  437. int residual_size = 0;
  438. int channel = s->cur_chan;
  439. int32_t coffset;
  440. /* get Rice code for residual decoding */
  441. if (cmd != FN_ZERO) {
  442. residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
  443. /* This is a hack as version 0 differed in the definition
  444. * of get_sr_golomb_shorten(). */
  445. if (s->version == 0)
  446. residual_size--;
  447. }
  448. /* calculate sample offset using means from previous blocks */
  449. if (s->nmean == 0)
  450. coffset = s->offset[channel][0];
  451. else {
  452. int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
  453. for (i=0; i<s->nmean; i++)
  454. sum += s->offset[channel][i];
  455. coffset = sum / s->nmean;
  456. if (s->version >= 2)
  457. coffset >>= FFMIN(1, s->bitshift);
  458. }
  459. /* decode samples for this channel */
  460. if (cmd == FN_ZERO) {
  461. for (i=0; i<s->blocksize; i++)
  462. s->decoded[channel][i] = 0;
  463. } else {
  464. if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
  465. return ret;
  466. }
  467. /* update means with info from the current block */
  468. if (s->nmean > 0) {
  469. int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
  470. for (i=0; i<s->blocksize; i++)
  471. sum += s->decoded[channel][i];
  472. for (i=1; i<s->nmean; i++)
  473. s->offset[channel][i-1] = s->offset[channel][i];
  474. if (s->version < 2)
  475. s->offset[channel][s->nmean - 1] = sum / s->blocksize;
  476. else
  477. s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
  478. }
  479. /* copy wrap samples for use with next block */
  480. for (i=-s->nwrap; i<0; i++)
  481. s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
  482. /* shift samples to add in unused zero bits which were removed
  483. during encoding */
  484. fix_bitshift(s, s->decoded[channel]);
  485. /* if this is the last channel in the block, output the samples */
  486. s->cur_chan++;
  487. if (s->cur_chan == s->channels) {
  488. /* get output buffer */
  489. frame->nb_samples = s->blocksize;
  490. if ((ret = ff_get_buffer(avctx, frame)) < 0) {
  491. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  492. return ret;
  493. }
  494. /* interleave output */
  495. output_buffer((int16_t **)frame->extended_data, s->channels,
  496. s->blocksize, s->decoded);
  497. *got_frame_ptr = 1;
  498. }
  499. }
  500. }
  501. if (s->cur_chan < s->channels)
  502. *got_frame_ptr = 0;
  503. finish_frame:
  504. s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
  505. i= (get_bits_count(&s->gb))/8;
  506. if (i > buf_size) {
  507. av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
  508. s->bitstream_size=0;
  509. s->bitstream_index=0;
  510. return -1;
  511. }
  512. if (s->bitstream_size) {
  513. s->bitstream_index += i;
  514. s->bitstream_size -= i;
  515. return input_buf_size;
  516. } else
  517. return i;
  518. }
  519. static av_cold int shorten_decode_close(AVCodecContext *avctx)
  520. {
  521. ShortenContext *s = avctx->priv_data;
  522. int i;
  523. for (i = 0; i < s->channels; i++) {
  524. s->decoded[i] = NULL;
  525. av_freep(&s->decoded_base[i]);
  526. av_freep(&s->offset[i]);
  527. }
  528. av_freep(&s->bitstream);
  529. av_freep(&s->coeffs);
  530. return 0;
  531. }
  532. AVCodec ff_shorten_decoder = {
  533. .name = "shorten",
  534. .type = AVMEDIA_TYPE_AUDIO,
  535. .id = AV_CODEC_ID_SHORTEN,
  536. .priv_data_size = sizeof(ShortenContext),
  537. .init = shorten_decode_init,
  538. .close = shorten_decode_close,
  539. .decode = shorten_decode_frame,
  540. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
  541. .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
  542. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
  543. AV_SAMPLE_FMT_NONE },
  544. };