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.

3308 lines
116KB

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