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.

3218 lines
114KB

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