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.

2362 lines
81KB

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