Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * MPEG4 decoder.
  3.  * Copyright (c) 2000,2001 Fabrice Bellard
  4.  * Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
  5.  *
  6.  * This file is part of FFmpeg.
  7.  *
  8.  * FFmpeg is free software; you can redistribute it and/or
  9.  * modify it under the terms of the GNU Lesser General Public
  10.  * License as published by the Free Software Foundation; either
  11.  * version 2.1 of the License, or (at your option) any later version.
  12.  *
  13.  * FFmpeg is distributed in the hope that it will be useful,
  14.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  16.  * Lesser General Public License for more details.
  17.  *
  18.  * You should have received a copy of the GNU Lesser General Public
  19.  * License along with FFmpeg; if not, write to the Free Software
  20.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21.  */
  22.  
  23. #define UNCHECKED_BITSTREAM_READER 1
  24.  
  25. #include "libavutil/internal.h"
  26. #include "libavutil/opt.h"
  27. #include "error_resilience.h"
  28. #include "idctdsp.h"
  29. #include "internal.h"
  30. #include "mpegutils.h"
  31. #include "mpegvideo.h"
  32. #include "mpegvideodata.h"
  33. #include "mpeg4video.h"
  34. #include "h263.h"
  35. #include "thread.h"
  36. #include "xvididct.h"
  37.  
  38. /* The defines below define the number of bits that are read at once for
  39.  * reading vlc values. Changing these may improve speed and data cache needs
  40.  * be aware though that decreasing them may need the number of stages that is
  41.  * passed to get_vlc* to be increased. */
  42. #define SPRITE_TRAJ_VLC_BITS 6
  43. #define DC_VLC_BITS 9
  44. #define MB_TYPE_B_VLC_BITS 4
  45.  
  46. static VLC dc_lum, dc_chrom;
  47. static VLC sprite_trajectory;
  48. static VLC mb_type_b_vlc;
  49.  
  50. static const int mb_type_b_map[4] = {
  51.     MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
  52.     MB_TYPE_L0L1    | MB_TYPE_16x16,
  53.     MB_TYPE_L1      | MB_TYPE_16x16,
  54.     MB_TYPE_L0      | MB_TYPE_16x16,
  55. };
  56.  
  57. /**
  58.  * Predict the ac.
  59.  * @param n block index (0-3 are luma, 4-5 are chroma)
  60.  * @param dir the ac prediction direction
  61.  */
  62. void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
  63. {
  64.     int i;
  65.     int16_t *ac_val, *ac_val1;
  66.     int8_t *const qscale_table = s->current_picture.qscale_table;
  67.  
  68.     /* find prediction */
  69.     ac_val  = s->ac_val[0][0] + s->block_index[n] * 16;
  70.     ac_val1 = ac_val;
  71.     if (s->ac_pred) {
  72.         if (dir == 0) {
  73.             const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
  74.             /* left prediction */
  75.             ac_val -= 16;
  76.  
  77.             if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
  78.                 n == 1 || n == 3) {
  79.                 /* same qscale */
  80.                 for (i = 1; i < 8; i++)
  81.                     block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
  82.             } else {
  83.                 /* different qscale, we must rescale */
  84.                 for (i = 1; i < 8; i++)
  85.                     block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
  86.             }
  87.         } else {
  88.             const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
  89.             /* top prediction */
  90.             ac_val -= 16 * s->block_wrap[n];
  91.  
  92.             if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
  93.                 n == 2 || n == 3) {
  94.                 /* same qscale */
  95.                 for (i = 1; i < 8; i++)
  96.                     block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
  97.             } else {
  98.                 /* different qscale, we must rescale */
  99.                 for (i = 1; i < 8; i++)
  100.                     block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
  101.             }
  102.         }
  103.     }
  104.     /* left copy */
  105.     for (i = 1; i < 8; i++)
  106.         ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
  107.  
  108.     /* top copy */
  109.     for (i = 1; i < 8; i++)
  110.         ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
  111. }
  112.  
  113. /**
  114.  * check if the next stuff is a resync marker or the end.
  115.  * @return 0 if not
  116.  */
  117. static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
  118. {
  119.     MpegEncContext *s = &ctx->m;
  120.     int bits_count = get_bits_count(&s->gb);
  121.     int v          = show_bits(&s->gb, 16);
  122.  
  123.     if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
  124.         return 0;
  125.  
  126.     while (v <= 0xFF) {
  127.         if (s->pict_type == AV_PICTURE_TYPE_B ||
  128.             (v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
  129.             break;
  130.         skip_bits(&s->gb, 8 + s->pict_type);
  131.         bits_count += 8 + s->pict_type;
  132.         v = show_bits(&s->gb, 16);
  133.     }
  134.  
  135.     if (bits_count + 8 >= s->gb.size_in_bits) {
  136.         v >>= 8;
  137.         v  |= 0x7F >> (7 - (bits_count & 7));
  138.  
  139.         if (v == 0x7F)
  140.             return s->mb_num;
  141.     } else {
  142.         if (v == ff_mpeg4_resync_prefix[bits_count & 7]) {
  143.             int len, mb_num;
  144.             int mb_num_bits = av_log2(s->mb_num - 1) + 1;
  145.             GetBitContext gb = s->gb;
  146.  
  147.             skip_bits(&s->gb, 1);
  148.             align_get_bits(&s->gb);
  149.  
  150.             for (len = 0; len < 32; len++)
  151.                 if (get_bits1(&s->gb))
  152.                     break;
  153.  
  154.             mb_num = get_bits(&s->gb, mb_num_bits);
  155.             if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
  156.                 mb_num= -1;
  157.  
  158.             s->gb = gb;
  159.  
  160.             if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
  161.                 return mb_num;
  162.         }
  163.     }
  164.     return 0;
  165. }
  166.  
  167. static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
  168. {
  169.     MpegEncContext *s = &ctx->m;
  170.     int a     = 2 << s->sprite_warping_accuracy;
  171.     int rho   = 3  - s->sprite_warping_accuracy;
  172.     int r     = 16 / a;
  173.     int alpha = 0;
  174.     int beta  = 0;
  175.     int w     = s->width;
  176.     int h     = s->height;
  177.     int min_ab, i, w2, h2, w3, h3;
  178.     int sprite_ref[4][2];
  179.     int virtual_ref[2][2];
  180.  
  181.     // only true for rectangle shapes
  182.     const int vop_ref[4][2] = { { 0, 0 },         { s->width, 0 },
  183.                                 { 0, s->height }, { s->width, s->height } };
  184.     int d[4][2]             = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
  185.  
  186.     if (w <= 0 || h <= 0)
  187.         return AVERROR_INVALIDDATA;
  188.  
  189.     for (i = 0; i < ctx->num_sprite_warping_points; i++) {
  190.         int length;
  191.         int x = 0, y = 0;
  192.  
  193.         length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
  194.         if (length > 0)
  195.             x = get_xbits(gb, length);
  196.  
  197.         if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
  198.             check_marker(gb, "before sprite_trajectory");
  199.  
  200.         length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
  201.         if (length > 0)
  202.             y = get_xbits(gb, length);
  203.  
  204.         check_marker(gb, "after sprite_trajectory");
  205.         ctx->sprite_traj[i][0] = d[i][0] = x;
  206.         ctx->sprite_traj[i][1] = d[i][1] = y;
  207.     }
  208.     for (; i < 4; i++)
  209.         ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
  210.  
  211.     while ((1 << alpha) < w)
  212.         alpha++;
  213.     while ((1 << beta) < h)
  214.         beta++;  /* typo in the mpeg4 std for the definition of w' and h' */
  215.     w2 = 1 << alpha;
  216.     h2 = 1 << beta;
  217.  
  218.     // Note, the 4th point isn't used for GMC
  219.     if (ctx->divx_version == 500 && ctx->divx_build == 413) {
  220.         sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
  221.         sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
  222.         sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
  223.         sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
  224.         sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
  225.         sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
  226.     } else {
  227.         sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
  228.         sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
  229.         sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
  230.         sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
  231.         sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
  232.         sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
  233.     }
  234.     /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
  235.      * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
  236.  
  237.     /* this is mostly identical to the mpeg4 std (and is totally unreadable
  238.      * because of that...). Perhaps it should be reordered to be more readable.
  239.      * The idea behind this virtual_ref mess is to be able to use shifts later
  240.      * per pixel instead of divides so the distance between points is converted
  241.      * from w&h based to w2&h2 based which are of the 2^x form. */
  242.     virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
  243.                          ROUNDED_DIV(((w - w2) *
  244.                                       (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) +
  245.                                       w2 * (r * sprite_ref[1][0] - 16 * vop_ref[1][0])), w);
  246.     virtual_ref[0][1] = 16 * vop_ref[0][1] +
  247.                         ROUNDED_DIV(((w - w2) *
  248.                                      (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) +
  249.                                      w2 * (r * sprite_ref[1][1] - 16 * vop_ref[1][1])), w);
  250.     virtual_ref[1][0] = 16 * vop_ref[0][0] +
  251.                         ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) +
  252.                                      h2 * (r * sprite_ref[2][0] - 16 * vop_ref[2][0])), h);
  253.     virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
  254.                         ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) +
  255.                                      h2 * (r * sprite_ref[2][1] - 16 * vop_ref[2][1])), h);
  256.  
  257.     switch (ctx->num_sprite_warping_points) {
  258.     case 0:
  259.         s->sprite_offset[0][0] =
  260.         s->sprite_offset[0][1] =
  261.         s->sprite_offset[1][0] =
  262.         s->sprite_offset[1][1] = 0;
  263.         s->sprite_delta[0][0]  = a;
  264.         s->sprite_delta[0][1]  =
  265.         s->sprite_delta[1][0]  = 0;
  266.         s->sprite_delta[1][1]  = a;
  267.         ctx->sprite_shift[0]   =
  268.         ctx->sprite_shift[1]   = 0;
  269.         break;
  270.     case 1:     // GMC only
  271.         s->sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0];
  272.         s->sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1];
  273.         s->sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
  274.                                  a * (vop_ref[0][0] / 2);
  275.         s->sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
  276.                                  a * (vop_ref[0][1] / 2);
  277.         s->sprite_delta[0][0]  = a;
  278.         s->sprite_delta[0][1]  =
  279.         s->sprite_delta[1][0]  = 0;
  280.         s->sprite_delta[1][1]  = a;
  281.         ctx->sprite_shift[0]   =
  282.         ctx->sprite_shift[1]   = 0;
  283.         break;
  284.     case 2:
  285.         s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + rho)) +
  286.                                  (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
  287.                                  (-vop_ref[0][0]) +
  288.                                  (r * sprite_ref[0][1] - virtual_ref[0][1]) *
  289.                                  (-vop_ref[0][1]) + (1 << (alpha + rho - 1));
  290.         s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + rho)) +
  291.                                  (-r * sprite_ref[0][1] + virtual_ref[0][1]) *
  292.                                  (-vop_ref[0][0]) +
  293.                                  (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
  294.                                  (-vop_ref[0][1]) + (1 << (alpha + rho - 1));
  295.         s->sprite_offset[1][0] = ((-r * sprite_ref[0][0] + virtual_ref[0][0]) *
  296.                                   (-2 * vop_ref[0][0] + 1) +
  297.                                   (r * sprite_ref[0][1] - virtual_ref[0][1]) *
  298.                                   (-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
  299.                                   sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
  300.         s->sprite_offset[1][1] = ((-r * sprite_ref[0][1] + virtual_ref[0][1]) *
  301.                                   (-2 * vop_ref[0][0] + 1) +
  302.                                   (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
  303.                                   (-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
  304.                                   sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
  305.         s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
  306.         s->sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
  307.         s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
  308.         s->sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
  309.  
  310.         ctx->sprite_shift[0]  = alpha + rho;
  311.         ctx->sprite_shift[1]  = alpha + rho + 2;
  312.         break;
  313.     case 3:
  314.         min_ab = FFMIN(alpha, beta);
  315.         w3     = w2 >> min_ab;
  316.         h3     = h2 >> min_ab;
  317.         s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + beta + rho - min_ab)) +
  318.                                  (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
  319.                                  h3 * (-vop_ref[0][0]) +
  320.                                  (-r * sprite_ref[0][0] + virtual_ref[1][0]) *
  321.                                  w3 * (-vop_ref[0][1]) +
  322.                                  (1 << (alpha + beta + rho - min_ab - 1));
  323.         s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + beta + rho - min_ab)) +
  324.                                  (-r * sprite_ref[0][1] + virtual_ref[0][1]) *
  325.                                  h3 * (-vop_ref[0][0]) +
  326.                                  (-r * sprite_ref[0][1] + virtual_ref[1][1]) *
  327.                                  w3 * (-vop_ref[0][1]) +
  328.                                  (1 << (alpha + beta + rho - min_ab - 1));
  329.         s->sprite_offset[1][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) *
  330.                                  h3 * (-2 * vop_ref[0][0] + 1) +
  331.                                  (-r * sprite_ref[0][0] + virtual_ref[1][0]) *
  332.                                  w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 *
  333.                                  r * sprite_ref[0][0] - 16 * w2 * h3 +
  334.                                  (1 << (alpha + beta + rho - min_ab + 1));
  335.         s->sprite_offset[1][1] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) *
  336.                                  h3 * (-2 * vop_ref[0][0] + 1) +
  337.                                  (-r * sprite_ref[0][1] + virtual_ref[1][1]) *
  338.                                  w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 *
  339.                                  r * sprite_ref[0][1] - 16 * w2 * h3 +
  340.                                  (1 << (alpha + beta + rho - min_ab + 1));
  341.         s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3;
  342.         s->sprite_delta[0][1] = (-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3;
  343.         s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3;
  344.         s->sprite_delta[1][1] = (-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3;
  345.  
  346.         ctx->sprite_shift[0]  = alpha + beta + rho - min_ab;
  347.         ctx->sprite_shift[1]  = alpha + beta + rho - min_ab + 2;
  348.         break;
  349.     }
  350.     /* try to simplify the situation */
  351.     if (s->sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
  352.         s->sprite_delta[0][1] == 0 &&
  353.         s->sprite_delta[1][0] == 0 &&
  354.         s->sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
  355.         s->sprite_offset[0][0] >>= ctx->sprite_shift[0];
  356.         s->sprite_offset[0][1] >>= ctx->sprite_shift[0];
  357.         s->sprite_offset[1][0] >>= ctx->sprite_shift[1];
  358.         s->sprite_offset[1][1] >>= ctx->sprite_shift[1];
  359.         s->sprite_delta[0][0] = a;
  360.         s->sprite_delta[0][1] = 0;
  361.         s->sprite_delta[1][0] = 0;
  362.         s->sprite_delta[1][1] = a;
  363.         ctx->sprite_shift[0] = 0;
  364.         ctx->sprite_shift[1] = 0;
  365.         s->real_sprite_warping_points = 1;
  366.     } else {
  367.         int shift_y = 16 - ctx->sprite_shift[0];
  368.         int shift_c = 16 - ctx->sprite_shift[1];
  369.         for (i = 0; i < 2; i++) {
  370.             s->sprite_offset[0][i] <<= shift_y;
  371.             s->sprite_offset[1][i] <<= shift_c;
  372.             s->sprite_delta[0][i]  <<= shift_y;
  373.             s->sprite_delta[1][i]  <<= shift_y;
  374.             ctx->sprite_shift[i]     = 16;
  375.         }
  376.         s->real_sprite_warping_points = ctx->num_sprite_warping_points;
  377.     }
  378.  
  379.     return 0;
  380. }
  381.  
  382. static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) {
  383.     int len = FFMIN(ctx->time_increment_bits + 3, 15);
  384.  
  385.     get_bits(gb, len);
  386.     if (get_bits1(gb))
  387.         get_bits(gb, len);
  388.     check_marker(gb, "after new_pred");
  389.  
  390.     return 0;
  391. }
  392.  
  393. /**
  394.  * Decode the next video packet.
  395.  * @return <0 if something went wrong
  396.  */
  397. int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
  398. {
  399.     MpegEncContext *s = &ctx->m;
  400.  
  401.     int mb_num_bits      = av_log2(s->mb_num - 1) + 1;
  402.     int header_extension = 0, mb_num, len;
  403.  
  404.     /* is there enough space left for a video packet + header */
  405.     if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
  406.         return -1;
  407.  
  408.     for (len = 0; len < 32; len++)
  409.         if (get_bits1(&s->gb))
  410.             break;
  411.  
  412.     if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
  413.         av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
  414.         return -1;
  415.     }
  416.  
  417.     if (ctx->shape != RECT_SHAPE) {
  418.         header_extension = get_bits1(&s->gb);
  419.         // FIXME more stuff here
  420.     }
  421.  
  422.     mb_num = get_bits(&s->gb, mb_num_bits);
  423.     if (mb_num >= s->mb_num) {
  424.         av_log(s->avctx, AV_LOG_ERROR,
  425.                "illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
  426.         return -1;
  427.     }
  428.  
  429.     s->mb_x = mb_num % s->mb_width;
  430.     s->mb_y = mb_num / s->mb_width;
  431.  
  432.     if (ctx->shape != BIN_ONLY_SHAPE) {
  433.         int qscale = get_bits(&s->gb, s->quant_precision);
  434.         if (qscale)
  435.             s->chroma_qscale = s->qscale = qscale;
  436.     }
  437.  
  438.     if (ctx->shape == RECT_SHAPE)
  439.         header_extension = get_bits1(&s->gb);
  440.  
  441.     if (header_extension) {
  442.         int time_incr = 0;
  443.  
  444.         while (get_bits1(&s->gb) != 0)
  445.             time_incr++;
  446.  
  447.         check_marker(&s->gb, "before time_increment in video packed header");
  448.         skip_bits(&s->gb, ctx->time_increment_bits);      /* time_increment */
  449.         check_marker(&s->gb, "before vop_coding_type in video packed header");
  450.  
  451.         skip_bits(&s->gb, 2); /* vop coding type */
  452.         // FIXME not rect stuff here
  453.  
  454.         if (ctx->shape != BIN_ONLY_SHAPE) {
  455.             skip_bits(&s->gb, 3); /* intra dc vlc threshold */
  456.             // FIXME don't just ignore everything
  457.             if (s->pict_type == AV_PICTURE_TYPE_S &&
  458.                 ctx->vol_sprite_usage == GMC_SPRITE) {
  459.                 if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
  460.                     return AVERROR_INVALIDDATA;
  461.                 av_log(s->avctx, AV_LOG_ERROR, "untested\n");
  462.             }
  463.  
  464.             // FIXME reduced res stuff here
  465.  
  466.             if (s->pict_type != AV_PICTURE_TYPE_I) {
  467.                 int f_code = get_bits(&s->gb, 3);       /* fcode_for */
  468.                 if (f_code == 0)
  469.                     av_log(s->avctx, AV_LOG_ERROR,
  470.                            "Error, video packet header damaged (f_code=0)\n");
  471.             }
  472.             if (s->pict_type == AV_PICTURE_TYPE_B) {
  473.                 int b_code = get_bits(&s->gb, 3);
  474.                 if (b_code == 0)
  475.                     av_log(s->avctx, AV_LOG_ERROR,
  476.                            "Error, video packet header damaged (b_code=0)\n");
  477.             }
  478.         }
  479.     }
  480.     if (ctx->new_pred)
  481.         decode_new_pred(ctx, &s->gb);
  482.  
  483.     return 0;
  484. }
  485.  
  486. /**
  487.  * Get the average motion vector for a GMC MB.
  488.  * @param n either 0 for the x component or 1 for y
  489.  * @return the average MV for a GMC MB
  490.  */
  491. static inline int get_amv(Mpeg4DecContext *ctx, int n)
  492. {
  493.     MpegEncContext *s = &ctx->m;
  494.     int x, y, mb_v, sum, dx, dy, shift;
  495.     int len     = 1 << (s->f_code + 4);
  496.     const int a = s->sprite_warping_accuracy;
  497.  
  498.     if (s->workaround_bugs & FF_BUG_AMV)
  499.         len >>= s->quarter_sample;
  500.  
  501.     if (s->real_sprite_warping_points == 1) {
  502.         if (ctx->divx_version == 500 && ctx->divx_build == 413)
  503.             sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
  504.         else
  505.             sum = RSHIFT(s->sprite_offset[0][n] << s->quarter_sample, a);
  506.     } else {
  507.         dx    = s->sprite_delta[n][0];
  508.         dy    = s->sprite_delta[n][1];
  509.         shift = ctx->sprite_shift[0];
  510.         if (n)
  511.             dy -= 1 << (shift + a + 1);
  512.         else
  513.             dx -= 1 << (shift + a + 1);
  514.         mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16;
  515.  
  516.         sum = 0;
  517.         for (y = 0; y < 16; y++) {
  518.             int v;
  519.  
  520.             v = mb_v + dy * y;
  521.             // FIXME optimize
  522.             for (x = 0; x < 16; x++) {
  523.                 sum += v >> shift;
  524.                 v   += dx;
  525.             }
  526.         }
  527.         sum = RSHIFT(sum, a + 8 - s->quarter_sample);
  528.     }
  529.  
  530.     if (sum < -len)
  531.         sum = -len;
  532.     else if (sum >= len)
  533.         sum = len - 1;
  534.  
  535.     return sum;
  536. }
  537.  
  538. /**
  539.  * Decode the dc value.
  540.  * @param n block index (0-3 are luma, 4-5 are chroma)
  541.  * @param dir_ptr the prediction direction will be stored here
  542.  * @return the quantized dc
  543.  */
  544. static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
  545. {
  546.     int level, code;
  547.  
  548.     if (n < 4)
  549.         code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
  550.     else
  551.         code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
  552.  
  553.     if (code < 0 || code > 9 /* && s->nbit < 9 */) {
  554.         av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
  555.         return -1;
  556.     }
  557.  
  558.     if (code == 0) {
  559.         level = 0;
  560.     } else {
  561.         if (IS_3IV1) {
  562.             if (code == 1)
  563.                 level = 2 * get_bits1(&s->gb) - 1;
  564.             else {
  565.                 if (get_bits1(&s->gb))
  566.                     level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
  567.                 else
  568.                     level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
  569.             }
  570.         } else {
  571.             level = get_xbits(&s->gb, code);
  572.         }
  573.  
  574.         if (code > 8) {
  575.             if (get_bits1(&s->gb) == 0) { /* marker */
  576.                 if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) {
  577.                     av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
  578.                     return -1;
  579.                 }
  580.             }
  581.         }
  582.     }
  583.  
  584.     return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
  585. }
  586.  
  587. /**
  588.  * Decode first partition.
  589.  * @return number of MBs decoded or <0 if an error occurred
  590.  */
  591. static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
  592. {
  593.     MpegEncContext *s = &ctx->m;
  594.     int mb_num = 0;
  595.     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
  596.  
  597.     /* decode first partition */
  598.     s->first_slice_line = 1;
  599.     for (; s->mb_y < s->mb_height; s->mb_y++) {
  600.         ff_init_block_index(s);
  601.         for (; s->mb_x < s->mb_width; s->mb_x++) {
  602.             const int xy = s->mb_x + s->mb_y * s->mb_stride;
  603.             int cbpc;
  604.             int dir = 0;
  605.  
  606.             mb_num++;
  607.             ff_update_block_index(s);
  608.             if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
  609.                 s->first_slice_line = 0;
  610.  
  611.             if (s->pict_type == AV_PICTURE_TYPE_I) {
  612.                 int i;
  613.  
  614.                 do {
  615.                     if (show_bits_long(&s->gb, 19) == DC_MARKER)
  616.                         return mb_num - 1;
  617.  
  618.                     cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
  619.                     if (cbpc < 0) {
  620.                         av_log(s->avctx, AV_LOG_ERROR,
  621.                                "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
  622.                         return -1;
  623.                     }
  624.                 } while (cbpc == 8);
  625.  
  626.                 s->cbp_table[xy]               = cbpc & 3;
  627.                 s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
  628.                 s->mb_intra                    = 1;
  629.  
  630.                 if (cbpc & 4)
  631.                     ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
  632.  
  633.                 s->current_picture.qscale_table[xy] = s->qscale;
  634.  
  635.                 s->mbintra_table[xy] = 1;
  636.                 for (i = 0; i < 6; i++) {
  637.                     int dc_pred_dir;
  638.                     int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
  639.                     if (dc < 0) {
  640.                         av_log(s->avctx, AV_LOG_ERROR,
  641.                                "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
  642.                         return -1;
  643.                     }
  644.                     dir <<= 1;
  645.                     if (dc_pred_dir)
  646.                         dir |= 1;
  647.                 }
  648.                 s->pred_dir_table[xy] = dir;
  649.             } else { /* P/S_TYPE */
  650.                 int mx, my, pred_x, pred_y, bits;
  651.                 int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]];
  652.                 const int stride       = s->b8_stride * 2;
  653.  
  654. try_again:
  655.                 bits = show_bits(&s->gb, 17);
  656.                 if (bits == MOTION_MARKER)
  657.                     return mb_num - 1;
  658.  
  659.                 skip_bits1(&s->gb);
  660.                 if (bits & 0x10000) {
  661.                     /* skip mb */
  662.                     if (s->pict_type == AV_PICTURE_TYPE_S &&
  663.                         ctx->vol_sprite_usage == GMC_SPRITE) {
  664.                         s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
  665.                                                          MB_TYPE_16x16 |
  666.                                                          MB_TYPE_GMC   |
  667.                                                          MB_TYPE_L0;
  668.                         mx = get_amv(ctx, 0);
  669.                         my = get_amv(ctx, 1);
  670.                     } else {
  671.                         s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
  672.                                                          MB_TYPE_16x16 |
  673.                                                          MB_TYPE_L0;
  674.                         mx = my = 0;
  675.                     }
  676.                     mot_val[0]          =
  677.                     mot_val[2]          =
  678.                     mot_val[0 + stride] =
  679.                     mot_val[2 + stride] = mx;
  680.                     mot_val[1]          =
  681.                     mot_val[3]          =
  682.                     mot_val[1 + stride] =
  683.                     mot_val[3 + stride] = my;
  684.  
  685.                     if (s->mbintra_table[xy])
  686.                         ff_clean_intra_table_entries(s);
  687.                     continue;
  688.                 }
  689.  
  690.                 cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
  691.                 if (cbpc < 0) {
  692.                     av_log(s->avctx, AV_LOG_ERROR,
  693.                            "mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
  694.                     return -1;
  695.                 }
  696.                 if (cbpc == 20)
  697.                     goto try_again;
  698.  
  699.                 s->cbp_table[xy] = cbpc & (8 + 3);  // 8 is dquant
  700.  
  701.                 s->mb_intra = ((cbpc & 4) != 0);
  702.  
  703.                 if (s->mb_intra) {
  704.                     s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
  705.                     s->mbintra_table[xy] = 1;
  706.                     mot_val[0]          =
  707.                     mot_val[2]          =
  708.                     mot_val[0 + stride] =
  709.                     mot_val[2 + stride] = 0;
  710.                     mot_val[1]          =
  711.                     mot_val[3]          =
  712.                     mot_val[1 + stride] =
  713.                     mot_val[3 + stride] = 0;
  714.                 } else {
  715.                     if (s->mbintra_table[xy])
  716.                         ff_clean_intra_table_entries(s);
  717.  
  718.                     if (s->pict_type == AV_PICTURE_TYPE_S &&
  719.                         ctx->vol_sprite_usage == GMC_SPRITE &&
  720.                         (cbpc & 16) == 0)
  721.                         s->mcsel = get_bits1(&s->gb);
  722.                     else
  723.                         s->mcsel = 0;
  724.  
  725.                     if ((cbpc & 16) == 0) {
  726.                         /* 16x16 motion prediction */
  727.  
  728.                         ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
  729.                         if (!s->mcsel) {
  730.                             mx = ff_h263_decode_motion(s, pred_x, s->f_code);
  731.                             if (mx >= 0xffff)
  732.                                 return -1;
  733.  
  734.                             my = ff_h263_decode_motion(s, pred_y, s->f_code);
  735.                             if (my >= 0xffff)
  736.                                 return -1;
  737.                             s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
  738.                                                              MB_TYPE_L0;
  739.                         } else {
  740.                             mx = get_amv(ctx, 0);
  741.                             my = get_amv(ctx, 1);
  742.                             s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
  743.                                                              MB_TYPE_GMC   |
  744.                                                              MB_TYPE_L0;
  745.                         }
  746.  
  747.                         mot_val[0]          =
  748.                         mot_val[2]          =
  749.                         mot_val[0 + stride] =
  750.                         mot_val[2 + stride] = mx;
  751.                         mot_val[1]          =
  752.                         mot_val[3]          =
  753.                         mot_val[1 + stride] =
  754.                         mot_val[3 + stride] = my;
  755.                     } else {
  756.                         int i;
  757.                         s->current_picture.mb_type[xy] = MB_TYPE_8x8 |
  758.                                                          MB_TYPE_L0;
  759.                         for (i = 0; i < 4; i++) {
  760.                             int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
  761.                             mx = ff_h263_decode_motion(s, pred_x, s->f_code);
  762.                             if (mx >= 0xffff)
  763.                                 return -1;
  764.  
  765.                             my = ff_h263_decode_motion(s, pred_y, s->f_code);
  766.                             if (my >= 0xffff)
  767.                                 return -1;
  768.                             mot_val[0] = mx;
  769.                             mot_val[1] = my;
  770.                         }
  771.                     }
  772.                 }
  773.             }
  774.         }
  775.         s->mb_x = 0;
  776.     }
  777.  
  778.     return mb_num;
  779. }
  780.  
  781. /**
  782.  * decode second partition.
  783.  * @return <0 if an error occurred
  784.  */
  785. static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
  786. {
  787.     int mb_num = 0;
  788.     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
  789.  
  790.     s->mb_x = s->resync_mb_x;
  791.     s->first_slice_line = 1;
  792.     for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
  793.         ff_init_block_index(s);
  794.         for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
  795.             const int xy = s->mb_x + s->mb_y * s->mb_stride;
  796.  
  797.             mb_num++;
  798.             ff_update_block_index(s);
  799.             if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
  800.                 s->first_slice_line = 0;
  801.  
  802.             if (s->pict_type == AV_PICTURE_TYPE_I) {
  803.                 int ac_pred = get_bits1(&s->gb);
  804.                 int cbpy    = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
  805.                 if (cbpy < 0) {
  806.                     av_log(s->avctx, AV_LOG_ERROR,
  807.                            "cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
  808.                     return -1;
  809.                 }
  810.  
  811.                 s->cbp_table[xy]               |= cbpy << 2;
  812.                 s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
  813.             } else { /* P || S_TYPE */
  814.                 if (IS_INTRA(s->current_picture.mb_type[xy])) {
  815.                     int i;
  816.                     int dir     = 0;
  817.                     int ac_pred = get_bits1(&s->gb);
  818.                     int cbpy    = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
  819.  
  820.                     if (cbpy < 0) {
  821.                         av_log(s->avctx, AV_LOG_ERROR,
  822.                                "I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
  823.                         return -1;
  824.                     }
  825.  
  826.                     if (s->cbp_table[xy] & 8)
  827.                         ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
  828.                     s->current_picture.qscale_table[xy] = s->qscale;
  829.  
  830.                     for (i = 0; i < 6; i++) {
  831.                         int dc_pred_dir;
  832.                         int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
  833.                         if (dc < 0) {
  834.                             av_log(s->avctx, AV_LOG_ERROR,
  835.                                    "DC corrupted at %d %d\n", s->mb_x, s->mb_y);
  836.                             return -1;
  837.                         }
  838.                         dir <<= 1;
  839.                         if (dc_pred_dir)
  840.                             dir |= 1;
  841.                     }
  842.                     s->cbp_table[xy]               &= 3;  // remove dquant
  843.                     s->cbp_table[xy]               |= cbpy << 2;
  844.                     s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
  845.                     s->pred_dir_table[xy]           = dir;
  846.                 } else if (IS_SKIP(s->current_picture.mb_type[xy])) {
  847.                     s->current_picture.qscale_table[xy] = s->qscale;
  848.                     s->cbp_table[xy]                    = 0;
  849.                 } else {
  850.                     int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
  851.  
  852.                     if (cbpy < 0) {
  853.                         av_log(s->avctx, AV_LOG_ERROR,
  854.                                "P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
  855.                         return -1;
  856.                     }
  857.  
  858.                     if (s->cbp_table[xy] & 8)
  859.                         ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
  860.                     s->current_picture.qscale_table[xy] = s->qscale;
  861.  
  862.                     s->cbp_table[xy] &= 3;  // remove dquant
  863.                     s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
  864.                 }
  865.             }
  866.         }
  867.         if (mb_num >= mb_count)
  868.             return 0;
  869.         s->mb_x = 0;
  870.     }
  871.     return 0;
  872. }
  873.  
  874. /**
  875.  * Decode the first and second partition.
  876.  * @return <0 if error (and sets error type in the error_status_table)
  877.  */
  878. int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
  879. {
  880.     MpegEncContext *s = &ctx->m;
  881.     int mb_num;
  882.     const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
  883.     const int part_a_end   = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END   | ER_MV_END)   : ER_MV_END;
  884.  
  885.     mb_num = mpeg4_decode_partition_a(ctx);
  886.     if (mb_num <= 0) {
  887.         ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
  888.                         s->mb_x, s->mb_y, part_a_error);
  889.         return -1;
  890.     }
  891.  
  892.     if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
  893.         av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
  894.         ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
  895.                         s->mb_x, s->mb_y, part_a_error);
  896.         return -1;
  897.     }
  898.  
  899.     s->mb_num_left = mb_num;
  900.  
  901.     if (s->pict_type == AV_PICTURE_TYPE_I) {
  902.         while (show_bits(&s->gb, 9) == 1)
  903.             skip_bits(&s->gb, 9);
  904.         if (get_bits_long(&s->gb, 19) != DC_MARKER) {
  905.             av_log(s->avctx, AV_LOG_ERROR,
  906.                    "marker missing after first I partition at %d %d\n",
  907.                    s->mb_x, s->mb_y);
  908.             return -1;
  909.         }
  910.     } else {
  911.         while (show_bits(&s->gb, 10) == 1)
  912.             skip_bits(&s->gb, 10);
  913.         if (get_bits(&s->gb, 17) != MOTION_MARKER) {
  914.             av_log(s->avctx, AV_LOG_ERROR,
  915.                    "marker missing after first P partition at %d %d\n",
  916.                    s->mb_x, s->mb_y);
  917.             return -1;
  918.         }
  919.     }
  920.     ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
  921.                     s->mb_x - 1, s->mb_y, part_a_end);
  922.  
  923.     if (mpeg4_decode_partition_b(s, mb_num) < 0) {
  924.         if (s->pict_type == AV_PICTURE_TYPE_P)
  925.             ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
  926.                             s->mb_x, s->mb_y, ER_DC_ERROR);
  927.         return -1;
  928.     } else {
  929.         if (s->pict_type == AV_PICTURE_TYPE_P)
  930.             ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
  931.                             s->mb_x - 1, s->mb_y, ER_DC_END);
  932.     }
  933.  
  934.     return 0;
  935. }
  936.  
  937. /**
  938.  * Decode a block.
  939.  * @return <0 if an error occurred
  940.  */
  941. static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
  942.                                      int n, int coded, int intra, int rvlc)
  943. {
  944.     MpegEncContext *s = &ctx->m;
  945.     int level, i, last, run, qmul, qadd;
  946.     int av_uninit(dc_pred_dir);
  947.     RLTable *rl;
  948.     RL_VLC_ELEM *rl_vlc;
  949.     const uint8_t *scan_table;
  950.  
  951.     // Note intra & rvlc should be optimized away if this is inlined
  952.  
  953.     if (intra) {
  954.         if (ctx->use_intra_dc_vlc) {
  955.             /* DC coef */
  956.             if (s->partitioned_frame) {
  957.                 level = s->dc_val[0][s->block_index[n]];
  958.                 if (n < 4)
  959.                     level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
  960.                 else
  961.                     level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
  962.                 dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
  963.             } else {
  964.                 level = mpeg4_decode_dc(s, n, &dc_pred_dir);
  965.                 if (level < 0)
  966.                     return -1;
  967.             }
  968.             block[0] = level;
  969.             i        = 0;
  970.         } else {
  971.             i = -1;
  972.             ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
  973.         }
  974.         if (!coded)
  975.             goto not_coded;
  976.  
  977.         if (rvlc) {
  978.             rl     = &ff_rvlc_rl_intra;
  979.             rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
  980.         } else {
  981.             rl     = &ff_mpeg4_rl_intra;
  982.             rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
  983.         }
  984.         if (s->ac_pred) {
  985.             if (dc_pred_dir == 0)
  986.                 scan_table = s->intra_v_scantable.permutated;  /* left */
  987.             else
  988.                 scan_table = s->intra_h_scantable.permutated;  /* top */
  989.         } else {
  990.             scan_table = s->intra_scantable.permutated;
  991.         }
  992.         qmul = 1;
  993.         qadd = 0;
  994.     } else {
  995.         i = -1;
  996.         if (!coded) {
  997.             s->block_last_index[n] = i;
  998.             return 0;
  999.         }
  1000.         if (rvlc)
  1001.             rl = &ff_rvlc_rl_inter;
  1002.         else
  1003.             rl = &ff_h263_rl_inter;
  1004.  
  1005.         scan_table = s->intra_scantable.permutated;
  1006.  
  1007.         if (s->mpeg_quant) {
  1008.             qmul = 1;
  1009.             qadd = 0;
  1010.             if (rvlc)
  1011.                 rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
  1012.             else
  1013.                 rl_vlc = ff_h263_rl_inter.rl_vlc[0];
  1014.         } else {
  1015.             qmul = s->qscale << 1;
  1016.             qadd = (s->qscale - 1) | 1;
  1017.             if (rvlc)
  1018.                 rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
  1019.             else
  1020.                 rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
  1021.         }
  1022.     }
  1023.     {
  1024.         OPEN_READER(re, &s->gb);
  1025.         for (;;) {
  1026.             UPDATE_CACHE(re, &s->gb);
  1027.             GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
  1028.             if (level == 0) {
  1029.                 /* escape */
  1030.                 if (rvlc) {
  1031.                     if (SHOW_UBITS(re, &s->gb, 1) == 0) {
  1032.                         av_log(s->avctx, AV_LOG_ERROR,
  1033.                                "1. marker bit missing in rvlc esc\n");
  1034.                         return -1;
  1035.                     }
  1036.                     SKIP_CACHE(re, &s->gb, 1);
  1037.  
  1038.                     last = SHOW_UBITS(re, &s->gb, 1);
  1039.                     SKIP_CACHE(re, &s->gb, 1);
  1040.                     run = SHOW_UBITS(re, &s->gb, 6);
  1041.                     SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
  1042.                     UPDATE_CACHE(re, &s->gb);
  1043.  
  1044.                     if (SHOW_UBITS(re, &s->gb, 1) == 0) {
  1045.                         av_log(s->avctx, AV_LOG_ERROR,
  1046.                                "2. marker bit missing in rvlc esc\n");
  1047.                         return -1;
  1048.                     }
  1049.                     SKIP_CACHE(re, &s->gb, 1);
  1050.  
  1051.                     level = SHOW_UBITS(re, &s->gb, 11);
  1052.                     SKIP_CACHE(re, &s->gb, 11);
  1053.  
  1054.                     if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
  1055.                         av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
  1056.                         return -1;
  1057.                     }
  1058.                     SKIP_CACHE(re, &s->gb, 5);
  1059.  
  1060.                     level = level * qmul + qadd;
  1061.                     level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
  1062.                     SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
  1063.  
  1064.                     i += run + 1;
  1065.                     if (last)
  1066.                         i += 192;
  1067.                 } else {
  1068.                     int cache;
  1069.                     cache = GET_CACHE(re, &s->gb);
  1070.  
  1071.                     if (IS_3IV1)
  1072.                         cache ^= 0xC0000000;
  1073.  
  1074.                     if (cache & 0x80000000) {
  1075.                         if (cache & 0x40000000) {
  1076.                             /* third escape */
  1077.                             SKIP_CACHE(re, &s->gb, 2);
  1078.                             last = SHOW_UBITS(re, &s->gb, 1);
  1079.                             SKIP_CACHE(re, &s->gb, 1);
  1080.                             run = SHOW_UBITS(re, &s->gb, 6);
  1081.                             SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
  1082.                             UPDATE_CACHE(re, &s->gb);
  1083.  
  1084.                             if (IS_3IV1) {
  1085.                                 level = SHOW_SBITS(re, &s->gb, 12);
  1086.                                 LAST_SKIP_BITS(re, &s->gb, 12);
  1087.                             } else {
  1088.                                 if (SHOW_UBITS(re, &s->gb, 1) == 0) {
  1089.                                     av_log(s->avctx, AV_LOG_ERROR,
  1090.                                            "1. marker bit missing in 3. esc\n");
  1091.                                     if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
  1092.                                         return -1;
  1093.                                 }
  1094.                                 SKIP_CACHE(re, &s->gb, 1);
  1095.  
  1096.                                 level = SHOW_SBITS(re, &s->gb, 12);
  1097.                                 SKIP_CACHE(re, &s->gb, 12);
  1098.  
  1099.                                 if (SHOW_UBITS(re, &s->gb, 1) == 0) {
  1100.                                     av_log(s->avctx, AV_LOG_ERROR,
  1101.                                            "2. marker bit missing in 3. esc\n");
  1102.                                     if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
  1103.                                         return -1;
  1104.                                 }
  1105.  
  1106.                                 SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
  1107.                             }
  1108.  
  1109. #if 0
  1110.                             if (s->error_recognition >= FF_ER_COMPLIANT) {
  1111.                                 const int abs_level= FFABS(level);
  1112.                                 if (abs_level<=MAX_LEVEL && run<=MAX_RUN) {
  1113.                                     const int run1= run - rl->max_run[last][abs_level] - 1;
  1114.                                     if (abs_level <= rl->max_level[last][run]) {
  1115.                                         av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
  1116.                                         return -1;
  1117.                                     }
  1118.                                     if (s->error_recognition > FF_ER_COMPLIANT) {
  1119.                                         if (abs_level <= rl->max_level[last][run]*2) {
  1120.                                             av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
  1121.                                             return -1;
  1122.                                         }
  1123.                                         if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) {
  1124.                                             av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
  1125.                                             return -1;
  1126.                                         }
  1127.                                     }
  1128.                                 }
  1129.                             }
  1130. #endif
  1131.                             if (level > 0)
  1132.                                 level = level * qmul + qadd;
  1133.                             else
  1134.                                 level = level * qmul - qadd;
  1135.  
  1136.                             if ((unsigned)(level + 2048) > 4095) {
  1137.                                 if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) {
  1138.                                     if (level > 2560 || level < -2560) {
  1139.                                         av_log(s->avctx, AV_LOG_ERROR,
  1140.                                                "|level| overflow in 3. esc, qp=%d\n",
  1141.                                                s->qscale);
  1142.                                         return -1;
  1143.                                     }
  1144.                                 }
  1145.                                 level = level < 0 ? -2048 : 2047;
  1146.                             }
  1147.  
  1148.                             i += run + 1;
  1149.                             if (last)
  1150.                                 i += 192;
  1151.                         } else {
  1152.                             /* second escape */
  1153.                             SKIP_BITS(re, &s->gb, 2);
  1154.                             GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
  1155.                             i    += run + rl->max_run[run >> 7][level / qmul] + 1;  // FIXME opt indexing
  1156.                             level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
  1157.                             LAST_SKIP_BITS(re, &s->gb, 1);
  1158.                         }
  1159.                     } else {
  1160.                         /* first escape */
  1161.                         SKIP_BITS(re, &s->gb, 1);
  1162.                         GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
  1163.                         i    += run;
  1164.                         level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul;  // FIXME opt indexing
  1165.                         level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
  1166.                         LAST_SKIP_BITS(re, &s->gb, 1);
  1167.                     }
  1168.                 }
  1169.             } else {
  1170.                 i    += run;
  1171.                 level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
  1172.                 LAST_SKIP_BITS(re, &s->gb, 1);
  1173.             }
  1174.             ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62);
  1175.             if (i > 62) {
  1176.                 i -= 192;
  1177.                 if (i & (~63)) {
  1178.                     av_log(s->avctx, AV_LOG_ERROR,
  1179.                            "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
  1180.                     return -1;
  1181.                 }
  1182.  
  1183.                 block[scan_table[i]] = level;
  1184.                 break;
  1185.             }
  1186.  
  1187.             block[scan_table[i]] = level;
  1188.         }
  1189.         CLOSE_READER(re, &s->gb);
  1190.     }
  1191.  
  1192. not_coded:
  1193.     if (intra) {
  1194.         if (!ctx->use_intra_dc_vlc) {
  1195.             block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
  1196.  
  1197.             i -= i >> 31;  // if (i == -1) i = 0;
  1198.         }
  1199.  
  1200.         ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
  1201.         if (s->ac_pred)
  1202.             i = 63;  // FIXME not optimal
  1203.     }
  1204.     s->block_last_index[n] = i;
  1205.     return 0;
  1206. }
  1207.  
  1208. /**
  1209.  * decode partition C of one MB.
  1210.  * @return <0 if an error occurred
  1211.  */
  1212. static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
  1213. {
  1214.     Mpeg4DecContext *ctx = (Mpeg4DecContext *)s;
  1215.     int cbp, mb_type;
  1216.     const int xy = s->mb_x + s->mb_y * s->mb_stride;
  1217.  
  1218.     mb_type = s->current_picture.mb_type[xy];
  1219.     cbp     = s->cbp_table[xy];
  1220.  
  1221.     ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
  1222.  
  1223.     if (s->current_picture.qscale_table[xy] != s->qscale)
  1224.         ff_set_qscale(s, s->current_picture.qscale_table[xy]);
  1225.  
  1226.     if (s->pict_type == AV_PICTURE_TYPE_P ||
  1227.         s->pict_type == AV_PICTURE_TYPE_S) {
  1228.         int i;
  1229.         for (i = 0; i < 4; i++) {
  1230.             s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  1231.             s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  1232.         }
  1233.         s->mb_intra = IS_INTRA(mb_type);
  1234.  
  1235.         if (IS_SKIP(mb_type)) {
  1236.             /* skip mb */
  1237.             for (i = 0; i < 6; i++)
  1238.                 s->block_last_index[i] = -1;
  1239.             s->mv_dir  = MV_DIR_FORWARD;
  1240.             s->mv_type = MV_TYPE_16X16;
  1241.             if (s->pict_type == AV_PICTURE_TYPE_S
  1242.                 && ctx->vol_sprite_usage == GMC_SPRITE) {
  1243.                 s->mcsel      = 1;
  1244.                 s->mb_skipped = 0;
  1245.             } else {
  1246.                 s->mcsel      = 0;
  1247.                 s->mb_skipped = 1;
  1248.             }
  1249.         } else if (s->mb_intra) {
  1250.             s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
  1251.         } else if (!s->mb_intra) {
  1252.             // s->mcsel = 0;  // FIXME do we need to init that?
  1253.  
  1254.             s->mv_dir = MV_DIR_FORWARD;
  1255.             if (IS_8X8(mb_type)) {
  1256.                 s->mv_type = MV_TYPE_8X8;
  1257.             } else {
  1258.                 s->mv_type = MV_TYPE_16X16;
  1259.             }
  1260.         }
  1261.     } else { /* I-Frame */
  1262.         s->mb_intra = 1;
  1263.         s->ac_pred  = IS_ACPRED(s->current_picture.mb_type[xy]);
  1264.     }
  1265.  
  1266.     if (!IS_SKIP(mb_type)) {
  1267.         int i;
  1268.         s->bdsp.clear_blocks(s->block[0]);
  1269.         /* decode each block */
  1270.         for (i = 0; i < 6; i++) {
  1271.             if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) {
  1272.                 av_log(s->avctx, AV_LOG_ERROR,
  1273.                        "texture corrupted at %d %d %d\n",
  1274.                        s->mb_x, s->mb_y, s->mb_intra);
  1275.                 return -1;
  1276.             }
  1277.             cbp += cbp;
  1278.         }
  1279.     }
  1280.  
  1281.     /* per-MB end of slice check */
  1282.     if (--s->mb_num_left <= 0) {
  1283.         if (mpeg4_is_resync(ctx))
  1284.             return SLICE_END;
  1285.         else
  1286.             return SLICE_NOEND;
  1287.     } else {
  1288.         if (mpeg4_is_resync(ctx)) {
  1289.             const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
  1290.             if (s->cbp_table[xy + delta])
  1291.                 return SLICE_END;
  1292.         }
  1293.         return SLICE_OK;
  1294.     }
  1295. }
  1296.  
  1297. static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
  1298. {
  1299.     Mpeg4DecContext *ctx = (Mpeg4DecContext *)s;
  1300.     int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
  1301.     int16_t *mot_val;
  1302.     static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
  1303.     const int xy = s->mb_x + s->mb_y * s->mb_stride;
  1304.  
  1305.     av_assert2(s->h263_pred);
  1306.  
  1307.     if (s->pict_type == AV_PICTURE_TYPE_P ||
  1308.         s->pict_type == AV_PICTURE_TYPE_S) {
  1309.         do {
  1310.             if (get_bits1(&s->gb)) {
  1311.                 /* skip mb */
  1312.                 s->mb_intra = 0;
  1313.                 for (i = 0; i < 6; i++)
  1314.                     s->block_last_index[i] = -1;
  1315.                 s->mv_dir  = MV_DIR_FORWARD;
  1316.                 s->mv_type = MV_TYPE_16X16;
  1317.                 if (s->pict_type == AV_PICTURE_TYPE_S &&
  1318.                     ctx->vol_sprite_usage == GMC_SPRITE) {
  1319.                     s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
  1320.                                                      MB_TYPE_GMC   |
  1321.                                                      MB_TYPE_16x16 |
  1322.                                                      MB_TYPE_L0;
  1323.                     s->mcsel       = 1;
  1324.                     s->mv[0][0][0] = get_amv(ctx, 0);
  1325.                     s->mv[0][0][1] = get_amv(ctx, 1);
  1326.                     s->mb_skipped  = 0;
  1327.                 } else {
  1328.                     s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
  1329.                                                      MB_TYPE_16x16 |
  1330.                                                      MB_TYPE_L0;
  1331.                     s->mcsel       = 0;
  1332.                     s->mv[0][0][0] = 0;
  1333.                     s->mv[0][0][1] = 0;
  1334.                     s->mb_skipped  = 1;
  1335.                 }
  1336.                 goto end;
  1337.             }
  1338.             cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
  1339.             if (cbpc < 0) {
  1340.                 av_log(s->avctx, AV_LOG_ERROR,
  1341.                        "mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);
  1342.                 return -1;
  1343.             }
  1344.         } while (cbpc == 20);
  1345.  
  1346.         s->bdsp.clear_blocks(s->block[0]);
  1347.         dquant      = cbpc & 8;
  1348.         s->mb_intra = ((cbpc & 4) != 0);
  1349.         if (s->mb_intra)
  1350.             goto intra;
  1351.  
  1352.         if (s->pict_type == AV_PICTURE_TYPE_S &&
  1353.             ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
  1354.             s->mcsel = get_bits1(&s->gb);
  1355.         else
  1356.             s->mcsel = 0;
  1357.         cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
  1358.         if (cbpy < 0) {
  1359.             av_log(s->avctx, AV_LOG_ERROR,
  1360.                    "P cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
  1361.             return AVERROR_INVALIDDATA;
  1362.         }
  1363.  
  1364.         cbp = (cbpc & 3) | (cbpy << 2);
  1365.         if (dquant)
  1366.             ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
  1367.         if ((!s->progressive_sequence) &&
  1368.             (cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
  1369.             s->interlaced_dct = get_bits1(&s->gb);
  1370.  
  1371.         s->mv_dir = MV_DIR_FORWARD;
  1372.         if ((cbpc & 16) == 0) {
  1373.             if (s->mcsel) {
  1374.                 s->current_picture.mb_type[xy] = MB_TYPE_GMC   |
  1375.                                                  MB_TYPE_16x16 |
  1376.                                                  MB_TYPE_L0;
  1377.                 /* 16x16 global motion prediction */
  1378.                 s->mv_type     = MV_TYPE_16X16;
  1379.                 mx             = get_amv(ctx, 0);
  1380.                 my             = get_amv(ctx, 1);
  1381.                 s->mv[0][0][0] = mx;
  1382.                 s->mv[0][0][1] = my;
  1383.             } else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
  1384.                 s->current_picture.mb_type[xy] = MB_TYPE_16x8 |
  1385.                                                  MB_TYPE_L0   |
  1386.                                                  MB_TYPE_INTERLACED;
  1387.                 /* 16x8 field motion prediction */
  1388.                 s->mv_type = MV_TYPE_FIELD;
  1389.  
  1390.                 s->field_select[0][0] = get_bits1(&s->gb);
  1391.                 s->field_select[0][1] = get_bits1(&s->gb);
  1392.  
  1393.                 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
  1394.  
  1395.                 for (i = 0; i < 2; i++) {
  1396.                     mx = ff_h263_decode_motion(s, pred_x, s->f_code);
  1397.                     if (mx >= 0xffff)
  1398.                         return -1;
  1399.  
  1400.                     my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
  1401.                     if (my >= 0xffff)
  1402.                         return -1;
  1403.  
  1404.                     s->mv[0][i][0] = mx;
  1405.                     s->mv[0][i][1] = my;
  1406.                 }
  1407.             } else {
  1408.                 s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
  1409.                 /* 16x16 motion prediction */
  1410.                 s->mv_type = MV_TYPE_16X16;
  1411.                 ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
  1412.                 mx = ff_h263_decode_motion(s, pred_x, s->f_code);
  1413.  
  1414.                 if (mx >= 0xffff)
  1415.                     return -1;
  1416.  
  1417.                 my = ff_h263_decode_motion(s, pred_y, s->f_code);
  1418.  
  1419.                 if (my >= 0xffff)
  1420.                     return -1;
  1421.                 s->mv[0][0][0] = mx;
  1422.                 s->mv[0][0][1] = my;
  1423.             }
  1424.         } else {
  1425.             s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
  1426.             s->mv_type                     = MV_TYPE_8X8;
  1427.             for (i = 0; i < 4; i++) {
  1428.                 mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
  1429.                 mx      = ff_h263_decode_motion(s, pred_x, s->f_code);
  1430.                 if (mx >= 0xffff)
  1431.                     return -1;
  1432.  
  1433.                 my = ff_h263_decode_motion(s, pred_y, s->f_code);
  1434.                 if (my >= 0xffff)
  1435.                     return -1;
  1436.                 s->mv[0][i][0] = mx;
  1437.                 s->mv[0][i][1] = my;
  1438.                 mot_val[0]     = mx;
  1439.                 mot_val[1]     = my;
  1440.             }
  1441.         }
  1442.     } else if (s->pict_type == AV_PICTURE_TYPE_B) {
  1443.         int modb1;   // first bit of modb
  1444.         int modb2;   // second bit of modb
  1445.         int mb_type;
  1446.  
  1447.         s->mb_intra = 0;  // B-frames never contain intra blocks
  1448.         s->mcsel    = 0;  //      ...               true gmc blocks
  1449.  
  1450.         if (s->mb_x == 0) {
  1451.             for (i = 0; i < 2; i++) {
  1452.                 s->last_mv[i][0][0] =
  1453.                 s->last_mv[i][0][1] =
  1454.                 s->last_mv[i][1][0] =
  1455.                 s->last_mv[i][1][1] = 0;
  1456.             }
  1457.  
  1458.             ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);
  1459.         }
  1460.  
  1461.         /* if we skipped it in the future P Frame than skip it now too */
  1462.         s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x];  // Note, skiptab=0 if last was GMC
  1463.  
  1464.         if (s->mb_skipped) {
  1465.             /* skip mb */
  1466.             for (i = 0; i < 6; i++)
  1467.                 s->block_last_index[i] = -1;
  1468.  
  1469.             s->mv_dir      = MV_DIR_FORWARD;
  1470.             s->mv_type     = MV_TYPE_16X16;
  1471.             s->mv[0][0][0] =
  1472.             s->mv[0][0][1] =
  1473.             s->mv[1][0][0] =
  1474.             s->mv[1][0][1] = 0;
  1475.             s->current_picture.mb_type[xy] = MB_TYPE_SKIP  |
  1476.                                              MB_TYPE_16x16 |
  1477.                                              MB_TYPE_L0;
  1478.             goto end;
  1479.         }
  1480.  
  1481.         modb1 = get_bits1(&s->gb);
  1482.         if (modb1) {
  1483.             // like MB_TYPE_B_DIRECT but no vectors coded
  1484.             mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;
  1485.             cbp     = 0;
  1486.         } else {
  1487.             modb2   = get_bits1(&s->gb);
  1488.             mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
  1489.             if (mb_type < 0) {
  1490.                 av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
  1491.                 return -1;
  1492.             }
  1493.             mb_type = mb_type_b_map[mb_type];
  1494.             if (modb2) {
  1495.                 cbp = 0;
  1496.             } else {
  1497.                 s->bdsp.clear_blocks(s->block[0]);
  1498.                 cbp = get_bits(&s->gb, 6);
  1499.             }
  1500.  
  1501.             if ((!IS_DIRECT(mb_type)) && cbp) {
  1502.                 if (get_bits1(&s->gb))
  1503.                     ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
  1504.             }
  1505.  
  1506.             if (!s->progressive_sequence) {
  1507.                 if (cbp)
  1508.                     s->interlaced_dct = get_bits1(&s->gb);
  1509.  
  1510.                 if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
  1511.                     mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
  1512.                     mb_type &= ~MB_TYPE_16x16;
  1513.  
  1514.                     if (USES_LIST(mb_type, 0)) {
  1515.                         s->field_select[0][0] = get_bits1(&s->gb);
  1516.                         s->field_select[0][1] = get_bits1(&s->gb);
  1517.                     }
  1518.                     if (USES_LIST(mb_type, 1)) {
  1519.                         s->field_select[1][0] = get_bits1(&s->gb);
  1520.                         s->field_select[1][1] = get_bits1(&s->gb);
  1521.                     }
  1522.                 }
  1523.             }
  1524.  
  1525.             s->mv_dir = 0;
  1526.             if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
  1527.                 s->mv_type = MV_TYPE_16X16;
  1528.  
  1529.                 if (USES_LIST(mb_type, 0)) {
  1530.                     s->mv_dir = MV_DIR_FORWARD;
  1531.  
  1532.                     mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
  1533.                     my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
  1534.                     s->last_mv[0][1][0] =
  1535.                     s->last_mv[0][0][0] =
  1536.                     s->mv[0][0][0]      = mx;
  1537.                     s->last_mv[0][1][1] =
  1538.                     s->last_mv[0][0][1] =
  1539.                     s->mv[0][0][1]      = my;
  1540.                 }
  1541.  
  1542.                 if (USES_LIST(mb_type, 1)) {
  1543.                     s->mv_dir |= MV_DIR_BACKWARD;
  1544.  
  1545.                     mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
  1546.                     my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
  1547.                     s->last_mv[1][1][0] =
  1548.                     s->last_mv[1][0][0] =
  1549.                     s->mv[1][0][0]      = mx;
  1550.                     s->last_mv[1][1][1] =
  1551.                     s->last_mv[1][0][1] =
  1552.                     s->mv[1][0][1]      = my;
  1553.                 }
  1554.             } else if (!IS_DIRECT(mb_type)) {
  1555.                 s->mv_type = MV_TYPE_FIELD;
  1556.  
  1557.                 if (USES_LIST(mb_type, 0)) {
  1558.                     s->mv_dir = MV_DIR_FORWARD;
  1559.  
  1560.                     for (i = 0; i < 2; i++) {
  1561.                         mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
  1562.                         my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
  1563.                         s->last_mv[0][i][0] =
  1564.                         s->mv[0][i][0]      = mx;
  1565.                         s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
  1566.                     }
  1567.                 }
  1568.  
  1569.                 if (USES_LIST(mb_type, 1)) {
  1570.                     s->mv_dir |= MV_DIR_BACKWARD;
  1571.  
  1572.                     for (i = 0; i < 2; i++) {
  1573.                         mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
  1574.                         my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
  1575.                         s->last_mv[1][i][0] =
  1576.                         s->mv[1][i][0]      = mx;
  1577.                         s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
  1578.                     }
  1579.                 }
  1580.             }
  1581.         }
  1582.  
  1583.         if (IS_DIRECT(mb_type)) {
  1584.             if (IS_SKIP(mb_type)) {
  1585.                 mx =
  1586.                 my = 0;
  1587.             } else {
  1588.                 mx = ff_h263_decode_motion(s, 0, 1);
  1589.                 my = ff_h263_decode_motion(s, 0, 1);
  1590.             }
  1591.  
  1592.             s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  1593.             mb_type  |= ff_mpeg4_set_direct_mv(s, mx, my);
  1594.         }
  1595.         s->current_picture.mb_type[xy] = mb_type;
  1596.     } else { /* I-Frame */
  1597.         do {
  1598.             cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
  1599.             if (cbpc < 0) {
  1600.                 av_log(s->avctx, AV_LOG_ERROR,
  1601.                        "I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
  1602.                 return -1;
  1603.             }
  1604.         } while (cbpc == 8);
  1605.  
  1606.         dquant = cbpc & 4;
  1607.         s->mb_intra = 1;
  1608.  
  1609. intra:
  1610.         s->ac_pred = get_bits1(&s->gb);
  1611.         if (s->ac_pred)
  1612.             s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
  1613.         else
  1614.             s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
  1615.  
  1616.         cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
  1617.         if (cbpy < 0) {
  1618.             av_log(s->avctx, AV_LOG_ERROR,
  1619.                    "I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
  1620.             return -1;
  1621.         }
  1622.         cbp = (cbpc & 3) | (cbpy << 2);
  1623.  
  1624.         ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
  1625.  
  1626.         if (dquant)
  1627.             ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
  1628.  
  1629.         if (!s->progressive_sequence)
  1630.             s->interlaced_dct = get_bits1(&s->gb);
  1631.  
  1632.         s->bdsp.clear_blocks(s->block[0]);
  1633.         /* decode each block */
  1634.         for (i = 0; i < 6; i++) {
  1635.             if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)
  1636.                 return -1;
  1637.             cbp += cbp;
  1638.         }
  1639.         goto end;
  1640.     }
  1641.  
  1642.     /* decode each block */
  1643.     for (i = 0; i < 6; i++) {
  1644.         if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)
  1645.             return -1;
  1646.         cbp += cbp;
  1647.     }
  1648.  
  1649. end:
  1650.     /* per-MB end of slice check */
  1651.     if (s->codec_id == AV_CODEC_ID_MPEG4) {
  1652.         int next = mpeg4_is_resync(ctx);
  1653.         if (next) {
  1654.             if        (s->mb_x + s->mb_y*s->mb_width + 1 >  next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
  1655.                 return -1;
  1656.             } else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
  1657.                 return SLICE_END;
  1658.  
  1659.             if (s->pict_type == AV_PICTURE_TYPE_B) {
  1660.                 const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
  1661.                 ff_thread_await_progress(&s->next_picture_ptr->tf,
  1662.                                          (s->mb_x + delta >= s->mb_width)
  1663.                                          ? FFMIN(s->mb_y + 1, s->mb_height - 1)
  1664.                                          : s->mb_y, 0);
  1665.                 if (s->next_picture.mbskip_table[xy + delta])
  1666.                     return SLICE_OK;
  1667.             }
  1668.  
  1669.             return SLICE_END;
  1670.         }
  1671.     }
  1672.  
  1673.     return SLICE_OK;
  1674. }
  1675.  
  1676. static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
  1677. {
  1678.     int hours, minutes, seconds;
  1679.  
  1680.     if (!show_bits(gb, 23)) {
  1681.         av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
  1682.         return -1;
  1683.     }
  1684.  
  1685.     hours   = get_bits(gb, 5);
  1686.     minutes = get_bits(gb, 6);
  1687.     check_marker(gb, "in gop_header");
  1688.     seconds = get_bits(gb, 6);
  1689.  
  1690.     s->time_base = seconds + 60*(minutes + 60*hours);
  1691.  
  1692.     skip_bits1(gb);
  1693.     skip_bits1(gb);
  1694.  
  1695.     return 0;
  1696. }
  1697.  
  1698. static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb)
  1699. {
  1700.  
  1701.     s->avctx->profile = get_bits(gb, 4);
  1702.     s->avctx->level   = get_bits(gb, 4);
  1703.  
  1704.     // for Simple profile, level 0
  1705.     if (s->avctx->profile == 0 && s->avctx->level == 8) {
  1706.         s->avctx->level = 0;
  1707.     }
  1708.  
  1709.     return 0;
  1710. }
  1711.  
  1712. static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
  1713. {
  1714.     MpegEncContext *s = &ctx->m;
  1715.     int width, height, vo_ver_id;
  1716.  
  1717.     /* vol header */
  1718.     skip_bits(gb, 1);                   /* random access */
  1719.     s->vo_type = get_bits(gb, 8);
  1720.     if (get_bits1(gb) != 0) {           /* is_ol_id */
  1721.         vo_ver_id = get_bits(gb, 4);    /* vo_ver_id */
  1722.         skip_bits(gb, 3);               /* vo_priority */
  1723.     } else {
  1724.         vo_ver_id = 1;
  1725.     }
  1726.     s->aspect_ratio_info = get_bits(gb, 4);
  1727.     if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
  1728.         s->avctx->sample_aspect_ratio.num = get_bits(gb, 8);  // par_width
  1729.         s->avctx->sample_aspect_ratio.den = get_bits(gb, 8);  // par_height
  1730.     } else {
  1731.         s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
  1732.     }
  1733.  
  1734.     if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
  1735.         int chroma_format = get_bits(gb, 2);
  1736.         if (chroma_format != CHROMA_420)
  1737.             av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
  1738.  
  1739.         s->low_delay = get_bits1(gb);
  1740.         if (get_bits1(gb)) {    /* vbv parameters */
  1741.             get_bits(gb, 15);   /* first_half_bitrate */
  1742.             check_marker(gb, "after first_half_bitrate");
  1743.             get_bits(gb, 15);   /* latter_half_bitrate */
  1744.             check_marker(gb, "after latter_half_bitrate");
  1745.             get_bits(gb, 15);   /* first_half_vbv_buffer_size */
  1746.             check_marker(gb, "after first_half_vbv_buffer_size");
  1747.             get_bits(gb, 3);    /* latter_half_vbv_buffer_size */
  1748.             get_bits(gb, 11);   /* first_half_vbv_occupancy */
  1749.             check_marker(gb, "after first_half_vbv_occupancy");
  1750.             get_bits(gb, 15);   /* latter_half_vbv_occupancy */
  1751.             check_marker(gb, "after latter_half_vbv_occupancy");
  1752.         }
  1753.     } else {
  1754.         /* is setting low delay flag only once the smartest thing to do?
  1755.          * low delay detection won't be overridden. */
  1756.         if (s->picture_number == 0)
  1757.             s->low_delay = 0;
  1758.     }
  1759.  
  1760.     ctx->shape = get_bits(gb, 2); /* vol shape */
  1761.     if (ctx->shape != RECT_SHAPE)
  1762.         av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
  1763.     if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
  1764.         av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
  1765.         skip_bits(gb, 4);  /* video_object_layer_shape_extension */
  1766.     }
  1767.  
  1768.     check_marker(gb, "before time_increment_resolution");
  1769.  
  1770.     s->avctx->framerate.num = get_bits(gb, 16);
  1771.     if (!s->avctx->framerate.num) {
  1772.         av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
  1773.         return AVERROR_INVALIDDATA;
  1774.     }
  1775.  
  1776.     ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
  1777.     if (ctx->time_increment_bits < 1)
  1778.         ctx->time_increment_bits = 1;
  1779.  
  1780.     check_marker(gb, "before fixed_vop_rate");
  1781.  
  1782.     if (get_bits1(gb) != 0)     /* fixed_vop_rate  */
  1783.         s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
  1784.     else
  1785.         s->avctx->framerate.den = 1;
  1786.  
  1787.     s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
  1788.  
  1789.     ctx->t_frame = 0;
  1790.  
  1791.     if (ctx->shape != BIN_ONLY_SHAPE) {
  1792.         if (ctx->shape == RECT_SHAPE) {
  1793.             check_marker(gb, "before width");
  1794.             width = get_bits(gb, 13);
  1795.             check_marker(gb, "before height");
  1796.             height = get_bits(gb, 13);
  1797.             check_marker(gb, "after height");
  1798.             if (width && height &&  /* they should be non zero but who knows */
  1799.                 !(s->width && s->codec_tag == AV_RL32("MP4S"))) {
  1800.                 if (s->width && s->height &&
  1801.                     (s->width != width || s->height != height))
  1802.                     s->context_reinit = 1;
  1803.                 s->width  = width;
  1804.                 s->height = height;
  1805.             }
  1806.         }
  1807.  
  1808.         s->progressive_sequence  =
  1809.         s->progressive_frame     = get_bits1(gb) ^ 1;
  1810.         s->interlaced_dct        = 0;
  1811.         if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
  1812.             av_log(s->avctx, AV_LOG_INFO,           /* OBMC Disable */
  1813.                    "MPEG4 OBMC not supported (very likely buggy encoder)\n");
  1814.         if (vo_ver_id == 1)
  1815.             ctx->vol_sprite_usage = get_bits1(gb);    /* vol_sprite_usage */
  1816.         else
  1817.             ctx->vol_sprite_usage = get_bits(gb, 2);  /* vol_sprite_usage */
  1818.  
  1819.         if (ctx->vol_sprite_usage == STATIC_SPRITE)
  1820.             av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
  1821.         if (ctx->vol_sprite_usage == STATIC_SPRITE ||
  1822.             ctx->vol_sprite_usage == GMC_SPRITE) {
  1823.             if (ctx->vol_sprite_usage == STATIC_SPRITE) {
  1824.                 skip_bits(gb, 13); // sprite_width
  1825.                 check_marker(gb, "after sprite_width");
  1826.                 skip_bits(gb, 13); // sprite_height
  1827.                 check_marker(gb, "after sprite_height");
  1828.                 skip_bits(gb, 13); // sprite_left
  1829.                 check_marker(gb, "after sprite_left");
  1830.                 skip_bits(gb, 13); // sprite_top
  1831.                 check_marker(gb, "after sprite_top");
  1832.             }
  1833.             ctx->num_sprite_warping_points = get_bits(gb, 6);
  1834.             if (ctx->num_sprite_warping_points > 3) {
  1835.                 av_log(s->avctx, AV_LOG_ERROR,
  1836.                        "%d sprite_warping_points\n",
  1837.                        ctx->num_sprite_warping_points);
  1838.                 ctx->num_sprite_warping_points = 0;
  1839.                 return AVERROR_INVALIDDATA;
  1840.             }
  1841.             s->sprite_warping_accuracy  = get_bits(gb, 2);
  1842.             ctx->sprite_brightness_change = get_bits1(gb);
  1843.             if (ctx->vol_sprite_usage == STATIC_SPRITE)
  1844.                 skip_bits1(gb); // low_latency_sprite
  1845.         }
  1846.         // FIXME sadct disable bit if verid!=1 && shape not rect
  1847.  
  1848.         if (get_bits1(gb) == 1) {                   /* not_8_bit */
  1849.             s->quant_precision = get_bits(gb, 4);   /* quant_precision */
  1850.             if (get_bits(gb, 4) != 8)               /* bits_per_pixel */
  1851.                 av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
  1852.             if (s->quant_precision != 5)
  1853.                 av_log(s->avctx, AV_LOG_ERROR,
  1854.                        "quant precision %d\n", s->quant_precision);
  1855.             if (s->quant_precision<3 || s->quant_precision>9) {
  1856.                 s->quant_precision = 5;
  1857.             }
  1858.         } else {
  1859.             s->quant_precision = 5;
  1860.         }
  1861.  
  1862.         // FIXME a bunch of grayscale shape things
  1863.  
  1864.         if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
  1865.             int i, v;
  1866.  
  1867.             /* load default matrixes */
  1868.             for (i = 0; i < 64; i++) {
  1869.                 int j = s->idsp.idct_permutation[i];
  1870.                 v = ff_mpeg4_default_intra_matrix[i];
  1871.                 s->intra_matrix[j]        = v;
  1872.                 s->chroma_intra_matrix[j] = v;
  1873.  
  1874.                 v = ff_mpeg4_default_non_intra_matrix[i];
  1875.                 s->inter_matrix[j]        = v;
  1876.                 s->chroma_inter_matrix[j] = v;
  1877.             }
  1878.  
  1879.             /* load custom intra matrix */
  1880.             if (get_bits1(gb)) {
  1881.                 int last = 0;
  1882.                 for (i = 0; i < 64; i++) {
  1883.                     int j;
  1884.                     if (get_bits_left(gb) < 8) {
  1885.                         av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
  1886.                         return AVERROR_INVALIDDATA;
  1887.                     }
  1888.                     v = get_bits(gb, 8);
  1889.                     if (v == 0)
  1890.                         break;
  1891.  
  1892.                     last = v;
  1893.                     j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
  1894.                     s->intra_matrix[j]        = last;
  1895.                     s->chroma_intra_matrix[j] = last;
  1896.                 }
  1897.  
  1898.                 /* replicate last value */
  1899.                 for (; i < 64; i++) {
  1900.                     int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
  1901.                     s->intra_matrix[j]        = last;
  1902.                     s->chroma_intra_matrix[j] = last;
  1903.                 }
  1904.             }
  1905.  
  1906.             /* load custom non intra matrix */
  1907.             if (get_bits1(gb)) {
  1908.                 int last = 0;
  1909.                 for (i = 0; i < 64; i++) {
  1910.                     int j;
  1911.                     if (get_bits_left(gb) < 8) {
  1912.                         av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
  1913.                         return AVERROR_INVALIDDATA;
  1914.                     }
  1915.                     v = get_bits(gb, 8);
  1916.                     if (v == 0)
  1917.                         break;
  1918.  
  1919.                     last = v;
  1920.                     j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
  1921.                     s->inter_matrix[j]        = v;
  1922.                     s->chroma_inter_matrix[j] = v;
  1923.                 }
  1924.  
  1925.                 /* replicate last value */
  1926.                 for (; i < 64; i++) {
  1927.                     int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
  1928.                     s->inter_matrix[j]        = last;
  1929.                     s->chroma_inter_matrix[j] = last;
  1930.                 }
  1931.             }
  1932.  
  1933.             // FIXME a bunch of grayscale shape things
  1934.         }
  1935.  
  1936.         if (vo_ver_id != 1)
  1937.             s->quarter_sample = get_bits1(gb);
  1938.         else
  1939.             s->quarter_sample = 0;
  1940.  
  1941.         if (get_bits_left(gb) < 4) {
  1942.             av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
  1943.             return AVERROR_INVALIDDATA;
  1944.         }
  1945.  
  1946.         if (!get_bits1(gb)) {
  1947.             int pos               = get_bits_count(gb);
  1948.             int estimation_method = get_bits(gb, 2);
  1949.             if (estimation_method < 2) {
  1950.                 if (!get_bits1(gb)) {
  1951.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* opaque */
  1952.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* transparent */
  1953.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_cae */
  1954.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* inter_cae */
  1955.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* no_update */
  1956.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* upampling */
  1957.                 }
  1958.                 if (!get_bits1(gb)) {
  1959.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* intra_blocks */
  1960.                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter_blocks */
  1961.                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* inter4v_blocks */
  1962.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* not coded blocks */
  1963.                 }
  1964.                 if (!check_marker(gb, "in complexity estimation part 1")) {
  1965.                     skip_bits_long(gb, pos - get_bits_count(gb));
  1966.                     goto no_cplx_est;
  1967.                 }
  1968.                 if (!get_bits1(gb)) {
  1969.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_coeffs */
  1970.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* dct_lines */
  1971.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* vlc_syms */
  1972.                     ctx->cplx_estimation_trash_i += 4 * get_bits1(gb);  /* vlc_bits */
  1973.                 }
  1974.                 if (!get_bits1(gb)) {
  1975.                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* apm */
  1976.                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* npm */
  1977.                     ctx->cplx_estimation_trash_b += 8 * get_bits1(gb);  /* interpolate_mc_q */
  1978.                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* forwback_mc_q */
  1979.                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel2 */
  1980.                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* halfpel4 */
  1981.                 }
  1982.                 if (!check_marker(gb, "in complexity estimation part 2")) {
  1983.                     skip_bits_long(gb, pos - get_bits_count(gb));
  1984.                     goto no_cplx_est;
  1985.                 }
  1986.                 if (estimation_method == 1) {
  1987.                     ctx->cplx_estimation_trash_i += 8 * get_bits1(gb);  /* sadct */
  1988.                     ctx->cplx_estimation_trash_p += 8 * get_bits1(gb);  /* qpel */
  1989.                 }
  1990.             } else
  1991.                 av_log(s->avctx, AV_LOG_ERROR,
  1992.                        "Invalid Complexity estimation method %d\n",
  1993.                        estimation_method);
  1994.         } else {
  1995.  
  1996. no_cplx_est:
  1997.             ctx->cplx_estimation_trash_i =
  1998.             ctx->cplx_estimation_trash_p =
  1999.             ctx->cplx_estimation_trash_b = 0;
  2000.         }
  2001.  
  2002.         ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
  2003.  
  2004.         s->data_partitioning = get_bits1(gb);
  2005.         if (s->data_partitioning)
  2006.             ctx->rvlc = get_bits1(gb);
  2007.  
  2008.         if (vo_ver_id != 1) {
  2009.             ctx->new_pred = get_bits1(gb);
  2010.             if (ctx->new_pred) {
  2011.                 av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
  2012.                 skip_bits(gb, 2); /* requested upstream message type */
  2013.                 skip_bits1(gb);   /* newpred segment type */
  2014.             }
  2015.             if (get_bits1(gb)) // reduced_res_vop
  2016.                 av_log(s->avctx, AV_LOG_ERROR,
  2017.                        "reduced resolution VOP not supported\n");
  2018.         } else {
  2019.             ctx->new_pred = 0;
  2020.         }
  2021.  
  2022.         ctx->scalability = get_bits1(gb);
  2023.  
  2024.         if (ctx->scalability) {
  2025.             GetBitContext bak = *gb;
  2026.             int h_sampling_factor_n;
  2027.             int h_sampling_factor_m;
  2028.             int v_sampling_factor_n;
  2029.             int v_sampling_factor_m;
  2030.  
  2031.             skip_bits1(gb);    // hierarchy_type
  2032.             skip_bits(gb, 4);  /* ref_layer_id */
  2033.             skip_bits1(gb);    /* ref_layer_sampling_dir */
  2034.             h_sampling_factor_n = get_bits(gb, 5);
  2035.             h_sampling_factor_m = get_bits(gb, 5);
  2036.             v_sampling_factor_n = get_bits(gb, 5);
  2037.             v_sampling_factor_m = get_bits(gb, 5);
  2038.             ctx->enhancement_type = get_bits1(gb);
  2039.  
  2040.             if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
  2041.                 v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
  2042.                 /* illegal scalability header (VERY broken encoder),
  2043.                  * trying to workaround */
  2044.                 ctx->scalability = 0;
  2045.                 *gb            = bak;
  2046.             } else
  2047.                 av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
  2048.  
  2049.             // bin shape stuff FIXME
  2050.         }
  2051.     }
  2052.  
  2053.     if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
  2054.         av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d,  %s%s%s%s\n",
  2055.                s->avctx->framerate.den, s->avctx->framerate.num,
  2056.                ctx->time_increment_bits,
  2057.                s->quant_precision,
  2058.                s->progressive_sequence,
  2059.                ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
  2060.                s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
  2061.         );
  2062.     }
  2063.  
  2064.     return 0;
  2065. }
  2066.  
  2067. /**
  2068.  * Decode the user data stuff in the header.
  2069.  * Also initializes divx/xvid/lavc_version/build.
  2070.  */
  2071. static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
  2072. {
  2073.     MpegEncContext *s = &ctx->m;
  2074.     char buf[256];
  2075.     int i;
  2076.     int e;
  2077.     int ver = 0, build = 0, ver2 = 0, ver3 = 0;
  2078.     char last;
  2079.  
  2080.     for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
  2081.         if (show_bits(gb, 23) == 0)
  2082.             break;
  2083.         buf[i] = get_bits(gb, 8);
  2084.     }
  2085.     buf[i] = 0;
  2086.  
  2087.     /* divx detection */
  2088.     e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
  2089.     if (e < 2)
  2090.         e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
  2091.     if (e >= 2) {
  2092.         ctx->divx_version = ver;
  2093.         ctx->divx_build   = build;
  2094.         s->divx_packed  = e == 3 && last == 'p';
  2095.     }
  2096.  
  2097.     /* libavcodec detection */
  2098.     e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
  2099.     if (e != 4)
  2100.         e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
  2101.     if (e != 4) {
  2102.         e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
  2103.         if (e > 1)
  2104.             build = (ver << 16) + (ver2 << 8) + ver3;
  2105.     }
  2106.     if (e != 4) {
  2107.         if (strcmp(buf, "ffmpeg") == 0)
  2108.             ctx->lavc_build = 4600;
  2109.     }
  2110.     if (e == 4)
  2111.         ctx->lavc_build = build;
  2112.  
  2113.     /* Xvid detection */
  2114.     e = sscanf(buf, "XviD%d", &build);
  2115.     if (e == 1)
  2116.         ctx->xvid_build = build;
  2117.  
  2118.     return 0;
  2119. }
  2120.  
  2121. int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
  2122. {
  2123.     Mpeg4DecContext *ctx = avctx->priv_data;
  2124.     MpegEncContext *s = &ctx->m;
  2125.  
  2126.     if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
  2127.         if (s->codec_tag        == AV_RL32("XVID") ||
  2128.             s->codec_tag        == AV_RL32("XVIX") ||
  2129.             s->codec_tag        == AV_RL32("RMP4") ||
  2130.             s->codec_tag        == AV_RL32("ZMP4") ||
  2131.             s->codec_tag        == AV_RL32("SIPP"))
  2132.             ctx->xvid_build = 0;
  2133.     }
  2134.  
  2135.     if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
  2136.         if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
  2137.             ctx->vol_control_parameters == 0)
  2138.             ctx->divx_version = 400;  // divx 4
  2139.  
  2140.     if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
  2141.         ctx->divx_version =
  2142.         ctx->divx_build   = -1;
  2143.     }
  2144.  
  2145.     if (s->workaround_bugs & FF_BUG_AUTODETECT) {
  2146.         if (s->codec_tag == AV_RL32("XVIX"))
  2147.             s->workaround_bugs |= FF_BUG_XVID_ILACE;
  2148.  
  2149.         if (s->codec_tag == AV_RL32("UMP4"))
  2150.             s->workaround_bugs |= FF_BUG_UMP4;
  2151.  
  2152.         if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
  2153.             s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
  2154.  
  2155.         if (ctx->divx_version > 502 && ctx->divx_build < 1814)
  2156.             s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
  2157.  
  2158.         if (ctx->xvid_build <= 3U)
  2159.             s->padding_bug_score = 256 * 256 * 256 * 64;
  2160.  
  2161.         if (ctx->xvid_build <= 1U)
  2162.             s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
  2163.  
  2164.         if (ctx->xvid_build <= 12U)
  2165.             s->workaround_bugs |= FF_BUG_EDGE;
  2166.  
  2167.         if (ctx->xvid_build <= 32U)
  2168.             s->workaround_bugs |= FF_BUG_DC_CLIP;
  2169.  
  2170. #define SET_QPEL_FUNC(postfix1, postfix2)                           \
  2171.     s->qdsp.put_        ## postfix1 = ff_put_        ## postfix2;   \
  2172.     s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;   \
  2173.     s->qdsp.avg_        ## postfix1 = ff_avg_        ## postfix2;
  2174.  
  2175.         if (ctx->lavc_build < 4653U)
  2176.             s->workaround_bugs |= FF_BUG_STD_QPEL;
  2177.  
  2178.         if (ctx->lavc_build < 4655U)
  2179.             s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
  2180.  
  2181.         if (ctx->lavc_build < 4670U)
  2182.             s->workaround_bugs |= FF_BUG_EDGE;
  2183.  
  2184.         if (ctx->lavc_build <= 4712U)
  2185.             s->workaround_bugs |= FF_BUG_DC_CLIP;
  2186.  
  2187.         if (ctx->divx_version >= 0)
  2188.             s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
  2189.         if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
  2190.             s->padding_bug_score = 256 * 256 * 256 * 64;
  2191.  
  2192.         if (ctx->divx_version < 500U)
  2193.             s->workaround_bugs |= FF_BUG_EDGE;
  2194.  
  2195.         if (ctx->divx_version >= 0)
  2196.             s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
  2197.     }
  2198.  
  2199.     if (s->workaround_bugs & FF_BUG_STD_QPEL) {
  2200.         SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
  2201.         SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
  2202.         SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
  2203.         SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
  2204.         SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
  2205.         SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
  2206.  
  2207.         SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
  2208.         SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
  2209.         SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
  2210.         SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
  2211.         SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
  2212.         SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
  2213.     }
  2214.  
  2215.     if (avctx->debug & FF_DEBUG_BUGS)
  2216.         av_log(s->avctx, AV_LOG_DEBUG,
  2217.                "bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
  2218.                s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
  2219.                ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
  2220.  
  2221.     if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
  2222.         s->codec_id == AV_CODEC_ID_MPEG4 &&
  2223.         avctx->idct_algo == FF_IDCT_AUTO) {
  2224.         avctx->idct_algo = FF_IDCT_XVID;
  2225.         ff_mpv_idct_init(s);
  2226.         return 1;
  2227.     }
  2228.  
  2229.     return 0;
  2230. }
  2231.  
  2232. static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
  2233. {
  2234.     MpegEncContext *s = &ctx->m;
  2235.     int time_incr, time_increment;
  2236.     int64_t pts;
  2237.  
  2238.     s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */
  2239.     if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
  2240.         ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
  2241.         av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
  2242.         s->low_delay = 0;
  2243.     }
  2244.  
  2245.     s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
  2246.     if (s->partitioned_frame)
  2247.         s->decode_mb = mpeg4_decode_partitioned_mb;
  2248.     else
  2249.         s->decode_mb = mpeg4_decode_mb;
  2250.  
  2251.     time_incr = 0;
  2252.     while (get_bits1(gb) != 0)
  2253.         time_incr++;
  2254.  
  2255.     check_marker(gb, "before time_increment");
  2256.  
  2257.     if (ctx->time_increment_bits == 0 ||
  2258.         !(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
  2259.         av_log(s->avctx, AV_LOG_WARNING,
  2260.                "time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits);
  2261.  
  2262.         for (ctx->time_increment_bits = 1;
  2263.              ctx->time_increment_bits < 16;
  2264.              ctx->time_increment_bits++) {
  2265.             if (s->pict_type == AV_PICTURE_TYPE_P ||
  2266.                 (s->pict_type == AV_PICTURE_TYPE_S &&
  2267.                  ctx->vol_sprite_usage == GMC_SPRITE)) {
  2268.                 if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
  2269.                     break;
  2270.             } else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
  2271.                 break;
  2272.         }
  2273.  
  2274.         av_log(s->avctx, AV_LOG_WARNING,
  2275.                "time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
  2276.         if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) {
  2277.             s->avctx->framerate.num = 1<<ctx->time_increment_bits;
  2278.             s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
  2279.         }
  2280.     }
  2281.  
  2282.     if (IS_3IV1)
  2283.         time_increment = get_bits1(gb);        // FIXME investigate further
  2284.     else
  2285.         time_increment = get_bits(gb, ctx->time_increment_bits);
  2286.  
  2287.     if (s->pict_type != AV_PICTURE_TYPE_B) {
  2288.         s->last_time_base = s->time_base;
  2289.         s->time_base     += time_incr;
  2290.         s->time = s->time_base * s->avctx->framerate.num + time_increment;
  2291.         if (s->workaround_bugs & FF_BUG_UMP4) {
  2292.             if (s->time < s->last_non_b_time) {
  2293.                 /* header is not mpeg-4-compatible, broken encoder,
  2294.                  * trying to workaround */
  2295.                 s->time_base++;
  2296.                 s->time += s->avctx->framerate.num;
  2297.             }
  2298.         }
  2299.         s->pp_time         = s->time - s->last_non_b_time;
  2300.         s->last_non_b_time = s->time;
  2301.     } else {
  2302.         s->time    = (s->last_time_base + time_incr) * s->avctx->framerate.num + time_increment;
  2303.         s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
  2304.         if (s->pp_time <= s->pb_time ||
  2305.             s->pp_time <= s->pp_time - s->pb_time ||
  2306.             s->pp_time <= 0) {
  2307.             /* messed up order, maybe after seeking? skipping current b-frame */
  2308.             return FRAME_SKIPPED;
  2309.         }
  2310.         ff_mpeg4_init_direct_mv(s);
  2311.  
  2312.         if (ctx->t_frame == 0)
  2313.             ctx->t_frame = s->pb_time;
  2314.         if (ctx->t_frame == 0)
  2315.             ctx->t_frame = 1;  // 1/0 protection
  2316.         s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
  2317.                             ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
  2318.         s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
  2319.                             ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
  2320.         if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
  2321.             s->pb_field_time = 2;
  2322.             s->pp_field_time = 4;
  2323.             if (!s->progressive_sequence)
  2324.                 return FRAME_SKIPPED;
  2325.         }
  2326.     }
  2327.  
  2328.     if (s->avctx->framerate.den)
  2329.         pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
  2330.     else
  2331.         pts = AV_NOPTS_VALUE;
  2332.     ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
  2333.  
  2334.     check_marker(gb, "before vop_coded");
  2335.  
  2336.     /* vop coded */
  2337.     if (get_bits1(gb) != 1) {
  2338.         if (s->avctx->debug & FF_DEBUG_PICT_INFO)
  2339.             av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
  2340.         return FRAME_SKIPPED;
  2341.     }
  2342.     if (ctx->new_pred)
  2343.         decode_new_pred(ctx, gb);
  2344.  
  2345.     if (ctx->shape != BIN_ONLY_SHAPE &&
  2346.                     (s->pict_type == AV_PICTURE_TYPE_P ||
  2347.                      (s->pict_type == AV_PICTURE_TYPE_S &&
  2348.                       ctx->vol_sprite_usage == GMC_SPRITE))) {
  2349.         /* rounding type for motion estimation */
  2350.         s->no_rounding = get_bits1(gb);
  2351.     } else {
  2352.         s->no_rounding = 0;
  2353.     }
  2354.     // FIXME reduced res stuff
  2355.  
  2356.     if (ctx->shape != RECT_SHAPE) {
  2357.         if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
  2358.             skip_bits(gb, 13);  /* width */
  2359.             check_marker(gb, "after width");
  2360.             skip_bits(gb, 13);  /* height */
  2361.             check_marker(gb, "after height");
  2362.             skip_bits(gb, 13);  /* hor_spat_ref */
  2363.             check_marker(gb, "after hor_spat_ref");
  2364.             skip_bits(gb, 13);  /* ver_spat_ref */
  2365.         }
  2366.         skip_bits1(gb);         /* change_CR_disable */
  2367.  
  2368.         if (get_bits1(gb) != 0)
  2369.             skip_bits(gb, 8);   /* constant_alpha_value */
  2370.     }
  2371.  
  2372.     // FIXME complexity estimation stuff
  2373.  
  2374.     if (ctx->shape != BIN_ONLY_SHAPE) {
  2375.         skip_bits_long(gb, ctx->cplx_estimation_trash_i);
  2376.         if (s->pict_type != AV_PICTURE_TYPE_I)
  2377.             skip_bits_long(gb, ctx->cplx_estimation_trash_p);
  2378.         if (s->pict_type == AV_PICTURE_TYPE_B)
  2379.             skip_bits_long(gb, ctx->cplx_estimation_trash_b);
  2380.  
  2381.         if (get_bits_left(gb) < 3) {
  2382.             av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
  2383.             return AVERROR_INVALIDDATA;
  2384.         }
  2385.         ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
  2386.         if (!s->progressive_sequence) {
  2387.             s->top_field_first = get_bits1(gb);
  2388.             s->alternate_scan  = get_bits1(gb);
  2389.         } else
  2390.             s->alternate_scan = 0;
  2391.     }
  2392.  
  2393.     if (s->alternate_scan) {
  2394.         ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_alternate_vertical_scan);
  2395.         ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_alternate_vertical_scan);
  2396.         ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
  2397.         ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
  2398.     } else {
  2399.         ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable,   ff_zigzag_direct);
  2400.         ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable,   ff_zigzag_direct);
  2401.         ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
  2402.         ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
  2403.     }
  2404.  
  2405.     if (s->pict_type == AV_PICTURE_TYPE_S &&
  2406.         (ctx->vol_sprite_usage == STATIC_SPRITE ||
  2407.          ctx->vol_sprite_usage == GMC_SPRITE)) {
  2408.         if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
  2409.             return AVERROR_INVALIDDATA;
  2410.         if (ctx->sprite_brightness_change)
  2411.             av_log(s->avctx, AV_LOG_ERROR,
  2412.                    "sprite_brightness_change not supported\n");
  2413.         if (ctx->vol_sprite_usage == STATIC_SPRITE)
  2414.             av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
  2415.     }
  2416.  
  2417.     if (ctx->shape != BIN_ONLY_SHAPE) {
  2418.         s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
  2419.         if (s->qscale == 0) {
  2420.             av_log(s->avctx, AV_LOG_ERROR,
  2421.                    "Error, header damaged or not MPEG4 header (qscale=0)\n");
  2422.             return AVERROR_INVALIDDATA;  // makes no sense to continue, as there is nothing left from the image then
  2423.         }
  2424.  
  2425.         if (s->pict_type != AV_PICTURE_TYPE_I) {
  2426.             s->f_code = get_bits(gb, 3);        /* fcode_for */
  2427.             if (s->f_code == 0) {
  2428.                 av_log(s->avctx, AV_LOG_ERROR,
  2429.                        "Error, header damaged or not MPEG4 header (f_code=0)\n");
  2430.                 s->f_code = 1;
  2431.                 return AVERROR_INVALIDDATA;  // makes no sense to continue, as there is nothing left from the image then
  2432.             }
  2433.         } else
  2434.             s->f_code = 1;
  2435.  
  2436.         if (s->pict_type == AV_PICTURE_TYPE_B) {
  2437.             s->b_code = get_bits(gb, 3);
  2438.             if (s->b_code == 0) {
  2439.                 av_log(s->avctx, AV_LOG_ERROR,
  2440.                        "Error, header damaged or not MPEG4 header (b_code=0)\n");
  2441.                 s->b_code=1;
  2442.                 return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
  2443.             }
  2444.         } else
  2445.             s->b_code = 1;
  2446.  
  2447.         if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
  2448.             av_log(s->avctx, AV_LOG_DEBUG,
  2449.                    "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",
  2450.                    s->qscale, s->f_code, s->b_code,
  2451.                    s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
  2452.                    gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
  2453.                    s->top_field_first, s->quarter_sample ? "q" : "h",
  2454.                    s->data_partitioning, ctx->resync_marker,
  2455.                    ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
  2456.                    1 - s->no_rounding, s->vo_type,
  2457.                    ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
  2458.                    ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
  2459.                    ctx->cplx_estimation_trash_b,
  2460.                    s->time,
  2461.                    time_increment
  2462.                   );
  2463.         }
  2464.  
  2465.         if (!ctx->scalability) {
  2466.             if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
  2467.                 skip_bits1(gb);  // vop shape coding type
  2468.         } else {
  2469.             if (ctx->enhancement_type) {
  2470.                 int load_backward_shape = get_bits1(gb);
  2471.                 if (load_backward_shape)
  2472.                     av_log(s->avctx, AV_LOG_ERROR,
  2473.                            "load backward shape isn't supported\n");
  2474.             }
  2475.             skip_bits(gb, 2);  // ref_select_code
  2476.         }
  2477.     }
  2478.     /* detect buggy encoders which don't set the low_delay flag
  2479.      * (divx4/xvid/opendivx). Note we cannot detect divx5 without b-frames
  2480.      * easily (although it's buggy too) */
  2481.     if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
  2482.         ctx->divx_version == -1 && s->picture_number == 0) {
  2483.         av_log(s->avctx, AV_LOG_WARNING,
  2484.                "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
  2485.         s->low_delay = 1;
  2486.     }
  2487.  
  2488.     s->picture_number++;  // better than pic number==0 always ;)
  2489.  
  2490.     // FIXME add short header support
  2491.     s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
  2492.     s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
  2493.  
  2494.     if (s->workaround_bugs & FF_BUG_EDGE) {
  2495.         s->h_edge_pos = s->width;
  2496.         s->v_edge_pos = s->height;
  2497.     }
  2498.     return 0;
  2499. }
  2500.  
  2501. /**
  2502.  * Decode mpeg4 headers.
  2503.  * @return <0 if no VOP found (or a damaged one)
  2504.  *         FRAME_SKIPPED if a not coded VOP is found
  2505.  *         0 if a VOP is found
  2506.  */
  2507. int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
  2508. {
  2509.     MpegEncContext *s = &ctx->m;
  2510.     unsigned startcode, v;
  2511.     int ret;
  2512.  
  2513.     /* search next start code */
  2514.     align_get_bits(gb);
  2515.  
  2516.     if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
  2517.         skip_bits(gb, 24);
  2518.         if (get_bits(gb, 8) == 0xF0)
  2519.             goto end;
  2520.     }
  2521.  
  2522.     startcode = 0xff;
  2523.     for (;;) {
  2524.         if (get_bits_count(gb) >= gb->size_in_bits) {
  2525.             if (gb->size_in_bits == 8 &&
  2526.                 (ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
  2527.                 av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
  2528.                 return FRAME_SKIPPED;  // divx bug
  2529.             } else
  2530.                 return -1;  // end of stream
  2531.         }
  2532.  
  2533.         /* use the bits after the test */
  2534.         v = get_bits(gb, 8);
  2535.         startcode = ((startcode << 8) | v) & 0xffffffff;
  2536.  
  2537.         if ((startcode & 0xFFFFFF00) != 0x100)
  2538.             continue;  // no startcode
  2539.  
  2540.         if (s->avctx->debug & FF_DEBUG_STARTCODE) {
  2541.             av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
  2542.             if (startcode <= 0x11F)
  2543.                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
  2544.             else if (startcode <= 0x12F)
  2545.                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
  2546.             else if (startcode <= 0x13F)
  2547.                 av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
  2548.             else if (startcode <= 0x15F)
  2549.                 av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
  2550.             else if (startcode <= 0x1AF)
  2551.                 av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
  2552.             else if (startcode == 0x1B0)
  2553.                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
  2554.             else if (startcode == 0x1B1)
  2555.                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
  2556.             else if (startcode == 0x1B2)
  2557.                 av_log(s->avctx, AV_LOG_DEBUG, "User Data");
  2558.             else if (startcode == 0x1B3)
  2559.                 av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
  2560.             else if (startcode == 0x1B4)
  2561.                 av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
  2562.             else if (startcode == 0x1B5)
  2563.                 av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
  2564.             else if (startcode == 0x1B6)
  2565.                 av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
  2566.             else if (startcode == 0x1B7)
  2567.                 av_log(s->avctx, AV_LOG_DEBUG, "slice start");
  2568.             else if (startcode == 0x1B8)
  2569.                 av_log(s->avctx, AV_LOG_DEBUG, "extension start");
  2570.             else if (startcode == 0x1B9)
  2571.                 av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
  2572.             else if (startcode == 0x1BA)
  2573.                 av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
  2574.             else if (startcode == 0x1BB)
  2575.                 av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
  2576.             else if (startcode == 0x1BC)
  2577.                 av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
  2578.             else if (startcode == 0x1BD)
  2579.                 av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
  2580.             else if (startcode == 0x1BE)
  2581.                 av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
  2582.             else if (startcode == 0x1BF)
  2583.                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
  2584.             else if (startcode == 0x1C0)
  2585.                 av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
  2586.             else if (startcode == 0x1C1)
  2587.                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
  2588.             else if (startcode == 0x1C2)
  2589.                 av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
  2590.             else if (startcode == 0x1C3)
  2591.                 av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
  2592.             else if (startcode <= 0x1C5)
  2593.                 av_log(s->avctx, AV_LOG_DEBUG, "reserved");
  2594.             else if (startcode <= 0x1FF)
  2595.                 av_log(s->avctx, AV_LOG_DEBUG, "System start");
  2596.             av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
  2597.         }
  2598.  
  2599.         if (startcode >= 0x120 && startcode <= 0x12F) {
  2600.             if ((ret = decode_vol_header(ctx, gb)) < 0)
  2601.                 return ret;
  2602.         } else if (startcode == USER_DATA_STARTCODE) {
  2603.             decode_user_data(ctx, gb);
  2604.         } else if (startcode == GOP_STARTCODE) {
  2605.             mpeg4_decode_gop_header(s, gb);
  2606.         } else if (startcode == VOS_STARTCODE) {
  2607.             mpeg4_decode_profile_level(s, gb);
  2608.         } else if (startcode == VOP_STARTCODE) {
  2609.             break;
  2610.         }
  2611.  
  2612.         align_get_bits(gb);
  2613.         startcode = 0xff;
  2614.     }
  2615.  
  2616. end:
  2617.     if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
  2618.         s->low_delay = 1;
  2619.     s->avctx->has_b_frames = !s->low_delay;
  2620.  
  2621.     return decode_vop_header(ctx, gb);
  2622. }
  2623.  
  2624. av_cold void ff_mpeg4videodec_static_init(void) {
  2625.     static int done = 0;
  2626.  
  2627.     if (!done) {
  2628.         ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
  2629.         ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
  2630.         ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
  2631.         INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
  2632.         INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
  2633.         INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
  2634.         INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
  2635.                         &ff_mpeg4_DCtab_lum[0][1], 2, 1,
  2636.                         &ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
  2637.         INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
  2638.                         &ff_mpeg4_DCtab_chrom[0][1], 2, 1,
  2639.                         &ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
  2640.         INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
  2641.                         &ff_sprite_trajectory_tab[0][1], 4, 2,
  2642.                         &ff_sprite_trajectory_tab[0][0], 4, 2, 128);
  2643.         INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
  2644.                         &ff_mb_type_b_tab[0][1], 2, 1,
  2645.                         &ff_mb_type_b_tab[0][0], 2, 1, 16);
  2646.         done = 1;
  2647.     }
  2648. }
  2649.  
  2650. int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
  2651. {
  2652.     Mpeg4DecContext *ctx = avctx->priv_data;
  2653.     MpegEncContext    *s = &ctx->m;
  2654.  
  2655.     /* divx 5.01+ bitstream reorder stuff */
  2656.     /* Since this clobbers the input buffer and hwaccel codecs still need the
  2657.      * data during hwaccel->end_frame we should not do this any earlier */
  2658.     if (s->divx_packed) {
  2659.         int current_pos     = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
  2660.         int startcode_found = 0;
  2661.  
  2662.         if (buf_size - current_pos > 7) {
  2663.  
  2664.             int i;
  2665.             for (i = current_pos; i < buf_size - 4; i++)
  2666.  
  2667.                 if (buf[i]     == 0 &&
  2668.                     buf[i + 1] == 0 &&
  2669.                     buf[i + 2] == 1 &&
  2670.                     buf[i + 3] == 0xB6) {
  2671.                     startcode_found = !(buf[i + 4] & 0x40);
  2672.                     break;
  2673.                 }
  2674.         }
  2675.  
  2676.         if (startcode_found) {
  2677.             if (!ctx->showed_packed_warning) {
  2678.                 av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
  2679.                        "wasteful way to store B-frames ('packed B-frames'). "
  2680.                        "Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n");
  2681.                 ctx->showed_packed_warning = 1;
  2682.             }
  2683.             av_fast_padded_malloc(&s->bitstream_buffer,
  2684.                            &s->allocated_bitstream_buffer_size,
  2685.                            buf_size - current_pos);
  2686.             if (!s->bitstream_buffer) {
  2687.                 s->bitstream_buffer_size = 0;
  2688.                 return AVERROR(ENOMEM);
  2689.             }
  2690.             memcpy(s->bitstream_buffer, buf + current_pos,
  2691.                    buf_size - current_pos);
  2692.             s->bitstream_buffer_size = buf_size - current_pos;
  2693.         }
  2694.     }
  2695.  
  2696.     return 0;
  2697. }
  2698.  
  2699. static int mpeg4_update_thread_context(AVCodecContext *dst,
  2700.                                        const AVCodecContext *src)
  2701. {
  2702.     Mpeg4DecContext *s = dst->priv_data;
  2703.     const Mpeg4DecContext *s1 = src->priv_data;
  2704.     int init = s->m.context_initialized;
  2705.  
  2706.     int ret = ff_mpeg_update_thread_context(dst, src);
  2707.  
  2708.     if (ret < 0)
  2709.         return ret;
  2710.  
  2711.     memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext));
  2712.  
  2713.     if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0)
  2714.         ff_xvid_idct_init(&s->m.idsp, dst);
  2715.  
  2716.     return 0;
  2717. }
  2718.  
  2719. static av_cold int decode_init(AVCodecContext *avctx)
  2720. {
  2721.     Mpeg4DecContext *ctx = avctx->priv_data;
  2722.     MpegEncContext *s = &ctx->m;
  2723.     int ret;
  2724.  
  2725.     ctx->divx_version =
  2726.     ctx->divx_build   =
  2727.     ctx->xvid_build   =
  2728.     ctx->lavc_build   = -1;
  2729.  
  2730.     if ((ret = ff_h263_decode_init(avctx)) < 0)
  2731.         return ret;
  2732.  
  2733.     ff_mpeg4videodec_static_init();
  2734.  
  2735.     s->h263_pred = 1;
  2736.     s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
  2737.     s->decode_mb = mpeg4_decode_mb;
  2738.     ctx->time_increment_bits = 4; /* default value for broken headers */
  2739.  
  2740.     avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
  2741.     avctx->internal->allocate_progress = 1;
  2742.  
  2743.     return 0;
  2744. }
  2745.  
  2746. static const AVProfile mpeg4_video_profiles[] = {
  2747.     { FF_PROFILE_MPEG4_SIMPLE,                    "Simple Profile" },
  2748.     { FF_PROFILE_MPEG4_SIMPLE_SCALABLE,           "Simple Scalable Profile" },
  2749.     { FF_PROFILE_MPEG4_CORE,                      "Core Profile" },
  2750.     { FF_PROFILE_MPEG4_MAIN,                      "Main Profile" },
  2751.     { FF_PROFILE_MPEG4_N_BIT,                     "N-bit Profile" },
  2752.     { FF_PROFILE_MPEG4_SCALABLE_TEXTURE,          "Scalable Texture Profile" },
  2753.     { FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION,     "Simple Face Animation Profile" },
  2754.     { FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE,    "Basic Animated Texture Profile" },
  2755.     { FF_PROFILE_MPEG4_HYBRID,                    "Hybrid Profile" },
  2756.     { FF_PROFILE_MPEG4_ADVANCED_REAL_TIME,        "Advanced Real Time Simple Profile" },
  2757.     { FF_PROFILE_MPEG4_CORE_SCALABLE,             "Code Scalable Profile" },
  2758.     { FF_PROFILE_MPEG4_ADVANCED_CODING,           "Advanced Coding Profile" },
  2759.     { FF_PROFILE_MPEG4_ADVANCED_CORE,             "Advanced Core Profile" },
  2760.     { FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE, "Advanced Scalable Texture Profile" },
  2761.     { FF_PROFILE_MPEG4_SIMPLE_STUDIO,             "Simple Studio Profile" },
  2762.     { FF_PROFILE_MPEG4_ADVANCED_SIMPLE,           "Advanced Simple Profile" },
  2763.     { FF_PROFILE_UNKNOWN },
  2764. };
  2765.  
  2766. static const AVOption mpeg4_options[] = {
  2767.     {"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  2768.     {"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0},
  2769.     {NULL}
  2770. };
  2771.  
  2772. static const AVClass mpeg4_class = {
  2773.     "MPEG4 Video Decoder",
  2774.     av_default_item_name,
  2775.     mpeg4_options,
  2776.     LIBAVUTIL_VERSION_INT,
  2777. };
  2778.  
  2779. AVCodec ff_mpeg4_decoder = {
  2780.     .name                  = "mpeg4",
  2781.     .long_name             = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
  2782.     .type                  = AVMEDIA_TYPE_VIDEO,
  2783.     .id                    = AV_CODEC_ID_MPEG4,
  2784.     .priv_data_size        = sizeof(Mpeg4DecContext),
  2785.     .init                  = decode_init,
  2786.     .close                 = ff_h263_decode_end,
  2787.     .decode                = ff_h263_decode_frame,
  2788.     .capabilities          = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
  2789.                              AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
  2790.                              AV_CODEC_CAP_FRAME_THREADS,
  2791.     .flush                 = ff_mpeg_flush,
  2792.     .max_lowres            = 3,
  2793.     .pix_fmts              = ff_h263_hwaccel_pixfmt_list_420,
  2794.     .profiles              = NULL_IF_CONFIG_SMALL(mpeg4_video_profiles),
  2795.     .update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
  2796.     .priv_class = &mpeg4_class,
  2797. };
  2798.  
  2799.  
  2800. #if CONFIG_MPEG4_VDPAU_DECODER && FF_API_VDPAU
  2801. static const AVClass mpeg4_vdpau_class = {
  2802.     "MPEG4 Video VDPAU Decoder",
  2803.     av_default_item_name,
  2804.     mpeg4_options,
  2805.     LIBAVUTIL_VERSION_INT,
  2806. };
  2807.  
  2808. AVCodec ff_mpeg4_vdpau_decoder = {
  2809.     .name           = "mpeg4_vdpau",
  2810.     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 (VDPAU)"),
  2811.     .type           = AVMEDIA_TYPE_VIDEO,
  2812.     .id             = AV_CODEC_ID_MPEG4,
  2813.     .priv_data_size = sizeof(Mpeg4DecContext),
  2814.     .init           = decode_init,
  2815.     .close          = ff_h263_decode_end,
  2816.     .decode         = ff_h263_decode_frame,
  2817.     .capabilities   = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
  2818.                       AV_CODEC_CAP_HWACCEL_VDPAU,
  2819.     .pix_fmts       = (const enum AVPixelFormat[]) { AV_PIX_FMT_VDPAU_MPEG4,
  2820.                                                   AV_PIX_FMT_NONE },
  2821.     .priv_class     = &mpeg4_vdpau_class,
  2822. };
  2823. #endif
  2824.