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.

638 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->channels = 1;
  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. init_offset(s);
  307. if (s->version > 1)
  308. s->lpcqoffset = V2LPCQOFFSET;
  309. if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
  310. av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
  311. return -1;
  312. }
  313. s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  314. if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
  315. av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
  316. return -1;
  317. }
  318. for (i=0; i<s->header_size; i++)
  319. s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  320. if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
  321. return -1;
  322. s->cur_chan = 0;
  323. s->bitshift = 0;
  324. s->got_header = 1;
  325. return 0;
  326. }
  327. static int shorten_decode_frame(AVCodecContext *avctx, void *data,
  328. int *got_frame_ptr, AVPacket *avpkt)
  329. {
  330. const uint8_t *buf = avpkt->data;
  331. int buf_size = avpkt->size;
  332. ShortenContext *s = avctx->priv_data;
  333. int i, input_buf_size = 0;
  334. int ret;
  335. /* allocate internal bitstream buffer */
  336. if(s->max_framesize == 0){
  337. void *tmp_ptr;
  338. s->max_framesize= 1024; // should hopefully be enough for the first header
  339. tmp_ptr = av_fast_realloc(s->bitstream, &s->allocated_bitstream_size,
  340. s->max_framesize);
  341. if (!tmp_ptr) {
  342. av_log(avctx, AV_LOG_ERROR, "error allocating bitstream buffer\n");
  343. return AVERROR(ENOMEM);
  344. }
  345. s->bitstream = tmp_ptr;
  346. }
  347. /* append current packet data to bitstream buffer */
  348. if(1 && s->max_framesize){//FIXME truncated
  349. buf_size= FFMIN(buf_size, s->max_framesize - s->bitstream_size);
  350. input_buf_size= buf_size;
  351. if(s->bitstream_index + s->bitstream_size + buf_size > s->allocated_bitstream_size){
  352. memmove(s->bitstream, &s->bitstream[s->bitstream_index], s->bitstream_size);
  353. s->bitstream_index=0;
  354. }
  355. if (buf)
  356. memcpy(&s->bitstream[s->bitstream_index + s->bitstream_size], buf, buf_size);
  357. buf= &s->bitstream[s->bitstream_index];
  358. buf_size += s->bitstream_size;
  359. s->bitstream_size= buf_size;
  360. /* do not decode until buffer has at least max_framesize bytes or
  361. the end of the file has been reached */
  362. if (buf_size < s->max_framesize && avpkt->data) {
  363. *got_frame_ptr = 0;
  364. return input_buf_size;
  365. }
  366. }
  367. /* init and position bitstream reader */
  368. init_get_bits(&s->gb, buf, buf_size*8);
  369. skip_bits(&s->gb, s->bitindex);
  370. /* process header or next subblock */
  371. if (!s->got_header) {
  372. if ((ret = read_header(s)) < 0)
  373. return ret;
  374. *got_frame_ptr = 0;
  375. goto finish_frame;
  376. }
  377. /* if quit command was read previously, don't decode anything */
  378. if (s->got_quit_command) {
  379. *got_frame_ptr = 0;
  380. return avpkt->size;
  381. }
  382. s->cur_chan = 0;
  383. while (s->cur_chan < s->channels) {
  384. int cmd;
  385. int len;
  386. if (get_bits_left(&s->gb) < 3+FNSIZE) {
  387. *got_frame_ptr = 0;
  388. break;
  389. }
  390. cmd = get_ur_golomb_shorten(&s->gb, FNSIZE);
  391. if (cmd > FN_VERBATIM) {
  392. av_log(avctx, AV_LOG_ERROR, "unknown shorten function %d\n", cmd);
  393. *got_frame_ptr = 0;
  394. break;
  395. }
  396. if (!is_audio_command[cmd]) {
  397. /* process non-audio command */
  398. switch (cmd) {
  399. case FN_VERBATIM:
  400. len = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  401. while (len--) {
  402. get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  403. }
  404. break;
  405. case FN_BITSHIFT:
  406. s->bitshift = get_ur_golomb_shorten(&s->gb, BITSHIFTSIZE);
  407. break;
  408. case FN_BLOCKSIZE: {
  409. int blocksize = get_uint(s, av_log2(s->blocksize));
  410. if (blocksize > s->blocksize) {
  411. av_log(avctx, AV_LOG_ERROR, "Increasing block size is not supported\n");
  412. return AVERROR_PATCHWELCOME;
  413. }
  414. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  415. av_log(avctx, AV_LOG_ERROR, "invalid or unsupported "
  416. "block size: %d\n", blocksize);
  417. return AVERROR(EINVAL);
  418. }
  419. s->blocksize = blocksize;
  420. break;
  421. }
  422. case FN_QUIT:
  423. s->got_quit_command = 1;
  424. break;
  425. }
  426. if (cmd == FN_BLOCKSIZE || cmd == FN_QUIT) {
  427. *got_frame_ptr = 0;
  428. break;
  429. }
  430. } else {
  431. /* process audio command */
  432. int residual_size = 0;
  433. int channel = s->cur_chan;
  434. int32_t coffset;
  435. /* get Rice code for residual decoding */
  436. if (cmd != FN_ZERO) {
  437. residual_size = get_ur_golomb_shorten(&s->gb, ENERGYSIZE);
  438. /* this is a hack as version 0 differed in defintion of get_sr_golomb_shorten */
  439. if (s->version == 0)
  440. residual_size--;
  441. }
  442. /* calculate sample offset using means from previous blocks */
  443. if (s->nmean == 0)
  444. coffset = s->offset[channel][0];
  445. else {
  446. int32_t sum = (s->version < 2) ? 0 : s->nmean / 2;
  447. for (i=0; i<s->nmean; i++)
  448. sum += s->offset[channel][i];
  449. coffset = sum / s->nmean;
  450. if (s->version >= 2)
  451. coffset >>= FFMIN(1, s->bitshift);
  452. }
  453. /* decode samples for this channel */
  454. if (cmd == FN_ZERO) {
  455. for (i=0; i<s->blocksize; i++)
  456. s->decoded[channel][i] = 0;
  457. } else {
  458. if ((ret = decode_subframe_lpc(s, cmd, channel, residual_size, coffset)) < 0)
  459. return ret;
  460. }
  461. /* update means with info from the current block */
  462. if (s->nmean > 0) {
  463. int32_t sum = (s->version < 2) ? 0 : s->blocksize / 2;
  464. for (i=0; i<s->blocksize; i++)
  465. sum += s->decoded[channel][i];
  466. for (i=1; i<s->nmean; i++)
  467. s->offset[channel][i-1] = s->offset[channel][i];
  468. if (s->version < 2)
  469. s->offset[channel][s->nmean - 1] = sum / s->blocksize;
  470. else
  471. s->offset[channel][s->nmean - 1] = (sum / s->blocksize) << s->bitshift;
  472. }
  473. /* copy wrap samples for use with next block */
  474. for (i=-s->nwrap; i<0; i++)
  475. s->decoded[channel][i] = s->decoded[channel][i + s->blocksize];
  476. /* shift samples to add in unused zero bits which were removed
  477. during encoding */
  478. fix_bitshift(s, s->decoded[channel]);
  479. /* if this is the last channel in the block, output the samples */
  480. s->cur_chan++;
  481. if (s->cur_chan == s->channels) {
  482. /* get output buffer */
  483. s->frame.nb_samples = s->blocksize;
  484. if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
  485. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  486. return ret;
  487. }
  488. /* interleave output */
  489. interleave_buffer((int16_t *)s->frame.data[0], s->channels,
  490. s->blocksize, s->decoded);
  491. *got_frame_ptr = 1;
  492. *(AVFrame *)data = s->frame;
  493. }
  494. }
  495. }
  496. if (s->cur_chan < s->channels)
  497. *got_frame_ptr = 0;
  498. finish_frame:
  499. s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
  500. i= (get_bits_count(&s->gb))/8;
  501. if (i > buf_size) {
  502. av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
  503. s->bitstream_size=0;
  504. s->bitstream_index=0;
  505. return -1;
  506. }
  507. if (s->bitstream_size) {
  508. s->bitstream_index += i;
  509. s->bitstream_size -= i;
  510. return input_buf_size;
  511. } else
  512. return i;
  513. }
  514. static av_cold int shorten_decode_close(AVCodecContext *avctx)
  515. {
  516. ShortenContext *s = avctx->priv_data;
  517. int i;
  518. for (i = 0; i < s->channels; i++) {
  519. s->decoded[i] -= s->nwrap;
  520. av_freep(&s->decoded[i]);
  521. av_freep(&s->offset[i]);
  522. }
  523. av_freep(&s->bitstream);
  524. av_freep(&s->coeffs);
  525. return 0;
  526. }
  527. AVCodec ff_shorten_decoder = {
  528. .name = "shorten",
  529. .type = AVMEDIA_TYPE_AUDIO,
  530. .id = CODEC_ID_SHORTEN,
  531. .priv_data_size = sizeof(ShortenContext),
  532. .init = shorten_decode_init,
  533. .close = shorten_decode_close,
  534. .decode = shorten_decode_frame,
  535. .capabilities = CODEC_CAP_DELAY | CODEC_CAP_DR1,
  536. .long_name= NULL_IF_CONFIG_SMALL("Shorten"),
  537. };