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.

642 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], sizeof(int32_t)*(s->blocksize + s->nwrap));
  121. if (!tmp_ptr)
  122. return AVERROR(ENOMEM);
  123. s->decoded_base[chan] = tmp_ptr;
  124. for (i=0; i<s->nwrap; i++)
  125. s->decoded_base[chan][i] = 0;
  126. s->decoded[chan] = s->decoded_base[chan] + s->nwrap;
  127. }
  128. coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
  129. if (!coeffs)
  130. return AVERROR(ENOMEM);
  131. s->coeffs = coeffs;
  132. return 0;
  133. }
  134. static inline unsigned int get_uint(ShortenContext *s, int k)
  135. {
  136. if (s->version != 0)
  137. k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
  138. return get_ur_golomb_shorten(&s->gb, k);
  139. }
  140. static void fix_bitshift(ShortenContext *s, int32_t *buffer)
  141. {
  142. int i;
  143. if (s->bitshift != 0)
  144. for (i = 0; i < s->blocksize; i++)
  145. buffer[i] <<= s->bitshift;
  146. }
  147. static int init_offset(ShortenContext *s)
  148. {
  149. int32_t mean = 0;
  150. int chan, i;
  151. int nblock = FFMAX(1, s->nmean);
  152. /* initialise offset */
  153. switch (s->internal_ftype)
  154. {
  155. case TYPE_S16HL:
  156. case TYPE_S16LH:
  157. mean = 0;
  158. break;
  159. default:
  160. av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
  161. return AVERROR_INVALIDDATA;
  162. }
  163. for (chan = 0; chan < s->channels; chan++)
  164. for (i = 0; i < nblock; i++)
  165. s->offset[chan][i] = mean;
  166. return 0;
  167. }
  168. static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
  169. int header_size)
  170. {
  171. int len;
  172. short wave_format;
  173. const uint8_t *end= header + header_size;
  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. if(len<0 || end - header - 8 < len)
  186. return AVERROR_INVALIDDATA;
  187. header += len;
  188. }
  189. len = bytestream_get_le32(&header);
  190. if (len < 16) {
  191. av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
  192. return -1;
  193. }
  194. wave_format = bytestream_get_le16(&header);
  195. switch (wave_format) {
  196. case WAVE_FORMAT_PCM:
  197. break;
  198. default:
  199. av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
  200. return -1;
  201. }
  202. header += 2; // skip channels (already got from shorten header)
  203. avctx->sample_rate = bytestream_get_le32(&header);
  204. header += 4; // skip bit rate (represents original uncompressed bit rate)
  205. header += 2; // skip block align (not needed)
  206. avctx->bits_per_coded_sample = bytestream_get_le16(&header);
  207. if (avctx->bits_per_coded_sample != 16) {
  208. av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
  209. return -1;
  210. }
  211. len -= 16;
  212. if (len > 0)
  213. av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
  214. return 0;
  215. }
  216. static void interleave_buffer(int16_t *samples, int nchan, int blocksize,
  217. int32_t **buffer)
  218. {
  219. int i, chan;
  220. for (i=0; i<blocksize; i++)
  221. for (chan=0; chan < nchan; chan++)
  222. *samples++ = av_clip_int16(buffer[chan][i]);
  223. }
  224. static const int fixed_coeffs[3][3] = {
  225. { 1, 0, 0 },
  226. { 2, -1, 0 },
  227. { 3, -3, 1 }
  228. };
  229. static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
  230. int residual_size, int32_t coffset)
  231. {
  232. int pred_order, sum, qshift, init_sum, i, j;
  233. const int *coeffs;
  234. if (command == FN_QLPC) {
  235. /* read/validate prediction order */
  236. pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
  237. if (pred_order > s->nwrap) {
  238. av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
  239. return AVERROR(EINVAL);
  240. }
  241. /* read LPC coefficients */
  242. for (i=0; i<pred_order; i++)
  243. s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
  244. coeffs = s->coeffs;
  245. qshift = LPCQUANT;
  246. } else {
  247. /* fixed LPC coeffs */
  248. pred_order = command;
  249. coeffs = fixed_coeffs[pred_order-1];
  250. qshift = 0;
  251. }
  252. /* subtract offset from previous samples to use in prediction */
  253. if (command == FN_QLPC && coffset)
  254. for (i = -pred_order; i < 0; i++)
  255. s->decoded[channel][i] -= coffset;
  256. /* decode residual and do LPC prediction */
  257. init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
  258. for (i=0; i < s->blocksize; i++) {
  259. sum = init_sum;
  260. for (j=0; j<pred_order; j++)
  261. sum += coeffs[j] * s->decoded[channel][i-j-1];
  262. s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
  263. }
  264. /* add offset to current samples */
  265. if (command == FN_QLPC && coffset)
  266. for (i = 0; i < s->blocksize; i++)
  267. s->decoded[channel][i] += coffset;
  268. return 0;
  269. }
  270. static int read_header(ShortenContext *s)
  271. {
  272. int i, ret;
  273. int maxnlpc = 0;
  274. /* shorten signature */
  275. if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
  276. av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
  277. return -1;
  278. }
  279. s->lpcqoffset = 0;
  280. s->blocksize = DEFAULT_BLOCK_SIZE;
  281. s->nmean = -1;
  282. s->version = get_bits(&s->gb, 8);
  283. s->internal_ftype = get_uint(s, TYPESIZE);
  284. s->channels = get_uint(s, CHANSIZE);
  285. if (s->channels > MAX_CHANNELS) {
  286. av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
  287. return -1;
  288. }
  289. s->avctx->channels = s->channels;
  290. /* get blocksize if version > 0 */
  291. if (s->version > 0) {
  292. int skip_bytes, blocksize;
  293. blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
  294. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  295. av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
  296. blocksize);
  297. return AVERROR(EINVAL);
  298. }
  299. s->blocksize = blocksize;
  300. maxnlpc = get_uint(s, LPCQSIZE);
  301. s->nmean = get_uint(s, 0);
  302. skip_bytes = get_uint(s, NSKIPSIZE);
  303. for (i=0; i<skip_bytes; i++) {
  304. skip_bits(&s->gb, 8);
  305. }
  306. }
  307. s->nwrap = FFMAX(NWRAP, maxnlpc);
  308. if ((ret = allocate_buffers(s)) < 0)
  309. return ret;
  310. if ((ret = init_offset(s)) < 0)
  311. return ret;
  312. if (s->version > 1)
  313. s->lpcqoffset = V2LPCQOFFSET;
  314. if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
  315. av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
  316. return -1;
  317. }
  318. s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  319. if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
  320. av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
  321. return -1;
  322. }
  323. for (i=0; i<s->header_size; i++)
  324. s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  325. if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
  326. return -1;
  327. s->cur_chan = 0;
  328. s->bitshift = 0;
  329. s->got_header = 1;
  330. return 0;
  331. }
  332. static int shorten_decode_frame(AVCodecContext *avctx, void *data,
  333. int *got_frame_ptr, AVPacket *avpkt)
  334. {
  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. int 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 defintion of get_sr_golomb_shorten */
  444. if (s->version == 0)
  445. residual_size--;
  446. }
  447. /* calculate sample offset using means from previous blocks */
  448. if (s->nmean == 0)
  449. coffset = s->offset[channel][0];
  450. else {
  451. int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
  452. for (i=0; i<s->nmean; i++)
  453. sum += s->offset[channel][i];
  454. coffset = sum / s->nmean;
  455. if (s->version >= 2)
  456. coffset >>= FFMIN(1, s->bitshift);
  457. }
  458. /* decode samples for this channel */
  459. if (cmd == FN_ZERO) {
  460. for (i=0; i<s->blocksize; i++)
  461. s->decoded[channel][i] = 0;
  462. } else {
  463. if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
  464. return ret;
  465. }
  466. /* update means with info from the current block */
  467. if (s->nmean > 0) {
  468. int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
  469. for (i=0; i<s->blocksize; i++)
  470. sum += s->decoded[channel][i];
  471. for (i=1; i<s->nmean; i++)
  472. s->offset[channel][i-1] = s->offset[channel][i];
  473. if (s->version < 2)
  474. s->offset[channel][s->nmean - 1] = sum / s->blocksize;
  475. else
  476. s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
  477. }
  478. /* copy wrap samples for use with next block */
  479. for (i=-s->nwrap; i<0; i++)
  480. s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
  481. /* shift samples to add in unused zero bits which were removed
  482. during encoding */
  483. fix_bitshift(s, s->decoded[channel]);
  484. /* if this is the last channel in the block, output the samples */
  485. s->cur_chan++;
  486. if (s->cur_chan == s->channels) {
  487. /* get output buffer */
  488. s->frame.nb_samples = s->blocksize;
  489. if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
  490. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  491. return ret;
  492. }
  493. /* interleave output */
  494. interleave_buffer((int16_t *)s->frame.data[0], s->channels,
  495. s->blocksize, s->decoded);
  496. *got_frame_ptr = 1;
  497. *(AVFrame *)data = s->frame;
  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 = 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. };