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.

2373 lines
82KB

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