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.

631 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. GetBitContext gb;
  68. int min_framesize, max_framesize;
  69. int channels;
  70. int32_t *decoded[MAX_CHANNELS];
  71. int32_t *offset[MAX_CHANNELS];
  72. int *coeffs;
  73. uint8_t *bitstream;
  74. int bitstream_size;
  75. int bitstream_index;
  76. unsigned int allocated_bitstream_size;
  77. int header_size;
  78. uint8_t header[OUT_BUFFER_SIZE];
  79. int version;
  80. int cur_chan;
  81. int bitshift;
  82. int nmean;
  83. int internal_ftype;
  84. int nwrap;
  85. int blocksize;
  86. int bitindex;
  87. int32_t lpcqoffset;
  88. int got_header;
  89. int got_quit_command;
  90. } ShortenContext;
  91. static av_cold int shorten_decode_init(AVCodecContext * avctx)
  92. {
  93. ShortenContext *s = avctx->priv_data;
  94. s->avctx = avctx;
  95. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  96. return 0;
  97. }
  98. static int allocate_buffers(ShortenContext *s)
  99. {
  100. int i, chan;
  101. int *coeffs;
  102. void *tmp_ptr;
  103. for (chan=0; chan<s->channels; chan++) {
  104. if(FFMAX(1, s->nmean) >= UINT_MAX/sizeof(int32_t)){
  105. av_log(s->avctx, AV_LOG_ERROR, "nmean too large\n");
  106. return -1;
  107. }
  108. if(s->blocksize + s->nwrap >= UINT_MAX/sizeof(int32_t) || s->blocksize + s->nwrap <= (unsigned)s->nwrap){
  109. av_log(s->avctx, AV_LOG_ERROR, "s->blocksize + s->nwrap too large\n");
  110. return -1;
  111. }
  112. tmp_ptr = av_realloc(s->offset[chan], sizeof(int32_t)*FFMAX(1, s->nmean));
  113. if (!tmp_ptr)
  114. return AVERROR(ENOMEM);
  115. s->offset[chan] = tmp_ptr;
  116. tmp_ptr = av_realloc(s->decoded[chan], sizeof(int32_t)*(s->blocksize + s->nwrap));
  117. if (!tmp_ptr)
  118. return AVERROR(ENOMEM);
  119. s->decoded[chan] = tmp_ptr;
  120. for (i=0; i<s->nwrap; i++)
  121. s->decoded[chan][i] = 0;
  122. s->decoded[chan] += s->nwrap;
  123. }
  124. coeffs = av_realloc(s->coeffs, s->nwrap * sizeof(*s->coeffs));
  125. if (!coeffs)
  126. return AVERROR(ENOMEM);
  127. s->coeffs = coeffs;
  128. return 0;
  129. }
  130. static inline unsigned int get_uint(ShortenContext *s, int k)
  131. {
  132. if (s->version != 0)
  133. k = get_ur_golomb_shorten(&s->gb, ULONGSIZE);
  134. return get_ur_golomb_shorten(&s->gb, k);
  135. }
  136. static void fix_bitshift(ShortenContext *s, int32_t *buffer)
  137. {
  138. int i;
  139. if (s->bitshift != 0)
  140. for (i = 0; i < s->blocksize; i++)
  141. buffer[i] <<= s->bitshift;
  142. }
  143. static void init_offset(ShortenContext *s)
  144. {
  145. int32_t mean = 0;
  146. int chan, i;
  147. int nblock = FFMAX(1, s->nmean);
  148. /* initialise offset */
  149. switch (s->internal_ftype)
  150. {
  151. case TYPE_S16HL:
  152. case TYPE_S16LH:
  153. mean = 0;
  154. break;
  155. default:
  156. av_log(s->avctx, AV_LOG_ERROR, "unknown audio type");
  157. abort();
  158. }
  159. for (chan = 0; chan < s->channels; chan++)
  160. for (i = 0; i < nblock; i++)
  161. s->offset[chan][i] = mean;
  162. }
  163. static int decode_wave_header(AVCodecContext *avctx, const uint8_t *header,
  164. int header_size)
  165. {
  166. int len;
  167. short wave_format;
  168. if (bytestream_get_le32(&header) != MKTAG('R','I','F','F')) {
  169. av_log(avctx, AV_LOG_ERROR, "missing RIFF tag\n");
  170. return -1;
  171. }
  172. header += 4; /* chunk size */;
  173. if (bytestream_get_le32(&header) != MKTAG('W','A','V','E')) {
  174. av_log(avctx, AV_LOG_ERROR, "missing WAVE tag\n");
  175. return -1;
  176. }
  177. while (bytestream_get_le32(&header) != MKTAG('f','m','t',' ')) {
  178. len = bytestream_get_le32(&header);
  179. header += len;
  180. }
  181. len = bytestream_get_le32(&header);
  182. if (len < 16) {
  183. av_log(avctx, AV_LOG_ERROR, "fmt chunk was too short\n");
  184. return -1;
  185. }
  186. wave_format = bytestream_get_le16(&header);
  187. switch (wave_format) {
  188. case WAVE_FORMAT_PCM:
  189. break;
  190. default:
  191. av_log(avctx, AV_LOG_ERROR, "unsupported wave format\n");
  192. return -1;
  193. }
  194. header += 2; // skip channels (already got from shorten header)
  195. avctx->sample_rate = bytestream_get_le32(&header);
  196. header += 4; // skip bit rate (represents original uncompressed bit rate)
  197. header += 2; // skip block align (not needed)
  198. avctx->bits_per_coded_sample = bytestream_get_le16(&header);
  199. if (avctx->bits_per_coded_sample != 16) {
  200. av_log(avctx, AV_LOG_ERROR, "unsupported number of bits per sample\n");
  201. return -1;
  202. }
  203. len -= 16;
  204. if (len > 0)
  205. av_log(avctx, AV_LOG_INFO, "%d header bytes unparsed\n", len);
  206. return 0;
  207. }
  208. static void interleave_buffer(int16_t *samples, int nchan, int blocksize,
  209. int32_t **buffer)
  210. {
  211. int i, chan;
  212. for (i=0; i<blocksize; i++)
  213. for (chan=0; chan < nchan; chan++)
  214. *samples++ = av_clip_int16(buffer[chan][i]);
  215. }
  216. static const int fixed_coeffs[3][3] = {
  217. { 1, 0, 0 },
  218. { 2, -1, 0 },
  219. { 3, -3, 1 }
  220. };
  221. static int decode_subframe_lpc(ShortenContext *s, int command, int channel,
  222. int residual_size, int32_t coffset)
  223. {
  224. int pred_order, sum, qshift, init_sum, i, j;
  225. const int *coeffs;
  226. if (command == FN_QLPC) {
  227. /* read/validate prediction order */
  228. pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);
  229. if (pred_order > s->nwrap) {
  230. av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n", pred_order);
  231. return AVERROR(EINVAL);
  232. }
  233. /* read LPC coefficients */
  234. for (i=0; i<pred_order; i++)
  235. s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);
  236. coeffs = s->coeffs;
  237. qshift = LPCQUANT;
  238. } else {
  239. /* fixed LPC coeffs */
  240. pred_order = command;
  241. coeffs = fixed_coeffs[pred_order-1];
  242. qshift = 0;
  243. }
  244. /* subtract offset from previous samples to use in prediction */
  245. if (command == FN_QLPC && coffset)
  246. for (i = -pred_order; i < 0; i++)
  247. s->decoded[channel][i] -= coffset;
  248. /* decode residual and do LPC prediction */
  249. init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;
  250. for (i=0; i < s->blocksize; i++) {
  251. sum = init_sum;
  252. for (j=0; j<pred_order; j++)
  253. sum += coeffs[j] * s->decoded[channel][i-j-1];
  254. s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) + (sum >> qshift);
  255. }
  256. /* add offset to current samples */
  257. if (command == FN_QLPC && coffset)
  258. for (i = 0; i < s->blocksize; i++)
  259. s->decoded[channel][i] += coffset;
  260. return 0;
  261. }
  262. static int read_header(ShortenContext *s)
  263. {
  264. int i, ret;
  265. int maxnlpc = 0;
  266. /* shorten signature */
  267. if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {
  268. av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");
  269. return -1;
  270. }
  271. s->lpcqoffset = 0;
  272. s->blocksize = DEFAULT_BLOCK_SIZE;
  273. s->channels = 1;
  274. s->nmean = -1;
  275. s->version = get_bits(&s->gb, 8);
  276. s->internal_ftype = get_uint(s, TYPESIZE);
  277. s->channels = get_uint(s, CHANSIZE);
  278. if (s->channels > MAX_CHANNELS) {
  279. av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);
  280. return -1;
  281. }
  282. s->avctx->channels = s->channels;
  283. /* get blocksize if version > 0 */
  284. if (s->version > 0) {
  285. int skip_bytes, blocksize;
  286. blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));
  287. if (!blocksize || blocksize > MAX_BLOCKSIZE) {
  288. av_log(s->avctx, AV_LOG_ERROR, "invalid or unsupported block size: %d\n",
  289. blocksize);
  290. return AVERROR(EINVAL);
  291. }
  292. s->blocksize = blocksize;
  293. maxnlpc = get_uint(s, LPCQSIZE);
  294. s->nmean = get_uint(s, 0);
  295. skip_bytes = get_uint(s, NSKIPSIZE);
  296. for (i=0; i<skip_bytes; i++) {
  297. skip_bits(&s->gb, 8);
  298. }
  299. }
  300. s->nwrap = FFMAX(NWRAP, maxnlpc);
  301. if ((ret = allocate_buffers(s)) < 0)
  302. return ret;
  303. init_offset(s);
  304. if (s->version > 1)
  305. s->lpcqoffset = V2LPCQOFFSET;
  306. if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {
  307. av_log(s->avctx, AV_LOG_ERROR, "missing verbatim section at beginning of stream\n");
  308. return -1;
  309. }
  310. s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);
  311. if (s->header_size >= OUT_BUFFER_SIZE || s->header_size < CANONICAL_HEADER_SIZE) {
  312. av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n", s->header_size);
  313. return -1;
  314. }
  315. for (i=0; i<s->header_size; i++)
  316. s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);
  317. if (decode_wave_header(s->avctx, s->header, s->header_size) < 0)
  318. return -1;
  319. s->cur_chan = 0;
  320. s->bitshift = 0;
  321. s->got_header = 1;
  322. return 0;
  323. }
  324. static int shorten_decode_frame(AVCodecContext *avctx,
  325. void *data, int *data_size,
  326. AVPacket *avpkt)
  327. {
  328. const uint8_t *buf = avpkt->data;
  329. int buf_size = avpkt->size;
  330. ShortenContext *s = avctx->priv_data;
  331. int i, input_buf_size = 0;
  332. int16_t *samples = data;
  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. *data_size = 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. *data_size = 0;
  374. goto finish_frame;
  375. }
  376. /* if quit command was read previously, don't decode anything */
  377. if (s->got_quit_command) {
  378. *data_size = 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. *data_size = 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. *data_size = 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. *data_size = 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. int out_size = s->blocksize * s->channels *
  482. av_get_bytes_per_sample(avctx->sample_fmt);
  483. if (*data_size < out_size) {
  484. av_log(avctx, AV_LOG_ERROR, "Output buffer is too small\n");
  485. return AVERROR(EINVAL);
  486. }
  487. interleave_buffer(samples, s->channels, s->blocksize, s->decoded);
  488. *data_size = out_size;
  489. }
  490. }
  491. }
  492. if (s->cur_chan < s->channels)
  493. *data_size = 0;
  494. finish_frame:
  495. s->bitindex = get_bits_count(&s->gb) - 8*((get_bits_count(&s->gb))/8);
  496. i= (get_bits_count(&s->gb))/8;
  497. if (i > buf_size) {
  498. av_log(s->avctx, AV_LOG_ERROR, "overread: %d\n", i - buf_size);
  499. s->bitstream_size=0;
  500. s->bitstream_index=0;
  501. return -1;
  502. }
  503. if (s->bitstream_size) {
  504. s->bitstream_index += i;
  505. s->bitstream_size -= i;
  506. return input_buf_size;
  507. } else
  508. return i;
  509. }
  510. static av_cold int shorten_decode_close(AVCodecContext *avctx)
  511. {
  512. ShortenContext *s = avctx->priv_data;
  513. int i;
  514. for (i = 0; i < s->channels; i++) {
  515. s->decoded[i] -= s->nwrap;
  516. av_freep(&s->decoded[i]);
  517. av_freep(&s->offset[i]);
  518. }
  519. av_freep(&s->bitstream);
  520. av_freep(&s->coeffs);
  521. return 0;
  522. }
  523. AVCodec ff_shorten_decoder = {
  524. .name = "shorten",
  525. .type = AVMEDIA_TYPE_AUDIO,
  526. .id = CODEC_ID_SHORTEN,
  527. .priv_data_size = sizeof(ShortenContext),
  528. .init = shorten_decode_init,
  529. .close = shorten_decode_close,
  530. .decode = shorten_decode_frame,
  531. .capabilities = CODEC_CAP_DELAY,
  532. .long_name= NULL_IF_CONFIG_SMALL("Shorten"),
  533. };