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.

2570 lines
91KB

  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;
  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) << 9) + ((zero_run) << 2) + 1)
  184. #define TOKEN_COEFF(coeff) (((coeff) << 2) + 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 deferences */
  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 coefficents at level %d\n", coeff_index);
  828. if (eob_run > num_coeffs) {
  829. coeff_i =
  830. blocks_ended = num_coeffs;
  831. eob_run -= num_coeffs;
  832. } else {
  833. coeff_i =
  834. blocks_ended = eob_run;
  835. eob_run = 0;
  836. }
  837. // insert fake EOB token to cover the split between planes or zzi
  838. if (blocks_ended)
  839. dct_tokens[j++] = blocks_ended << 2;
  840. while (coeff_i < num_coeffs && get_bits_left(gb) > 0) {
  841. /* decode a VLC into a token */
  842. token = get_vlc2(gb, vlc_table, 11, 3);
  843. /* use the token to get a zero run, a coefficient, and an eob run */
  844. if ((unsigned) token <= 6U) {
  845. eob_run = eob_run_base[token];
  846. if (eob_run_get_bits[token])
  847. eob_run += get_bits(gb, eob_run_get_bits[token]);
  848. // record only the number of blocks ended in this plane,
  849. // any spill will be recorded in the next plane.
  850. if (eob_run > num_coeffs - coeff_i) {
  851. dct_tokens[j++] = TOKEN_EOB(num_coeffs - coeff_i);
  852. blocks_ended += num_coeffs - coeff_i;
  853. eob_run -= num_coeffs - coeff_i;
  854. coeff_i = num_coeffs;
  855. } else {
  856. dct_tokens[j++] = TOKEN_EOB(eob_run);
  857. blocks_ended += eob_run;
  858. coeff_i += eob_run;
  859. eob_run = 0;
  860. }
  861. } else if (token >= 0) {
  862. bits_to_get = coeff_get_bits[token];
  863. if (bits_to_get)
  864. bits_to_get = get_bits(gb, bits_to_get);
  865. coeff = coeff_tables[token][bits_to_get];
  866. zero_run = zero_run_base[token];
  867. if (zero_run_get_bits[token])
  868. zero_run += get_bits(gb, zero_run_get_bits[token]);
  869. if (zero_run) {
  870. dct_tokens[j++] = TOKEN_ZERO_RUN(coeff, zero_run);
  871. } else {
  872. // Save DC into the fragment structure. DC prediction is
  873. // done in raster order, so the actual DC can't be in with
  874. // other tokens. We still need the token in dct_tokens[]
  875. // however, or else the structure collapses on itself.
  876. if (!coeff_index)
  877. all_fragments[coded_fragment_list[coeff_i]].dc = coeff;
  878. dct_tokens[j++] = TOKEN_COEFF(coeff);
  879. }
  880. if (coeff_index + zero_run > 64) {
  881. av_log(s->avctx, AV_LOG_DEBUG,
  882. "Invalid zero run of %d with %d coeffs left\n",
  883. zero_run, 64 - coeff_index);
  884. zero_run = 64 - coeff_index;
  885. }
  886. // zero runs code multiple coefficients,
  887. // so don't try to decode coeffs for those higher levels
  888. for (i = coeff_index + 1; i <= coeff_index + zero_run; i++)
  889. s->num_coded_frags[plane][i]--;
  890. coeff_i++;
  891. } else {
  892. av_log(s->avctx, AV_LOG_ERROR, "Invalid token %d\n", token);
  893. return -1;
  894. }
  895. }
  896. if (blocks_ended > s->num_coded_frags[plane][coeff_index])
  897. av_log(s->avctx, AV_LOG_ERROR, "More blocks ended than coded!\n");
  898. // decrement the number of blocks that have higher coefficients for each
  899. // EOB run at this level
  900. if (blocks_ended)
  901. for (i = coeff_index + 1; i < 64; i++)
  902. s->num_coded_frags[plane][i] -= blocks_ended;
  903. // setup the next buffer
  904. if (plane < 2)
  905. s->dct_tokens[plane + 1][coeff_index] = dct_tokens + j;
  906. else if (coeff_index < 63)
  907. s->dct_tokens[0][coeff_index + 1] = dct_tokens + j;
  908. return eob_run;
  909. }
  910. static void reverse_dc_prediction(Vp3DecodeContext *s,
  911. int first_fragment,
  912. int fragment_width,
  913. int fragment_height);
  914. /*
  915. * This function unpacks all of the DCT coefficient data from the
  916. * bitstream.
  917. */
  918. static int unpack_dct_coeffs(Vp3DecodeContext *s, GetBitContext *gb)
  919. {
  920. int i;
  921. int dc_y_table;
  922. int dc_c_table;
  923. int ac_y_table;
  924. int ac_c_table;
  925. int residual_eob_run = 0;
  926. VLC *y_tables[64];
  927. VLC *c_tables[64];
  928. s->dct_tokens[0][0] = s->dct_tokens_base;
  929. /* fetch the DC table indexes */
  930. dc_y_table = get_bits(gb, 4);
  931. dc_c_table = get_bits(gb, 4);
  932. /* unpack the Y plane DC coefficients */
  933. residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_y_table], 0,
  934. 0, residual_eob_run);
  935. if (residual_eob_run < 0)
  936. return residual_eob_run;
  937. /* reverse prediction of the Y-plane DC coefficients */
  938. reverse_dc_prediction(s, 0, s->fragment_width[0], s->fragment_height[0]);
  939. /* unpack the C plane DC coefficients */
  940. residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
  941. 1, residual_eob_run);
  942. if (residual_eob_run < 0)
  943. return residual_eob_run;
  944. residual_eob_run = unpack_vlcs(s, gb, &s->dc_vlc[dc_c_table], 0,
  945. 2, residual_eob_run);
  946. if (residual_eob_run < 0)
  947. return residual_eob_run;
  948. /* reverse prediction of the C-plane DC coefficients */
  949. if (!(s->avctx->flags & AV_CODEC_FLAG_GRAY)) {
  950. reverse_dc_prediction(s, s->fragment_start[1],
  951. s->fragment_width[1], s->fragment_height[1]);
  952. reverse_dc_prediction(s, s->fragment_start[2],
  953. s->fragment_width[1], s->fragment_height[1]);
  954. }
  955. /* fetch the AC table indexes */
  956. ac_y_table = get_bits(gb, 4);
  957. ac_c_table = get_bits(gb, 4);
  958. /* build tables of AC VLC tables */
  959. for (i = 1; i <= 5; i++) {
  960. y_tables[i] = &s->ac_vlc_1[ac_y_table];
  961. c_tables[i] = &s->ac_vlc_1[ac_c_table];
  962. }
  963. for (i = 6; i <= 14; i++) {
  964. y_tables[i] = &s->ac_vlc_2[ac_y_table];
  965. c_tables[i] = &s->ac_vlc_2[ac_c_table];
  966. }
  967. for (i = 15; i <= 27; i++) {
  968. y_tables[i] = &s->ac_vlc_3[ac_y_table];
  969. c_tables[i] = &s->ac_vlc_3[ac_c_table];
  970. }
  971. for (i = 28; i <= 63; i++) {
  972. y_tables[i] = &s->ac_vlc_4[ac_y_table];
  973. c_tables[i] = &s->ac_vlc_4[ac_c_table];
  974. }
  975. /* decode all AC coefficents */
  976. for (i = 1; i <= 63; i++) {
  977. residual_eob_run = unpack_vlcs(s, gb, y_tables[i], i,
  978. 0, residual_eob_run);
  979. if (residual_eob_run < 0)
  980. return residual_eob_run;
  981. residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
  982. 1, residual_eob_run);
  983. if (residual_eob_run < 0)
  984. return residual_eob_run;
  985. residual_eob_run = unpack_vlcs(s, gb, c_tables[i], i,
  986. 2, residual_eob_run);
  987. if (residual_eob_run < 0)
  988. return residual_eob_run;
  989. }
  990. return 0;
  991. }
  992. /*
  993. * This function reverses the DC prediction for each coded fragment in
  994. * the frame. Much of this function is adapted directly from the original
  995. * VP3 source code.
  996. */
  997. #define COMPATIBLE_FRAME(x) \
  998. (compatible_frame[s->all_fragments[x].coding_method] == current_frame_type)
  999. #define DC_COEFF(u) s->all_fragments[u].dc
  1000. static void reverse_dc_prediction(Vp3DecodeContext *s,
  1001. int first_fragment,
  1002. int fragment_width,
  1003. int fragment_height)
  1004. {
  1005. #define PUL 8
  1006. #define PU 4
  1007. #define PUR 2
  1008. #define PL 1
  1009. int x, y;
  1010. int i = first_fragment;
  1011. int predicted_dc;
  1012. /* DC values for the left, up-left, up, and up-right fragments */
  1013. int vl, vul, vu, vur;
  1014. /* indexes for the left, up-left, up, and up-right fragments */
  1015. int l, ul, u, ur;
  1016. /*
  1017. * The 6 fields mean:
  1018. * 0: up-left multiplier
  1019. * 1: up multiplier
  1020. * 2: up-right multiplier
  1021. * 3: left multiplier
  1022. */
  1023. static const int predictor_transform[16][4] = {
  1024. { 0, 0, 0, 0 },
  1025. { 0, 0, 0, 128 }, // PL
  1026. { 0, 0, 128, 0 }, // PUR
  1027. { 0, 0, 53, 75 }, // PUR|PL
  1028. { 0, 128, 0, 0 }, // PU
  1029. { 0, 64, 0, 64 }, // PU |PL
  1030. { 0, 128, 0, 0 }, // PU |PUR
  1031. { 0, 0, 53, 75 }, // PU |PUR|PL
  1032. { 128, 0, 0, 0 }, // PUL
  1033. { 0, 0, 0, 128 }, // PUL|PL
  1034. { 64, 0, 64, 0 }, // PUL|PUR
  1035. { 0, 0, 53, 75 }, // PUL|PUR|PL
  1036. { 0, 128, 0, 0 }, // PUL|PU
  1037. { -104, 116, 0, 116 }, // PUL|PU |PL
  1038. { 24, 80, 24, 0 }, // PUL|PU |PUR
  1039. { -104, 116, 0, 116 } // PUL|PU |PUR|PL
  1040. };
  1041. /* This table shows which types of blocks can use other blocks for
  1042. * prediction. For example, INTRA is the only mode in this table to
  1043. * have a frame number of 0. That means INTRA blocks can only predict
  1044. * from other INTRA blocks. There are 2 golden frame coding types;
  1045. * blocks encoding in these modes can only predict from other blocks
  1046. * that were encoded with these 1 of these 2 modes. */
  1047. static const unsigned char compatible_frame[9] = {
  1048. 1, /* MODE_INTER_NO_MV */
  1049. 0, /* MODE_INTRA */
  1050. 1, /* MODE_INTER_PLUS_MV */
  1051. 1, /* MODE_INTER_LAST_MV */
  1052. 1, /* MODE_INTER_PRIOR_MV */
  1053. 2, /* MODE_USING_GOLDEN */
  1054. 2, /* MODE_GOLDEN_MV */
  1055. 1, /* MODE_INTER_FOUR_MV */
  1056. 3 /* MODE_COPY */
  1057. };
  1058. int current_frame_type;
  1059. /* there is a last DC predictor for each of the 3 frame types */
  1060. short last_dc[3];
  1061. int transform = 0;
  1062. vul =
  1063. vu =
  1064. vur =
  1065. vl = 0;
  1066. last_dc[0] =
  1067. last_dc[1] =
  1068. last_dc[2] = 0;
  1069. /* for each fragment row... */
  1070. for (y = 0; y < fragment_height; y++) {
  1071. /* for each fragment in a row... */
  1072. for (x = 0; x < fragment_width; x++, i++) {
  1073. /* reverse prediction if this block was coded */
  1074. if (s->all_fragments[i].coding_method != MODE_COPY) {
  1075. current_frame_type =
  1076. compatible_frame[s->all_fragments[i].coding_method];
  1077. transform = 0;
  1078. if (x) {
  1079. l = i - 1;
  1080. vl = DC_COEFF(l);
  1081. if (COMPATIBLE_FRAME(l))
  1082. transform |= PL;
  1083. }
  1084. if (y) {
  1085. u = i - fragment_width;
  1086. vu = DC_COEFF(u);
  1087. if (COMPATIBLE_FRAME(u))
  1088. transform |= PU;
  1089. if (x) {
  1090. ul = i - fragment_width - 1;
  1091. vul = DC_COEFF(ul);
  1092. if (COMPATIBLE_FRAME(ul))
  1093. transform |= PUL;
  1094. }
  1095. if (x + 1 < fragment_width) {
  1096. ur = i - fragment_width + 1;
  1097. vur = DC_COEFF(ur);
  1098. if (COMPATIBLE_FRAME(ur))
  1099. transform |= PUR;
  1100. }
  1101. }
  1102. if (transform == 0) {
  1103. /* if there were no fragments to predict from, use last
  1104. * DC saved */
  1105. predicted_dc = last_dc[current_frame_type];
  1106. } else {
  1107. /* apply the appropriate predictor transform */
  1108. predicted_dc =
  1109. (predictor_transform[transform][0] * vul) +
  1110. (predictor_transform[transform][1] * vu) +
  1111. (predictor_transform[transform][2] * vur) +
  1112. (predictor_transform[transform][3] * vl);
  1113. predicted_dc /= 128;
  1114. /* check for outranging on the [ul u l] and
  1115. * [ul u ur l] predictors */
  1116. if ((transform == 15) || (transform == 13)) {
  1117. if (FFABS(predicted_dc - vu) > 128)
  1118. predicted_dc = vu;
  1119. else if (FFABS(predicted_dc - vl) > 128)
  1120. predicted_dc = vl;
  1121. else if (FFABS(predicted_dc - vul) > 128)
  1122. predicted_dc = vul;
  1123. }
  1124. }
  1125. /* at long last, apply the predictor */
  1126. DC_COEFF(i) += predicted_dc;
  1127. /* save the DC */
  1128. last_dc[current_frame_type] = DC_COEFF(i);
  1129. }
  1130. }
  1131. }
  1132. }
  1133. static void apply_loop_filter(Vp3DecodeContext *s, int plane,
  1134. int ystart, int yend)
  1135. {
  1136. int x, y;
  1137. int *bounding_values = s->bounding_values_array + 127;
  1138. int width = s->fragment_width[!!plane];
  1139. int height = s->fragment_height[!!plane];
  1140. int fragment = s->fragment_start[plane] + ystart * width;
  1141. ptrdiff_t stride = s->current_frame.f->linesize[plane];
  1142. uint8_t *plane_data = s->current_frame.f->data[plane];
  1143. if (!s->flipped_image)
  1144. stride = -stride;
  1145. plane_data += s->data_offset[plane] + 8 * ystart * stride;
  1146. for (y = ystart; y < yend; y++) {
  1147. for (x = 0; x < width; x++) {
  1148. /* This code basically just deblocks on the edges of coded blocks.
  1149. * However, it has to be much more complicated because of the
  1150. * braindamaged deblock ordering used in VP3/Theora. Order matters
  1151. * because some pixels get filtered twice. */
  1152. if (s->all_fragments[fragment].coding_method != MODE_COPY) {
  1153. /* do not perform left edge filter for left columns frags */
  1154. if (x > 0) {
  1155. s->vp3dsp.h_loop_filter(
  1156. plane_data + 8 * x,
  1157. stride, bounding_values);
  1158. }
  1159. /* do not perform top edge filter for top row fragments */
  1160. if (y > 0) {
  1161. s->vp3dsp.v_loop_filter(
  1162. plane_data + 8 * x,
  1163. stride, bounding_values);
  1164. }
  1165. /* do not perform right edge filter for right column
  1166. * fragments or if right fragment neighbor is also coded
  1167. * in this frame (it will be filtered in next iteration) */
  1168. if ((x < width - 1) &&
  1169. (s->all_fragments[fragment + 1].coding_method == MODE_COPY)) {
  1170. s->vp3dsp.h_loop_filter(
  1171. plane_data + 8 * x + 8,
  1172. stride, bounding_values);
  1173. }
  1174. /* do not perform bottom edge filter for bottom row
  1175. * fragments or if bottom fragment neighbor is also coded
  1176. * in this frame (it will be filtered in the next row) */
  1177. if ((y < height - 1) &&
  1178. (s->all_fragments[fragment + width].coding_method == MODE_COPY)) {
  1179. s->vp3dsp.v_loop_filter(
  1180. plane_data + 8 * x + 8 * stride,
  1181. stride, bounding_values);
  1182. }
  1183. }
  1184. fragment++;
  1185. }
  1186. plane_data += 8 * stride;
  1187. }
  1188. }
  1189. /**
  1190. * Pull DCT tokens from the 64 levels to decode and dequant the coefficients
  1191. * for the next block in coding order
  1192. */
  1193. static inline int vp3_dequant(Vp3DecodeContext *s, Vp3Fragment *frag,
  1194. int plane, int inter, int16_t block[64])
  1195. {
  1196. int16_t *dequantizer = s->qmat[frag->qpi][inter][plane];
  1197. uint8_t *perm = s->idct_scantable;
  1198. int i = 0;
  1199. do {
  1200. int token = *s->dct_tokens[plane][i];
  1201. switch (token & 3) {
  1202. case 0: // EOB
  1203. if (--token < 4) // 0-3 are token types so the EOB run must now be 0
  1204. s->dct_tokens[plane][i]++;
  1205. else
  1206. *s->dct_tokens[plane][i] = token & ~3;
  1207. goto end;
  1208. case 1: // zero run
  1209. s->dct_tokens[plane][i]++;
  1210. i += (token >> 2) & 0x7f;
  1211. if (i > 63) {
  1212. av_log(s->avctx, AV_LOG_ERROR, "Coefficient index overflow\n");
  1213. return i;
  1214. }
  1215. block[perm[i]] = (token >> 9) * dequantizer[perm[i]];
  1216. i++;
  1217. break;
  1218. case 2: // coeff
  1219. block[perm[i]] = (token >> 2) * dequantizer[perm[i]];
  1220. s->dct_tokens[plane][i++]++;
  1221. break;
  1222. default: // shouldn't happen
  1223. return i;
  1224. }
  1225. } while (i < 64);
  1226. // return value is expected to be a valid level
  1227. i--;
  1228. end:
  1229. // the actual DC+prediction is in the fragment structure
  1230. block[0] = frag->dc * s->qmat[0][inter][plane][0];
  1231. return i;
  1232. }
  1233. /**
  1234. * called when all pixels up to row y are complete
  1235. */
  1236. static void vp3_draw_horiz_band(Vp3DecodeContext *s, int y)
  1237. {
  1238. int h, cy, i;
  1239. int offset[AV_NUM_DATA_POINTERS];
  1240. if (HAVE_THREADS && s->avctx->active_thread_type & FF_THREAD_FRAME) {
  1241. int y_flipped = s->flipped_image ? s->height - y : y;
  1242. /* At the end of the frame, report INT_MAX instead of the height of
  1243. * the frame. This makes the other threads' ff_thread_await_progress()
  1244. * calls cheaper, because they don't have to clip their values. */
  1245. ff_thread_report_progress(&s->current_frame,
  1246. y_flipped == s->height ? INT_MAX
  1247. : y_flipped - 1,
  1248. 0);
  1249. }
  1250. if (!s->avctx->draw_horiz_band)
  1251. return;
  1252. h = y - s->last_slice_end;
  1253. s->last_slice_end = y;
  1254. y -= h;
  1255. if (!s->flipped_image)
  1256. y = s->height - y - h;
  1257. cy = y >> s->chroma_y_shift;
  1258. offset[0] = s->current_frame.f->linesize[0] * y;
  1259. offset[1] = s->current_frame.f->linesize[1] * cy;
  1260. offset[2] = s->current_frame.f->linesize[2] * cy;
  1261. for (i = 3; i < AV_NUM_DATA_POINTERS; i++)
  1262. offset[i] = 0;
  1263. emms_c();
  1264. s->avctx->draw_horiz_band(s->avctx, s->current_frame.f, offset, y, 3, h);
  1265. }
  1266. /**
  1267. * Wait for the reference frame of the current fragment.
  1268. * The progress value is in luma pixel rows.
  1269. */
  1270. static void await_reference_row(Vp3DecodeContext *s, Vp3Fragment *fragment,
  1271. int motion_y, int y)
  1272. {
  1273. ThreadFrame *ref_frame;
  1274. int ref_row;
  1275. int border = motion_y & 1;
  1276. if (fragment->coding_method == MODE_USING_GOLDEN ||
  1277. fragment->coding_method == MODE_GOLDEN_MV)
  1278. ref_frame = &s->golden_frame;
  1279. else
  1280. ref_frame = &s->last_frame;
  1281. ref_row = y + (motion_y >> 1);
  1282. ref_row = FFMAX(FFABS(ref_row), ref_row + 8 + border);
  1283. ff_thread_await_progress(ref_frame, ref_row, 0);
  1284. }
  1285. /*
  1286. * Perform the final rendering for a particular slice of data.
  1287. * The slice number ranges from 0..(c_superblock_height - 1).
  1288. */
  1289. static void render_slice(Vp3DecodeContext *s, int slice)
  1290. {
  1291. int x, y, i, j, fragment;
  1292. int16_t *block = s->block;
  1293. int motion_x = 0xdeadbeef, motion_y = 0xdeadbeef;
  1294. int motion_halfpel_index;
  1295. uint8_t *motion_source;
  1296. int plane, first_pixel;
  1297. if (slice >= s->c_superblock_height)
  1298. return;
  1299. for (plane = 0; plane < 3; plane++) {
  1300. uint8_t *output_plane = s->current_frame.f->data[plane] +
  1301. s->data_offset[plane];
  1302. uint8_t *last_plane = s->last_frame.f->data[plane] +
  1303. s->data_offset[plane];
  1304. uint8_t *golden_plane = s->golden_frame.f->data[plane] +
  1305. s->data_offset[plane];
  1306. ptrdiff_t stride = s->current_frame.f->linesize[plane];
  1307. int plane_width = s->width >> (plane && s->chroma_x_shift);
  1308. int plane_height = s->height >> (plane && s->chroma_y_shift);
  1309. int8_t(*motion_val)[2] = s->motion_val[!!plane];
  1310. int sb_x, sb_y = slice << (!plane && s->chroma_y_shift);
  1311. int slice_height = sb_y + 1 + (!plane && s->chroma_y_shift);
  1312. int slice_width = plane ? s->c_superblock_width
  1313. : s->y_superblock_width;
  1314. int fragment_width = s->fragment_width[!!plane];
  1315. int fragment_height = s->fragment_height[!!plane];
  1316. int fragment_start = s->fragment_start[plane];
  1317. int do_await = !plane && HAVE_THREADS &&
  1318. (s->avctx->active_thread_type & FF_THREAD_FRAME);
  1319. if (!s->flipped_image)
  1320. stride = -stride;
  1321. if (CONFIG_GRAY && plane && (s->avctx->flags & AV_CODEC_FLAG_GRAY))
  1322. continue;
  1323. /* for each superblock row in the slice (both of them)... */
  1324. for (; sb_y < slice_height; sb_y++) {
  1325. /* for each superblock in a row... */
  1326. for (sb_x = 0; sb_x < slice_width; sb_x++) {
  1327. /* for each block in a superblock... */
  1328. for (j = 0; j < 16; j++) {
  1329. x = 4 * sb_x + hilbert_offset[j][0];
  1330. y = 4 * sb_y + hilbert_offset[j][1];
  1331. fragment = y * fragment_width + x;
  1332. i = fragment_start + fragment;
  1333. // bounds check
  1334. if (x >= fragment_width || y >= fragment_height)
  1335. continue;
  1336. first_pixel = 8 * y * stride + 8 * x;
  1337. if (do_await &&
  1338. s->all_fragments[i].coding_method != MODE_INTRA)
  1339. await_reference_row(s, &s->all_fragments[i],
  1340. motion_val[fragment][1],
  1341. (16 * y) >> s->chroma_y_shift);
  1342. /* transform if this block was coded */
  1343. if (s->all_fragments[i].coding_method != MODE_COPY) {
  1344. if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||
  1345. (s->all_fragments[i].coding_method == MODE_GOLDEN_MV))
  1346. motion_source = golden_plane;
  1347. else
  1348. motion_source = last_plane;
  1349. motion_source += first_pixel;
  1350. motion_halfpel_index = 0;
  1351. /* sort out the motion vector if this fragment is coded
  1352. * using a motion vector method */
  1353. if ((s->all_fragments[i].coding_method > MODE_INTRA) &&
  1354. (s->all_fragments[i].coding_method != MODE_USING_GOLDEN)) {
  1355. int src_x, src_y;
  1356. motion_x = motion_val[fragment][0];
  1357. motion_y = motion_val[fragment][1];
  1358. src_x = (motion_x >> 1) + 8 * x;
  1359. src_y = (motion_y >> 1) + 8 * y;
  1360. motion_halfpel_index = motion_x & 0x01;
  1361. motion_source += (motion_x >> 1);
  1362. motion_halfpel_index |= (motion_y & 0x01) << 1;
  1363. motion_source += ((motion_y >> 1) * stride);
  1364. if (src_x < 0 || src_y < 0 ||
  1365. src_x + 9 >= plane_width ||
  1366. src_y + 9 >= plane_height) {
  1367. uint8_t *temp = s->edge_emu_buffer;
  1368. if (stride < 0)
  1369. temp -= 8 * stride;
  1370. s->vdsp.emulated_edge_mc(temp, motion_source,
  1371. stride, stride,
  1372. 9, 9, src_x, src_y,
  1373. plane_width,
  1374. plane_height);
  1375. motion_source = temp;
  1376. }
  1377. }
  1378. /* first, take care of copying a block from either the
  1379. * previous or the golden frame */
  1380. if (s->all_fragments[i].coding_method != MODE_INTRA) {
  1381. /* Note, it is possible to implement all MC cases
  1382. * with put_no_rnd_pixels_l2 which would look more
  1383. * like the VP3 source but this would be slower as
  1384. * put_no_rnd_pixels_tab is better optimzed */
  1385. if (motion_halfpel_index != 3) {
  1386. s->hdsp.put_no_rnd_pixels_tab[1][motion_halfpel_index](
  1387. output_plane + first_pixel,
  1388. motion_source, stride, 8);
  1389. } else {
  1390. /* d is 0 if motion_x and _y have the same sign,
  1391. * else -1 */
  1392. int d = (motion_x ^ motion_y) >> 31;
  1393. s->vp3dsp.put_no_rnd_pixels_l2(output_plane + first_pixel,
  1394. motion_source - d,
  1395. motion_source + stride + 1 + d,
  1396. stride, 8);
  1397. }
  1398. }
  1399. /* invert DCT and place (or add) in final output */
  1400. if (s->all_fragments[i].coding_method == MODE_INTRA) {
  1401. vp3_dequant(s, s->all_fragments + i,
  1402. plane, 0, block);
  1403. s->vp3dsp.idct_put(output_plane + first_pixel,
  1404. stride,
  1405. block);
  1406. } else {
  1407. if (vp3_dequant(s, s->all_fragments + i,
  1408. plane, 1, block)) {
  1409. s->vp3dsp.idct_add(output_plane + first_pixel,
  1410. stride,
  1411. block);
  1412. } else {
  1413. s->vp3dsp.idct_dc_add(output_plane + first_pixel,
  1414. stride, block);
  1415. }
  1416. }
  1417. } else {
  1418. /* copy directly from the previous frame */
  1419. s->hdsp.put_pixels_tab[1][0](
  1420. output_plane + first_pixel,
  1421. last_plane + first_pixel,
  1422. stride, 8);
  1423. }
  1424. }
  1425. }
  1426. // Filter up to the last row in the superblock row
  1427. if (!s->skip_loop_filter)
  1428. apply_loop_filter(s, plane, 4 * sb_y - !!sb_y,
  1429. FFMIN(4 * sb_y + 3, fragment_height - 1));
  1430. }
  1431. }
  1432. /* this looks like a good place for slice dispatch... */
  1433. /* algorithm:
  1434. * if (slice == s->macroblock_height - 1)
  1435. * dispatch (both last slice & 2nd-to-last slice);
  1436. * else if (slice > 0)
  1437. * dispatch (slice - 1);
  1438. */
  1439. vp3_draw_horiz_band(s, FFMIN((32 << s->chroma_y_shift) * (slice + 1) - 16,
  1440. s->height - 16));
  1441. }
  1442. /// Allocate tables for per-frame data in Vp3DecodeContext
  1443. static av_cold int allocate_tables(AVCodecContext *avctx)
  1444. {
  1445. Vp3DecodeContext *s = avctx->priv_data;
  1446. int y_fragment_count, c_fragment_count;
  1447. free_tables(avctx);
  1448. y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
  1449. c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
  1450. s->superblock_coding = av_mallocz(s->superblock_count);
  1451. s->all_fragments = av_mallocz_array(s->fragment_count, sizeof(Vp3Fragment));
  1452. s->coded_fragment_list[0] = av_mallocz_array(s->fragment_count, sizeof(int));
  1453. s->dct_tokens_base = av_mallocz_array(s->fragment_count,
  1454. 64 * sizeof(*s->dct_tokens_base));
  1455. s->motion_val[0] = av_mallocz_array(y_fragment_count, sizeof(*s->motion_val[0]));
  1456. s->motion_val[1] = av_mallocz_array(c_fragment_count, sizeof(*s->motion_val[1]));
  1457. /* work out the block mapping tables */
  1458. s->superblock_fragments = av_mallocz_array(s->superblock_count, 16 * sizeof(int));
  1459. s->macroblock_coding = av_mallocz(s->macroblock_count + 1);
  1460. if (!s->superblock_coding || !s->all_fragments ||
  1461. !s->dct_tokens_base || !s->coded_fragment_list[0] ||
  1462. !s->superblock_fragments || !s->macroblock_coding ||
  1463. !s->motion_val[0] || !s->motion_val[1]) {
  1464. vp3_decode_end(avctx);
  1465. return -1;
  1466. }
  1467. init_block_mapping(s);
  1468. return 0;
  1469. }
  1470. static av_cold int init_frames(Vp3DecodeContext *s)
  1471. {
  1472. s->current_frame.f = av_frame_alloc();
  1473. s->last_frame.f = av_frame_alloc();
  1474. s->golden_frame.f = av_frame_alloc();
  1475. if (!s->current_frame.f || !s->last_frame.f || !s->golden_frame.f) {
  1476. av_frame_free(&s->current_frame.f);
  1477. av_frame_free(&s->last_frame.f);
  1478. av_frame_free(&s->golden_frame.f);
  1479. return AVERROR(ENOMEM);
  1480. }
  1481. return 0;
  1482. }
  1483. static av_cold int vp3_decode_init(AVCodecContext *avctx)
  1484. {
  1485. Vp3DecodeContext *s = avctx->priv_data;
  1486. int i, inter, plane, ret;
  1487. int c_width;
  1488. int c_height;
  1489. int y_fragment_count, c_fragment_count;
  1490. ret = init_frames(s);
  1491. if (ret < 0)
  1492. return ret;
  1493. avctx->internal->allocate_progress = 1;
  1494. if (avctx->codec_tag == MKTAG('V', 'P', '3', '0'))
  1495. s->version = 0;
  1496. else
  1497. s->version = 1;
  1498. s->avctx = avctx;
  1499. s->width = FFALIGN(avctx->coded_width, 16);
  1500. s->height = FFALIGN(avctx->coded_height, 16);
  1501. if (avctx->codec_id != AV_CODEC_ID_THEORA)
  1502. avctx->pix_fmt = AV_PIX_FMT_YUV420P;
  1503. avctx->chroma_sample_location = AVCHROMA_LOC_CENTER;
  1504. ff_hpeldsp_init(&s->hdsp, avctx->flags | AV_CODEC_FLAG_BITEXACT);
  1505. ff_videodsp_init(&s->vdsp, 8);
  1506. ff_vp3dsp_init(&s->vp3dsp, avctx->flags);
  1507. for (i = 0; i < 64; i++) {
  1508. #define TRANSPOSE(x) (((x) >> 3) | (((x) & 7) << 3))
  1509. s->idct_permutation[i] = TRANSPOSE(i);
  1510. s->idct_scantable[i] = TRANSPOSE(ff_zigzag_direct[i]);
  1511. #undef TRANSPOSE
  1512. }
  1513. /* initialize to an impossible value which will force a recalculation
  1514. * in the first frame decode */
  1515. for (i = 0; i < 3; i++)
  1516. s->qps[i] = -1;
  1517. avcodec_get_chroma_sub_sample(avctx->pix_fmt, &s->chroma_x_shift, &s->chroma_y_shift);
  1518. s->y_superblock_width = (s->width + 31) / 32;
  1519. s->y_superblock_height = (s->height + 31) / 32;
  1520. s->y_superblock_count = s->y_superblock_width * s->y_superblock_height;
  1521. /* work out the dimensions for the C planes */
  1522. c_width = s->width >> s->chroma_x_shift;
  1523. c_height = s->height >> s->chroma_y_shift;
  1524. s->c_superblock_width = (c_width + 31) / 32;
  1525. s->c_superblock_height = (c_height + 31) / 32;
  1526. s->c_superblock_count = s->c_superblock_width * s->c_superblock_height;
  1527. s->superblock_count = s->y_superblock_count + (s->c_superblock_count * 2);
  1528. s->u_superblock_start = s->y_superblock_count;
  1529. s->v_superblock_start = s->u_superblock_start + s->c_superblock_count;
  1530. s->macroblock_width = (s->width + 15) / 16;
  1531. s->macroblock_height = (s->height + 15) / 16;
  1532. s->macroblock_count = s->macroblock_width * s->macroblock_height;
  1533. s->fragment_width[0] = s->width / FRAGMENT_PIXELS;
  1534. s->fragment_height[0] = s->height / FRAGMENT_PIXELS;
  1535. s->fragment_width[1] = s->fragment_width[0] >> s->chroma_x_shift;
  1536. s->fragment_height[1] = s->fragment_height[0] >> s->chroma_y_shift;
  1537. /* fragment count covers all 8x8 blocks for all 3 planes */
  1538. y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
  1539. c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
  1540. s->fragment_count = y_fragment_count + 2 * c_fragment_count;
  1541. s->fragment_start[1] = y_fragment_count;
  1542. s->fragment_start[2] = y_fragment_count + c_fragment_count;
  1543. if (!s->theora_tables) {
  1544. for (i = 0; i < 64; i++) {
  1545. s->coded_dc_scale_factor[i] = vp31_dc_scale_factor[i];
  1546. s->coded_ac_scale_factor[i] = vp31_ac_scale_factor[i];
  1547. s->base_matrix[0][i] = vp31_intra_y_dequant[i];
  1548. s->base_matrix[1][i] = vp31_intra_c_dequant[i];
  1549. s->base_matrix[2][i] = vp31_inter_dequant[i];
  1550. s->filter_limit_values[i] = vp31_filter_limit_values[i];
  1551. }
  1552. for (inter = 0; inter < 2; inter++) {
  1553. for (plane = 0; plane < 3; plane++) {
  1554. s->qr_count[inter][plane] = 1;
  1555. s->qr_size[inter][plane][0] = 63;
  1556. s->qr_base[inter][plane][0] =
  1557. s->qr_base[inter][plane][1] = 2 * inter + (!!plane) * !inter;
  1558. }
  1559. }
  1560. /* init VLC tables */
  1561. for (i = 0; i < 16; i++) {
  1562. /* DC histograms */
  1563. init_vlc(&s->dc_vlc[i], 11, 32,
  1564. &dc_bias[i][0][1], 4, 2,
  1565. &dc_bias[i][0][0], 4, 2, 0);
  1566. /* group 1 AC histograms */
  1567. init_vlc(&s->ac_vlc_1[i], 11, 32,
  1568. &ac_bias_0[i][0][1], 4, 2,
  1569. &ac_bias_0[i][0][0], 4, 2, 0);
  1570. /* group 2 AC histograms */
  1571. init_vlc(&s->ac_vlc_2[i], 11, 32,
  1572. &ac_bias_1[i][0][1], 4, 2,
  1573. &ac_bias_1[i][0][0], 4, 2, 0);
  1574. /* group 3 AC histograms */
  1575. init_vlc(&s->ac_vlc_3[i], 11, 32,
  1576. &ac_bias_2[i][0][1], 4, 2,
  1577. &ac_bias_2[i][0][0], 4, 2, 0);
  1578. /* group 4 AC histograms */
  1579. init_vlc(&s->ac_vlc_4[i], 11, 32,
  1580. &ac_bias_3[i][0][1], 4, 2,
  1581. &ac_bias_3[i][0][0], 4, 2, 0);
  1582. }
  1583. } else {
  1584. for (i = 0; i < 16; i++) {
  1585. /* DC histograms */
  1586. if (init_vlc(&s->dc_vlc[i], 11, 32,
  1587. &s->huffman_table[i][0][1], 8, 4,
  1588. &s->huffman_table[i][0][0], 8, 4, 0) < 0)
  1589. goto vlc_fail;
  1590. /* group 1 AC histograms */
  1591. if (init_vlc(&s->ac_vlc_1[i], 11, 32,
  1592. &s->huffman_table[i + 16][0][1], 8, 4,
  1593. &s->huffman_table[i + 16][0][0], 8, 4, 0) < 0)
  1594. goto vlc_fail;
  1595. /* group 2 AC histograms */
  1596. if (init_vlc(&s->ac_vlc_2[i], 11, 32,
  1597. &s->huffman_table[i + 16 * 2][0][1], 8, 4,
  1598. &s->huffman_table[i + 16 * 2][0][0], 8, 4, 0) < 0)
  1599. goto vlc_fail;
  1600. /* group 3 AC histograms */
  1601. if (init_vlc(&s->ac_vlc_3[i], 11, 32,
  1602. &s->huffman_table[i + 16 * 3][0][1], 8, 4,
  1603. &s->huffman_table[i + 16 * 3][0][0], 8, 4, 0) < 0)
  1604. goto vlc_fail;
  1605. /* group 4 AC histograms */
  1606. if (init_vlc(&s->ac_vlc_4[i], 11, 32,
  1607. &s->huffman_table[i + 16 * 4][0][1], 8, 4,
  1608. &s->huffman_table[i + 16 * 4][0][0], 8, 4, 0) < 0)
  1609. goto vlc_fail;
  1610. }
  1611. }
  1612. init_vlc(&s->superblock_run_length_vlc, 6, 34,
  1613. &superblock_run_length_vlc_table[0][1], 4, 2,
  1614. &superblock_run_length_vlc_table[0][0], 4, 2, 0);
  1615. init_vlc(&s->fragment_run_length_vlc, 5, 30,
  1616. &fragment_run_length_vlc_table[0][1], 4, 2,
  1617. &fragment_run_length_vlc_table[0][0], 4, 2, 0);
  1618. init_vlc(&s->mode_code_vlc, 3, 8,
  1619. &mode_code_vlc_table[0][1], 2, 1,
  1620. &mode_code_vlc_table[0][0], 2, 1, 0);
  1621. init_vlc(&s->motion_vector_vlc, 6, 63,
  1622. &motion_vector_vlc_table[0][1], 2, 1,
  1623. &motion_vector_vlc_table[0][0], 2, 1, 0);
  1624. return allocate_tables(avctx);
  1625. vlc_fail:
  1626. av_log(avctx, AV_LOG_FATAL, "Invalid huffman table\n");
  1627. return -1;
  1628. }
  1629. /// Release and shuffle frames after decode finishes
  1630. static int update_frames(AVCodecContext *avctx)
  1631. {
  1632. Vp3DecodeContext *s = avctx->priv_data;
  1633. int ret = 0;
  1634. /* shuffle frames (last = current) */
  1635. ff_thread_release_buffer(avctx, &s->last_frame);
  1636. ret = ff_thread_ref_frame(&s->last_frame, &s->current_frame);
  1637. if (ret < 0)
  1638. goto fail;
  1639. if (s->keyframe) {
  1640. ff_thread_release_buffer(avctx, &s->golden_frame);
  1641. ret = ff_thread_ref_frame(&s->golden_frame, &s->current_frame);
  1642. }
  1643. fail:
  1644. ff_thread_release_buffer(avctx, &s->current_frame);
  1645. return ret;
  1646. }
  1647. static int ref_frame(Vp3DecodeContext *s, ThreadFrame *dst, ThreadFrame *src)
  1648. {
  1649. ff_thread_release_buffer(s->avctx, dst);
  1650. if (src->f->data[0])
  1651. return ff_thread_ref_frame(dst, src);
  1652. return 0;
  1653. }
  1654. static int ref_frames(Vp3DecodeContext *dst, Vp3DecodeContext *src)
  1655. {
  1656. int ret;
  1657. if ((ret = ref_frame(dst, &dst->current_frame, &src->current_frame)) < 0 ||
  1658. (ret = ref_frame(dst, &dst->golden_frame, &src->golden_frame)) < 0 ||
  1659. (ret = ref_frame(dst, &dst->last_frame, &src->last_frame)) < 0)
  1660. return ret;
  1661. return 0;
  1662. }
  1663. static int vp3_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
  1664. {
  1665. Vp3DecodeContext *s = dst->priv_data, *s1 = src->priv_data;
  1666. int qps_changed = 0, i, err;
  1667. #define copy_fields(to, from, start_field, end_field) \
  1668. memcpy(&to->start_field, &from->start_field, \
  1669. (char *) &to->end_field - (char *) &to->start_field)
  1670. if (!s1->current_frame.f->data[0] ||
  1671. s->width != s1->width || s->height != s1->height) {
  1672. if (s != s1)
  1673. ref_frames(s, s1);
  1674. return -1;
  1675. }
  1676. if (s != s1) {
  1677. if (!s->current_frame.f)
  1678. return AVERROR(ENOMEM);
  1679. // init tables if the first frame hasn't been decoded
  1680. if (!s->current_frame.f->data[0]) {
  1681. int y_fragment_count, c_fragment_count;
  1682. s->avctx = dst;
  1683. err = allocate_tables(dst);
  1684. if (err)
  1685. return err;
  1686. y_fragment_count = s->fragment_width[0] * s->fragment_height[0];
  1687. c_fragment_count = s->fragment_width[1] * s->fragment_height[1];
  1688. memcpy(s->motion_val[0], s1->motion_val[0],
  1689. y_fragment_count * sizeof(*s->motion_val[0]));
  1690. memcpy(s->motion_val[1], s1->motion_val[1],
  1691. c_fragment_count * sizeof(*s->motion_val[1]));
  1692. }
  1693. // copy previous frame data
  1694. if ((err = ref_frames(s, s1)) < 0)
  1695. return err;
  1696. s->keyframe = s1->keyframe;
  1697. // copy qscale data if necessary
  1698. for (i = 0; i < 3; i++) {
  1699. if (s->qps[i] != s1->qps[1]) {
  1700. qps_changed = 1;
  1701. memcpy(&s->qmat[i], &s1->qmat[i], sizeof(s->qmat[i]));
  1702. }
  1703. }
  1704. if (s->qps[0] != s1->qps[0])
  1705. memcpy(&s->bounding_values_array, &s1->bounding_values_array,
  1706. sizeof(s->bounding_values_array));
  1707. if (qps_changed)
  1708. copy_fields(s, s1, qps, superblock_count);
  1709. #undef copy_fields
  1710. }
  1711. return update_frames(dst);
  1712. }
  1713. static int vp3_decode_frame(AVCodecContext *avctx,
  1714. void *data, int *got_frame,
  1715. AVPacket *avpkt)
  1716. {
  1717. const uint8_t *buf = avpkt->data;
  1718. int buf_size = avpkt->size;
  1719. Vp3DecodeContext *s = avctx->priv_data;
  1720. GetBitContext gb;
  1721. int i, ret;
  1722. if ((ret = init_get_bits8(&gb, buf, buf_size)) < 0)
  1723. return ret;
  1724. #if CONFIG_THEORA_DECODER
  1725. if (s->theora && get_bits1(&gb)) {
  1726. int type = get_bits(&gb, 7);
  1727. skip_bits_long(&gb, 6*8); /* "theora" */
  1728. if (s->avctx->active_thread_type&FF_THREAD_FRAME) {
  1729. av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");
  1730. return AVERROR_PATCHWELCOME;
  1731. }
  1732. if (type == 0) {
  1733. vp3_decode_end(avctx);
  1734. ret = theora_decode_header(avctx, &gb);
  1735. if (ret < 0) {
  1736. vp3_decode_end(avctx);
  1737. } else
  1738. ret = vp3_decode_init(avctx);
  1739. return ret;
  1740. } else if (type == 2) {
  1741. ret = theora_decode_tables(avctx, &gb);
  1742. if (ret < 0) {
  1743. vp3_decode_end(avctx);
  1744. } else
  1745. ret = vp3_decode_init(avctx);
  1746. return ret;
  1747. }
  1748. av_log(avctx, AV_LOG_ERROR,
  1749. "Header packet passed to frame decoder, skipping\n");
  1750. return -1;
  1751. }
  1752. #endif
  1753. s->keyframe = !get_bits1(&gb);
  1754. if (!s->all_fragments) {
  1755. av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");
  1756. return -1;
  1757. }
  1758. if (!s->theora)
  1759. skip_bits(&gb, 1);
  1760. for (i = 0; i < 3; i++)
  1761. s->last_qps[i] = s->qps[i];
  1762. s->nqps = 0;
  1763. do {
  1764. s->qps[s->nqps++] = get_bits(&gb, 6);
  1765. } while (s->theora >= 0x030200 && s->nqps < 3 && get_bits1(&gb));
  1766. for (i = s->nqps; i < 3; i++)
  1767. s->qps[i] = -1;
  1768. if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  1769. av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",
  1770. s->keyframe ? "key" : "", avctx->frame_number + 1, s->qps[0]);
  1771. s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||
  1772. avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL
  1773. : AVDISCARD_NONKEY);
  1774. if (s->qps[0] != s->last_qps[0])
  1775. init_loop_filter(s);
  1776. for (i = 0; i < s->nqps; i++)
  1777. // reinit all dequantizers if the first one changed, because
  1778. // the DC of the first quantizer must be used for all matrices
  1779. if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])
  1780. init_dequantizer(s, i);
  1781. if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)
  1782. return buf_size;
  1783. s->current_frame.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I
  1784. : AV_PICTURE_TYPE_P;
  1785. s->current_frame.f->key_frame = s->keyframe;
  1786. if (ff_thread_get_buffer(avctx, &s->current_frame, AV_GET_BUFFER_FLAG_REF) < 0)
  1787. goto error;
  1788. if (!s->edge_emu_buffer)
  1789. s->edge_emu_buffer = av_malloc(9 * FFABS(s->current_frame.f->linesize[0]));
  1790. if (s->keyframe) {
  1791. if (!s->theora) {
  1792. skip_bits(&gb, 4); /* width code */
  1793. skip_bits(&gb, 4); /* height code */
  1794. if (s->version) {
  1795. s->version = get_bits(&gb, 5);
  1796. if (avctx->frame_number == 0)
  1797. av_log(s->avctx, AV_LOG_DEBUG,
  1798. "VP version: %d\n", s->version);
  1799. }
  1800. }
  1801. if (s->version || s->theora) {
  1802. if (get_bits1(&gb))
  1803. av_log(s->avctx, AV_LOG_ERROR,
  1804. "Warning, unsupported keyframe coding type?!\n");
  1805. skip_bits(&gb, 2); /* reserved? */
  1806. }
  1807. } else {
  1808. if (!s->golden_frame.f->data[0]) {
  1809. av_log(s->avctx, AV_LOG_WARNING,
  1810. "vp3: first frame not a keyframe\n");
  1811. s->golden_frame.f->pict_type = AV_PICTURE_TYPE_I;
  1812. if (ff_thread_get_buffer(avctx, &s->golden_frame,
  1813. AV_GET_BUFFER_FLAG_REF) < 0)
  1814. goto error;
  1815. ff_thread_release_buffer(avctx, &s->last_frame);
  1816. if ((ret = ff_thread_ref_frame(&s->last_frame,
  1817. &s->golden_frame)) < 0)
  1818. goto error;
  1819. ff_thread_report_progress(&s->last_frame, INT_MAX, 0);
  1820. }
  1821. }
  1822. memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));
  1823. ff_thread_finish_setup(avctx);
  1824. if (unpack_superblocks(s, &gb)) {
  1825. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");
  1826. goto error;
  1827. }
  1828. if (unpack_modes(s, &gb)) {
  1829. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");
  1830. goto error;
  1831. }
  1832. if (unpack_vectors(s, &gb)) {
  1833. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");
  1834. goto error;
  1835. }
  1836. if (unpack_block_qpis(s, &gb)) {
  1837. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");
  1838. goto error;
  1839. }
  1840. if (unpack_dct_coeffs(s, &gb)) {
  1841. av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");
  1842. goto error;
  1843. }
  1844. for (i = 0; i < 3; i++) {
  1845. int height = s->height >> (i && s->chroma_y_shift);
  1846. if (s->flipped_image)
  1847. s->data_offset[i] = 0;
  1848. else
  1849. s->data_offset[i] = (height - 1) * s->current_frame.f->linesize[i];
  1850. }
  1851. s->last_slice_end = 0;
  1852. for (i = 0; i < s->c_superblock_height; i++)
  1853. render_slice(s, i);
  1854. // filter the last row
  1855. for (i = 0; i < 3; i++) {
  1856. int row = (s->height >> (3 + (i && s->chroma_y_shift))) - 1;
  1857. apply_loop_filter(s, i, row, row + 1);
  1858. }
  1859. vp3_draw_horiz_band(s, s->height);
  1860. /* output frame, offset as needed */
  1861. if ((ret = av_frame_ref(data, s->current_frame.f)) < 0)
  1862. return ret;
  1863. for (i = 0; i < 3; i++) {
  1864. AVFrame *dst = data;
  1865. int off = (s->offset_x >> (i && s->chroma_y_shift)) +
  1866. (s->offset_y >> (i && s->chroma_y_shift)) * dst->linesize[i];
  1867. dst->data[i] += off;
  1868. }
  1869. *got_frame = 1;
  1870. if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME)) {
  1871. ret = update_frames(avctx);
  1872. if (ret < 0)
  1873. return ret;
  1874. }
  1875. return buf_size;
  1876. error:
  1877. ff_thread_report_progress(&s->current_frame, INT_MAX, 0);
  1878. if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_FRAME))
  1879. av_frame_unref(s->current_frame.f);
  1880. return -1;
  1881. }
  1882. static int read_huffman_tree(AVCodecContext *avctx, GetBitContext *gb)
  1883. {
  1884. Vp3DecodeContext *s = avctx->priv_data;
  1885. if (get_bits1(gb)) {
  1886. int token;
  1887. if (s->entries >= 32) { /* overflow */
  1888. av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
  1889. return -1;
  1890. }
  1891. token = get_bits(gb, 5);
  1892. ff_dlog(avctx, "hti %d hbits %x token %d entry : %d size %d\n",
  1893. s->hti, s->hbits, token, s->entries, s->huff_code_size);
  1894. s->huffman_table[s->hti][token][0] = s->hbits;
  1895. s->huffman_table[s->hti][token][1] = s->huff_code_size;
  1896. s->entries++;
  1897. } else {
  1898. if (s->huff_code_size >= 32) { /* overflow */
  1899. av_log(avctx, AV_LOG_ERROR, "huffman tree overflow\n");
  1900. return -1;
  1901. }
  1902. s->huff_code_size++;
  1903. s->hbits <<= 1;
  1904. if (read_huffman_tree(avctx, gb))
  1905. return -1;
  1906. s->hbits |= 1;
  1907. if (read_huffman_tree(avctx, gb))
  1908. return -1;
  1909. s->hbits >>= 1;
  1910. s->huff_code_size--;
  1911. }
  1912. return 0;
  1913. }
  1914. static int vp3_init_thread_copy(AVCodecContext *avctx)
  1915. {
  1916. Vp3DecodeContext *s = avctx->priv_data;
  1917. s->superblock_coding = NULL;
  1918. s->all_fragments = NULL;
  1919. s->coded_fragment_list[0] = NULL;
  1920. s->dct_tokens_base = NULL;
  1921. s->superblock_fragments = NULL;
  1922. s->macroblock_coding = NULL;
  1923. s->motion_val[0] = NULL;
  1924. s->motion_val[1] = NULL;
  1925. s->edge_emu_buffer = NULL;
  1926. return init_frames(s);
  1927. }
  1928. #if CONFIG_THEORA_DECODER
  1929. static const enum AVPixelFormat theora_pix_fmts[4] = {
  1930. AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P
  1931. };
  1932. static int theora_decode_header(AVCodecContext *avctx, GetBitContext *gb)
  1933. {
  1934. Vp3DecodeContext *s = avctx->priv_data;
  1935. int visible_width, visible_height, colorspace;
  1936. uint8_t offset_x = 0, offset_y = 0;
  1937. int ret;
  1938. AVRational fps, aspect;
  1939. s->theora = get_bits_long(gb, 24);
  1940. av_log(avctx, AV_LOG_DEBUG, "Theora bitstream version %X\n", s->theora);
  1941. /* 3.2.0 aka alpha3 has the same frame orientation as original vp3
  1942. * but previous versions have the image flipped relative to vp3 */
  1943. if (s->theora < 0x030200) {
  1944. s->flipped_image = 1;
  1945. av_log(avctx, AV_LOG_DEBUG,
  1946. "Old (<alpha3) Theora bitstream, flipped image\n");
  1947. }
  1948. visible_width =
  1949. s->width = get_bits(gb, 16) << 4;
  1950. visible_height =
  1951. s->height = get_bits(gb, 16) << 4;
  1952. if (s->theora >= 0x030200) {
  1953. visible_width = get_bits_long(gb, 24);
  1954. visible_height = get_bits_long(gb, 24);
  1955. offset_x = get_bits(gb, 8); /* offset x */
  1956. offset_y = get_bits(gb, 8); /* offset y, from bottom */
  1957. }
  1958. /* sanity check */
  1959. if (av_image_check_size(visible_width, visible_height, 0, avctx) < 0 ||
  1960. visible_width + offset_x > s->width ||
  1961. visible_height + offset_y > s->height) {
  1962. av_log(avctx, AV_LOG_ERROR,
  1963. "Invalid frame dimensions - w:%d h:%d x:%d y:%d (%dx%d).\n",
  1964. visible_width, visible_height, offset_x, offset_y,
  1965. s->width, s->height);
  1966. return AVERROR_INVALIDDATA;
  1967. }
  1968. fps.num = get_bits_long(gb, 32);
  1969. fps.den = get_bits_long(gb, 32);
  1970. if (fps.num && fps.den) {
  1971. if (fps.num < 0 || fps.den < 0) {
  1972. av_log(avctx, AV_LOG_ERROR, "Invalid framerate\n");
  1973. return AVERROR_INVALIDDATA;
  1974. }
  1975. av_reduce(&avctx->framerate.den, &avctx->framerate.num,
  1976. fps.den, fps.num, 1 << 30);
  1977. }
  1978. aspect.num = get_bits_long(gb, 24);
  1979. aspect.den = get_bits_long(gb, 24);
  1980. if (aspect.num && aspect.den) {
  1981. av_reduce(&avctx->sample_aspect_ratio.num,
  1982. &avctx->sample_aspect_ratio.den,
  1983. aspect.num, aspect.den, 1 << 30);
  1984. ff_set_sar(avctx, avctx->sample_aspect_ratio);
  1985. }
  1986. if (s->theora < 0x030200)
  1987. skip_bits(gb, 5); /* keyframe frequency force */
  1988. colorspace = get_bits(gb, 8);
  1989. skip_bits(gb, 24); /* bitrate */
  1990. skip_bits(gb, 6); /* quality hint */
  1991. if (s->theora >= 0x030200) {
  1992. skip_bits(gb, 5); /* keyframe frequency force */
  1993. avctx->pix_fmt = theora_pix_fmts[get_bits(gb, 2)];
  1994. if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
  1995. av_log(avctx, AV_LOG_ERROR, "Invalid pixel format\n");
  1996. return AVERROR_INVALIDDATA;
  1997. }
  1998. skip_bits(gb, 3); /* reserved */
  1999. }
  2000. ret = ff_set_dimensions(avctx, s->width, s->height);
  2001. if (ret < 0)
  2002. return ret;
  2003. if (!(avctx->flags2 & AV_CODEC_FLAG2_IGNORE_CROP)) {
  2004. avctx->width = visible_width;
  2005. avctx->height = visible_height;
  2006. // translate offsets from theora axis ([0,0] lower left)
  2007. // to normal axis ([0,0] upper left)
  2008. s->offset_x = offset_x;
  2009. s->offset_y = s->height - visible_height - offset_y;
  2010. if ((s->offset_x & 0x1F) && !(avctx->flags & AV_CODEC_FLAG_UNALIGNED)) {
  2011. s->offset_x &= ~0x1F;
  2012. if (!s->offset_x_warned) {
  2013. s->offset_x_warned = 1;
  2014. av_log(avctx, AV_LOG_WARNING, "Reducing offset_x from %d to %d"
  2015. "chroma samples to preserve alignment.\n",
  2016. offset_x, s->offset_x);
  2017. }
  2018. }
  2019. }
  2020. if (colorspace == 1)
  2021. avctx->color_primaries = AVCOL_PRI_BT470M;
  2022. else if (colorspace == 2)
  2023. avctx->color_primaries = AVCOL_PRI_BT470BG;
  2024. if (colorspace == 1 || colorspace == 2) {
  2025. avctx->colorspace = AVCOL_SPC_BT470BG;
  2026. avctx->color_trc = AVCOL_TRC_BT709;
  2027. }
  2028. return 0;
  2029. }
  2030. static int theora_decode_tables(AVCodecContext *avctx, GetBitContext *gb)
  2031. {
  2032. Vp3DecodeContext *s = avctx->priv_data;
  2033. int i, n, matrices, inter, plane;
  2034. if (s->theora >= 0x030200) {
  2035. n = get_bits(gb, 3);
  2036. /* loop filter limit values table */
  2037. if (n)
  2038. for (i = 0; i < 64; i++)
  2039. s->filter_limit_values[i] = get_bits(gb, n);
  2040. }
  2041. if (s->theora >= 0x030200)
  2042. n = get_bits(gb, 4) + 1;
  2043. else
  2044. n = 16;
  2045. /* quality threshold table */
  2046. for (i = 0; i < 64; i++)
  2047. s->coded_ac_scale_factor[i] = get_bits(gb, n);
  2048. if (s->theora >= 0x030200)
  2049. n = get_bits(gb, 4) + 1;
  2050. else
  2051. n = 16;
  2052. /* dc scale factor table */
  2053. for (i = 0; i < 64; i++)
  2054. s->coded_dc_scale_factor[i] = get_bits(gb, n);
  2055. if (s->theora >= 0x030200)
  2056. matrices = get_bits(gb, 9) + 1;
  2057. else
  2058. matrices = 3;
  2059. if (matrices > 384) {
  2060. av_log(avctx, AV_LOG_ERROR, "invalid number of base matrixes\n");
  2061. return -1;
  2062. }
  2063. for (n = 0; n < matrices; n++)
  2064. for (i = 0; i < 64; i++)
  2065. s->base_matrix[n][i] = get_bits(gb, 8);
  2066. for (inter = 0; inter <= 1; inter++) {
  2067. for (plane = 0; plane <= 2; plane++) {
  2068. int newqr = 1;
  2069. if (inter || plane > 0)
  2070. newqr = get_bits1(gb);
  2071. if (!newqr) {
  2072. int qtj, plj;
  2073. if (inter && get_bits1(gb)) {
  2074. qtj = 0;
  2075. plj = plane;
  2076. } else {
  2077. qtj = (3 * inter + plane - 1) / 3;
  2078. plj = (plane + 2) % 3;
  2079. }
  2080. s->qr_count[inter][plane] = s->qr_count[qtj][plj];
  2081. memcpy(s->qr_size[inter][plane], s->qr_size[qtj][plj],
  2082. sizeof(s->qr_size[0][0]));
  2083. memcpy(s->qr_base[inter][plane], s->qr_base[qtj][plj],
  2084. sizeof(s->qr_base[0][0]));
  2085. } else {
  2086. int qri = 0;
  2087. int qi = 0;
  2088. for (;;) {
  2089. i = get_bits(gb, av_log2(matrices - 1) + 1);
  2090. if (i >= matrices) {
  2091. av_log(avctx, AV_LOG_ERROR,
  2092. "invalid base matrix index\n");
  2093. return -1;
  2094. }
  2095. s->qr_base[inter][plane][qri] = i;
  2096. if (qi >= 63)
  2097. break;
  2098. i = get_bits(gb, av_log2(63 - qi) + 1) + 1;
  2099. s->qr_size[inter][plane][qri++] = i;
  2100. qi += i;
  2101. }
  2102. if (qi > 63) {
  2103. av_log(avctx, AV_LOG_ERROR, "invalid qi %d > 63\n", qi);
  2104. return -1;
  2105. }
  2106. s->qr_count[inter][plane] = qri;
  2107. }
  2108. }
  2109. }
  2110. /* Huffman tables */
  2111. for (s->hti = 0; s->hti < 80; s->hti++) {
  2112. s->entries = 0;
  2113. s->huff_code_size = 1;
  2114. if (!get_bits1(gb)) {
  2115. s->hbits = 0;
  2116. if (read_huffman_tree(avctx, gb))
  2117. return -1;
  2118. s->hbits = 1;
  2119. if (read_huffman_tree(avctx, gb))
  2120. return -1;
  2121. }
  2122. }
  2123. s->theora_tables = 1;
  2124. return 0;
  2125. }
  2126. static av_cold int theora_decode_init(AVCodecContext *avctx)
  2127. {
  2128. Vp3DecodeContext *s = avctx->priv_data;
  2129. GetBitContext gb;
  2130. int ptype;
  2131. const uint8_t *header_start[3];
  2132. int header_len[3];
  2133. int i;
  2134. avctx->pix_fmt = AV_PIX_FMT_YUV420P;
  2135. s->theora = 1;
  2136. if (!avctx->extradata_size) {
  2137. av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");
  2138. return -1;
  2139. }
  2140. if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,
  2141. 42, header_start, header_len) < 0) {
  2142. av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");
  2143. return -1;
  2144. }
  2145. for (i = 0; i < 3; i++) {
  2146. if (header_len[i] <= 0)
  2147. continue;
  2148. init_get_bits8(&gb, header_start[i], header_len[i]);
  2149. ptype = get_bits(&gb, 8);
  2150. if (!(ptype & 0x80)) {
  2151. av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");
  2152. // return -1;
  2153. }
  2154. // FIXME: Check for this as well.
  2155. skip_bits_long(&gb, 6 * 8); /* "theora" */
  2156. switch (ptype) {
  2157. case 0x80:
  2158. if (theora_decode_header(avctx, &gb) < 0)
  2159. return -1;
  2160. break;
  2161. case 0x81:
  2162. // FIXME: is this needed? it breaks sometimes
  2163. // theora_decode_comments(avctx, gb);
  2164. break;
  2165. case 0x82:
  2166. if (theora_decode_tables(avctx, &gb))
  2167. return -1;
  2168. break;
  2169. default:
  2170. av_log(avctx, AV_LOG_ERROR,
  2171. "Unknown Theora config packet: %d\n", ptype & ~0x80);
  2172. break;
  2173. }
  2174. if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))
  2175. av_log(avctx, AV_LOG_WARNING,
  2176. "%d bits left in packet %X\n",
  2177. 8 * header_len[i] - get_bits_count(&gb), ptype);
  2178. if (s->theora < 0x030200)
  2179. break;
  2180. }
  2181. return vp3_decode_init(avctx);
  2182. }
  2183. AVCodec ff_theora_decoder = {
  2184. .name = "theora",
  2185. .long_name = NULL_IF_CONFIG_SMALL("Theora"),
  2186. .type = AVMEDIA_TYPE_VIDEO,
  2187. .id = AV_CODEC_ID_THEORA,
  2188. .priv_data_size = sizeof(Vp3DecodeContext),
  2189. .init = theora_decode_init,
  2190. .close = vp3_decode_end,
  2191. .decode = vp3_decode_frame,
  2192. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
  2193. AV_CODEC_CAP_FRAME_THREADS,
  2194. .flush = vp3_decode_flush,
  2195. .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
  2196. .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context)
  2197. };
  2198. #endif
  2199. AVCodec ff_vp3_decoder = {
  2200. .name = "vp3",
  2201. .long_name = NULL_IF_CONFIG_SMALL("On2 VP3"),
  2202. .type = AVMEDIA_TYPE_VIDEO,
  2203. .id = AV_CODEC_ID_VP3,
  2204. .priv_data_size = sizeof(Vp3DecodeContext),
  2205. .init = vp3_decode_init,
  2206. .close = vp3_decode_end,
  2207. .decode = vp3_decode_frame,
  2208. .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DRAW_HORIZ_BAND |
  2209. AV_CODEC_CAP_FRAME_THREADS,
  2210. .flush = vp3_decode_flush,
  2211. .init_thread_copy = ONLY_IF_THREADS_ENABLED(vp3_init_thread_copy),
  2212. .update_thread_context = ONLY_IF_THREADS_ENABLED(vp3_update_thread_context),
  2213. };