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.

2611 lines
93KB

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