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.

639 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 *offset[MAX_CHANNELS];
  73. int *coeffs;
  74. uint8_t *bitstream;
  75. int bitstream_size;
  76. int bitstream_index;
  77. unsigned int allocated_bitstream_size;
  78. int header_size;
  79. uint8_t header[OUT_BUFFER_SIZE];
  80. int version;
  81. int cur_chan;
  82. int bitshift;
  83. int nmean;
  84. int internal_ftype;
  85. int nwrap;
  86. int blocksize;
  87. int bitindex;
  88. int32_t lpcqoffset;
  89. int got_header;
  90. int got_quit_command;
  91. } ShortenContext;
  92. static av_cold int shorten_decode_init(AVCodecContext * avctx)
  93. {
  94. ShortenContext *s = avctx->priv_data;
  95. s->avctx = avctx;
  96. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  97. avcodec_get_frame_defaults(&s->frame);
  98. avctx->coded_frame = &s->frame;
  99. return 0;
  100. }
  101. static int allocate_buffers(ShortenContext *s)
  102. {
  103. int i, chan;
  104. int *coeffs;
  105. void *tmp_ptr;
  106. for (chan=0; chan<s->channels; chan++) {
  107. if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
  108. av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
  109. return -1;
  110. }
  111. if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
  112. av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
  113. return -1;
  114. }
  115. tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
  116. if (!tmp_ptr)
  117. return AVERROR(ENOMEM);
  118. s->offset[chan] = tmp_ptr;
  119. tmp_ptr = av_realloc(s->decoded[chan], sizeof(int32_t)*(s->blocksize + s->nwrap));
  120. if (!tmp_ptr)
  121. return AVERROR(ENOMEM);
  122. s->decoded[chan] = tmp_ptr;
  123. for (i=0; i<s->nwrap; i++)
  124. s->decoded[chan][i] = 0;
  125. s->decoded[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 interleave_buffer(int16_t *samples, int nchan, int blocksize,
  213. int32_t **buffer)
  214. {
  215. int i, chan;
  216. for (i=0; i<blocksize; i++)
  217. for (chan=0; chan < nchan; chan++)
  218. *samples++ = av_clip_int16(buffer[chan][i]);
  219. }
  220. static const int fixed_coeffs[3][3] = {
  221. { 1, 0, 0 },
  222. { 2, -1, 0 },
  223. { 3, -3, 1 }
  224. };
  225. static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
  226. int residual_size, int32_t coffset)
  227. {
  228. int pred_order, sum, qshift, init_sum, i, j;
  229. const int *coeffs;
  230. if (command == FN_QLPC) {
  231. /* read/validate prediction order */
  232. pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
  233. if (pred_order > s->nwrap) {
  234. av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
  235. return AVERROR(EINVAL);
  236. }
  237. /* read LPC coefficients */
  238. for (i=0; i<pred_order; i++)
  239. s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
  240. coeffs = s->coeffs;
  241. qshift = LPCQUANT;
  242. } else {
  243. /* fixed LPC coeffs */
  244. pred_order = command;
  245. coeffs = fixed_coeffs[pred_order-1];
  246. qshift = 0;
  247. }
  248. /* subtract offset from previous samples to use in prediction */
  249. if (command == FN_QLPC && coffset)
  250. for (i = -pred_order; i < 0; i++)
  251. s->decoded[channel][i] -= coffset;
  252. /* decode residual and do LPC prediction */
  253. init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
  254. for (i=0; i < s->blocksize; i++) {
  255. sum = init_sum;
  256. for (j=0; j<pred_order; j++)
  257. sum += coeffs[j] * s->decoded[channel][i-j-1];
  258. s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
  259. }
  260. /* add offset to current samples */
  261. if (command == FN_QLPC && coffset)
  262. for (i = 0; i < s->blocksize; i++)
  263. s->decoded[channel][i] += coffset;
  264. return 0;
  265. }
  266. static int read_header(ShortenContext *s)
  267. {
  268. int i, ret;
  269. int maxnlpc = 0;
  270. /* shorten signature */
  271. if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
  272. av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
  273. return -1;
  274. }
  275. s->lpcqoffset = 0;
  276. s->blocksize = DEFAULT_BLOCK_SIZE;
  277. s->nmean = -1;
  278. s->version = get_bits(&s->gb, 8);
  279. s->internal_ftype = get_uint(s, TYPESIZE);
  280. s->channels = get_uint(s, CHANSIZE);
  281. if (s->channels > MAX_CHANNELS) {
  282. av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
  283. return -1;
  284. }
  285. s->avctx->channels = s->channels;
  286. /* get blocksize if version > 0 */
  287. if (s->version > 0) {
  288. int skip_bytes, blocksize;
  289. blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
  290. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  291. av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
  292. blocksize);
  293. return AVERROR(EINVAL);
  294. }
  295. s->blocksize = blocksize;
  296. maxnlpc = get_uint(s, LPCQSIZE);
  297. s->nmean = get_uint(s, 0);
  298. skip_bytes = get_uint(s, NSKIPSIZE);
  299. for (i=0; i<skip_bytes; i++) {
  300. skip_bits(&s->gb, 8);
  301. }
  302. }
  303. s->nwrap = FFMAX(NWRAP, maxnlpc);
  304. if ((ret = allocate_buffers(s)) < 0)
  305. return ret;
  306. if ((ret = init_offset(s)) < 0)
  307. return ret;
  308. if (s->version > 1)
  309. s->lpcqoffset = V2LPCQOFFSET;
  310. if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
  311. av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
  312. return -1;
  313. }
  314. s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  315. if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
  316. av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
  317. return -1;
  318. }
  319. for (i=0; i<s->header_size; i++)
  320. s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  321. if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
  322. return -1;
  323. s->cur_chan = 0;
  324. s->bitshift = 0;
  325. s->got_header = 1;
  326. return 0;
  327. }
  328. static int shorten_decode_frame(AVCodecContext *avctx, void *data,
  329. int *got_frame_ptr, AVPacket *avpkt)
  330. {
  331. const uint8_t *buf = avpkt->data;
  332. int buf_size = avpkt->size;
  333. ShortenContext *s = avctx->priv_data;
  334. int i, input_buf_size = 0;
  335. int ret;
  336. /* allocate internal bitstream buffer */
  337. if(s->max_framesize == 0){
  338. void *tmp_ptr;
  339. s->max_framesize= 1024; // should hopefully be enough for the first header
  340. tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
  341. s->max_framesize);
  342. if (!tmp_ptr) {
  343. av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
  344. return AVERROR(ENOMEM);
  345. }
  346. s->bitstream = tmp_ptr;
  347. }
  348. /* append current packet data to bitstream buffer */
  349. if(1 && s->max_framesize){//FIXME truncated
  350. buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
  351. input_buf_size= buf_size;
  352. if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
  353. memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
  354. s->bitstream_index=0;
  355. }
  356. if (buf)
  357. memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
  358. buf= &s->bitstream[s->bitstream_index];
  359. buf_size += s->bitstream_size;
  360. s->bitstream_size= buf_size;
  361. /* do not decode until buffer has at least max_framesize bytes or
  362. the end of the file has been reached */
  363. if (buf_size < s->max_framesize && avpkt->data) {
  364. *got_frame_ptr = 0;
  365. return input_buf_size;
  366. }
  367. }
  368. /* init and position bitstream reader */
  369. init_get_bits(&s->gb, buf, buf_size*8);
  370. skip_bits(&s->gb, s->bitindex);
  371. /* process header or next subblock */
  372. if (!s->got_header) {
  373. if ((ret = read_header(s)) < 0)
  374. return ret;
  375. *got_frame_ptr = 0;
  376. goto finish_frame;
  377. }
  378. /* if quit command was read previously, don't decode anything */
  379. if (s->got_quit_command) {
  380. *got_frame_ptr = 0;
  381. return avpkt->size;
  382. }
  383. s->cur_chan = 0;
  384. while (s->cur_chan < s->channels) {
  385. int cmd;
  386. int len;
  387. if (get_bits_left(&s->gb) < 3+FNSIZE) {
  388. *got_frame_ptr = 0;
  389. break;
  390. }
  391. cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
  392. if (cmd > FN_VERBATIM) {
  393. av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
  394. *got_frame_ptr = 0;
  395. break;
  396. }
  397. if (!is_audio_command[cmd]) {
  398. /* process non-audio command */
  399. switch (cmd) {
  400. case FN_VERBATIM:
  401. len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  402. while (len--) {
  403. get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  404. }
  405. break;
  406. case FN_BITSHIFT:
  407. s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
  408. break;
  409. case FN_BLOCKSIZE: {
  410. int blocksize = get_uint(s, av_log2(s->blocksize));
  411. if (blocksize > s->blocksize) {
  412. av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
  413. return AVERROR_PATCHWELCOME;
  414. }
  415. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  416. av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
  417. "block size: %d\n", blocksize);
  418. return AVERROR(EINVAL);
  419. }
  420. s->blocksize = blocksize;
  421. break;
  422. }
  423. case FN_QUIT:
  424. s->got_quit_command = 1;
  425. break;
  426. }
  427. if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
  428. *got_frame_ptr = 0;
  429. break;
  430. }
  431. } else {
  432. /* process audio command */
  433. int residual_size = 0;
  434. int channel = s->cur_chan;
  435. int32_t coffset;
  436. /* get Rice code for residual decoding */
  437. if (cmd != FN_ZERO) {
  438. residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
  439. /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
  440. if (s->version == 0)
  441. residual_size--;
  442. }
  443. /* calculate sample offset using means from previous blocks */
  444. if (s->nmean == 0)
  445. coffset = s->offset[channel][0];
  446. else {
  447. int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
  448. for (i=0; i<s->nmean; i++)
  449. sum += s->offset[channel][i];
  450. coffset = sum / s->nmean;
  451. if (s->version >= 2)
  452. coffset >>= FFMIN(1, s->bitshift);
  453. }
  454. /* decode samples for this channel */
  455. if (cmd == FN_ZERO) {
  456. for (i=0; i<s->blocksize; i++)
  457. s->decoded[channel][i] = 0;
  458. } else {
  459. if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
  460. return ret;
  461. }
  462. /* update means with info from the current block */
  463. if (s->nmean > 0) {
  464. int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
  465. for (i=0; i<s->blocksize; i++)
  466. sum += s->decoded[channel][i];
  467. for (i=1; i<s->nmean; i++)
  468. s->offset[channel][i-1] = s->offset[channel][i];
  469. if (s->version < 2)
  470. s->offset[channel][s->nmean - 1] = sum / s->blocksize;
  471. else
  472. s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
  473. }
  474. /* copy wrap samples for use with next block */
  475. for (i=-s->nwrap; i<0; i++)
  476. s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
  477. /* shift samples to add in unused zero bits which were removed
  478. during encoding */
  479. fix_bitshift(s, s->decoded[channel]);
  480. /* if this is the last channel in the block, output the samples */
  481. s->cur_chan++;
  482. if (s->cur_chan == s->channels) {
  483. /* get output buffer */
  484. s->frame.nb_samples = s->blocksize;
  485. if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
  486. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  487. return ret;
  488. }
  489. /* interleave output */
  490. interleave_buffer((int16_t *)s->frame.data[0], s->channels,
  491. s->blocksize, s->decoded);
  492. *got_frame_ptr = 1;
  493. *(AVFrame *)data = s->frame;
  494. }
  495. }
  496. }
  497. if (s->cur_chan < s->channels)
  498. *got_frame_ptr = 0;
  499. finish_frame:
  500. s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
  501. i= (get_bits_count(&s->gb))/8;
  502. if (i > buf_size) {
  503. av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
  504. s->bitstream_size=0;
  505. s->bitstream_index=0;
  506. return -1;
  507. }
  508. if (s->bitstream_size) {
  509. s->bitstream_index += i;
  510. s->bitstream_size -= i;
  511. return input_buf_size;
  512. } else
  513. return i;
  514. }
  515. static av_cold int shorten_decode_close(AVCodecContext *avctx)
  516. {
  517. ShortenContext *s = avctx->priv_data;
  518. int i;
  519. for (i = 0; i < s->channels; i++) {
  520. s->decoded[i] -= s->nwrap;
  521. av_freep(&s->decoded[i]);
  522. av_freep(&s->offset[i]);
  523. }
  524. av_freep(&s->bitstream);
  525. av_freep(&s->coeffs);
  526. return 0;
  527. }
  528. AVCodec ff_shorten_decoder = {
  529. .name = "shorten",
  530. .type = AVMEDIA_TYPE_AUDIO,
  531. .id = CODEC_ID_SHORTEN,
  532. .priv_data_size = sizeof(ShortenContext),
  533. .init = shorten_decode_init,
  534. .close = shorten_decode_close,
  535. .decode = shorten_decode_frame,
  536. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
  537. .long_name= NULL_IF_CONFIG_SMALL("Shorten"),
  538. };