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.

643 lines
19KB

  1. /*
  2. * Shorten decoder
  3. * Copyright (c) 2005 Jeff Muizelaar
  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. * 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\n");
  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. const uint8_t *end= header + header_size;
  175. if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
  176. av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
  177. return -1;
  178. }
  179. header += 4; /* chunk size */;
  180. if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
  181. av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
  182. return -1;
  183. }
  184. while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
  185. len = bytestream_get_le32(&header);
  186. if(len<0 || end - header - 8 < len)
  187. return AVERROR_INVALIDDATA;
  188. header += len;
  189. }
  190. len = bytestream_get_le32(&header);
  191. if (len < 16) {
  192. av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
  193. return -1;
  194. }
  195. wave_format = bytestream_get_le16(&header);
  196. switch (wave_format) {
  197. case WAVE_FORMAT_PCM:
  198. break;
  199. default:
  200. av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
  201. return -1;
  202. }
  203. header += 2; // skip channels (already got from shorten header)
  204. avctx->sample_rate = bytestream_get_le32(&header);
  205. header += 4; // skip bit rate (represents original uncompressed bit rate)
  206. header += 2; // skip block align (not needed)
  207. avctx->bits_per_coded_sample = bytestream_get_le16(&header);
  208. if (avctx->bits_per_coded_sample != 16) {
  209. av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
  210. return -1;
  211. }
  212. len -= 16;
  213. if (len > 0)
  214. av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
  215. return 0;
  216. }
  217. static void interleave_buffer(int16_t *samples, int nchan, int blocksize,
  218. int32_t **buffer)
  219. {
  220. int i, chan;
  221. for (i=0; i<blocksize; i++)
  222. for (chan=0; chan < nchan; chan++)
  223. *samples++ = av_clip_int16(buffer[chan][i]);
  224. }
  225. static const int fixed_coeffs[3][3] = {
  226. { 1, 0, 0 },
  227. { 2, -1, 0 },
  228. { 3, -3, 1 }
  229. };
  230. static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
  231. int residual_size, int32_t coffset)
  232. {
  233. int pred_order, sum, qshift, init_sum, i, j;
  234. const int *coeffs;
  235. if (command == FN_QLPC) {
  236. /* read/validate prediction order */
  237. pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
  238. if (pred_order > s->nwrap) {
  239. av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
  240. return AVERROR(EINVAL);
  241. }
  242. /* read LPC coefficients */
  243. for (i=0; i<pred_order; i++)
  244. s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
  245. coeffs = s->coeffs;
  246. qshift = LPCQUANT;
  247. } else {
  248. /* fixed LPC coeffs */
  249. pred_order = command;
  250. coeffs = fixed_coeffs[pred_order-1];
  251. qshift = 0;
  252. }
  253. /* subtract offset from previous samples to use in prediction */
  254. if (command == FN_QLPC && coffset)
  255. for (i = -pred_order; i < 0; i++)
  256. s->decoded[channel][i] -= coffset;
  257. /* decode residual and do LPC prediction */
  258. init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
  259. for (i=0; i < s->blocksize; i++) {
  260. sum = init_sum;
  261. for (j=0; j<pred_order; j++)
  262. sum += coeffs[j] * s->decoded[channel][i-j-1];
  263. s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
  264. }
  265. /* add offset to current samples */
  266. if (command == FN_QLPC && coffset)
  267. for (i = 0; i < s->blocksize; i++)
  268. s->decoded[channel][i] += coffset;
  269. return 0;
  270. }
  271. static int read_header(ShortenContext *s)
  272. {
  273. int i, ret;
  274. int maxnlpc = 0;
  275. /* shorten signature */
  276. if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
  277. av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
  278. return -1;
  279. }
  280. s->lpcqoffset = 0;
  281. s->blocksize = DEFAULT_BLOCK_SIZE;
  282. s->nmean = -1;
  283. s->version = get_bits(&s->gb, 8);
  284. s->internal_ftype = get_uint(s, TYPESIZE);
  285. s->channels = get_uint(s, CHANSIZE);
  286. if (s->channels > MAX_CHANNELS) {
  287. av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
  288. return -1;
  289. }
  290. s->avctx->channels = s->channels;
  291. /* get blocksize if version > 0 */
  292. if (s->version > 0) {
  293. int skip_bytes, blocksize;
  294. blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
  295. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  296. av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
  297. blocksize);
  298. return AVERROR(EINVAL);
  299. }
  300. s->blocksize = blocksize;
  301. maxnlpc = get_uint(s, LPCQSIZE);
  302. s->nmean = get_uint(s, 0);
  303. skip_bytes = get_uint(s, NSKIPSIZE);
  304. for (i=0; i<skip_bytes; i++) {
  305. skip_bits(&s->gb, 8);
  306. }
  307. }
  308. s->nwrap = FFMAX(NWRAP, maxnlpc);
  309. if ((ret = allocate_buffers(s)) < 0)
  310. return ret;
  311. if ((ret = init_offset(s)) < 0)
  312. return ret;
  313. if (s->version > 1)
  314. s->lpcqoffset = V2LPCQOFFSET;
  315. if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
  316. av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
  317. return -1;
  318. }
  319. s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  320. if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
  321. av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
  322. return -1;
  323. }
  324. for (i=0; i<s->header_size; i++)
  325. s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  326. if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
  327. return -1;
  328. s->cur_chan = 0;
  329. s->bitshift = 0;
  330. s->got_header = 1;
  331. return 0;
  332. }
  333. static int shorten_decode_frame(AVCodecContext *avctx, void *data,
  334. int *got_frame_ptr, AVPacket *avpkt)
  335. {
  336. const uint8_t *buf = avpkt->data;
  337. int buf_size = avpkt->size;
  338. ShortenContext *s = avctx->priv_data;
  339. int i, input_buf_size = 0;
  340. int ret;
  341. /* allocate internal bitstream buffer */
  342. if(s->max_framesize == 0){
  343. void *tmp_ptr;
  344. s->max_framesize= 1024; // should hopefully be enough for the first header
  345. tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
  346. s->max_framesize);
  347. if (!tmp_ptr) {
  348. av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
  349. return AVERROR(ENOMEM);
  350. }
  351. s->bitstream = tmp_ptr;
  352. }
  353. /* append current packet data to bitstream buffer */
  354. if(1 && s->max_framesize){//FIXME truncated
  355. buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
  356. input_buf_size= buf_size;
  357. if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
  358. memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
  359. s->bitstream_index=0;
  360. }
  361. if (buf)
  362. memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
  363. buf= &s->bitstream[s->bitstream_index];
  364. buf_size += s->bitstream_size;
  365. s->bitstream_size= buf_size;
  366. /* do not decode until buffer has at least max_framesize bytes or
  367. the end of the file has been reached */
  368. if (buf_size < s->max_framesize && avpkt->data) {
  369. *got_frame_ptr = 0;
  370. return input_buf_size;
  371. }
  372. }
  373. /* init and position bitstream reader */
  374. init_get_bits(&s->gb, buf, buf_size*8);
  375. skip_bits(&s->gb, s->bitindex);
  376. /* process header or next subblock */
  377. if (!s->got_header) {
  378. if ((ret = read_header(s)) < 0)
  379. return ret;
  380. *got_frame_ptr = 0;
  381. goto finish_frame;
  382. }
  383. /* if quit command was read previously, don't decode anything */
  384. if (s->got_quit_command) {
  385. *got_frame_ptr = 0;
  386. return avpkt->size;
  387. }
  388. s->cur_chan = 0;
  389. while (s->cur_chan < s->channels) {
  390. int cmd;
  391. int len;
  392. if (get_bits_left(&s->gb) < 3+FNSIZE) {
  393. *got_frame_ptr = 0;
  394. break;
  395. }
  396. cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
  397. if (cmd > FN_VERBATIM) {
  398. av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
  399. *got_frame_ptr = 0;
  400. break;
  401. }
  402. if (!is_audio_command[cmd]) {
  403. /* process non-audio command */
  404. switch (cmd) {
  405. case FN_VERBATIM:
  406. len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  407. while (len--) {
  408. get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  409. }
  410. break;
  411. case FN_BITSHIFT:
  412. s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
  413. break;
  414. case FN_BLOCKSIZE: {
  415. int blocksize = get_uint(s, av_log2(s->blocksize));
  416. if (blocksize > s->blocksize) {
  417. av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
  418. return AVERROR_PATCHWELCOME;
  419. }
  420. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  421. av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
  422. "block size: %d\n", blocksize);
  423. return AVERROR(EINVAL);
  424. }
  425. s->blocksize = blocksize;
  426. break;
  427. }
  428. case FN_QUIT:
  429. s->got_quit_command = 1;
  430. break;
  431. }
  432. if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
  433. *got_frame_ptr = 0;
  434. break;
  435. }
  436. } else {
  437. /* process audio command */
  438. int residual_size = 0;
  439. int channel = s->cur_chan;
  440. int32_t coffset;
  441. /* get Rice code for residual decoding */
  442. if (cmd != FN_ZERO) {
  443. residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
  444. /* this is a hack as version 0 differed in defintion 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. s->frame.nb_samples = s->blocksize;
  490. if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
  491. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  492. return ret;
  493. }
  494. /* interleave output */
  495. interleave_buffer((int16_t *)s->frame.data[0], s->channels,
  496. s->blocksize, s->decoded);
  497. *got_frame_ptr = 1;
  498. *(AVFrame *)data = s->frame;
  499. }
  500. }
  501. }
  502. if (s->cur_chan < s->channels)
  503. *got_frame_ptr = 0;
  504. finish_frame:
  505. s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
  506. i= (get_bits_count(&s->gb))/8;
  507. if (i > buf_size) {
  508. av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
  509. s->bitstream_size=0;
  510. s->bitstream_index=0;
  511. return -1;
  512. }
  513. if (s->bitstream_size) {
  514. s->bitstream_index += i;
  515. s->bitstream_size -= i;
  516. return input_buf_size;
  517. } else
  518. return i;
  519. }
  520. static av_cold int shorten_decode_close(AVCodecContext *avctx)
  521. {
  522. ShortenContext *s = avctx->priv_data;
  523. int i;
  524. for (i = 0; i < s->channels; i++) {
  525. s->decoded[i] = NULL;
  526. av_freep(&s->decoded_base[i]);
  527. av_freep(&s->offset[i]);
  528. }
  529. av_freep(&s->bitstream);
  530. av_freep(&s->coeffs);
  531. return 0;
  532. }
  533. AVCodec ff_shorten_decoder = {
  534. .name = "shorten",
  535. .type = AVMEDIA_TYPE_AUDIO,
  536. .id = CODEC_ID_SHORTEN,
  537. .priv_data_size = sizeof(ShortenContext),
  538. .init = shorten_decode_init,
  539. .close = shorten_decode_close,
  540. .decode = shorten_decode_frame,
  541. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
  542. .long_name = NULL_IF_CONFIG_SMALL("Shorten"),
  543. };