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.

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