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.

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