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.

2594 lines
92KB

  1. /*
  2. * Copyright (C) 2003-2004 The FFmpeg project
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * On2 VP3 Video Decoder
  23. *
  24. * VP3 Video Decoder by Mike Melanson (mike at multimedia.cx)
  25. * For more information about the VP3 coding process, visit:
  26. * http://wiki.multimedia.cx/index.php?title=On2_VP3
  27. *
  28. * Theora decoder by Alex Beregszaszi
  29. */
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include "libavutil/imgutils.h"
  34. #include "avcodec.h"
  35. #include "get_bits.h"
  36. #include "hpeldsp.h"
  37. #include "internal.h"
  38. #include "mathops.h"
  39. #include "thread.h"
  40. #include "videodsp.h"
  41. #include "vp3data.h"
  42. #include "vp3dsp.h"
  43. #include "xiph.h"
  44. #define FRAGMENT_PIXELS 8
  45. // FIXME split things out into their own arrays
  46. typedef struct Vp3Fragment {
  47. int16_t dc;
  48. uint8_t coding_method;
  49. uint8_t qpi;
  50. } Vp3Fragment;
  51. #define SB_NOT_CODED 0
  52. #define SB_PARTIALLY_CODED 1
  53. #define SB_FULLY_CODED 2
  54. // This is the maximum length of a single long bit run that can be encoded
  55. // for superblock coding or block qps. Theora special-cases this to read a
  56. // bit instead of flipping the current bit to allow for runs longer than 4129.
  57. #define MAXIMUM_LONG_BIT_RUN 4129
  58. #define MODE_INTER_NO_MV 0
  59. #define MODE_INTRA 1
  60. #define MODE_INTER_PLUS_MV 2
  61. #define MODE_INTER_LAST_MV 3
  62. #define MODE_INTER_PRIOR_LAST 4
  63. #define MODE_USING_GOLDEN 5
  64. #define MODE_GOLDEN_MV 6
  65. #define MODE_INTER_FOURMV 7
  66. #define CODING_MODE_COUNT 8
  67. /* special internal mode */
  68. #define MODE_COPY 8
  69. static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb);
  70. static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb);
  71. /* There are 6 preset schemes, plus a free-form scheme */
  72. static const int ModeAlphabet[6][CODING_MODE_COUNT] = {
  73. /* scheme 1: Last motion vector dominates */
  74. { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
  75. MODE_INTER_PLUS_MV, MODE_INTER_NO_MV,
  76. MODE_INTRA, MODE_USING_GOLDEN,
  77. MODE_GOLDEN_MV, MODE_INTER_FOURMV },
  78. /* scheme 2 */
  79. { MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
  80. MODE_INTER_NO_MV, MODE_INTER_PLUS_MV,
  81. MODE_INTRA, MODE_USING_GOLDEN,
  82. MODE_GOLDEN_MV, MODE_INTER_FOURMV },
  83. /* scheme 3 */
  84. { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
  85. MODE_INTER_PRIOR_LAST, MODE_INTER_NO_MV,
  86. MODE_INTRA, MODE_USING_GOLDEN,
  87. MODE_GOLDEN_MV, MODE_INTER_FOURMV },
  88. /* scheme 4 */
  89. { MODE_INTER_LAST_MV, MODE_INTER_PLUS_MV,
  90. MODE_INTER_NO_MV, MODE_INTER_PRIOR_LAST,
  91. MODE_INTRA, MODE_USING_GOLDEN,
  92. MODE_GOLDEN_MV, MODE_INTER_FOURMV },
  93. /* scheme 5: No motion vector dominates */
  94. { MODE_INTER_NO_MV, MODE_INTER_LAST_MV,
  95. MODE_INTER_PRIOR_LAST, MODE_INTER_PLUS_MV,
  96. MODE_INTRA, MODE_USING_GOLDEN,
  97. MODE_GOLDEN_MV, MODE_INTER_FOURMV },
  98. /* scheme 6 */
  99. { MODE_INTER_NO_MV, MODE_USING_GOLDEN,
  100. MODE_INTER_LAST_MV, MODE_INTER_PRIOR_LAST,
  101. MODE_INTER_PLUS_MV, MODE_INTRA,
  102. MODE_GOLDEN_MV, MODE_INTER_FOURMV },
  103. };
  104. static const uint8_t hilbert_offset[16][2] = {
  105. { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 },
  106. { 0, 2 }, { 0, 3 }, { 1, 3 }, { 1, 2 },
  107. { 2, 2 }, { 2, 3 }, { 3, 3 }, { 3, 2 },
  108. { 3, 1 }, { 2, 1 }, { 2, 0 }, { 3, 0 }
  109. };
  110. #define MIN_DEQUANT_VAL 2
  111. typedef struct Vp3DecodeContext {
  112. AVCodecContext *avctx;
  113. int theora, theora_tables, theora_header;
  114. int version;
  115. int width, height;
  116. int chroma_x_shift, chroma_y_shift;
  117. ThreadFrame golden_frame;
  118. ThreadFrame last_frame;
  119. ThreadFrame current_frame;
  120. int keyframe;
  121. uint8_t idct_permutation[64];
  122. uint8_t idct_scantable[64];
  123. HpelDSPContext hdsp;
  124. VideoDSPContext vdsp;
  125. VP3DSPContext vp3dsp;
  126. DECLARE_ALIGNED(16, int16_t, block)[64];
  127. int flipped_image;
  128. int last_slice_end;
  129. int skip_loop_filter;
  130. int qps[3];
  131. int nqps;
  132. int last_qps[3];
  133. int superblock_count;
  134. int y_superblock_width;
  135. int y_superblock_height;
  136. int y_superblock_count;
  137. int c_superblock_width;
  138. int c_superblock_height;
  139. int c_superblock_count;
  140. int u_superblock_start;
  141. int v_superblock_start;
  142. unsigned char *superblock_coding;
  143. int macroblock_count;
  144. int macroblock_width;
  145. int macroblock_height;
  146. int fragment_count;
  147. int fragment_width[2];
  148. int fragment_height[2];
  149. Vp3Fragment *all_fragments;
  150. int fragment_start[3];
  151. int data_offset[3];
  152. uint8_t offset_x;
  153. uint8_t offset_y;
  154. int offset_x_warned;
  155. int8_t (*motion_val[2])[2];
  156. /* tables */
  157. uint16_t coded_dc_scale_factor[64];
  158. uint32_t coded_ac_scale_factor[64];
  159. uint8_t base_matrix[384][64];
  160. uint8_t qr_count[2][3];
  161. uint8_t qr_size[2][3][64];
  162. uint16_t qr_base[2][3][64];
  163. /**
  164. * This is a list of all tokens in bitstream order. Reordering takes place
  165. * by pulling from each level during IDCT. As a consequence, IDCT must be
  166. * in Hilbert order, making the minimum slice height 64 for 4:2:0 and 32
  167. * otherwise. The 32 different tokens with up to 12 bits of extradata are
  168. * collapsed into 3 types, packed as follows:
  169. * (from the low to high bits)
  170. *
  171. * 2 bits: type (0,1,2)
  172. * 0: EOB run, 14 bits for run length (12 needed)
  173. * 1: zero run, 7 bits for run length
  174. * 7 bits for the next coefficient (3 needed)
  175. * 2: coefficient, 14 bits (11 needed)
  176. *
  177. * Coefficients are signed, so are packed in the highest bits for automatic
  178. * sign extension.
  179. */
  180. int16_t *dct_tokens[3][64];
  181. int16_t *dct_tokens_base;
  182. #define TOKEN_EOB(eob_run) ((eob_run) << 2)
  183. #define TOKEN_ZERO_RUN(coeff, zero_run) (((coeff) * 512) + ((zero_run) << 2) + 1)
  184. #define TOKEN_COEFF(coeff) (((coeff) * 4) + 2)
  185. /**
  186. * number of blocks that contain DCT coefficients at
  187. * the given level or higher
  188. */
  189. int num_coded_frags[3][64];
  190. int total_num_coded_frags;
  191. /* this is a list of indexes into the all_fragments array indicating
  192. * which of the fragments are coded */
  193. int *coded_fragment_list[3];
  194. VLC dc_vlc[16];
  195. VLC ac_vlc_1[16];
  196. VLC ac_vlc_2[16];
  197. VLC ac_vlc_3[16];
  198. VLC ac_vlc_4[16];
  199. VLC superblock_run_length_vlc;
  200. VLC fragment_run_length_vlc;
  201. VLC mode_code_vlc;
  202. VLC motion_vector_vlc;
  203. /* these arrays need to be on 16-byte boundaries since SSE2 operations
  204. * index into them */
  205. DECLARE_ALIGNED(16, int16_t, qmat)[3][2][3][64]; ///< qmat[qpi][is_inter][plane]
  206. /* This table contains superblock_count * 16 entries. Each set of 16
  207. * numbers corresponds to the fragment indexes 0..15 of the superblock.
  208. * An entry will be -1 to indicate that no entry corresponds to that
  209. * index. */
  210. int *superblock_fragments;
  211. /* This is an array that indicates how a particular macroblock
  212. * is coded. */
  213. unsigned char *macroblock_coding;
  214. uint8_t *edge_emu_buffer;
  215. /* Huffman decode */
  216. int hti;
  217. unsigned int hbits;
  218. int entries;
  219. int huff_code_size;
  220. uint32_t huffman_table[80][32][2];
  221. uint8_t filter_limit_values[64];
  222. DECLARE_ALIGNED(8, int, bounding_values_array)[256 + 2];
  223. } Vp3DecodeContext;
  224. /************************************************************************
  225. * VP3 specific functions
  226. ************************************************************************/
  227. static av_cold void free_tables(AVCodecContext *avctx)
  228. {
  229. Vp3DecodeContext *s = avctx->priv_data;
  230. av_freep(&s->superblock_coding);
  231. av_freep(&s->all_fragments);
  232. av_freep(&s->coded_fragment_list[0]);
  233. av_freep(&s->dct_tokens_base);
  234. av_freep(&s->superblock_fragments);
  235. av_freep(&s->macroblock_coding);
  236. av_freep(&s->motion_val[0]);
  237. av_freep(&s->motion_val[1]);
  238. }
  239. static void vp3_decode_flush(AVCodecContext *avctx)
  240. {
  241. Vp3DecodeContext *s = avctx->priv_data;
  242. if (s->golden_frame.f)
  243. ff_thread_release_buffer(avctx, &s->golden_frame);
  244. if (s->last_frame.f)
  245. ff_thread_release_buffer(avctx, &s->last_frame);
  246. if (s->current_frame.f)
  247. ff_thread_release_buffer(avctx, &s->current_frame);
  248. }
  249. static av_cold int vp3_decode_end(AVCodecContext *avctx)
  250. {
  251. Vp3DecodeContext *s = avctx->priv_data;
  252. int i;
  253. free_tables(avctx);
  254. av_freep(&s->edge_emu_buffer);
  255. s->theora_tables = 0;
  256. /* release all frames */
  257. vp3_decode_flush(avctx);
  258. av_frame_free(&s->current_frame.f);
  259. av_frame_free(&s->last_frame.f);
  260. av_frame_free(&s->golden_frame.f);
  261. if (avctx->internal->is_copy)
  262. return 0;
  263. for (i = 0; i < 16; i++) {
  264. ff_free_vlc(&s->dc_vlc[i]);
  265. ff_free_vlc(&s->ac_vlc_1[i]);
  266. ff_free_vlc(&s->ac_vlc_2[i]);
  267. ff_free_vlc(&s->ac_vlc_3[i]);
  268. ff_free_vlc(&s->ac_vlc_4[i]);
  269. }
  270. ff_free_vlc(&s->superblock_run_length_vlc);
  271. ff_free_vlc(&s->fragment_run_length_vlc);
  272. ff_free_vlc(&s->mode_code_vlc);
  273. ff_free_vlc(&s->motion_vector_vlc);
  274. return 0;
  275. }
  276. /**
  277. * This function sets up all of the various blocks mappings:
  278. * superblocks <-> fragments, macroblocks <-> fragments,
  279. * superblocks <-> macroblocks
  280. *
  281. * @return 0 is successful; returns 1 if *anything* went wrong.
  282. */
  283. static int init_block_mapping(Vp3DecodeContext *s)
  284. {
  285. int sb_x, sb_y, plane;
  286. int x, y, i, j = 0;
  287. for (plane = 0; plane < 3; plane++) {
  288. int sb_width = plane ? s->c_superblock_width
  289. : s->y_superblock_width;
  290. int sb_height = plane ? s->c_superblock_height
  291. : s->y_superblock_height;
  292. int frag_width = s->fragment_width[!!plane];
  293. int frag_height = s->fragment_height[!!plane];
  294. for (sb_y = 0; sb_y < sb_height; sb_y++)
  295. for (sb_x = 0; sb_x < sb_width; sb_x++)
  296. for (i = 0; i < 16; i++) {
  297. x = 4 * sb_x + hilbert_offset[i][0];
  298. y = 4 * sb_y + hilbert_offset[i][1];
  299. if (x < frag_width && y < frag_height)
  300. s->superblock_fragments[j++] = s->fragment_start[plane] +
  301. y * frag_width + x;
  302. else
  303. s->superblock_fragments[j++] = -1;
  304. }
  305. }
  306. return 0; /* successful path out */
  307. }
  308. /*
  309. * This function sets up the dequantization tables used for a particular
  310. * frame.
  311. */
  312. static void init_dequantizer(Vp3DecodeContext *s, int qpi)
  313. {
  314. int ac_scale_factor = s->coded_ac_scale_factor[s->qps[qpi]];
  315. int dc_scale_factor = s->coded_dc_scale_factor[s->qps[qpi]];
  316. int i, plane, inter, qri, bmi, bmj, qistart;
  317. for (inter = 0; inter < 2; inter++) {
  318. for (plane = 0; plane < 3; plane++) {
  319. int sum = 0;
  320. for (qri = 0; qri < s->qr_count[inter][plane]; qri++) {
  321. sum += s->qr_size[inter][plane][qri];
  322. if (s->qps[qpi] <= sum)
  323. break;
  324. }
  325. qistart = sum - s->qr_size[inter][plane][qri];
  326. bmi = s->qr_base[inter][plane][qri];
  327. bmj = s->qr_base[inter][plane][qri + 1];
  328. for (i = 0; i < 64; i++) {
  329. int coeff = (2 * (sum - s->qps[qpi]) * s->base_matrix[bmi][i] -
  330. 2 * (qistart - s->qps[qpi]) * s->base_matrix[bmj][i] +
  331. s->qr_size[inter][plane][qri]) /
  332. (2 * s->qr_size[inter][plane][qri]);
  333. int qmin = 8 << (inter + !i);
  334. int qscale = i ? ac_scale_factor : dc_scale_factor;
  335. s->qmat[qpi][inter][plane][s->idct_permutation[i]] =
  336. av_clip((qscale * coeff) / 100 * 4, qmin, 4096);
  337. }
  338. /* all DC coefficients use the same quant so as not to interfere
  339. * with DC prediction */
  340. s->qmat[qpi][inter][plane][0] = s->qmat[0][inter][plane][0];
  341. }
  342. }
  343. }
  344. /*
  345. * This function initializes the loop filter boundary limits if the frame's
  346. * quality index is different from the previous frame's.
  347. *
  348. * The filter_limit_values may not be larger than 127.
  349. */
  350. static void init_loop_filter(Vp3DecodeContext *s)
  351. {
  352. int *bounding_values = s->bounding_values_array + 127;
  353. int filter_limit;
  354. int x;
  355. int value;
  356. filter_limit = s->filter_limit_values[s->qps[0]];
  357. av_assert0(filter_limit < 128U);
  358. /* set up the bounding values */
  359. memset(s->bounding_values_array, 0, 256 * sizeof(int));
  360. for (x = 0; x < filter_limit; x++) {
  361. bounding_values[-x] = -x;
  362. bounding_values[x] = x;
  363. }
  364. for (x = value = filter_limit; x < 128 && value; x++, value--) {
  365. bounding_values[ x] = value;
  366. bounding_values[-x] = -value;
  367. }
  368. if (value)
  369. bounding_values[128] = value;
  370. bounding_values[129] = bounding_values[130] = filter_limit * 0x02020202;
  371. }
  372. /*
  373. * This function unpacks all of the superblock/macroblock/fragment coding
  374. * information from the bitstream.
  375. */
  376. static int unpack_superblocks(Vp3DecodeContext *s, GetBitContext *gb)
  377. {
  378. int superblock_starts[3] = {
  379. 0, s->u_superblock_start, s->v_superblock_start
  380. };
  381. int bit = 0;
  382. int current_superblock = 0;
  383. int current_run = 0;
  384. int num_partial_superblocks = 0;
  385. int i, j;
  386. int current_fragment;
  387. int plane;
  388. if (s->keyframe) {
  389. memset(s->superblock_coding, SB_FULLY_CODED, s->superblock_count);
  390. } else {
  391. /* unpack the list of partially-coded superblocks */
  392. bit = get_bits1(gb) ^ 1;
  393. current_run = 0;
  394. while (current_superblock < s->superblock_count && get_bits_left(gb) > 0) {
  395. if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
  396. bit = get_bits1(gb);
  397. else
  398. bit ^= 1;
  399. current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
  400. 6, 2) + 1;
  401. if (current_run == 34)
  402. current_run += get_bits(gb, 12);
  403. if (current_run > s->superblock_count - current_superblock) {
  404. av_log(s->avctx, AV_LOG_ERROR,
  405. "Invalid partially coded superblock run length\n");
  406. return -1;
  407. }
  408. memset(s->superblock_coding + current_superblock, bit, current_run);
  409. current_superblock += current_run;
  410. if (bit)
  411. num_partial_superblocks += current_run;
  412. }
  413. /* unpack the list of fully coded superblocks if any of the blocks were
  414. * not marked as partially coded in the previous step */
  415. if (num_partial_superblocks < s->superblock_count) {
  416. int superblocks_decoded = 0;
  417. current_superblock = 0;
  418. bit = get_bits1(gb) ^ 1;
  419. current_run = 0;
  420. while (superblocks_decoded < s->superblock_count - num_partial_superblocks &&
  421. get_bits_left(gb) > 0) {
  422. if (s->theora && current_run == MAXIMUM_LONG_BIT_RUN)
  423. bit = get_bits1(gb);
  424. else
  425. bit ^= 1;
  426. current_run = get_vlc2(gb, s->superblock_run_length_vlc.table,
  427. 6, 2) + 1;
  428. if (current_run == 34)
  429. current_run += get_bits(gb, 12);
  430. for (j = 0; j < current_run; current_superblock++) {
  431. if (current_superblock >= s->superblock_count) {
  432. av_log(s->avctx, AV_LOG_ERROR,
  433. "Invalid fully coded superblock run length\n");
  434. return -1;
  435. }
  436. /* skip any superblocks already marked as partially coded */
  437. if (s->superblock_coding[current_superblock] == SB_NOT_CODED) {
  438. s->superblock_coding[current_superblock] = 2 * bit;
  439. j++;
  440. }
  441. }
  442. superblocks_decoded += current_run;
  443. }
  444. }
  445. /* if there were partial blocks, initialize bitstream for
  446. * unpacking fragment codings */
  447. if (num_partial_superblocks) {
  448. current_run = 0;
  449. bit = get_bits1(gb);
  450. /* toggle the bit because as soon as the first run length is
  451. * fetched the bit will be toggled again */
  452. bit ^= 1;
  453. }
  454. }
  455. /* figure out which fragments are coded; iterate through each
  456. * superblock (all planes) */
  457. s->total_num_coded_frags = 0;
  458. memset(s->macroblock_coding, MODE_COPY, s->macroblock_count);
  459. for (plane = 0; plane < 3; plane++) {
  460. int sb_start = superblock_starts[plane];
  461. int sb_end = sb_start + (plane ? s->c_superblock_count
  462. : s->y_superblock_count);
  463. int num_coded_frags = 0;
  464. for (i = sb_start; i < sb_end && get_bits_left(gb) > 0; i++) {
  465. /* iterate through all 16 fragments in a superblock */
  466. for (j = 0; j < 16; j++) {
  467. /* if the fragment is in bounds, check its coding status */
  468. current_fragment = s->superblock_fragments[i * 16 + j];
  469. if (current_fragment != -1) {
  470. int coded = s->superblock_coding[i];
  471. if (s->superblock_coding[i] == SB_PARTIALLY_CODED) {
  472. /* fragment may or may not be coded; this is the case
  473. * that cares about the fragment coding runs */
  474. if (current_run-- == 0) {
  475. bit ^= 1;
  476. current_run = get_vlc2(gb, s->fragment_run_length_vlc.table, 5, 2);
  477. }
  478. coded = bit;
  479. }
  480. if (coded) {
  481. /* default mode; actual mode will be decoded in
  482. * the next phase */
  483. s->all_fragments[current_fragment].coding_method =
  484. MODE_INTER_NO_MV;
  485. s->coded_fragment_list[plane][num_coded_frags++] =
  486. current_fragment;
  487. } else {
  488. /* not coded; copy this fragment from the prior frame */
  489. s->all_fragments[current_fragment].coding_method =
  490. MODE_COPY;
  491. }
  492. }
  493. }
  494. }
  495. s->total_num_coded_frags += num_coded_frags;
  496. for (i = 0; i < 64; i++)
  497. s->num_coded_frags[plane][i] = num_coded_frags;
  498. if (plane < 2)
  499. s->coded_fragment_list[plane + 1] = s->coded_fragment_list[plane] +
  500. num_coded_frags;
  501. }
  502. return 0;
  503. }
  504. /*
  505. * This function unpacks all the coding mode data for individual macroblocks
  506. * from the bitstream.
  507. */
  508. static int unpack_modes(Vp3DecodeContext *s, GetBitContext *gb)
  509. {
  510. int i, j, k, sb_x, sb_y;
  511. int scheme;
  512. int current_macroblock;
  513. int current_fragment;
  514. int coding_mode;
  515. int custom_mode_alphabet[CODING_MODE_COUNT];
  516. const int *alphabet;
  517. Vp3Fragment *frag;
  518. if (s->keyframe) {
  519. for (i = 0; i < s->fragment_count; i++)
  520. s->all_fragments[i].coding_method = MODE_INTRA;
  521. } else {
  522. /* fetch the mode coding scheme for this frame */
  523. scheme = get_bits(gb, 3);
  524. /* is it a custom coding scheme? */
  525. if (scheme == 0) {
  526. for (i = 0; i < 8; i++)
  527. custom_mode_alphabet[i] = MODE_INTER_NO_MV;
  528. for (i = 0; i < 8; i++)
  529. custom_mode_alphabet[get_bits(gb, 3)] = i;
  530. alphabet = custom_mode_alphabet;
  531. } else
  532. alphabet = ModeAlphabet[scheme - 1];
  533. /* iterate through all of the macroblocks that contain 1 or more
  534. * coded fragments */
  535. for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
  536. for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
  537. if (get_bits_left(gb) <= 0)
  538. return -1;
  539. for (j = 0; j < 4; j++) {
  540. int mb_x = 2 * sb_x + (j >> 1);
  541. int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
  542. current_macroblock = mb_y * s->macroblock_width + mb_x;
  543. if (mb_x >= s->macroblock_width ||
  544. mb_y >= s->macroblock_height)
  545. continue;
  546. #define BLOCK_X (2 * mb_x + (k & 1))
  547. #define BLOCK_Y (2 * mb_y + (k >> 1))
  548. /* coding modes are only stored if the macroblock has
  549. * at least one luma block coded, otherwise it must be
  550. * INTER_NO_MV */
  551. for (k = 0; k < 4; k++) {
  552. current_fragment = BLOCK_Y *
  553. s->fragment_width[0] + BLOCK_X;
  554. if (s->all_fragments[current_fragment].coding_method != MODE_COPY)
  555. break;
  556. }
  557. if (k == 4) {
  558. s->macroblock_coding[current_macroblock] = MODE_INTER_NO_MV;
  559. continue;
  560. }
  561. /* mode 7 means get 3 bits for each coding mode */
  562. if (scheme == 7)
  563. coding_mode = get_bits(gb, 3);
  564. else
  565. coding_mode = alphabet[get_vlc2(gb, s->mode_code_vlc.table, 3, 3)];
  566. s->macroblock_coding[current_macroblock] = coding_mode;
  567. for (k = 0; k < 4; k++) {
  568. frag = s->all_fragments + BLOCK_Y * s->fragment_width[0] + BLOCK_X;
  569. if (frag->coding_method != MODE_COPY)
  570. frag->coding_method = coding_mode;
  571. }
  572. #define SET_CHROMA_MODES \
  573. if (frag[s->fragment_start[1]].coding_method != MODE_COPY) \
  574. frag[s->fragment_start[1]].coding_method = coding_mode; \
  575. if (frag[s->fragment_start[2]].coding_method != MODE_COPY) \
  576. frag[s->fragment_start[2]].coding_method = coding_mode;
  577. if (s->chroma_y_shift) {
  578. frag = s->all_fragments + mb_y *
  579. s->fragment_width[1] + mb_x;
  580. SET_CHROMA_MODES
  581. } else if (s->chroma_x_shift) {
  582. frag = s->all_fragments +
  583. 2 * mb_y * s->fragment_width[1] + mb_x;
  584. for (k = 0; k < 2; k++) {
  585. SET_CHROMA_MODES
  586. frag += s->fragment_width[1];
  587. }
  588. } else {
  589. for (k = 0; k < 4; k++) {
  590. frag = s->all_fragments +
  591. BLOCK_Y * s->fragment_width[1] + BLOCK_X;
  592. SET_CHROMA_MODES
  593. }
  594. }
  595. }
  596. }
  597. }
  598. }
  599. return 0;
  600. }
  601. /*
  602. * This function unpacks all the motion vectors for the individual
  603. * macroblocks from the bitstream.
  604. */
  605. static int unpack_vectors(Vp3DecodeContext *s, GetBitContext *gb)
  606. {
  607. int j, k, sb_x, sb_y;
  608. int coding_mode;
  609. int motion_x[4];
  610. int motion_y[4];
  611. int last_motion_x = 0;
  612. int last_motion_y = 0;
  613. int prior_last_motion_x = 0;
  614. int prior_last_motion_y = 0;
  615. int current_macroblock;
  616. int current_fragment;
  617. int frag;
  618. if (s->keyframe)
  619. return 0;
  620. /* coding mode 0 is the VLC scheme; 1 is the fixed code scheme */
  621. coding_mode = get_bits1(gb);
  622. /* iterate through all of the macroblocks that contain 1 or more
  623. * coded fragments */
  624. for (sb_y = 0; sb_y < s->y_superblock_height; sb_y++) {
  625. for (sb_x = 0; sb_x < s->y_superblock_width; sb_x++) {
  626. if (get_bits_left(gb) <= 0)
  627. return -1;
  628. for (j = 0; j < 4; j++) {
  629. int mb_x = 2 * sb_x + (j >> 1);
  630. int mb_y = 2 * sb_y + (((j >> 1) + j) & 1);
  631. current_macroblock = mb_y * s->macroblock_width + mb_x;
  632. if (mb_x >= s->macroblock_width ||
  633. mb_y >= s->macroblock_height ||
  634. s->macroblock_coding[current_macroblock] == MODE_COPY)
  635. continue;
  636. switch (s->macroblock_coding[current_macroblock]) {
  637. case MODE_INTER_PLUS_MV:
  638. case MODE_GOLDEN_MV:
  639. /* all 6 fragments use the same motion vector */
  640. if (coding_mode == 0) {
  641. motion_x[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
  642. motion_y[0] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
  643. } else {
  644. motion_x[0] = fixed_motion_vector_table[get_bits(gb, 6)];
  645. motion_y[0] = fixed_motion_vector_table[get_bits(gb, 6)];
  646. }
  647. /* vector maintenance, only on MODE_INTER_PLUS_MV */
  648. if (s->macroblock_coding[current_macroblock] == MODE_INTER_PLUS_MV) {
  649. prior_last_motion_x = last_motion_x;
  650. prior_last_motion_y = last_motion_y;
  651. last_motion_x = motion_x[0];
  652. last_motion_y = motion_y[0];
  653. }
  654. break;
  655. case MODE_INTER_FOURMV:
  656. /* vector maintenance */
  657. prior_last_motion_x = last_motion_x;
  658. prior_last_motion_y = last_motion_y;
  659. /* fetch 4 vectors from the bitstream, one for each
  660. * Y fragment, then average for the C fragment vectors */
  661. for (k = 0; k < 4; k++) {
  662. current_fragment = BLOCK_Y * s->fragment_width[0] + BLOCK_X;
  663. if (s->all_fragments[current_fragment].coding_method != MODE_COPY) {
  664. if (coding_mode == 0) {
  665. motion_x[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
  666. motion_y[k] = motion_vector_table[get_vlc2(gb, s->motion_vector_vlc.table, 6, 2)];
  667. } else {
  668. motion_x[k] = fixed_motion_vector_table[get_bits(gb, 6)];
  669. motion_y[k] = fixed_motion_vector_table[get_bits(gb, 6)];
  670. }
  671. last_motion_x = motion_x[k];
  672. last_motion_y = motion_y[k];
  673. } else {
  674. motion_x[k] = 0;
  675. motion_y[k] = 0;
  676. }
  677. }
  678. break;
  679. case MODE_INTER_LAST_MV:
  680. /* all 6 fragments use the last motion vector */
  681. motion_x[0] = last_motion_x;
  682. motion_y[0] = last_motion_y;
  683. /* no vector maintenance (last vector remains the
  684. * last vector) */
  685. break;
  686. case MODE_INTER_PRIOR_LAST:
  687. /* all 6 fragments use the motion vector prior to the
  688. * last motion vector */
  689. motion_x[0] = prior_last_motion_x;
  690. motion_y[0] = prior_last_motion_y;
  691. /* vector maintenance */
  692. prior_last_motion_x = last_motion_x;
  693. prior_last_motion_y = last_motion_y;
  694. last_motion_x = motion_x[0];
  695. last_motion_y = motion_y[0];
  696. break;
  697. default:
  698. /* covers intra, inter without MV, golden without MV */
  699. motion_x[0] = 0;
  700. motion_y[0] = 0;
  701. /* no vector maintenance */
  702. break;
  703. }
  704. /* assign the motion vectors to the correct fragments */
  705. for (k = 0; k < 4; k++) {
  706. current_fragment =
  707. BLOCK_Y * s->fragment_width[0] + BLOCK_X;
  708. if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
  709. s->motion_val[0][current_fragment][0] = motion_x[k];
  710. s->motion_val[0][current_fragment][1] = motion_y[k];
  711. } else {
  712. s->motion_val[0][current_fragment][0] = motion_x[0];
  713. s->motion_val[0][current_fragment][1] = motion_y[0];
  714. }
  715. }
  716. if (s->chroma_y_shift) {
  717. if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
  718. motion_x[0] = RSHIFT(motion_x[0] + motion_x[1] +
  719. motion_x[2] + motion_x[3], 2);
  720. motion_y[0] = RSHIFT(motion_y[0] + motion_y[1] +
  721. motion_y[2] + motion_y[3], 2);
  722. }
  723. motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
  724. motion_y[0] = (motion_y[0] >> 1) | (motion_y[0] & 1);
  725. frag = mb_y * s->fragment_width[1] + mb_x;
  726. s->motion_val[1][frag][0] = motion_x[0];
  727. s->motion_val[1][frag][1] = motion_y[0];
  728. } else if (s->chroma_x_shift) {
  729. if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
  730. motion_x[0] = RSHIFT(motion_x[0] + motion_x[1], 1);
  731. motion_y[0] = RSHIFT(motion_y[0] + motion_y[1], 1);
  732. motion_x[1] = RSHIFT(motion_x[2] + motion_x[3], 1);
  733. motion_y[1] = RSHIFT(motion_y[2] + motion_y[3], 1);
  734. } else {
  735. motion_x[1] = motion_x[0];
  736. motion_y[1] = motion_y[0];
  737. }
  738. motion_x[0] = (motion_x[0] >> 1) | (motion_x[0] & 1);
  739. motion_x[1] = (motion_x[1] >> 1) | (motion_x[1] & 1);
  740. frag = 2 * mb_y * s->fragment_width[1] + mb_x;
  741. for (k = 0; k < 2; k++) {
  742. s->motion_val[1][frag][0] = motion_x[k];
  743. s->motion_val[1][frag][1] = motion_y[k];
  744. frag += s->fragment_width[1];
  745. }
  746. } else {
  747. for (k = 0; k < 4; k++) {
  748. frag = BLOCK_Y * s->fragment_width[1] + BLOCK_X;
  749. if (s->macroblock_coding[current_macroblock] == MODE_INTER_FOURMV) {
  750. s->motion_val[1][frag][0] = motion_x[k];
  751. s->motion_val[1][frag][1] = motion_y[k];
  752. } else {
  753. s->motion_val[1][frag][0] = motion_x[0];
  754. s->motion_val[1][frag][1] = motion_y[0];
  755. }
  756. }
  757. }
  758. }
  759. }
  760. }
  761. return 0;
  762. }
  763. static int unpack_block_qpis(Vp3DecodeContext *s, GetBitContext *gb)
  764. {
  765. int qpi, i, j, bit, run_length, blocks_decoded, num_blocks_at_qpi;
  766. int num_blocks = s->total_num_coded_frags;
  767. for (qpi = 0; qpi < s->nqps - 1 && num_blocks > 0; qpi++) {
  768. i = blocks_decoded = num_blocks_at_qpi = 0;
  769. bit = get_bits1(gb) ^ 1;
  770. run_length = 0;
  771. do {
  772. if (run_length == MAXIMUM_LONG_BIT_RUN)
  773. bit = get_bits1(gb);
  774. else
  775. bit ^= 1;
  776. run_length = get_vlc2(gb, s->superblock_run_length_vlc.table, 6, 2) + 1;
  777. if (run_length == 34)
  778. run_length += get_bits(gb, 12);
  779. blocks_decoded += run_length;
  780. if (!bit)
  781. num_blocks_at_qpi += run_length;
  782. for (j = 0; j < run_length; i++) {
  783. if (i >= s->total_num_coded_frags)
  784. return -1;
  785. if (s->all_fragments[s->coded_fragment_list[0][i]].qpi == qpi) {
  786. s->all_fragments[s->coded_fragment_list[0][i]].qpi += bit;
  787. j++;
  788. }
  789. }
  790. } while (blocks_decoded < num_blocks && get_bits_left(gb) > 0);
  791. num_blocks -= num_blocks_at_qpi;
  792. }
  793. return 0;
  794. }
  795. /*
  796. * This function is called by unpack_dct_coeffs() to extract the VLCs from
  797. * the bitstream. The VLCs encode tokens which are used to unpack DCT
  798. * data. This function unpacks all the VLCs for either the Y plane or both
  799. * C planes, and is called for DC coefficients or different AC coefficient
  800. * levels (since different coefficient types require different VLC tables.
  801. *
  802. * This function returns a residual eob run. E.g, if a particular token gave
  803. * instructions to EOB the next 5 fragments and there were only 2 fragments
  804. * left in the current fragment range, 3 would be returned so that it could
  805. * be passed into the next call to this same function.
  806. */
  807. static int unpack_vlcs(Vp3DecodeContext *s, GetBitContext *gb,
  808. VLC *table, int coeff_index,
  809. int plane,
  810. int eob_run)
  811. {
  812. int i, j = 0;
  813. int token;
  814. int zero_run = 0;
  815. int16_t coeff = 0;
  816. int bits_to_get;
  817. int blocks_ended;
  818. int coeff_i = 0;
  819. int num_coeffs = s->num_coded_frags[plane][coeff_index];
  820. int16_t *dct_tokens = s->dct_tokens[plane][coeff_index];
  821. /* local references to structure members to avoid repeated dereferences */
  822. int *coded_fragment_list = s->coded_fragment_list[plane];
  823. Vp3Fragment *all_fragments = s->all_fragments;
  824. VLC_TYPE(*vlc_table)[2] = table->table;
  825. if (num_coeffs < 0) {
  826. av_log(s->avctx, AV_LOG_ERROR,
  827. "Invalid number of coefficients at level %d\n", coeff_index);
  828. return AVERROR_INVALIDDATA;
  829. }
  830. if (eob_run > num_coeffs) {
  831. coeff_i =
  832. blocks_ended = num_coeffs;
  833. eob_run -= num_coeffs;
  834. } else {
  835. coeff_i =
  836. blocks_ended = eob_run;
  837. eob_run = 0;
  838. }
  839. // insert fake EOB token to cover the split between planes or zzi
  840. if (blocks_ended)
  841. dct_tokens[j++] = blocks_ended << 2;
  842. while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
  843. /* decode a VLC into a token */
  844. token = get_vlc2(gb, vlc_table, 11, 3);
  845. /* use the token to get a zero run, a coefficient, and an eob run */
  846. if ((unsigned) token <= 6U) {
  847. eob_run = eob_run_base[token];
  848. if (eob_run_get_bits[token])
  849. eob_run += get_bits(gb, eob_run_get_bits[token]);
  850. if (!eob_run)
  851. eob_run = INT_MAX;
  852. // record only the number of blocks ended in this plane,
  853. // any spill will be recorded in the next plane.
  854. if (eob_run > num_coeffs - coeff_i) {
  855. dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
  856. blocks_ended += num_coeffs - coeff_i;
  857. eob_run -= num_coeffs - coeff_i;
  858. coeff_i = num_coeffs;
  859. } else {
  860. dct_tokens[j++] = TOKEN_EOB(eob_run);
  861. blocks_ended += eob_run;
  862. coeff_i += eob_run;
  863. eob_run = 0;
  864. }
  865. } else if (token >= 0) {
  866. bits_to_get = coeff_get_bits[token];
  867. if (bits_to_get)
  868. bits_to_get = get_bits(gb, bits_to_get);
  869. coeff = coeff_tables[token][bits_to_get];
  870. zero_run = zero_run_base[token];
  871. if (zero_run_get_bits[token])
  872. zero_run += get_bits(gb, zero_run_get_bits[token]);
  873. if (zero_run) {
  874. dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
  875. } else {
  876. // Save DC into the fragment structure. DC prediction is
  877. // done in raster order, so the actual DC can't be in with
  878. // other tokens. We still need the token in dct_tokens[]
  879. // however, or else the structure collapses on itself.
  880. if (!coeff_index)
  881. all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
  882. dct_tokens[j++] = TOKEN_COEFF(coeff);
  883. }
  884. if (coeff_index + zero_run > 64) {
  885. av_log(s->avctx, AV_LOG_DEBUG,
  886. "Invalid zero run of %d with %d coeffs left\n",
  887. zero_run, 64 - coeff_index);
  888. zero_run = 64 - coeff_index;
  889. }
  890. // zero runs code multiple coefficients,
  891. // so don't try to decode coeffs for those higher levels
  892. for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
  893. s->num_coded_frags[plane][i]--;
  894. coeff_i++;
  895. } else {
  896. av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
  897. return -1;
  898. }
  899. }
  900. if (blocks_ended > s->num_coded_frags[plane][coeff_index])
  901. av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
  902. // decrement the number of blocks that have higher coefficients for each
  903. // EOB run at this level
  904. if (blocks_ended)
  905. for (i = coeff_index + 1; i < 64; i++)
  906. s->num_coded_frags[plane][i] -= blocks_ended;
  907. // setup the next buffer
  908. if (plane < 2)
  909. s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
  910. else if (coeff_index < 63)
  911. s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
  912. return eob_run;
  913. }
  914. static void reverse_dc_prediction(Vp3DecodeContext *s,
  915. int first_fragment,
  916. int fragment_width,
  917. int fragment_height);
  918. /*
  919. * This function unpacks all of the DCT coefficient data from the
  920. * bitstream.
  921. */
  922. static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
  923. {
  924. int i;
  925. int dc_y_table;
  926. int dc_c_table;
  927. int ac_y_table;
  928. int ac_c_table;
  929. int residual_eob_run = 0;
  930. VLC *y_tables[64];
  931. VLC *c_tables[64];
  932. s->dct_tokens[0][0] = s->dct_tokens_base;
  933. if (get_bits_left(gb) < 16)
  934. return AVERROR_INVALIDDATA;
  935. /* fetch the DC table indexes */
  936. dc_y_table = get_bits(gb, 4);
  937. dc_c_table = get_bits(gb, 4);
  938. /* unpack the Y plane DC coefficients */
  939. residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
  940. 0, residual_eob_run);
  941. if (residual_eob_run < 0)
  942. return residual_eob_run;
  943. if (get_bits_left(gb) < 8)
  944. return AVERROR_INVALIDDATA;
  945. /* reverse prediction of the Y-plane DC coefficients */
  946. reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
  947. /* unpack the C plane DC coefficients */
  948. residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
  949. 1, residual_eob_run);
  950. if (residual_eob_run < 0)
  951. return residual_eob_run;
  952. residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
  953. 2, residual_eob_run);
  954. if (residual_eob_run < 0)
  955. return residual_eob_run;
  956. /* reverse prediction of the C-plane DC coefficients */
  957. if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
  958. reverse_dc_prediction(s, s->fragment_start[1],
  959. s->fragment_width[1], s->fragment_height[1]);
  960. reverse_dc_prediction(s, s->fragment_start[2],
  961. s->fragment_width[1], s->fragment_height[1]);
  962. }
  963. if (get_bits_left(gb) < 8)
  964. return AVERROR_INVALIDDATA;
  965. /* fetch the AC table indexes */
  966. ac_y_table = get_bits(gb, 4);
  967. ac_c_table = get_bits(gb, 4);
  968. /* build tables of AC VLC tables */
  969. for (i = 1; i <= 5; i++) {
  970. y_tables[i] = &s->ac_vlc_1[ac_y_table];
  971. c_tables[i] = &s->ac_vlc_1[ac_c_table];
  972. }
  973. for (i = 6; i <= 14; i++) {
  974. y_tables[i] = &s->ac_vlc_2[ac_y_table];
  975. c_tables[i] = &s->ac_vlc_2[ac_c_table];
  976. }
  977. for (i = 15; i <= 27; i++) {
  978. y_tables[i] = &s->ac_vlc_3[ac_y_table];
  979. c_tables[i] = &s->ac_vlc_3[ac_c_table];
  980. }
  981. for (i = 28; i <= 63; i++) {
  982. y_tables[i] = &s->ac_vlc_4[ac_y_table];
  983. c_tables[i] = &s->ac_vlc_4[ac_c_table];
  984. }
  985. /* decode all AC coefficients */
  986. for (i = 1; i <= 63; i++) {
  987. residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
  988. 0, residual_eob_run);
  989. if (residual_eob_run < 0)
  990. return residual_eob_run;
  991. residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
  992. 1, residual_eob_run);
  993. if (residual_eob_run < 0)
  994. return residual_eob_run;
  995. residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
  996. 2, residual_eob_run);
  997. if (residual_eob_run < 0)
  998. return residual_eob_run;
  999. }
  1000. return 0;
  1001. }
  1002. /*
  1003. * This function reverses the DC prediction for each coded fragment in
  1004. * the frame. Much of this function is adapted directly from the original
  1005. * VP3 source code.
  1006. */
  1007. #define COMPATIBLE_FRAME(x) \
  1008. (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
  1009. #define DC_COEFF(u) s->all_fragments[u].dc
  1010. static void reverse_dc_prediction(Vp3DecodeContext *s,
  1011. int first_fragment,
  1012. int fragment_width,
  1013. int fragment_height)
  1014. {
  1015. #define PUL 8
  1016. #define PU 4
  1017. #define PUR 2
  1018. #define PL 1
  1019. int x, y;
  1020. int i = first_fragment;
  1021. int predicted_dc;
  1022. /* DC values for the left, up-left, up, and up-right fragments */
  1023. int vl, vul, vu, vur;
  1024. /* indexes for the left, up-left, up, and up-right fragments */
  1025. int l, ul, u, ur;
  1026. /*
  1027. * The 6 fields mean:
  1028. * 0: up-left multiplier
  1029. * 1: up multiplier
  1030. * 2: up-right multiplier
  1031. * 3: left multiplier
  1032. */
  1033. static const int predictor_transform[16][4] = {
  1034. { 0, 0, 0, 0 },
  1035. { 0, 0, 0, 128 }, // PL
  1036. { 0, 0, 128, 0 }, // PUR
  1037. { 0, 0, 53, 75 }, // PUR|PL
  1038. { 0, 128, 0, 0 }, // PU
  1039. { 0, 64, 0, 64 }, // PU |PL
  1040. { 0, 128, 0, 0 }, // PU |PUR
  1041. { 0, 0, 53, 75 }, // PU |PUR|PL
  1042. { 128, 0, 0, 0 }, // PUL
  1043. { 0, 0, 0, 128 }, // PUL|PL
  1044. { 64, 0, 64, 0 }, // PUL|PUR
  1045. { 0, 0, 53, 75 }, // PUL|PUR|PL
  1046. { 0, 128, 0, 0 }, // PUL|PU
  1047. { -104, 116, 0, 116 }, // PUL|PU |PL
  1048. { 24, 80, 24, 0 }, // PUL|PU |PUR
  1049. { -104, 116, 0, 116 } // PUL|PU |PUR|PL
  1050. };
  1051. /* This table shows which types of blocks can use other blocks for
  1052. * prediction. For example, INTRA is the only mode in this table to
  1053. * have a frame number of 0. That means INTRA blocks can only predict
  1054. * from other INTRA blocks. There are 2 golden frame coding types;
  1055. * blocks encoding in these modes can only predict from other blocks
  1056. * that were encoded with these 1 of these 2 modes. */
  1057. static const unsigned char compatible_frame[9] = {
  1058. 1, /* MODE_INTER_NO_MV */
  1059. 0, /* MODE_INTRA */
  1060. 1, /* MODE_INTER_PLUS_MV */
  1061. 1, /* MODE_INTER_LAST_MV */
  1062. 1, /* MODE_INTER_PRIOR_MV */
  1063. 2, /* MODE_USING_GOLDEN */
  1064. 2, /* MODE_GOLDEN_MV */
  1065. 1, /* MODE_INTER_FOUR_MV */
  1066. 3 /* MODE_COPY */
  1067. };
  1068. int current_frame_type;
  1069. /* there is a last DC predictor for each of the 3 frame types */
  1070. short last_dc[3];
  1071. int transform = 0;
  1072. vul =
  1073. vu =
  1074. vur =
  1075. vl = 0;
  1076. last_dc[0] =
  1077. last_dc[1] =
  1078. last_dc[2] = 0;
  1079. /* for each fragment row... */
  1080. for (y = 0; y < fragment_height; y++) {
  1081. /* for each fragment in a row... */
  1082. for (x = 0; x < fragment_width; x++, i++) {
  1083. /* reverse prediction if this block was coded */
  1084. if (s->all_fragments[i].coding_method != MODE_COPY) {
  1085. current_frame_type =
  1086. compatible_frame[s->all_fragments[i].coding_method];
  1087. transform = 0;
  1088. if (x) {
  1089. l = i - 1;
  1090. vl = DC_COEFF(l);
  1091. if (COMPATIBLE_FRAME(l))
  1092. transform |= PL;
  1093. }
  1094. if (y) {
  1095. u = i - fragment_width;
  1096. vu = DC_COEFF(u);
  1097. if (COMPATIBLE_FRAME(u))
  1098. transform |= PU;
  1099. if (x) {
  1100. ul = i - fragment_width - 1;
  1101. vul = DC_COEFF(ul);
  1102. if (COMPATIBLE_FRAME(ul))
  1103. transform |= PUL;
  1104. }
  1105. if (x + 1 < fragment_width) {
  1106. ur = i - fragment_width + 1;
  1107. vur = DC_COEFF(ur);
  1108. if (COMPATIBLE_FRAME(ur))
  1109. transform |= PUR;
  1110. }
  1111. }
  1112. if (transform == 0) {
  1113. /* if there were no fragments to predict from, use last
  1114. * DC saved */
  1115. predicted_dc = last_dc[current_frame_type];
  1116. } else {
  1117. /* apply the appropriate predictor transform */
  1118. predicted_dc =
  1119. (predictor_transform[transform][0] * vul) +
  1120. (predictor_transform[transform][1] * vu) +
  1121. (predictor_transform[transform][2] * vur) +
  1122. (predictor_transform[transform][3] * vl);
  1123. predicted_dc /= 128;
  1124. /* check for outranging on the [ul u l] and
  1125. * [ul u ur l] predictors */
  1126. if ((transform == 15) || (transform == 13)) {
  1127. if (FFABS(predicted_dc - vu) > 128)
  1128. predicted_dc = vu;
  1129. else if (FFABS(predicted_dc - vl) > 128)
  1130. predicted_dc = vl;
  1131. else if (FFABS(predicted_dc - vul) > 128)
  1132. predicted_dc = vul;
  1133. }
  1134. }
  1135. /* at long last, apply the predictor */
  1136. DC_COEFF(i) += predicted_dc;
  1137. /* save the DC */
  1138. last_dc[current_frame_type] = DC_COEFF(i);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. static void apply_loop_filter(Vp3DecodeContext *s, int plane,
  1144. int ystart, int yend)
  1145. {
  1146. int x, y;
  1147. int *bounding_values = s->bounding_values_array + 127;
  1148. int width = s->fragment_width[!!plane];
  1149. int height = s->fragment_height[!!plane];
  1150. int fragment = s->fragment_start[plane] + ystart * width;
  1151. ptrdiff_t stride = s->current_frame.f->linesize[plane];
  1152. uint8_t *plane_data = s->current_frame.f->data[plane];
  1153. if (!s->flipped_image)
  1154. stride = -stride;
  1155. plane_data += s->data_offset[plane] + 8 * ystart * stride;
  1156. for (y = ystart; y < yend; y++) {
  1157. for (x = 0; x < width; x++) {
  1158. /* This code basically just deblocks on the edges of coded blocks.
  1159. * However, it has to be much more complicated because of the
  1160. * brain damaged deblock ordering used in VP3/Theora. Order matters
  1161. * because some pixels get filtered twice. */
  1162. if (s->all_fragments[fragment].coding_method != MODE_COPY) {
  1163. /* do not perform left edge filter for left columns frags */
  1164. if (x > 0) {
  1165. s->vp3dsp.h_loop_filter(
  1166. plane_data + 8 * x,
  1167. stride, bounding_values);
  1168. }
  1169. /* do not perform top edge filter for top row fragments */
  1170. if (y > 0) {
  1171. s->vp3dsp.v_loop_filter(
  1172. plane_data + 8 * x,
  1173. stride, bounding_values);
  1174. }
  1175. /* do not perform right edge filter for right column
  1176. * fragments or if right fragment neighbor is also coded
  1177. * in this frame (it will be filtered in next iteration) */
  1178. if ((x < width - 1) &&
  1179. (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
  1180. s->vp3dsp.h_loop_filter(
  1181. plane_data + 8 * x + 8,
  1182. stride, bounding_values);
  1183. }
  1184. /* do not perform bottom edge filter for bottom row
  1185. * fragments or if bottom fragment neighbor is also coded
  1186. * in this frame (it will be filtered in the next row) */
  1187. if ((y < height - 1) &&
  1188. (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
  1189. s->vp3dsp.v_loop_filter(
  1190. plane_data + 8 * x + 8 * stride,
  1191. stride, bounding_values);
  1192. }
  1193. }
  1194. fragment++;
  1195. }
  1196. plane_data += 8 * stride;
  1197. }
  1198. }
  1199. /**
  1200. * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
  1201. * for the next block in coding order
  1202. */
  1203. static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
  1204. int plane, int inter, int16_t block[64])
  1205. {
  1206. int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
  1207. uint8_t *perm = s->idct_scantable;
  1208. int i = 0;
  1209. do {
  1210. int token = *s->dct_tokens[plane][i];
  1211. switch (token & 3) {
  1212. case 0: // EOB
  1213. if (--token < 4) // 0-3 are token types so the EOB run must now be 0
  1214. s->dct_tokens[plane][i]++;
  1215. else
  1216. *s->dct_tokens[plane][i] = token & ~3;
  1217. goto end;
  1218. case 1: // zero run
  1219. s->dct_tokens[plane][i]++;
  1220. i += (token >> 2) & 0x7f;
  1221. if (i > 63) {
  1222. av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
  1223. return i;
  1224. }
  1225. block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
  1226. i++;
  1227. break;
  1228. case 2: // coeff
  1229. block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
  1230. s->dct_tokens[plane][i++]++;
  1231. break;
  1232. default: // shouldn't happen
  1233. return i;
  1234. }
  1235. } while (i < 64);
  1236. // return value is expected to be a valid level
  1237. i--;
  1238. end:
  1239. // the actual DC+prediction is in the fragment structure
  1240. block[0] = frag->dc * s->qmat[0][inter][plane][0];
  1241. return i;
  1242. }
  1243. /**
  1244. * called when all pixels up to row y are complete
  1245. */
  1246. static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
  1247. {
  1248. int h, cy, i;
  1249. int offset[AV_NUM_DATA_POINTERS];
  1250. if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
  1251. int y_flipped = s->flipped_image ? s->height - y : y;
  1252. /* At the end of the frame, report INT_MAX instead of the height of
  1253. * the frame. This makes the other threads' ff_thread_await_progress()
  1254. * calls cheaper, because they don't have to clip their values. */
  1255. ff_thread_report_progress(&s->current_frame,
  1256. y_flipped == s->height ? INT_MAX
  1257. : y_flipped - 1,
  1258. 0);
  1259. }
  1260. if (!s->avctx->draw_horiz_band)
  1261. return;
  1262. h = y - s->last_slice_end;
  1263. s->last_slice_end = y;
  1264. y -= h;
  1265. if (!s->flipped_image)
  1266. y = s->height - y - h;
  1267. cy = y >> s->chroma_y_shift;
  1268. offset[0] = s->current_frame.f->linesize[0] * y;
  1269. offset[1] = s->current_frame.f->linesize[1] * cy;
  1270. offset[2] = s->current_frame.f->linesize[2] * cy;
  1271. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  1272. offset[i] = 0;
  1273. emms_c();
  1274. s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
  1275. }
  1276. /**
  1277. * Wait for the reference frame of the current fragment.
  1278. * The progress value is in luma pixel rows.
  1279. */
  1280. static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
  1281. int motion_y, int y)
  1282. {
  1283. ThreadFrame *ref_frame;
  1284. int ref_row;
  1285. int border = motion_y & 1;
  1286. if (fragment->coding_method == MODE_USING_GOLDEN ||
  1287. fragment->coding_method == MODE_GOLDEN_MV)
  1288. ref_frame = &s->golden_frame;
  1289. else
  1290. ref_frame = &s->last_frame;
  1291. ref_row = y + (motion_y >> 1);
  1292. ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
  1293. ff_thread_await_progress(ref_frame, ref_row, 0);
  1294. }
  1295. /*
  1296. * Perform the final rendering for a particular slice of data.
  1297. * The slice number ranges from 0..(c_superblock_height - 1).
  1298. */
  1299. static void render_slice(Vp3DecodeContext *s, int slice)
  1300. {
  1301. int x, y, i, j, fragment;
  1302. int16_t *block = s->block;
  1303. int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
  1304. int motion_halfpel_index;
  1305. uint8_t *motion_source;
  1306. int plane, first_pixel;
  1307. if (slice >= s->c_superblock_height)
  1308. return;
  1309. for (plane = 0; plane < 3; plane++) {
  1310. uint8_t *output_plane = s->current_frame.f->data[plane] +
  1311. s->data_offset[plane];
  1312. uint8_t *last_plane = s->last_frame.f->data[plane] +
  1313. s->data_offset[plane];
  1314. uint8_t *golden_plane = s->golden_frame.f->data[plane] +
  1315. s->data_offset[plane];
  1316. ptrdiff_t stride = s->current_frame.f->linesize[plane];
  1317. int plane_width = s->width >> (plane && s->chroma_x_shift);
  1318. int plane_height = s->height >> (plane && s->chroma_y_shift);
  1319. int8_t(*motion_val)[2] = s->motion_val[!!plane];
  1320. int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
  1321. int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
  1322. int slice_width = plane ? s->c_superblock_width
  1323. : s->y_superblock_width;
  1324. int fragment_width = s->fragment_width[!!plane];
  1325. int fragment_height = s->fragment_height[!!plane];
  1326. int fragment_start = s->fragment_start[plane];
  1327. int do_await = !plane && HAVE_THREADS &&
  1328. (s->avctx->active_thread_type & FF_THREAD_FRAME);
  1329. if (!s->flipped_image)
  1330. stride = -stride;
  1331. if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
  1332. continue;
  1333. /* for each superblock row in the slice (both of them)... */
  1334. for (; sb_y < slice_height; sb_y++) {
  1335. /* for each superblock in a row... */
  1336. for (sb_x = 0; sb_x < slice_width; sb_x++) {
  1337. /* for each block in a superblock... */
  1338. for (j = 0; j < 16; j++) {
  1339. x = 4 * sb_x + hilbert_offset[j][0];
  1340. y = 4 * sb_y + hilbert_offset[j][1];
  1341. fragment = y * fragment_width + x;
  1342. i = fragment_start + fragment;
  1343. // bounds check
  1344. if (x >= fragment_width || y >= fragment_height)
  1345. continue;
  1346. first_pixel = 8 * y * stride + 8 * x;
  1347. if (do_await &&
  1348. s->all_fragments[i].coding_method != MODE_INTRA)
  1349. await_reference_row(s, &s->all_fragments[i],
  1350. motion_val[fragment][1],
  1351. (16 * y) >> s->chroma_y_shift);
  1352. /* transform if this block was coded */
  1353. if (s->all_fragments[i].coding_method != MODE_COPY) {
  1354. if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
  1355. (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
  1356. motion_source = golden_plane;
  1357. else
  1358. motion_source = last_plane;
  1359. motion_source += first_pixel;
  1360. motion_halfpel_index = 0;
  1361. /* sort out the motion vector if this fragment is coded
  1362. * using a motion vector method */
  1363. if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
  1364. (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
  1365. int src_x, src_y;
  1366. motion_x = motion_val[fragment][0];
  1367. motion_y = motion_val[fragment][1];
  1368. src_x = (motion_x >> 1) + 8 * x;
  1369. src_y = (motion_y >> 1) + 8 * y;
  1370. motion_halfpel_index = motion_x & 0x01;
  1371. motion_source += (motion_x >> 1);
  1372. motion_halfpel_index |= (motion_y & 0x01) << 1;
  1373. motion_source += ((motion_y >> 1) * stride);
  1374. if (src_x < 0 || src_y < 0 ||
  1375. src_x + 9 >= plane_width ||
  1376. src_y + 9 >= plane_height) {
  1377. uint8_t *temp = s->edge_emu_buffer;
  1378. if (stride < 0)
  1379. temp -= 8 * stride;
  1380. s->vdsp.emulated_edge_mc(temp, motion_source,
  1381. stride, stride,
  1382. 9, 9, src_x, src_y,
  1383. plane_width,
  1384. plane_height);
  1385. motion_source = temp;
  1386. }
  1387. }
  1388. /* first, take care of copying a block from either the
  1389. * previous or the golden frame */
  1390. if (s->all_fragments[i].coding_method != MODE_INTRA) {
  1391. /* Note, it is possible to implement all MC cases
  1392. * with put_no_rnd_pixels_l2 which would look more
  1393. * like the VP3 source but this would be slower as
  1394. * put_no_rnd_pixels_tab is better optimized */
  1395. if (motion_halfpel_index != 3) {
  1396. s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
  1397. output_plane + first_pixel,
  1398. motion_source, stride, 8);
  1399. } else {
  1400. /* d is 0 if motion_x and _y have the same sign,
  1401. * else -1 */
  1402. int d = (motion_x ^ motion_y) >> 31;
  1403. s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
  1404. motion_source - d,
  1405. motion_source + stride + 1 + d,
  1406. stride, 8);
  1407. }
  1408. }
  1409. /* invert DCT and place (or add) in final output */
  1410. if (s->all_fragments[i].coding_method == MODE_INTRA) {
  1411. vp3_dequant(s, s->all_fragments + i,
  1412. plane, 0, block);
  1413. s->vp3dsp.idct_put(output_plane + first_pixel,
  1414. stride,
  1415. block);
  1416. } else {
  1417. if (vp3_dequant(s, s->all_fragments + i,
  1418. plane, 1, block)) {
  1419. s->vp3dsp.idct_add(output_plane + first_pixel,
  1420. stride,
  1421. block);
  1422. } else {
  1423. s->vp3dsp.idct_dc_add(output_plane + first_pixel,
  1424. stride, block);
  1425. }
  1426. }
  1427. } else {
  1428. /* copy directly from the previous frame */
  1429. s->hdsp.put_pixels_tab[1][0](
  1430. output_plane + first_pixel,
  1431. last_plane + first_pixel,
  1432. stride, 8);
  1433. }
  1434. }
  1435. }
  1436. // Filter up to the last row in the superblock row
  1437. if (!s->skip_loop_filter)
  1438. apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
  1439. FFMIN(4 * sb_y + 3, fragment_height - 1));
  1440. }
  1441. }
  1442. /* this looks like a good place for slice dispatch... */
  1443. /* algorithm:
  1444. * if (slice == s->macroblock_height - 1)
  1445. * dispatch (both last slice & 2nd-to-last slice);
  1446. * else if (slice > 0)
  1447. * dispatch (slice - 1);
  1448. */
  1449. vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
  1450. s->height - 16));
  1451. }
  1452. /// Allocate tables for per-frame data in Vp3DecodeContext
  1453. static av_cold int allocate_tables(AVCodecContext *avctx)
  1454. {
  1455. Vp3DecodeContext *s = avctx->priv_data;
  1456. int y_fragment_count, c_fragment_count;
  1457. free_tables(avctx);
  1458. y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
  1459. c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
  1460. s->superblock_coding = av_mallocz(s->superblock_count);
  1461. s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
  1462. s->coded_fragment_list[0] = av_mallocz_array(s->fragment_count, sizeof(int));
  1463. s->dct_tokens_base = av_mallocz_array(s->fragment_count,
  1464. 64 * sizeof(*s->dct_tokens_base));
  1465. s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
  1466. s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
  1467. /* work out the block mapping tables */
  1468. s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
  1469. s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
  1470. if (!s->superblock_coding || !s->all_fragments ||
  1471. !s->dct_tokens_base || !s->coded_fragment_list[0] ||
  1472. !s->superblock_fragments || !s->macroblock_coding ||
  1473. !s->motion_val[0] || !s->motion_val[1]) {
  1474. vp3_decode_end(avctx);
  1475. return -1;
  1476. }
  1477. init_block_mapping(s);
  1478. return 0;
  1479. }
  1480. static av_cold int init_frames(Vp3DecodeContext *s)
  1481. {
  1482. s->current_frame.f = av_frame_alloc();
  1483. s->last_frame.f = av_frame_alloc();
  1484. s->golden_frame.f = av_frame_alloc();
  1485. if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
  1486. av_frame_free(&s->current_frame.f);
  1487. av_frame_free(&s->last_frame.f);
  1488. av_frame_free(&s->golden_frame.f);
  1489. return AVERROR(ENOMEM);
  1490. }
  1491. return 0;
  1492. }
  1493. static av_cold int vp3_decode_init(AVCodecContext *avctx)
  1494. {
  1495. Vp3DecodeContext *s = avctx->priv_data;
  1496. int i, inter, plane, ret;
  1497. int c_width;
  1498. int c_height;
  1499. int y_fragment_count, c_fragment_count;
  1500. ret = init_frames(s);
  1501. if (ret < 0)
  1502. return ret;
  1503. avctx->internal->allocate_progress = 1;
  1504. if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
  1505. s->version = 0;
  1506. else
  1507. s->version = 1;
  1508. s->avctx = avctx;
  1509. s->width = FFALIGN(avctx->coded_width, 16);
  1510. s->height = FFALIGN(avctx->coded_height, 16);
  1511. if (avctx->codec_id != AV_CODEC_ID_THEORA)
  1512. avctx->pix_fmt = AV_PIX_FMT_YUV420P;
  1513. avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
  1514. ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
  1515. ff_videodsp_init(&s->vdsp, 8);
  1516. ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
  1517. for (i = 0; i < 64; i++) {
  1518. #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
  1519. s->idct_permutation[i] = TRANSPOSE(i);
  1520. s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
  1521. #undef TRANSPOSE
  1522. }
  1523. /* initialize to an impossible value which will force a recalculation
  1524. * in the first frame decode */
  1525. for (i = 0; i < 3; i++)
  1526. s->qps[i] = -1;
  1527. ret = av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
  1528. if (ret)
  1529. return ret;
  1530. s->y_superblock_width = (s->width + 31) / 32;
  1531. s->y_superblock_height = (s->height + 31) / 32;
  1532. s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
  1533. /* work out the dimensions for the C planes */
  1534. c_width = s->width >> s->chroma_x_shift;
  1535. c_height = s->height >> s->chroma_y_shift;
  1536. s->c_superblock_width = (c_width + 31) / 32;
  1537. s->c_superblock_height = (c_height + 31) / 32;
  1538. s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
  1539. s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
  1540. s->u_superblock_start = s->y_superblock_count;
  1541. s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
  1542. s->macroblock_width = (s->width + 15) / 16;
  1543. s->macroblock_height = (s->height + 15) / 16;
  1544. s->macroblock_count = s->macroblock_width * s->macroblock_height;
  1545. s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
  1546. s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
  1547. s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
  1548. s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
  1549. /* fragment count covers all 8x8 blocks for all 3 planes */
  1550. y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
  1551. c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
  1552. s->fragment_count = y_fragment_count + 2 * c_fragment_count;
  1553. s->fragment_start[1] = y_fragment_count;
  1554. s->fragment_start[2] = y_fragment_count + c_fragment_count;
  1555. if (!s->theora_tables) {
  1556. for (i = 0; i < 64; i++) {
  1557. s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
  1558. s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
  1559. s->base_matrix[0][i] = vp31_intra_y_dequant[i];
  1560. s->base_matrix[1][i] = vp31_intra_c_dequant[i];
  1561. s->base_matrix[2][i] = vp31_inter_dequant[i];
  1562. s->filter_limit_values[i] = vp31_filter_limit_values[i];
  1563. }
  1564. for (inter = 0; inter < 2; inter++) {
  1565. for (plane = 0; plane < 3; plane++) {
  1566. s->qr_count[inter][plane] = 1;
  1567. s->qr_size[inter][plane][0] = 63;
  1568. s->qr_base[inter][plane][0] =
  1569. s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
  1570. }
  1571. }
  1572. /* init VLC tables */
  1573. for (i = 0; i < 16; i++) {
  1574. /* DC histograms */
  1575. init_vlc(&s->dc_vlc[i], 11, 32,
  1576. &dc_bias[i][0][1], 4, 2,
  1577. &dc_bias[i][0][0], 4, 2, 0);
  1578. /* group 1 AC histograms */
  1579. init_vlc(&s->ac_vlc_1[i], 11, 32,
  1580. &ac_bias_0[i][0][1], 4, 2,
  1581. &ac_bias_0[i][0][0], 4, 2, 0);
  1582. /* group 2 AC histograms */
  1583. init_vlc(&s->ac_vlc_2[i], 11, 32,
  1584. &ac_bias_1[i][0][1], 4, 2,
  1585. &ac_bias_1[i][0][0], 4, 2, 0);
  1586. /* group 3 AC histograms */
  1587. init_vlc(&s->ac_vlc_3[i], 11, 32,
  1588. &ac_bias_2[i][0][1], 4, 2,
  1589. &ac_bias_2[i][0][0], 4, 2, 0);
  1590. /* group 4 AC histograms */
  1591. init_vlc(&s->ac_vlc_4[i], 11, 32,
  1592. &ac_bias_3[i][0][1], 4, 2,
  1593. &ac_bias_3[i][0][0], 4, 2, 0);
  1594. }
  1595. } else {
  1596. for (i = 0; i < 16; i++) {
  1597. /* DC histograms */
  1598. if (init_vlc(&s->dc_vlc[i], 11, 32,
  1599. &s->huffman_table[i][0][1], 8, 4,
  1600. &s->huffman_table[i][0][0], 8, 4, 0) < 0)
  1601. goto vlc_fail;
  1602. /* group 1 AC histograms */
  1603. if (init_vlc(&s->ac_vlc_1[i], 11, 32,
  1604. &s->huffman_table[i + 16][0][1], 8, 4,
  1605. &s->huffman_table[i + 16][0][0], 8, 4, 0) < 0)
  1606. goto vlc_fail;
  1607. /* group 2 AC histograms */
  1608. if (init_vlc(&s->ac_vlc_2[i], 11, 32,
  1609. &s->huffman_table[i + 16 * 2][0][1], 8, 4,
  1610. &s->huffman_table[i + 16 * 2][0][0], 8, 4, 0) < 0)
  1611. goto vlc_fail;
  1612. /* group 3 AC histograms */
  1613. if (init_vlc(&s->ac_vlc_3[i], 11, 32,
  1614. &s->huffman_table[i + 16 * 3][0][1], 8, 4,
  1615. &s->huffman_table[i + 16 * 3][0][0], 8, 4, 0) < 0)
  1616. goto vlc_fail;
  1617. /* group 4 AC histograms */
  1618. if (init_vlc(&s->ac_vlc_4[i], 11, 32,
  1619. &s->huffman_table[i + 16 * 4][0][1], 8, 4,
  1620. &s->huffman_table[i + 16 * 4][0][0], 8, 4, 0) < 0)
  1621. goto vlc_fail;
  1622. }
  1623. }
  1624. init_vlc(&s->superblock_run_length_vlc, 6, 34,
  1625. &superblock_run_length_vlc_table[0][1], 4, 2,
  1626. &superblock_run_length_vlc_table[0][0], 4, 2, 0);
  1627. init_vlc(&s->fragment_run_length_vlc, 5, 30,
  1628. &fragment_run_length_vlc_table[0][1], 4, 2,
  1629. &fragment_run_length_vlc_table[0][0], 4, 2, 0);
  1630. init_vlc(&s->mode_code_vlc, 3, 8,
  1631. &mode_code_vlc_table[0][1], 2, 1,
  1632. &mode_code_vlc_table[0][0], 2, 1, 0);
  1633. init_vlc(&s->motion_vector_vlc, 6, 63,
  1634. &motion_vector_vlc_table[0][1], 2, 1,
  1635. &motion_vector_vlc_table[0][0], 2, 1, 0);
  1636. return allocate_tables(avctx);
  1637. vlc_fail:
  1638. av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
  1639. return -1;
  1640. }
  1641. /// Release and shuffle frames after decode finishes
  1642. static int update_frames(AVCodecContext *avctx)
  1643. {
  1644. Vp3DecodeContext *s = avctx->priv_data;
  1645. int ret = 0;
  1646. /* shuffle frames (last = current) */
  1647. ff_thread_release_buffer(avctx, &s->last_frame);
  1648. ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
  1649. if (ret < 0)
  1650. goto fail;
  1651. if (s->keyframe) {
  1652. ff_thread_release_buffer(avctx, &s->golden_frame);
  1653. ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
  1654. }
  1655. fail:
  1656. ff_thread_release_buffer(avctx, &s->current_frame);
  1657. return ret;
  1658. }
  1659. static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
  1660. {
  1661. ff_thread_release_buffer(s->avctx, dst);
  1662. if (src->f->data[0])
  1663. return ff_thread_ref_frame(dst, src);
  1664. return 0;
  1665. }
  1666. static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
  1667. {
  1668. int ret;
  1669. if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
  1670. (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
  1671. (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
  1672. return ret;
  1673. return 0;
  1674. }
  1675. #if HAVE_THREADS
  1676. static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  1677. {
  1678. Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
  1679. int qps_changed = 0, i, err;
  1680. #define copy_fields(to, from, start_field, end_field) \
  1681. memcpy(&to->start_field, &from->start_field, \
  1682. (char *) &to->end_field - (char *) &to->start_field)
  1683. if (!s1->current_frame.f->data[0] ||
  1684. s->width != s1->width || s->height != s1->height) {
  1685. if (s != s1)
  1686. ref_frames(s, s1);
  1687. return -1;
  1688. }
  1689. if (s != s1) {
  1690. if (!s->current_frame.f)
  1691. return AVERROR(ENOMEM);
  1692. // init tables if the first frame hasn't been decoded
  1693. if (!s->current_frame.f->data[0]) {
  1694. int y_fragment_count, c_fragment_count;
  1695. s->avctx = dst;
  1696. err = allocate_tables(dst);
  1697. if (err)
  1698. return err;
  1699. y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
  1700. c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
  1701. memcpy(s->motion_val[0], s1->motion_val[0],
  1702. y_fragment_count * sizeof(*s->motion_val[0]));
  1703. memcpy(s->motion_val[1], s1->motion_val[1],
  1704. c_fragment_count * sizeof(*s->motion_val[1]));
  1705. }
  1706. // copy previous frame data
  1707. if ((err = ref_frames(s, s1)) < 0)
  1708. return err;
  1709. s->keyframe = s1->keyframe;
  1710. // copy qscale data if necessary
  1711. for (i = 0; i < 3; i++) {
  1712. if (s->qps[i] != s1->qps[1]) {
  1713. qps_changed = 1;
  1714. memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
  1715. }
  1716. }
  1717. if (s->qps[0] != s1->qps[0])
  1718. memcpy(&s->bounding_values_array, &s1->bounding_values_array,
  1719. sizeof(s->bounding_values_array));
  1720. if (qps_changed)
  1721. copy_fields(s, s1, qps, superblock_count);
  1722. #undef copy_fields
  1723. }
  1724. return update_frames(dst);
  1725. }
  1726. #endif
  1727. static int vp3_decode_frame(AVCodecContext *avctx,
  1728. void *data, int *got_frame,
  1729. AVPacket *avpkt)
  1730. {
  1731. AVFrame *frame = data;
  1732. const uint8_t *buf = avpkt->data;
  1733. int buf_size = avpkt->size;
  1734. Vp3DecodeContext *s = avctx->priv_data;
  1735. GetBitContext gb;
  1736. int i, ret;
  1737. if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
  1738. return ret;
  1739. #if CONFIG_THEORA_DECODER
  1740. if (s->theora && get_bits1(&gb)) {
  1741. int type = get_bits(&gb, 7);
  1742. skip_bits_long(&gb, 6*8); /* "theora" */
  1743. if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
  1744. av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
  1745. return AVERROR_PATCHWELCOME;
  1746. }
  1747. if (type == 0) {
  1748. vp3_decode_end(avctx);
  1749. ret = theora_decode_header(avctx, &gb);
  1750. if (ret >= 0)
  1751. ret = vp3_decode_init(avctx);
  1752. if (ret < 0) {
  1753. vp3_decode_end(avctx);
  1754. return ret;
  1755. }
  1756. return buf_size;
  1757. } else if (type == 2) {
  1758. vp3_decode_end(avctx);
  1759. ret = theora_decode_tables(avctx, &gb);
  1760. if (ret >= 0)
  1761. ret = vp3_decode_init(avctx);
  1762. if (ret < 0) {
  1763. vp3_decode_end(avctx);
  1764. return ret;
  1765. }
  1766. return buf_size;
  1767. }
  1768. av_log(avctx, AV_LOG_ERROR,
  1769. "Header packet passed to frame decoder, skipping\n");
  1770. return -1;
  1771. }
  1772. #endif
  1773. s->keyframe = !get_bits1(&gb);
  1774. if (!s->all_fragments) {
  1775. av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
  1776. return -1;
  1777. }
  1778. if (!s->theora)
  1779. skip_bits(&gb, 1);
  1780. for (i = 0; i < 3; i++)
  1781. s->last_qps[i] = s->qps[i];
  1782. s->nqps = 0;
  1783. do {
  1784. s->qps[s->nqps++] = get_bits(&gb, 6);
  1785. } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
  1786. for (i = s->nqps; i < 3; i++)
  1787. s->qps[i] = -1;
  1788. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1789. av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
  1790. s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
  1791. s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
  1792. avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
  1793. : AVDISCARD_NONKEY);
  1794. if (s->qps[0] != s->last_qps[0])
  1795. init_loop_filter(s);
  1796. for (i = 0; i < s->nqps; i++)
  1797. // reinit all dequantizers if the first one changed, because
  1798. // the DC of the first quantizer must be used for all matrices
  1799. if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
  1800. init_dequantizer(s, i);
  1801. if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
  1802. return buf_size;
  1803. s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
  1804. : AV_PICTURE_TYPE_P;
  1805. s->current_frame.f->key_frame = s->keyframe;
  1806. if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
  1807. goto error;
  1808. if (!s->edge_emu_buffer)
  1809. s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
  1810. if (s->keyframe) {
  1811. if (!s->theora) {
  1812. skip_bits(&gb, 4); /* width code */
  1813. skip_bits(&gb, 4); /* height code */
  1814. if (s->version) {
  1815. s->version = get_bits(&gb, 5);
  1816. if (avctx->frame_number == 0)
  1817. av_log(s->avctx, AV_LOG_DEBUG,
  1818. "VP version: %d\n", s->version);
  1819. }
  1820. }
  1821. if (s->version || s->theora) {
  1822. if (get_bits1(&gb))
  1823. av_log(s->avctx, AV_LOG_ERROR,
  1824. "Warning, unsupported keyframe coding type?!\n");
  1825. skip_bits(&gb, 2); /* reserved? */
  1826. }
  1827. } else {
  1828. if (!s->golden_frame.f->data[0]) {
  1829. av_log(s->avctx, AV_LOG_WARNING,
  1830. "vp3: first frame not a keyframe\n");
  1831. s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
  1832. if (ff_thread_get_buffer(avctx, &s->golden_frame,
  1833. AV_GET_BUFFER_FLAG_REF) < 0)
  1834. goto error;
  1835. ff_thread_release_buffer(avctx, &s->last_frame);
  1836. if ((ret = ff_thread_ref_frame(&s->last_frame,
  1837. &s->golden_frame)) < 0)
  1838. goto error;
  1839. ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
  1840. }
  1841. }
  1842. memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
  1843. ff_thread_finish_setup(avctx);
  1844. if (unpack_superblocks(s, &gb)) {
  1845. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
  1846. goto error;
  1847. }
  1848. if (unpack_modes(s, &gb)) {
  1849. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
  1850. goto error;
  1851. }
  1852. if (unpack_vectors(s, &gb)) {
  1853. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
  1854. goto error;
  1855. }
  1856. if (unpack_block_qpis(s, &gb)) {
  1857. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
  1858. goto error;
  1859. }
  1860. if (unpack_dct_coeffs(s, &gb)) {
  1861. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
  1862. goto error;
  1863. }
  1864. for (i = 0; i < 3; i++) {
  1865. int height = s->height >> (i && s->chroma_y_shift);
  1866. if (s->flipped_image)
  1867. s->data_offset[i] = 0;
  1868. else
  1869. s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
  1870. }
  1871. s->last_slice_end = 0;
  1872. for (i = 0; i < s->c_superblock_height; i++)
  1873. render_slice(s, i);
  1874. // filter the last row
  1875. for (i = 0; i < 3; i++) {
  1876. int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
  1877. apply_loop_filter(s, i, row, row + 1);
  1878. }
  1879. vp3_draw_horiz_band(s, s->height);
  1880. /* output frame, offset as needed */
  1881. if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
  1882. return ret;
  1883. frame->crop_left = s->offset_x;
  1884. frame->crop_right = avctx->coded_width - avctx->width - s->offset_x;
  1885. frame->crop_top = s->offset_y;
  1886. frame->crop_bottom = avctx->coded_height - avctx->height - s->offset_y;
  1887. *got_frame = 1;
  1888. if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
  1889. ret = update_frames(avctx);
  1890. if (ret < 0)
  1891. return ret;
  1892. }
  1893. return buf_size;
  1894. error:
  1895. ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
  1896. if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
  1897. av_frame_unref(s->current_frame.f);
  1898. return -1;
  1899. }
  1900. static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
  1901. {
  1902. Vp3DecodeContext *s = avctx->priv_data;
  1903. if (get_bits1(gb)) {
  1904. int token;
  1905. if (s->entries >= 32) { /* overflow */
  1906. av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
  1907. return -1;
  1908. }
  1909. token = get_bits(gb, 5);
  1910. ff_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
  1911. s->hti, s->hbits, token, s->entries, s->huff_code_size);
  1912. s->huffman_table[s->hti][token][0] = s->hbits;
  1913. s->huffman_table[s->hti][token][1] = s->huff_code_size;
  1914. s->entries++;
  1915. } else {
  1916. if (s->huff_code_size >= 32) { /* overflow */
  1917. av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
  1918. return -1;
  1919. }
  1920. s->huff_code_size++;
  1921. s->hbits <<= 1;
  1922. if (read_huffman_tree(avctx, gb))
  1923. return -1;
  1924. s->hbits |= 1;
  1925. if (read_huffman_tree(avctx, gb))
  1926. return -1;
  1927. s->hbits >>= 1;
  1928. s->huff_code_size--;
  1929. }
  1930. return 0;
  1931. }
  1932. #if HAVE_THREADS
  1933. static int vp3_init_thread_copy(AVCodecContext *avctx)
  1934. {
  1935. Vp3DecodeContext *s = avctx->priv_data;
  1936. s->superblock_coding = NULL;
  1937. s->all_fragments = NULL;
  1938. s->coded_fragment_list[0] = NULL;
  1939. s->dct_tokens_base = NULL;
  1940. s->superblock_fragments = NULL;
  1941. s->macroblock_coding = NULL;
  1942. s->motion_val[0] = NULL;
  1943. s->motion_val[1] = NULL;
  1944. s->edge_emu_buffer = NULL;
  1945. return init_frames(s);
  1946. }
  1947. #endif
  1948. #if CONFIG_THEORA_DECODER
  1949. static const enum AVPixelFormat theora_pix_fmts[4] = {
  1950. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
  1951. };
  1952. static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
  1953. {
  1954. Vp3DecodeContext *s = avctx->priv_data;
  1955. int visible_width, visible_height, colorspace;
  1956. uint8_t offset_x = 0, offset_y = 0;
  1957. int ret;
  1958. AVRational fps, aspect;
  1959. s->theora_header = 0;
  1960. s->theora = get_bits_long(gb, 24);
  1961. av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
  1962. /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
  1963. * but previous versions have the image flipped relative to vp3 */
  1964. if (s->theora < 0x030200) {
  1965. s->flipped_image = 1;
  1966. av_log(avctx, AV_LOG_DEBUG,
  1967. "Old (<alpha3) Theora bitstream, flipped image\n");
  1968. }
  1969. visible_width =
  1970. s->width = get_bits(gb, 16) << 4;
  1971. visible_height =
  1972. s->height = get_bits(gb, 16) << 4;
  1973. if (s->theora >= 0x030200) {
  1974. visible_width = get_bits_long(gb, 24);
  1975. visible_height = get_bits_long(gb, 24);
  1976. offset_x = get_bits(gb, 8); /* offset x */
  1977. offset_y = get_bits(gb, 8); /* offset y, from bottom */
  1978. }
  1979. /* sanity check */
  1980. if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
  1981. visible_width + offset_x > s->width ||
  1982. visible_height + offset_y > s->height) {
  1983. av_log(avctx, AV_LOG_ERROR,
  1984. "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
  1985. visible_width, visible_height, offset_x, offset_y,
  1986. s->width, s->height);
  1987. return AVERROR_INVALIDDATA;
  1988. }
  1989. fps.num = get_bits_long(gb, 32);
  1990. fps.den = get_bits_long(gb, 32);
  1991. if (fps.num && fps.den) {
  1992. if (fps.num < 0 || fps.den < 0) {
  1993. av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
  1994. return AVERROR_INVALIDDATA;
  1995. }
  1996. av_reduce(&avctx->framerate.den, &avctx->framerate.num,
  1997. fps.den, fps.num, 1 << 30);
  1998. }
  1999. aspect.num = get_bits_long(gb, 24);
  2000. aspect.den = get_bits_long(gb, 24);
  2001. if (aspect.num && aspect.den) {
  2002. av_reduce(&avctx->sample_aspect_ratio.num,
  2003. &avctx->sample_aspect_ratio.den,
  2004. aspect.num, aspect.den, 1 << 30);
  2005. ff_set_sar(avctx, avctx->sample_aspect_ratio);
  2006. }
  2007. if (s->theora < 0x030200)
  2008. skip_bits(gb, 5); /* keyframe frequency force */
  2009. colorspace = get_bits(gb, 8);
  2010. skip_bits(gb, 24); /* bitrate */
  2011. skip_bits(gb, 6); /* quality hint */
  2012. if (s->theora >= 0x030200) {
  2013. skip_bits(gb, 5); /* keyframe frequency force */
  2014. avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
  2015. if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
  2016. av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
  2017. return AVERROR_INVALIDDATA;
  2018. }
  2019. skip_bits(gb, 3); /* reserved */
  2020. } else
  2021. avctx->pix_fmt = AV_PIX_FMT_YUV420P;
  2022. ret = ff_set_dimensions(avctx, s->width, s->height);
  2023. if (ret < 0)
  2024. return ret;
  2025. if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
  2026. avctx->width = visible_width;
  2027. avctx->height = visible_height;
  2028. // translate offsets from theora axis ([0,0] lower left)
  2029. // to normal axis ([0,0] upper left)
  2030. s->offset_x = offset_x;
  2031. s->offset_y = s->height - visible_height - offset_y;
  2032. }
  2033. if (colorspace == 1)
  2034. avctx->color_primaries = AVCOL_PRI_BT470M;
  2035. else if (colorspace == 2)
  2036. avctx->color_primaries = AVCOL_PRI_BT470BG;
  2037. if (colorspace == 1 || colorspace == 2) {
  2038. avctx->colorspace = AVCOL_SPC_BT470BG;
  2039. avctx->color_trc = AVCOL_TRC_BT709;
  2040. }
  2041. s->theora_header = 1;
  2042. return 0;
  2043. }
  2044. static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
  2045. {
  2046. Vp3DecodeContext *s = avctx->priv_data;
  2047. int i, n, matrices, inter, plane;
  2048. if (!s->theora_header)
  2049. return AVERROR_INVALIDDATA;
  2050. if (s->theora >= 0x030200) {
  2051. n = get_bits(gb, 3);
  2052. /* loop filter limit values table */
  2053. if (n)
  2054. for (i = 0; i < 64; i++)
  2055. s->filter_limit_values[i] = get_bits(gb, n);
  2056. }
  2057. if (s->theora >= 0x030200)
  2058. n = get_bits(gb, 4) + 1;
  2059. else
  2060. n = 16;
  2061. /* quality threshold table */
  2062. for (i = 0; i < 64; i++)
  2063. s->coded_ac_scale_factor[i] = get_bits(gb, n);
  2064. if (s->theora >= 0x030200)
  2065. n = get_bits(gb, 4) + 1;
  2066. else
  2067. n = 16;
  2068. /* dc scale factor table */
  2069. for (i = 0; i < 64; i++)
  2070. s->coded_dc_scale_factor[i] = get_bits(gb, n);
  2071. if (s->theora >= 0x030200)
  2072. matrices = get_bits(gb, 9) + 1;
  2073. else
  2074. matrices = 3;
  2075. if (matrices > 384) {
  2076. av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
  2077. return -1;
  2078. }
  2079. for (n = 0; n < matrices; n++)
  2080. for (i = 0; i < 64; i++)
  2081. s->base_matrix[n][i] = get_bits(gb, 8);
  2082. for (inter = 0; inter <= 1; inter++) {
  2083. for (plane = 0; plane <= 2; plane++) {
  2084. int newqr = 1;
  2085. if (inter || plane > 0)
  2086. newqr = get_bits1(gb);
  2087. if (!newqr) {
  2088. int qtj, plj;
  2089. if (inter && get_bits1(gb)) {
  2090. qtj = 0;
  2091. plj = plane;
  2092. } else {
  2093. qtj = (3 * inter + plane - 1) / 3;
  2094. plj = (plane + 2) % 3;
  2095. }
  2096. s->qr_count[inter][plane] = s->qr_count[qtj][plj];
  2097. memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
  2098. sizeof(s->qr_size[0][0]));
  2099. memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
  2100. sizeof(s->qr_base[0][0]));
  2101. } else {
  2102. int qri = 0;
  2103. int qi = 0;
  2104. for (;;) {
  2105. i = get_bits(gb, av_log2(matrices - 1) + 1);
  2106. if (i >= matrices) {
  2107. av_log(avctx, AV_LOG_ERROR,
  2108. "invalid base matrix index\n");
  2109. return -1;
  2110. }
  2111. s->qr_base[inter][plane][qri] = i;
  2112. if (qi >= 63)
  2113. break;
  2114. i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
  2115. s->qr_size[inter][plane][qri++] = i;
  2116. qi += i;
  2117. }
  2118. if (qi > 63) {
  2119. av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
  2120. return -1;
  2121. }
  2122. s->qr_count[inter][plane] = qri;
  2123. }
  2124. }
  2125. }
  2126. /* Huffman tables */
  2127. for (s->hti = 0; s->hti < 80; s->hti++) {
  2128. s->entries = 0;
  2129. s->huff_code_size = 1;
  2130. if (!get_bits1(gb)) {
  2131. s->hbits = 0;
  2132. if (read_huffman_tree(avctx, gb))
  2133. return -1;
  2134. s->hbits = 1;
  2135. if (read_huffman_tree(avctx, gb))
  2136. return -1;
  2137. }
  2138. }
  2139. s->theora_tables = 1;
  2140. return 0;
  2141. }
  2142. static av_cold int theora_decode_init(AVCodecContext *avctx)
  2143. {
  2144. Vp3DecodeContext *s = avctx->priv_data;
  2145. GetBitContext gb;
  2146. int ptype;
  2147. const uint8_t *header_start[3];
  2148. int header_len[3];
  2149. int i;
  2150. int ret;
  2151. avctx->pix_fmt = AV_PIX_FMT_YUV420P;
  2152. s->theora = 1;
  2153. if (!avctx->extradata_size) {
  2154. av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
  2155. return -1;
  2156. }
  2157. if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
  2158. 42, header_start, header_len) < 0) {
  2159. av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
  2160. return -1;
  2161. }
  2162. for (i = 0; i < 3; i++) {
  2163. if (header_len[i] <= 0)
  2164. continue;
  2165. ret = init_get_bits8(&gb, header_start[i], header_len[i]);
  2166. if (ret < 0)
  2167. return ret;
  2168. ptype = get_bits(&gb, 8);
  2169. if (!(ptype & 0x80)) {
  2170. av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
  2171. // return -1;
  2172. }
  2173. // FIXME: Check for this as well.
  2174. skip_bits_long(&gb, 6 * 8); /* "theora" */
  2175. switch (ptype) {
  2176. case 0x80:
  2177. if (theora_decode_header(avctx, &gb) < 0)
  2178. return -1;
  2179. break;
  2180. case 0x81:
  2181. // FIXME: is this needed? it breaks sometimes
  2182. // theora_decode_comments(avctx, gb);
  2183. break;
  2184. case 0x82:
  2185. if (theora_decode_tables(avctx, &gb))
  2186. return -1;
  2187. break;
  2188. default:
  2189. av_log(avctx, AV_LOG_ERROR,
  2190. "Unknown Theora config packet: %d\n", ptype & ~0x80);
  2191. break;
  2192. }
  2193. if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
  2194. av_log(avctx, AV_LOG_WARNING,
  2195. "%d bits left in packet %X\n",
  2196. 8 * header_len[i] - get_bits_count(&gb), ptype);
  2197. if (s->theora < 0x030200)
  2198. break;
  2199. }
  2200. return vp3_decode_init(avctx);
  2201. }
  2202. AVCodec ff_theora_decoder = {
  2203. .name = "theora",
  2204. .long_name = NULL_IF_CONFIG_SMALL("Theora"),
  2205. .type = AVMEDIA_TYPE_VIDEO,
  2206. .id = AV_CODEC_ID_THEORA,
  2207. .priv_data_size = sizeof(Vp3DecodeContext),
  2208. .init = theora_decode_init,
  2209. .close = vp3_decode_end,
  2210. .decode = vp3_decode_frame,
  2211. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
  2212. AV_CODEC_CAP_FRAME_THREADS,
  2213. .flush = vp3_decode_flush,
  2214. .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
  2215. .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
  2216. .caps_internal = FF_CODEC_CAP_EXPORTS_CROPPING,
  2217. };
  2218. #endif
  2219. AVCodec ff_vp3_decoder = {
  2220. .name = "vp3",
  2221. .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
  2222. .type = AVMEDIA_TYPE_VIDEO,
  2223. .id = AV_CODEC_ID_VP3,
  2224. .priv_data_size = sizeof(Vp3DecodeContext),
  2225. .init = vp3_decode_init,
  2226. .close = vp3_decode_end,
  2227. .decode = vp3_decode_frame,
  2228. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
  2229. AV_CODEC_CAP_FRAME_THREADS,
  2230. .flush = vp3_decode_flush,
  2231. .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
  2232. .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
  2233. };