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.

2631 lines
94KB

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