Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * The simplest mpeg encoder (well, it was the simplest!)
  3.  * Copyright (c) 2000,2001 Fabrice Bellard
  4.  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
  5.  *
  6.  * 4MV & hq & B-frame encoding stuff by Michael Niedermayer <michaelni@gmx.at>
  7.  *
  8.  * This file is part of FFmpeg.
  9.  *
  10.  * FFmpeg is free software; you can redistribute it and/or
  11.  * modify it under the terms of the GNU Lesser General Public
  12.  * License as published by the Free Software Foundation; either
  13.  * version 2.1 of the License, or (at your option) any later version.
  14.  *
  15.  * FFmpeg is distributed in the hope that it will be useful,
  16.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  18.  * Lesser General Public License for more details.
  19.  *
  20.  * You should have received a copy of the GNU Lesser General Public
  21.  * License along with FFmpeg; if not, write to the Free Software
  22.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23.  *
  24.  * non linear quantizers with large QPs and VBV with restrictive qmin fixes sponsored by NOA GmbH
  25.  */
  26.  
  27. /**
  28.  * @file
  29.  * The simplest mpeg encoder (well, it was the simplest!).
  30.  */
  31.  
  32. #include <stdint.h>
  33.  
  34. #include "libavutil/internal.h"
  35. #include "libavutil/intmath.h"
  36. #include "libavutil/mathematics.h"
  37. #include "libavutil/pixdesc.h"
  38. #include "libavutil/opt.h"
  39. #include "libavutil/timer.h"
  40. #include "avcodec.h"
  41. #include "dct.h"
  42. #include "idctdsp.h"
  43. #include "mpeg12.h"
  44. #include "mpegvideo.h"
  45. #include "mpegvideodata.h"
  46. #include "h261.h"
  47. #include "h263.h"
  48. #include "h263data.h"
  49. #include "mjpegenc_common.h"
  50. #include "mathops.h"
  51. #include "mpegutils.h"
  52. #include "mjpegenc.h"
  53. #include "msmpeg4.h"
  54. #include "pixblockdsp.h"
  55. #include "qpeldsp.h"
  56. #include "faandct.h"
  57. #include "thread.h"
  58. #include "aandcttab.h"
  59. #include "flv.h"
  60. #include "mpeg4video.h"
  61. #include "internal.h"
  62. #include "bytestream.h"
  63. #include "wmv2.h"
  64. #include "rv10.h"
  65. #include <limits.h>
  66. #include "sp5x.h"
  67.  
  68. #define QUANT_BIAS_SHIFT 8
  69.  
  70. #define QMAT_SHIFT_MMX 16
  71. #define QMAT_SHIFT 21
  72.  
  73. static int encode_picture(MpegEncContext *s, int picture_number);
  74. static int dct_quantize_refine(MpegEncContext *s, int16_t *block, int16_t *weight, int16_t *orig, int n, int qscale);
  75. static int sse_mb(MpegEncContext *s);
  76. static void denoise_dct_c(MpegEncContext *s, int16_t *block);
  77. static int dct_quantize_trellis_c(MpegEncContext *s, int16_t *block, int n, int qscale, int *overflow);
  78.  
  79. static uint8_t default_mv_penalty[MAX_FCODE + 1][MAX_DMV * 2 + 1];
  80. static uint8_t default_fcode_tab[MAX_MV * 2 + 1];
  81.  
  82. const AVOption ff_mpv_generic_options[] = {
  83.     FF_MPV_COMMON_OPTS
  84.     { NULL },
  85. };
  86.  
  87. void ff_convert_matrix(MpegEncContext *s, int (*qmat)[64],
  88.                        uint16_t (*qmat16)[2][64],
  89.                        const uint16_t *quant_matrix,
  90.                        int bias, int qmin, int qmax, int intra)
  91. {
  92.     FDCTDSPContext *fdsp = &s->fdsp;
  93.     int qscale;
  94.     int shift = 0;
  95.  
  96.     for (qscale = qmin; qscale <= qmax; qscale++) {
  97.         int i;
  98.         if (fdsp->fdct == ff_jpeg_fdct_islow_8  ||
  99. #if CONFIG_FAANDCT
  100.             fdsp->fdct == ff_faandct            ||
  101. #endif /* CONFIG_FAANDCT */
  102.             fdsp->fdct == ff_jpeg_fdct_islow_10) {
  103.             for (i = 0; i < 64; i++) {
  104.                 const int j = s->idsp.idct_permutation[i];
  105.                 int64_t den = (int64_t) qscale * quant_matrix[j];
  106.                 /* 16 <= qscale * quant_matrix[i] <= 7905
  107.                  * Assume x = ff_aanscales[i] * qscale * quant_matrix[i]
  108.                  *             19952 <=              x  <= 249205026
  109.                  * (1 << 36) / 19952 >= (1 << 36) / (x) >= (1 << 36) / 249205026
  110.                  *           3444240 >= (1 << 36) / (x) >= 275 */
  111.  
  112.                 qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / den);
  113.             }
  114.         } else if (fdsp->fdct == ff_fdct_ifast) {
  115.             for (i = 0; i < 64; i++) {
  116.                 const int j = s->idsp.idct_permutation[i];
  117.                 int64_t den = ff_aanscales[i] * (int64_t) qscale * quant_matrix[j];
  118.                 /* 16 <= qscale * quant_matrix[i] <= 7905
  119.                  * Assume x = ff_aanscales[i] * qscale * quant_matrix[i]
  120.                  *             19952 <=              x  <= 249205026
  121.                  * (1 << 36) / 19952 >= (1 << 36) / (x) >= (1 << 36) / 249205026
  122.                  *           3444240 >= (1 << 36) / (x) >= 275 */
  123.  
  124.                 qmat[qscale][i] = (int)((UINT64_C(1) << (QMAT_SHIFT + 14)) / den);
  125.             }
  126.         } else {
  127.             for (i = 0; i < 64; i++) {
  128.                 const int j = s->idsp.idct_permutation[i];
  129.                 int64_t den = (int64_t) qscale * quant_matrix[j];
  130.                 /* We can safely suppose that 16 <= quant_matrix[i] <= 255
  131.                  * Assume x = qscale * quant_matrix[i]
  132.                  * So             16 <=              x  <= 7905
  133.                  * so (1 << 19) / 16 >= (1 << 19) / (x) >= (1 << 19) / 7905
  134.                  * so          32768 >= (1 << 19) / (x) >= 67 */
  135.                 qmat[qscale][i] = (int)((UINT64_C(1) << QMAT_SHIFT) / den);
  136.                 //qmat  [qscale][i] = (1 << QMAT_SHIFT_MMX) /
  137.                 //                    (qscale * quant_matrix[i]);
  138.                 qmat16[qscale][0][i] = (1 << QMAT_SHIFT_MMX) / den;
  139.  
  140.                 if (qmat16[qscale][0][i] == 0 ||
  141.                     qmat16[qscale][0][i] == 128 * 256)
  142.                     qmat16[qscale][0][i] = 128 * 256 - 1;
  143.                 qmat16[qscale][1][i] =
  144.                     ROUNDED_DIV(bias << (16 - QUANT_BIAS_SHIFT),
  145.                                 qmat16[qscale][0][i]);
  146.             }
  147.         }
  148.  
  149.         for (i = intra; i < 64; i++) {
  150.             int64_t max = 8191;
  151.             if (fdsp->fdct == ff_fdct_ifast) {
  152.                 max = (8191LL * ff_aanscales[i]) >> 14;
  153.             }
  154.             while (((max * qmat[qscale][i]) >> shift) > INT_MAX) {
  155.                 shift++;
  156.             }
  157.         }
  158.     }
  159.     if (shift) {
  160.         av_log(NULL, AV_LOG_INFO,
  161.                "Warning, QMAT_SHIFT is larger than %d, overflows possible\n",
  162.                QMAT_SHIFT - shift);
  163.     }
  164. }
  165.  
  166. static inline void update_qscale(MpegEncContext *s)
  167. {
  168.     if (s->q_scale_type == 1) {
  169.         int i;
  170.         int bestdiff=INT_MAX;
  171.         int best = 1;
  172.         static const uint8_t non_linear_qscale[] = {
  173.             1,2,3,4,5,6,7,8,9,10,11,12,14,16,18,20,24,26,28
  174.         };
  175.  
  176.         for (i = 0 ; i<FF_ARRAY_ELEMS(non_linear_qscale); i++) {
  177.             int diff = FFABS((non_linear_qscale[i]<<(FF_LAMBDA_SHIFT + 7)) - (int)s->lambda * 139);
  178.             if (non_linear_qscale[i] < s->avctx->qmin ||
  179.                 (non_linear_qscale[i] > s->avctx->qmax && !s->vbv_ignore_qmax))
  180.                 continue;
  181.             if (diff < bestdiff) {
  182.                 bestdiff = diff;
  183.                 best = non_linear_qscale[i];
  184.             }
  185.         }
  186.         s->qscale = best;
  187.     } else {
  188.         s->qscale = (s->lambda * 139 + FF_LAMBDA_SCALE * 64) >>
  189.                     (FF_LAMBDA_SHIFT + 7);
  190.         s->qscale = av_clip(s->qscale, s->avctx->qmin, s->vbv_ignore_qmax ? 31 : s->avctx->qmax);
  191.     }
  192.  
  193.     s->lambda2 = (s->lambda * s->lambda + FF_LAMBDA_SCALE / 2) >>
  194.                  FF_LAMBDA_SHIFT;
  195. }
  196.  
  197. void ff_write_quant_matrix(PutBitContext *pb, uint16_t *matrix)
  198. {
  199.     int i;
  200.  
  201.     if (matrix) {
  202.         put_bits(pb, 1, 1);
  203.         for (i = 0; i < 64; i++) {
  204.             put_bits(pb, 8, matrix[ff_zigzag_direct[i]]);
  205.         }
  206.     } else
  207.         put_bits(pb, 1, 0);
  208. }
  209.  
  210. /**
  211.  * init s->current_picture.qscale_table from s->lambda_table
  212.  */
  213. void ff_init_qscale_tab(MpegEncContext *s)
  214. {
  215.     int8_t * const qscale_table = s->current_picture.qscale_table;
  216.     int i;
  217.  
  218.     for (i = 0; i < s->mb_num; i++) {
  219.         unsigned int lam = s->lambda_table[s->mb_index2xy[i]];
  220.         int qp = (lam * 139 + FF_LAMBDA_SCALE * 64) >> (FF_LAMBDA_SHIFT + 7);
  221.         qscale_table[s->mb_index2xy[i]] = av_clip(qp, s->avctx->qmin,
  222.                                                   s->avctx->qmax);
  223.     }
  224. }
  225.  
  226. static void update_duplicate_context_after_me(MpegEncContext *dst,
  227.                                               MpegEncContext *src)
  228. {
  229. #define COPY(a) dst->a= src->a
  230.     COPY(pict_type);
  231.     COPY(current_picture);
  232.     COPY(f_code);
  233.     COPY(b_code);
  234.     COPY(qscale);
  235.     COPY(lambda);
  236.     COPY(lambda2);
  237.     COPY(picture_in_gop_number);
  238.     COPY(gop_picture_number);
  239.     COPY(frame_pred_frame_dct); // FIXME don't set in encode_header
  240.     COPY(progressive_frame);    // FIXME don't set in encode_header
  241.     COPY(partitioned_frame);    // FIXME don't set in encode_header
  242. #undef COPY
  243. }
  244.  
  245. /**
  246.  * Set the given MpegEncContext to defaults for encoding.
  247.  * the changed fields will not depend upon the prior state of the MpegEncContext.
  248.  */
  249. static void mpv_encode_defaults(MpegEncContext *s)
  250. {
  251.     int i;
  252.     ff_mpv_common_defaults(s);
  253.  
  254.     for (i = -16; i < 16; i++) {
  255.         default_fcode_tab[i + MAX_MV] = 1;
  256.     }
  257.     s->me.mv_penalty = default_mv_penalty;
  258.     s->fcode_tab     = default_fcode_tab;
  259.  
  260.     s->input_picture_number  = 0;
  261.     s->picture_in_gop_number = 0;
  262. }
  263.  
  264. av_cold int ff_dct_encode_init(MpegEncContext *s) {
  265.     if (ARCH_X86)
  266.         ff_dct_encode_init_x86(s);
  267.  
  268.     if (CONFIG_H263_ENCODER)
  269.         ff_h263dsp_init(&s->h263dsp);
  270.     if (!s->dct_quantize)
  271.         s->dct_quantize = ff_dct_quantize_c;
  272.     if (!s->denoise_dct)
  273.         s->denoise_dct  = denoise_dct_c;
  274.     s->fast_dct_quantize = s->dct_quantize;
  275.     if (s->avctx->trellis)
  276.         s->dct_quantize  = dct_quantize_trellis_c;
  277.  
  278.     return 0;
  279. }
  280.  
  281. /* init video encoder */
  282. av_cold int ff_mpv_encode_init(AVCodecContext *avctx)
  283. {
  284.     MpegEncContext *s = avctx->priv_data;
  285.     int i, ret, format_supported;
  286.  
  287.     mpv_encode_defaults(s);
  288.  
  289.     switch (avctx->codec_id) {
  290.     case AV_CODEC_ID_MPEG2VIDEO:
  291.         if (avctx->pix_fmt != AV_PIX_FMT_YUV420P &&
  292.             avctx->pix_fmt != AV_PIX_FMT_YUV422P) {
  293.             av_log(avctx, AV_LOG_ERROR,
  294.                    "only YUV420 and YUV422 are supported\n");
  295.             return -1;
  296.         }
  297.         break;
  298.     case AV_CODEC_ID_MJPEG:
  299.     case AV_CODEC_ID_AMV:
  300.         format_supported = 0;
  301.         /* JPEG color space */
  302.         if (avctx->pix_fmt == AV_PIX_FMT_YUVJ420P ||
  303.             avctx->pix_fmt == AV_PIX_FMT_YUVJ422P ||
  304.             avctx->pix_fmt == AV_PIX_FMT_YUVJ444P ||
  305.             (avctx->color_range == AVCOL_RANGE_JPEG &&
  306.              (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
  307.               avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
  308.               avctx->pix_fmt == AV_PIX_FMT_YUV444P)))
  309.             format_supported = 1;
  310.         /* MPEG color space */
  311.         else if (avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL &&
  312.                  (avctx->pix_fmt == AV_PIX_FMT_YUV420P ||
  313.                   avctx->pix_fmt == AV_PIX_FMT_YUV422P ||
  314.                   avctx->pix_fmt == AV_PIX_FMT_YUV444P))
  315.             format_supported = 1;
  316.  
  317.         if (!format_supported) {
  318.             av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");
  319.             return -1;
  320.         }
  321.         break;
  322.     default:
  323.         if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {
  324.             av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");
  325.             return -1;
  326.         }
  327.     }
  328.  
  329.     switch (avctx->pix_fmt) {
  330.     case AV_PIX_FMT_YUVJ444P:
  331.     case AV_PIX_FMT_YUV444P:
  332.         s->chroma_format = CHROMA_444;
  333.         break;
  334.     case AV_PIX_FMT_YUVJ422P:
  335.     case AV_PIX_FMT_YUV422P:
  336.         s->chroma_format = CHROMA_422;
  337.         break;
  338.     case AV_PIX_FMT_YUVJ420P:
  339.     case AV_PIX_FMT_YUV420P:
  340.     default:
  341.         s->chroma_format = CHROMA_420;
  342.         break;
  343.     }
  344.  
  345.     avctx->bits_per_raw_sample = av_clip(avctx->bits_per_raw_sample, 0, 8);
  346.     s->bit_rate = avctx->bit_rate;
  347.     s->width    = avctx->width;
  348.     s->height   = avctx->height;
  349.     if (avctx->gop_size > 600 &&
  350.         avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  351.         av_log(avctx, AV_LOG_WARNING,
  352.                "keyframe interval too large!, reducing it from %d to %d\n",
  353.                avctx->gop_size, 600);
  354.         avctx->gop_size = 600;
  355.     }
  356.     s->gop_size     = avctx->gop_size;
  357.     s->avctx        = avctx;
  358.     if (avctx->max_b_frames > MAX_B_FRAMES) {
  359.         av_log(avctx, AV_LOG_ERROR, "Too many B-frames requested, maximum "
  360.                "is %d.\n", MAX_B_FRAMES);
  361.         avctx->max_b_frames = MAX_B_FRAMES;
  362.     }
  363.     s->max_b_frames = avctx->max_b_frames;
  364.     s->codec_id     = avctx->codec->id;
  365.     s->strict_std_compliance = avctx->strict_std_compliance;
  366.     s->quarter_sample     = (avctx->flags & AV_CODEC_FLAG_QPEL) != 0;
  367.     s->mpeg_quant         = avctx->mpeg_quant;
  368.     s->rtp_mode           = !!avctx->rtp_payload_size;
  369.     s->intra_dc_precision = avctx->intra_dc_precision;
  370.  
  371.     // workaround some differences between how applications specify dc precision
  372.     if (s->intra_dc_precision < 0) {
  373.         s->intra_dc_precision += 8;
  374.     } else if (s->intra_dc_precision >= 8)
  375.         s->intra_dc_precision -= 8;
  376.  
  377.     if (s->intra_dc_precision < 0) {
  378.         av_log(avctx, AV_LOG_ERROR,
  379.                 "intra dc precision must be positive, note some applications use"
  380.                 " 0 and some 8 as base meaning 8bit, the value must not be smaller than that\n");
  381.         return AVERROR(EINVAL);
  382.     }
  383.  
  384.     if (s->intra_dc_precision > (avctx->codec_id == AV_CODEC_ID_MPEG2VIDEO ? 3 : 0)) {
  385.         av_log(avctx, AV_LOG_ERROR, "intra dc precision too large\n");
  386.         return AVERROR(EINVAL);
  387.     }
  388.     s->user_specified_pts = AV_NOPTS_VALUE;
  389.  
  390.     if (s->gop_size <= 1) {
  391.         s->intra_only = 1;
  392.         s->gop_size   = 12;
  393.     } else {
  394.         s->intra_only = 0;
  395.     }
  396.  
  397. #if FF_API_MOTION_EST
  398. FF_DISABLE_DEPRECATION_WARNINGS
  399.     s->me_method = avctx->me_method;
  400. FF_ENABLE_DEPRECATION_WARNINGS
  401. #endif
  402.  
  403.     /* Fixed QSCALE */
  404.     s->fixed_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);
  405.  
  406. #if FF_API_MPV_OPT
  407.     FF_DISABLE_DEPRECATION_WARNINGS
  408.     if (avctx->border_masking != 0.0)
  409.         s->border_masking = avctx->border_masking;
  410.     FF_ENABLE_DEPRECATION_WARNINGS
  411. #endif
  412.  
  413.     s->adaptive_quant = (s->avctx->lumi_masking ||
  414.                          s->avctx->dark_masking ||
  415.                          s->avctx->temporal_cplx_masking ||
  416.                          s->avctx->spatial_cplx_masking  ||
  417.                          s->avctx->p_masking      ||
  418.                          s->border_masking ||
  419.                          (s->mpv_flags & FF_MPV_FLAG_QP_RD)) &&
  420.                         !s->fixed_qscale;
  421.  
  422.     s->loop_filter = !!(s->avctx->flags & AV_CODEC_FLAG_LOOP_FILTER);
  423.  
  424.     if (avctx->rc_max_rate && !avctx->rc_buffer_size) {
  425.         switch(avctx->codec_id) {
  426.         case AV_CODEC_ID_MPEG1VIDEO:
  427.         case AV_CODEC_ID_MPEG2VIDEO:
  428.             avctx->rc_buffer_size = FFMAX(avctx->rc_max_rate, 15000000) * 112LL / 15000000 * 16384;
  429.             break;
  430.         case AV_CODEC_ID_MPEG4:
  431.         case AV_CODEC_ID_MSMPEG4V1:
  432.         case AV_CODEC_ID_MSMPEG4V2:
  433.         case AV_CODEC_ID_MSMPEG4V3:
  434.             if       (avctx->rc_max_rate >= 15000000) {
  435.                 avctx->rc_buffer_size = 320 + (avctx->rc_max_rate - 15000000LL) * (760-320) / (38400000 - 15000000);
  436.             } else if(avctx->rc_max_rate >=  2000000) {
  437.                 avctx->rc_buffer_size =  80 + (avctx->rc_max_rate -  2000000LL) * (320- 80) / (15000000 -  2000000);
  438.             } else if(avctx->rc_max_rate >=   384000) {
  439.                 avctx->rc_buffer_size =  40 + (avctx->rc_max_rate -   384000LL) * ( 80- 40) / ( 2000000 -   384000);
  440.             } else
  441.                 avctx->rc_buffer_size = 40;
  442.             avctx->rc_buffer_size *= 16384;
  443.             break;
  444.         }
  445.         if (avctx->rc_buffer_size) {
  446.             av_log(avctx, AV_LOG_INFO, "Automatically choosing VBV buffer size of %d kbyte\n", avctx->rc_buffer_size/8192);
  447.         }
  448.     }
  449.  
  450.     if ((!avctx->rc_max_rate) != (!avctx->rc_buffer_size)) {
  451.         av_log(avctx, AV_LOG_ERROR, "Either both buffer size and max rate or neither must be specified\n");
  452.         return -1;
  453.     }
  454.  
  455.     if (avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate) {
  456.         av_log(avctx, AV_LOG_INFO,
  457.                "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");
  458.     }
  459.  
  460.     if (avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate) {
  461.         av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");
  462.         return -1;
  463.     }
  464.  
  465.     if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {
  466.         av_log(avctx, AV_LOG_ERROR, "bitrate above max bitrate\n");
  467.         return -1;
  468.     }
  469.  
  470.     if (avctx->rc_max_rate &&
  471.         avctx->rc_max_rate == avctx->bit_rate &&
  472.         avctx->rc_max_rate != avctx->rc_min_rate) {
  473.         av_log(avctx, AV_LOG_INFO,
  474.                "impossible bitrate constraints, this will fail\n");
  475.     }
  476.  
  477.     if (avctx->rc_buffer_size &&
  478.         avctx->bit_rate * (int64_t)avctx->time_base.num >
  479.             avctx->rc_buffer_size * (int64_t)avctx->time_base.den) {
  480.         av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");
  481.         return -1;
  482.     }
  483.  
  484.     if (!s->fixed_qscale &&
  485.         avctx->bit_rate * av_q2d(avctx->time_base) >
  486.             avctx->bit_rate_tolerance) {
  487.         av_log(avctx, AV_LOG_WARNING,
  488.                "bitrate tolerance %d too small for bitrate %d, overriding\n", avctx->bit_rate_tolerance, avctx->bit_rate);
  489.         avctx->bit_rate_tolerance = 5 * avctx->bit_rate * av_q2d(avctx->time_base);
  490.     }
  491.  
  492.     if (s->avctx->rc_max_rate &&
  493.         s->avctx->rc_min_rate == s->avctx->rc_max_rate &&
  494.         (s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||
  495.          s->codec_id == AV_CODEC_ID_MPEG2VIDEO) &&
  496.         90000LL * (avctx->rc_buffer_size - 1) >
  497.             s->avctx->rc_max_rate * 0xFFFFLL) {
  498.         av_log(avctx, AV_LOG_INFO,
  499.                "Warning vbv_delay will be set to 0xFFFF (=VBR) as the "
  500.                "specified vbv buffer is too large for the given bitrate!\n");
  501.     }
  502.  
  503.     if ((s->avctx->flags & AV_CODEC_FLAG_4MV) && s->codec_id != AV_CODEC_ID_MPEG4 &&
  504.         s->codec_id != AV_CODEC_ID_H263 && s->codec_id != AV_CODEC_ID_H263P &&
  505.         s->codec_id != AV_CODEC_ID_FLV1) {
  506.         av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");
  507.         return -1;
  508.     }
  509.  
  510.     if (s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE) {
  511.         av_log(avctx, AV_LOG_ERROR,
  512.                "OBMC is only supported with simple mb decision\n");
  513.         return -1;
  514.     }
  515.  
  516.     if (s->quarter_sample && s->codec_id != AV_CODEC_ID_MPEG4) {
  517.         av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");
  518.         return -1;
  519.     }
  520.  
  521.     if (s->max_b_frames                    &&
  522.         s->codec_id != AV_CODEC_ID_MPEG4      &&
  523.         s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&
  524.         s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
  525.         av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");
  526.         return -1;
  527.     }
  528.     if (s->max_b_frames < 0) {
  529.         av_log(avctx, AV_LOG_ERROR,
  530.                "max b frames must be 0 or positive for mpegvideo based encoders\n");
  531.         return -1;
  532.     }
  533.  
  534.     if ((s->codec_id == AV_CODEC_ID_MPEG4 ||
  535.          s->codec_id == AV_CODEC_ID_H263  ||
  536.          s->codec_id == AV_CODEC_ID_H263P) &&
  537.         (avctx->sample_aspect_ratio.num > 255 ||
  538.          avctx->sample_aspect_ratio.den > 255)) {
  539.         av_log(avctx, AV_LOG_WARNING,
  540.                "Invalid pixel aspect ratio %i/%i, limit is 255/255 reducing\n",
  541.                avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);
  542.         av_reduce(&avctx->sample_aspect_ratio.num, &avctx->sample_aspect_ratio.den,
  543.                    avctx->sample_aspect_ratio.num,  avctx->sample_aspect_ratio.den, 255);
  544.     }
  545.  
  546.     if ((s->codec_id == AV_CODEC_ID_H263  ||
  547.          s->codec_id == AV_CODEC_ID_H263P) &&
  548.         (avctx->width  > 2048 ||
  549.          avctx->height > 1152 )) {
  550.         av_log(avctx, AV_LOG_ERROR, "H.263 does not support resolutions above 2048x1152\n");
  551.         return -1;
  552.     }
  553.     if ((s->codec_id == AV_CODEC_ID_H263  ||
  554.          s->codec_id == AV_CODEC_ID_H263P) &&
  555.         ((avctx->width &3) ||
  556.          (avctx->height&3) )) {
  557.         av_log(avctx, AV_LOG_ERROR, "w/h must be a multiple of 4\n");
  558.         return -1;
  559.     }
  560.  
  561.     if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO &&
  562.         (avctx->width  > 4095 ||
  563.          avctx->height > 4095 )) {
  564.         av_log(avctx, AV_LOG_ERROR, "MPEG-1 does not support resolutions above 4095x4095\n");
  565.         return -1;
  566.     }
  567.  
  568.     if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
  569.         (avctx->width  > 16383 ||
  570.          avctx->height > 16383 )) {
  571.         av_log(avctx, AV_LOG_ERROR, "MPEG-2 does not support resolutions above 16383x16383\n");
  572.         return -1;
  573.     }
  574.  
  575.     if (s->codec_id == AV_CODEC_ID_RV10 &&
  576.         (avctx->width &15 ||
  577.          avctx->height&15 )) {
  578.         av_log(avctx, AV_LOG_ERROR, "width and height must be a multiple of 16\n");
  579.         return AVERROR(EINVAL);
  580.     }
  581.  
  582.     if (s->codec_id == AV_CODEC_ID_RV20 &&
  583.         (avctx->width &3 ||
  584.          avctx->height&3 )) {
  585.         av_log(avctx, AV_LOG_ERROR, "width and height must be a multiple of 4\n");
  586.         return AVERROR(EINVAL);
  587.     }
  588.  
  589.     if ((s->codec_id == AV_CODEC_ID_WMV1 ||
  590.          s->codec_id == AV_CODEC_ID_WMV2) &&
  591.          avctx->width & 1) {
  592.          av_log(avctx, AV_LOG_ERROR, "width must be multiple of 2\n");
  593.          return -1;
  594.     }
  595.  
  596.     if ((s->avctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME)) &&
  597.         s->codec_id != AV_CODEC_ID_MPEG4 && s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
  598.         av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");
  599.         return -1;
  600.     }
  601.  
  602.     // FIXME mpeg2 uses that too
  603.     if (s->mpeg_quant && (   s->codec_id != AV_CODEC_ID_MPEG4
  604.                           && s->codec_id != AV_CODEC_ID_MPEG2VIDEO)) {
  605.         av_log(avctx, AV_LOG_ERROR,
  606.                "mpeg2 style quantization not supported by codec\n");
  607.         return -1;
  608.     }
  609.  
  610.     if ((s->mpv_flags & FF_MPV_FLAG_CBP_RD) && !avctx->trellis) {
  611.         av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");
  612.         return -1;
  613.     }
  614.  
  615.     if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) &&
  616.         s->avctx->mb_decision != FF_MB_DECISION_RD) {
  617.         av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");
  618.         return -1;
  619.     }
  620.  
  621.     if (s->avctx->scenechange_threshold < 1000000000 &&
  622.         (s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)) {
  623.         av_log(avctx, AV_LOG_ERROR,
  624.                "closed gop with scene change detection are not supported yet, "
  625.                "set threshold to 1000000000\n");
  626.         return -1;
  627.     }
  628.  
  629.     if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY) {
  630.         if (s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {
  631.             av_log(avctx, AV_LOG_ERROR,
  632.                   "low delay forcing is only available for mpeg2\n");
  633.             return -1;
  634.         }
  635.         if (s->max_b_frames != 0) {
  636.             av_log(avctx, AV_LOG_ERROR,
  637.                    "b frames cannot be used with low delay\n");
  638.             return -1;
  639.         }
  640.     }
  641.  
  642.     if (s->q_scale_type == 1) {
  643.         if (avctx->qmax > 28) {
  644.             av_log(avctx, AV_LOG_ERROR,
  645.                    "non linear quant only supports qmax <= 28 currently\n");
  646.             return -1;
  647.         }
  648.     }
  649.  
  650.     if (s->avctx->thread_count > 1         &&
  651.         s->codec_id != AV_CODEC_ID_MPEG4      &&
  652.         s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&
  653.         s->codec_id != AV_CODEC_ID_MPEG2VIDEO &&
  654.         s->codec_id != AV_CODEC_ID_MJPEG      &&
  655.         (s->codec_id != AV_CODEC_ID_H263P)) {
  656.         av_log(avctx, AV_LOG_ERROR,
  657.                "multi threaded encoding not supported by codec\n");
  658.         return -1;
  659.     }
  660.  
  661.     if (s->avctx->thread_count < 1) {
  662.         av_log(avctx, AV_LOG_ERROR,
  663.                "automatic thread number detection not supported by codec, "
  664.                "patch welcome\n");
  665.         return -1;
  666.     }
  667.  
  668.     if (s->avctx->slices > 1 || s->avctx->thread_count > 1)
  669.         s->rtp_mode = 1;
  670.  
  671.     if (s->avctx->thread_count > 1 && s->codec_id == AV_CODEC_ID_H263P)
  672.         s->h263_slice_structured = 1;
  673.  
  674.     if (!avctx->time_base.den || !avctx->time_base.num) {
  675.         av_log(avctx, AV_LOG_ERROR, "framerate not set\n");
  676.         return -1;
  677.     }
  678.  
  679.     if (avctx->b_frame_strategy && (avctx->flags & AV_CODEC_FLAG_PASS2)) {
  680.         av_log(avctx, AV_LOG_INFO,
  681.                "notice: b_frame_strategy only affects the first pass\n");
  682.         avctx->b_frame_strategy = 0;
  683.     }
  684.  
  685.     i = av_gcd(avctx->time_base.den, avctx->time_base.num);
  686.     if (i > 1) {
  687.         av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");
  688.         avctx->time_base.den /= i;
  689.         avctx->time_base.num /= i;
  690.         //return -1;
  691.     }
  692.  
  693.     if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG1VIDEO || s->codec_id == AV_CODEC_ID_MPEG2VIDEO || s->codec_id == AV_CODEC_ID_MJPEG || s->codec_id==AV_CODEC_ID_AMV) {
  694.         // (a + x * 3 / 8) / x
  695.         s->intra_quant_bias = 3 << (QUANT_BIAS_SHIFT - 3);
  696.         s->inter_quant_bias = 0;
  697.     } else {
  698.         s->intra_quant_bias = 0;
  699.         // (a - x / 4) / x
  700.         s->inter_quant_bias = -(1 << (QUANT_BIAS_SHIFT - 2));
  701.     }
  702.  
  703.     if (avctx->qmin > avctx->qmax || avctx->qmin <= 0) {
  704.         av_log(avctx, AV_LOG_ERROR, "qmin and or qmax are invalid, they must be 0 < min <= max\n");
  705.         return AVERROR(EINVAL);
  706.     }
  707.  
  708. #if FF_API_QUANT_BIAS
  709. FF_DISABLE_DEPRECATION_WARNINGS
  710.     if (s->intra_quant_bias == FF_DEFAULT_QUANT_BIAS &&
  711.         avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)
  712.         s->intra_quant_bias = avctx->intra_quant_bias;
  713.     if (s->inter_quant_bias == FF_DEFAULT_QUANT_BIAS &&
  714.         avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)
  715.         s->inter_quant_bias = avctx->inter_quant_bias;
  716. FF_ENABLE_DEPRECATION_WARNINGS
  717. #endif
  718.  
  719.     av_log(avctx, AV_LOG_DEBUG, "intra_quant_bias = %d inter_quant_bias = %d\n",s->intra_quant_bias,s->inter_quant_bias);
  720.  
  721.     if (avctx->codec_id == AV_CODEC_ID_MPEG4 &&
  722.         s->avctx->time_base.den > (1 << 16) - 1) {
  723.         av_log(avctx, AV_LOG_ERROR,
  724.                "timebase %d/%d not supported by MPEG 4 standard, "
  725.                "the maximum admitted value for the timebase denominator "
  726.                "is %d\n", s->avctx->time_base.num, s->avctx->time_base.den,
  727.                (1 << 16) - 1);
  728.         return -1;
  729.     }
  730.     s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;
  731.  
  732.     switch (avctx->codec->id) {
  733.     case AV_CODEC_ID_MPEG1VIDEO:
  734.         s->out_format = FMT_MPEG1;
  735.         s->low_delay  = !!(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY);
  736.         avctx->delay  = s->low_delay ? 0 : (s->max_b_frames + 1);
  737.         break;
  738.     case AV_CODEC_ID_MPEG2VIDEO:
  739.         s->out_format = FMT_MPEG1;
  740.         s->low_delay  = !!(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY);
  741.         avctx->delay  = s->low_delay ? 0 : (s->max_b_frames + 1);
  742.         s->rtp_mode   = 1;
  743.         break;
  744.     case AV_CODEC_ID_MJPEG:
  745.     case AV_CODEC_ID_AMV:
  746.         s->out_format = FMT_MJPEG;
  747.         s->intra_only = 1; /* force intra only for jpeg */
  748.         if (!CONFIG_MJPEG_ENCODER ||
  749.             ff_mjpeg_encode_init(s) < 0)
  750.             return -1;
  751.         avctx->delay = 0;
  752.         s->low_delay = 1;
  753.         break;
  754.     case AV_CODEC_ID_H261:
  755.         if (!CONFIG_H261_ENCODER)
  756.             return -1;
  757.         if (ff_h261_get_picture_format(s->width, s->height) < 0) {
  758.             av_log(avctx, AV_LOG_ERROR,
  759.                    "The specified picture size of %dx%d is not valid for the "
  760.                    "H.261 codec.\nValid sizes are 176x144, 352x288\n",
  761.                     s->width, s->height);
  762.             return -1;
  763.         }
  764.         s->out_format = FMT_H261;
  765.         avctx->delay  = 0;
  766.         s->low_delay  = 1;
  767.         s->rtp_mode   = 0; /* Sliced encoding not supported */
  768.         break;
  769.     case AV_CODEC_ID_H263:
  770.         if (!CONFIG_H263_ENCODER)
  771.             return -1;
  772.         if (ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format),
  773.                              s->width, s->height) == 8) {
  774.             av_log(avctx, AV_LOG_ERROR,
  775.                    "The specified picture size of %dx%d is not valid for "
  776.                    "the H.263 codec.\nValid sizes are 128x96, 176x144, "
  777.                    "352x288, 704x576, and 1408x1152. "
  778.                    "Try H.263+.\n", s->width, s->height);
  779.             return -1;
  780.         }
  781.         s->out_format = FMT_H263;
  782.         avctx->delay  = 0;
  783.         s->low_delay  = 1;
  784.         break;
  785.     case AV_CODEC_ID_H263P:
  786.         s->out_format = FMT_H263;
  787.         s->h263_plus  = 1;
  788.         /* Fx */
  789.         s->h263_aic        = (avctx->flags & AV_CODEC_FLAG_AC_PRED) ? 1 : 0;
  790.         s->modified_quant  = s->h263_aic;
  791.         s->loop_filter     = (avctx->flags & AV_CODEC_FLAG_LOOP_FILTER) ? 1 : 0;
  792.         s->unrestricted_mv = s->obmc || s->loop_filter || s->umvplus;
  793.  
  794.         /* /Fx */
  795.         /* These are just to be sure */
  796.         avctx->delay = 0;
  797.         s->low_delay = 1;
  798.         break;
  799.     case AV_CODEC_ID_FLV1:
  800.         s->out_format      = FMT_H263;
  801.         s->h263_flv        = 2; /* format = 1; 11-bit codes */
  802.         s->unrestricted_mv = 1;
  803.         s->rtp_mode  = 0; /* don't allow GOB */
  804.         avctx->delay = 0;
  805.         s->low_delay = 1;
  806.         break;
  807.     case AV_CODEC_ID_RV10:
  808.         s->out_format = FMT_H263;
  809.         avctx->delay  = 0;
  810.         s->low_delay  = 1;
  811.         break;
  812.     case AV_CODEC_ID_RV20:
  813.         s->out_format      = FMT_H263;
  814.         avctx->delay       = 0;
  815.         s->low_delay       = 1;
  816.         s->modified_quant  = 1;
  817.         s->h263_aic        = 1;
  818.         s->h263_plus       = 1;
  819.         s->loop_filter     = 1;
  820.         s->unrestricted_mv = 0;
  821.         break;
  822.     case AV_CODEC_ID_MPEG4:
  823.         s->out_format      = FMT_H263;
  824.         s->h263_pred       = 1;
  825.         s->unrestricted_mv = 1;
  826.         s->low_delay       = s->max_b_frames ? 0 : 1;
  827.         avctx->delay       = s->low_delay ? 0 : (s->max_b_frames + 1);
  828.         break;
  829.     case AV_CODEC_ID_MSMPEG4V2:
  830.         s->out_format      = FMT_H263;
  831.         s->h263_pred       = 1;
  832.         s->unrestricted_mv = 1;
  833.         s->msmpeg4_version = 2;
  834.         avctx->delay       = 0;
  835.         s->low_delay       = 1;
  836.         break;
  837.     case AV_CODEC_ID_MSMPEG4V3:
  838.         s->out_format        = FMT_H263;
  839.         s->h263_pred         = 1;
  840.         s->unrestricted_mv   = 1;
  841.         s->msmpeg4_version   = 3;
  842.         s->flipflop_rounding = 1;
  843.         avctx->delay         = 0;
  844.         s->low_delay         = 1;
  845.         break;
  846.     case AV_CODEC_ID_WMV1:
  847.         s->out_format        = FMT_H263;
  848.         s->h263_pred         = 1;
  849.         s->unrestricted_mv   = 1;
  850.         s->msmpeg4_version   = 4;
  851.         s->flipflop_rounding = 1;
  852.         avctx->delay         = 0;
  853.         s->low_delay         = 1;
  854.         break;
  855.     case AV_CODEC_ID_WMV2:
  856.         s->out_format        = FMT_H263;
  857.         s->h263_pred         = 1;
  858.         s->unrestricted_mv   = 1;
  859.         s->msmpeg4_version   = 5;
  860.         s->flipflop_rounding = 1;
  861.         avctx->delay         = 0;
  862.         s->low_delay         = 1;
  863.         break;
  864.     default:
  865.         return -1;
  866.     }
  867.  
  868.     avctx->has_b_frames = !s->low_delay;
  869.  
  870.     s->encoding = 1;
  871.  
  872.     s->progressive_frame    =
  873.     s->progressive_sequence = !(avctx->flags & (AV_CODEC_FLAG_INTERLACED_DCT |
  874.                                                 AV_CODEC_FLAG_INTERLACED_ME) ||
  875.                                 s->alternate_scan);
  876.  
  877.     /* init */
  878.     ff_mpv_idct_init(s);
  879.     if (ff_mpv_common_init(s) < 0)
  880.         return -1;
  881.  
  882.     ff_fdctdsp_init(&s->fdsp, avctx);
  883.     ff_me_cmp_init(&s->mecc, avctx);
  884.     ff_mpegvideoencdsp_init(&s->mpvencdsp, avctx);
  885.     ff_pixblockdsp_init(&s->pdsp, avctx);
  886.     ff_qpeldsp_init(&s->qdsp);
  887.  
  888.     if (s->msmpeg4_version) {
  889.         FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_stats,
  890.                           2 * 2 * (MAX_LEVEL + 1) *
  891.                           (MAX_RUN + 1) * 2 * sizeof(int), fail);
  892.     }
  893.     FF_ALLOCZ_OR_GOTO(s->avctx, s->avctx->stats_out, 256, fail);
  894.  
  895.     FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix,   64 * 32 * sizeof(int), fail);
  896.     FF_ALLOCZ_OR_GOTO(s->avctx, s->q_chroma_intra_matrix, 64 * 32 * sizeof(int), fail);
  897.     FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix,   64 * 32 * sizeof(int), fail);
  898.     FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);
  899.     FF_ALLOCZ_OR_GOTO(s->avctx, s->q_chroma_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);
  900.     FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);
  901.     FF_ALLOCZ_OR_GOTO(s->avctx, s->input_picture,
  902.                       MAX_PICTURE_COUNT * sizeof(Picture *), fail);
  903.     FF_ALLOCZ_OR_GOTO(s->avctx, s->reordered_input_picture,
  904.                       MAX_PICTURE_COUNT * sizeof(Picture *), fail);
  905.  
  906.     if (s->avctx->noise_reduction) {
  907.         FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_offset,
  908.                           2 * 64 * sizeof(uint16_t), fail);
  909.     }
  910.  
  911.     ff_dct_encode_init(s);
  912.  
  913.     if ((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)
  914.         s->chroma_qscale_table = ff_h263_chroma_qscale_table;
  915.  
  916.     s->quant_precision = 5;
  917.  
  918.     ff_set_cmp(&s->mecc, s->mecc.ildct_cmp,      s->avctx->ildct_cmp);
  919.     ff_set_cmp(&s->mecc, s->mecc.frame_skip_cmp, s->avctx->frame_skip_cmp);
  920.  
  921.     if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)
  922.         ff_h261_encode_init(s);
  923.     if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  924.         ff_h263_encode_init(s);
  925.     if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  926.         if ((ret = ff_msmpeg4_encode_init(s)) < 0)
  927.             return ret;
  928.     if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  929.         && s->out_format == FMT_MPEG1)
  930.         ff_mpeg1_encode_init(s);
  931.  
  932.     /* init q matrix */
  933.     for (i = 0; i < 64; i++) {
  934.         int j = s->idsp.idct_permutation[i];
  935.         if (CONFIG_MPEG4_ENCODER && s->codec_id == AV_CODEC_ID_MPEG4 &&
  936.             s->mpeg_quant) {
  937.             s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];
  938.             s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];
  939.         } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
  940.             s->intra_matrix[j] =
  941.             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  942.         } else {
  943.             /* mpeg1/2 */
  944.             s->chroma_intra_matrix[j] =
  945.             s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];
  946.             s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];
  947.         }
  948.         if (s->avctx->intra_matrix)
  949.             s->intra_matrix[j] = s->avctx->intra_matrix[i];
  950.         if (s->avctx->inter_matrix)
  951.             s->inter_matrix[j] = s->avctx->inter_matrix[i];
  952.     }
  953.  
  954.     /* precompute matrix */
  955.     /* for mjpeg, we do include qscale in the matrix */
  956.     if (s->out_format != FMT_MJPEG) {
  957.         ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,
  958.                           s->intra_matrix, s->intra_quant_bias, avctx->qmin,
  959.                           31, 1);
  960.         ff_convert_matrix(s, s->q_inter_matrix, s->q_inter_matrix16,
  961.                           s->inter_matrix, s->inter_quant_bias, avctx->qmin,
  962.                           31, 0);
  963.     }
  964.  
  965.     if (ff_rate_control_init(s) < 0)
  966.         return -1;
  967.  
  968. #if FF_API_ERROR_RATE
  969.     FF_DISABLE_DEPRECATION_WARNINGS
  970.     if (avctx->error_rate)
  971.         s->error_rate = avctx->error_rate;
  972.     FF_ENABLE_DEPRECATION_WARNINGS;
  973. #endif
  974.  
  975. #if FF_API_NORMALIZE_AQP
  976.     FF_DISABLE_DEPRECATION_WARNINGS
  977.     if (avctx->flags & CODEC_FLAG_NORMALIZE_AQP)
  978.         s->mpv_flags |= FF_MPV_FLAG_NAQ;
  979.     FF_ENABLE_DEPRECATION_WARNINGS;
  980. #endif
  981.  
  982. #if FF_API_MV0
  983.     FF_DISABLE_DEPRECATION_WARNINGS
  984.     if (avctx->flags & CODEC_FLAG_MV0)
  985.         s->mpv_flags |= FF_MPV_FLAG_MV0;
  986.     FF_ENABLE_DEPRECATION_WARNINGS
  987. #endif
  988.  
  989. #if FF_API_MPV_OPT
  990.     FF_DISABLE_DEPRECATION_WARNINGS
  991.     if (avctx->rc_qsquish != 0.0)
  992.         s->rc_qsquish = avctx->rc_qsquish;
  993.     if (avctx->rc_qmod_amp != 0.0)
  994.         s->rc_qmod_amp = avctx->rc_qmod_amp;
  995.     if (avctx->rc_qmod_freq)
  996.         s->rc_qmod_freq = avctx->rc_qmod_freq;
  997.     if (avctx->rc_buffer_aggressivity != 1.0)
  998.         s->rc_buffer_aggressivity = avctx->rc_buffer_aggressivity;
  999.     if (avctx->rc_initial_cplx != 0.0)
  1000.         s->rc_initial_cplx = avctx->rc_initial_cplx;
  1001.     if (avctx->lmin)
  1002.         s->lmin = avctx->lmin;
  1003.     if (avctx->lmax)
  1004.         s->lmax = avctx->lmax;
  1005.  
  1006.     if (avctx->rc_eq) {
  1007.         av_freep(&s->rc_eq);
  1008.         s->rc_eq = av_strdup(avctx->rc_eq);
  1009.         if (!s->rc_eq)
  1010.             return AVERROR(ENOMEM);
  1011.     }
  1012.     FF_ENABLE_DEPRECATION_WARNINGS
  1013. #endif
  1014.  
  1015.     if (avctx->b_frame_strategy == 2) {
  1016.         for (i = 0; i < s->max_b_frames + 2; i++) {
  1017.             s->tmp_frames[i] = av_frame_alloc();
  1018.             if (!s->tmp_frames[i])
  1019.                 return AVERROR(ENOMEM);
  1020.  
  1021.             s->tmp_frames[i]->format = AV_PIX_FMT_YUV420P;
  1022.             s->tmp_frames[i]->width  = s->width  >> avctx->brd_scale;
  1023.             s->tmp_frames[i]->height = s->height >> avctx->brd_scale;
  1024.  
  1025.             ret = av_frame_get_buffer(s->tmp_frames[i], 32);
  1026.             if (ret < 0)
  1027.                 return ret;
  1028.         }
  1029.     }
  1030.  
  1031.     return 0;
  1032. fail:
  1033.     ff_mpv_encode_end(avctx);
  1034.     return AVERROR_UNKNOWN;
  1035. }
  1036.  
  1037. av_cold int ff_mpv_encode_end(AVCodecContext *avctx)
  1038. {
  1039.     MpegEncContext *s = avctx->priv_data;
  1040.     int i;
  1041.  
  1042.     ff_rate_control_uninit(s);
  1043.  
  1044.     ff_mpv_common_end(s);
  1045.     if (CONFIG_MJPEG_ENCODER &&
  1046.         s->out_format == FMT_MJPEG)
  1047.         ff_mjpeg_encode_close(s);
  1048.  
  1049.     av_freep(&avctx->extradata);
  1050.  
  1051.     for (i = 0; i < FF_ARRAY_ELEMS(s->tmp_frames); i++)
  1052.         av_frame_free(&s->tmp_frames[i]);
  1053.  
  1054.     ff_free_picture_tables(&s->new_picture);
  1055.     ff_mpeg_unref_picture(s->avctx, &s->new_picture);
  1056.  
  1057.     av_freep(&s->avctx->stats_out);
  1058.     av_freep(&s->ac_stats);
  1059.  
  1060.     if(s->q_chroma_intra_matrix   != s->q_intra_matrix  ) av_freep(&s->q_chroma_intra_matrix);
  1061.     if(s->q_chroma_intra_matrix16 != s->q_intra_matrix16) av_freep(&s->q_chroma_intra_matrix16);
  1062.     s->q_chroma_intra_matrix=   NULL;
  1063.     s->q_chroma_intra_matrix16= NULL;
  1064.     av_freep(&s->q_intra_matrix);
  1065.     av_freep(&s->q_inter_matrix);
  1066.     av_freep(&s->q_intra_matrix16);
  1067.     av_freep(&s->q_inter_matrix16);
  1068.     av_freep(&s->input_picture);
  1069.     av_freep(&s->reordered_input_picture);
  1070.     av_freep(&s->dct_offset);
  1071.  
  1072.     return 0;
  1073. }
  1074.  
  1075. static int get_sae(uint8_t *src, int ref, int stride)
  1076. {
  1077.     int x,y;
  1078.     int acc = 0;
  1079.  
  1080.     for (y = 0; y < 16; y++) {
  1081.         for (x = 0; x < 16; x++) {
  1082.             acc += FFABS(src[x + y * stride] - ref);
  1083.         }
  1084.     }
  1085.  
  1086.     return acc;
  1087. }
  1088.  
  1089. static int get_intra_count(MpegEncContext *s, uint8_t *src,
  1090.                            uint8_t *ref, int stride)
  1091. {
  1092.     int x, y, w, h;
  1093.     int acc = 0;
  1094.  
  1095.     w = s->width  & ~15;
  1096.     h = s->height & ~15;
  1097.  
  1098.     for (y = 0; y < h; y += 16) {
  1099.         for (x = 0; x < w; x += 16) {
  1100.             int offset = x + y * stride;
  1101.             int sad  = s->mecc.sad[0](NULL, src + offset, ref + offset,
  1102.                                       stride, 16);
  1103.             int mean = (s->mpvencdsp.pix_sum(src + offset, stride) + 128) >> 8;
  1104.             int sae  = get_sae(src + offset, mean, stride);
  1105.  
  1106.             acc += sae + 500 < sad;
  1107.         }
  1108.     }
  1109.     return acc;
  1110. }
  1111.  
  1112. static int alloc_picture(MpegEncContext *s, Picture *pic, int shared)
  1113. {
  1114.     return ff_alloc_picture(s->avctx, pic, &s->me, &s->sc, shared, 1,
  1115.                             s->chroma_x_shift, s->chroma_y_shift, s->out_format,
  1116.                             s->mb_stride, s->mb_width, s->mb_height, s->b8_stride,
  1117.                             &s->linesize, &s->uvlinesize);
  1118. }
  1119.  
  1120. static int load_input_picture(MpegEncContext *s, const AVFrame *pic_arg)
  1121. {
  1122.     Picture *pic = NULL;
  1123.     int64_t pts;
  1124.     int i, display_picture_number = 0, ret;
  1125.     const int encoding_delay = s->max_b_frames ? s->max_b_frames :
  1126.                                                  (s->low_delay ? 0 : 1);
  1127.     int direct = 1;
  1128.  
  1129.     if (pic_arg) {
  1130.         pts = pic_arg->pts;
  1131.         display_picture_number = s->input_picture_number++;
  1132.  
  1133.         if (pts != AV_NOPTS_VALUE) {
  1134.             if (s->user_specified_pts != AV_NOPTS_VALUE) {
  1135.                 int64_t last = s->user_specified_pts;
  1136.  
  1137.                 if (pts <= last) {
  1138.                     av_log(s->avctx, AV_LOG_ERROR,
  1139.                            "Invalid pts (%"PRId64") <= last (%"PRId64")\n",
  1140.                            pts, last);
  1141.                     return AVERROR(EINVAL);
  1142.                 }
  1143.  
  1144.                 if (!s->low_delay && display_picture_number == 1)
  1145.                     s->dts_delta = pts - last;
  1146.             }
  1147.             s->user_specified_pts = pts;
  1148.         } else {
  1149.             if (s->user_specified_pts != AV_NOPTS_VALUE) {
  1150.                 s->user_specified_pts =
  1151.                 pts = s->user_specified_pts + 1;
  1152.                 av_log(s->avctx, AV_LOG_INFO,
  1153.                        "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n",
  1154.                        pts);
  1155.             } else {
  1156.                 pts = display_picture_number;
  1157.             }
  1158.         }
  1159.     }
  1160.  
  1161.     if (pic_arg) {
  1162.         if (!pic_arg->buf[0] ||
  1163.             pic_arg->linesize[0] != s->linesize ||
  1164.             pic_arg->linesize[1] != s->uvlinesize ||
  1165.             pic_arg->linesize[2] != s->uvlinesize)
  1166.             direct = 0;
  1167.         if ((s->width & 15) || (s->height & 15))
  1168.             direct = 0;
  1169.         if (((intptr_t)(pic_arg->data[0])) & (STRIDE_ALIGN-1))
  1170.             direct = 0;
  1171.         if (s->linesize & (STRIDE_ALIGN-1))
  1172.             direct = 0;
  1173.  
  1174.         ff_dlog(s->avctx, "%d %d %"PTRDIFF_SPECIFIER" %"PTRDIFF_SPECIFIER"\n", pic_arg->linesize[0],
  1175.                 pic_arg->linesize[1], s->linesize, s->uvlinesize);
  1176.  
  1177.         i = ff_find_unused_picture(s->avctx, s->picture, direct);
  1178.         if (i < 0)
  1179.             return i;
  1180.  
  1181.         pic = &s->picture[i];
  1182.         pic->reference = 3;
  1183.  
  1184.         if (direct) {
  1185.             if ((ret = av_frame_ref(pic->f, pic_arg)) < 0)
  1186.                 return ret;
  1187.         }
  1188.         ret = alloc_picture(s, pic, direct);
  1189.         if (ret < 0)
  1190.             return ret;
  1191.  
  1192.         if (!direct) {
  1193.             if (pic->f->data[0] + INPLACE_OFFSET == pic_arg->data[0] &&
  1194.                 pic->f->data[1] + INPLACE_OFFSET == pic_arg->data[1] &&
  1195.                 pic->f->data[2] + INPLACE_OFFSET == pic_arg->data[2]) {
  1196.                 // empty
  1197.             } else {
  1198.                 int h_chroma_shift, v_chroma_shift;
  1199.                 av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,
  1200.                                                  &h_chroma_shift,
  1201.                                                  &v_chroma_shift);
  1202.  
  1203.                 for (i = 0; i < 3; i++) {
  1204.                     int src_stride = pic_arg->linesize[i];
  1205.                     int dst_stride = i ? s->uvlinesize : s->linesize;
  1206.                     int h_shift = i ? h_chroma_shift : 0;
  1207.                     int v_shift = i ? v_chroma_shift : 0;
  1208.                     int w = s->width  >> h_shift;
  1209.                     int h = s->height >> v_shift;
  1210.                     uint8_t *src = pic_arg->data[i];
  1211.                     uint8_t *dst = pic->f->data[i];
  1212.                     int vpad = 16;
  1213.  
  1214.                     if (   s->codec_id == AV_CODEC_ID_MPEG2VIDEO
  1215.                         && !s->progressive_sequence
  1216.                         && FFALIGN(s->height, 32) - s->height > 16)
  1217.                         vpad = 32;
  1218.  
  1219.                     if (!s->avctx->rc_buffer_size)
  1220.                         dst += INPLACE_OFFSET;
  1221.  
  1222.                     if (src_stride == dst_stride)
  1223.                         memcpy(dst, src, src_stride * h);
  1224.                     else {
  1225.                         int h2 = h;
  1226.                         uint8_t *dst2 = dst;
  1227.                         while (h2--) {
  1228.                             memcpy(dst2, src, w);
  1229.                             dst2 += dst_stride;
  1230.                             src += src_stride;
  1231.                         }
  1232.                     }
  1233.                     if ((s->width & 15) || (s->height & (vpad-1))) {
  1234.                         s->mpvencdsp.draw_edges(dst, dst_stride,
  1235.                                                 w, h,
  1236.                                                 16 >> h_shift,
  1237.                                                 vpad >> v_shift,
  1238.                                                 EDGE_BOTTOM);
  1239.                     }
  1240.                 }
  1241.             }
  1242.         }
  1243.         ret = av_frame_copy_props(pic->f, pic_arg);
  1244.         if (ret < 0)
  1245.             return ret;
  1246.  
  1247.         pic->f->display_picture_number = display_picture_number;
  1248.         pic->f->pts = pts; // we set this here to avoid modifiying pic_arg
  1249.     }
  1250.  
  1251.     /* shift buffer entries */
  1252.     for (i = 1; i < MAX_PICTURE_COUNT /*s->encoding_delay + 1*/; i++)
  1253.         s->input_picture[i - 1] = s->input_picture[i];
  1254.  
  1255.     s->input_picture[encoding_delay] = (Picture*) pic;
  1256.  
  1257.     return 0;
  1258. }
  1259.  
  1260. static int skip_check(MpegEncContext *s, Picture *p, Picture *ref)
  1261. {
  1262.     int x, y, plane;
  1263.     int score = 0;
  1264.     int64_t score64 = 0;
  1265.  
  1266.     for (plane = 0; plane < 3; plane++) {
  1267.         const int stride = p->f->linesize[plane];
  1268.         const int bw = plane ? 1 : 2;
  1269.         for (y = 0; y < s->mb_height * bw; y++) {
  1270.             for (x = 0; x < s->mb_width * bw; x++) {
  1271.                 int off = p->shared ? 0 : 16;
  1272.                 uint8_t *dptr = p->f->data[plane] + 8 * (x + y * stride) + off;
  1273.                 uint8_t *rptr = ref->f->data[plane] + 8 * (x + y * stride);
  1274.                 int v = s->mecc.frame_skip_cmp[1](s, dptr, rptr, stride, 8);
  1275.  
  1276.                 switch (FFABS(s->avctx->frame_skip_exp)) {
  1277.                 case 0: score    =  FFMAX(score, v);          break;
  1278.                 case 1: score   += FFABS(v);                  break;
  1279.                 case 2: score64 += v * (int64_t)v;                       break;
  1280.                 case 3: score64 += FFABS(v * (int64_t)v * v);            break;
  1281.                 case 4: score64 += (v * (int64_t)v) * (v * (int64_t)v);  break;
  1282.                 }
  1283.             }
  1284.         }
  1285.     }
  1286.     emms_c();
  1287.  
  1288.     if (score)
  1289.         score64 = score;
  1290.     if (s->avctx->frame_skip_exp < 0)
  1291.         score64 = pow(score64 / (double)(s->mb_width * s->mb_height),
  1292.                       -1.0/s->avctx->frame_skip_exp);
  1293.  
  1294.     if (score64 < s->avctx->frame_skip_threshold)
  1295.         return 1;
  1296.     if (score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda) >> 8))
  1297.         return 1;
  1298.     return 0;
  1299. }
  1300.  
  1301. static int encode_frame(AVCodecContext *c, AVFrame *frame)
  1302. {
  1303.     AVPacket pkt = { 0 };
  1304.     int ret, got_output;
  1305.  
  1306.     av_init_packet(&pkt);
  1307.     ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
  1308.     if (ret < 0)
  1309.         return ret;
  1310.  
  1311.     ret = pkt.size;
  1312.     av_free_packet(&pkt);
  1313.     return ret;
  1314. }
  1315.  
  1316. static int estimate_best_b_count(MpegEncContext *s)
  1317. {
  1318.     AVCodec *codec    = avcodec_find_encoder(s->avctx->codec_id);
  1319.     AVCodecContext *c = avcodec_alloc_context3(NULL);
  1320.     const int scale = s->avctx->brd_scale;
  1321.     int i, j, out_size, p_lambda, b_lambda, lambda2;
  1322.     int64_t best_rd  = INT64_MAX;
  1323.     int best_b_count = -1;
  1324.  
  1325.     if (!c)
  1326.         return AVERROR(ENOMEM);
  1327.     av_assert0(scale >= 0 && scale <= 3);
  1328.  
  1329.     //emms_c();
  1330.     //s->next_picture_ptr->quality;
  1331.     p_lambda = s->last_lambda_for[AV_PICTURE_TYPE_P];
  1332.     //p_lambda * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;
  1333.     b_lambda = s->last_lambda_for[AV_PICTURE_TYPE_B];
  1334.     if (!b_lambda) // FIXME we should do this somewhere else
  1335.         b_lambda = p_lambda;
  1336.     lambda2  = (b_lambda * b_lambda + (1 << FF_LAMBDA_SHIFT) / 2) >>
  1337.                FF_LAMBDA_SHIFT;
  1338.  
  1339.     c->width        = s->width  >> scale;
  1340.     c->height       = s->height >> scale;
  1341.     c->flags        = AV_CODEC_FLAG_QSCALE | AV_CODEC_FLAG_PSNR;
  1342.     c->flags       |= s->avctx->flags & AV_CODEC_FLAG_QPEL;
  1343.     c->mb_decision  = s->avctx->mb_decision;
  1344.     c->me_cmp       = s->avctx->me_cmp;
  1345.     c->mb_cmp       = s->avctx->mb_cmp;
  1346.     c->me_sub_cmp   = s->avctx->me_sub_cmp;
  1347.     c->pix_fmt      = AV_PIX_FMT_YUV420P;
  1348.     c->time_base    = s->avctx->time_base;
  1349.     c->max_b_frames = s->max_b_frames;
  1350.  
  1351.     if (avcodec_open2(c, codec, NULL) < 0)
  1352.         return -1;
  1353.  
  1354.     for (i = 0; i < s->max_b_frames + 2; i++) {
  1355.         Picture pre_input, *pre_input_ptr = i ? s->input_picture[i - 1] :
  1356.                                                 s->next_picture_ptr;
  1357.         uint8_t *data[4];
  1358.  
  1359.         if (pre_input_ptr && (!i || s->input_picture[i - 1])) {
  1360.             pre_input = *pre_input_ptr;
  1361.             memcpy(data, pre_input_ptr->f->data, sizeof(data));
  1362.  
  1363.             if (!pre_input.shared && i) {
  1364.                 data[0] += INPLACE_OFFSET;
  1365.                 data[1] += INPLACE_OFFSET;
  1366.                 data[2] += INPLACE_OFFSET;
  1367.             }
  1368.  
  1369.             s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[0],
  1370.                                        s->tmp_frames[i]->linesize[0],
  1371.                                        data[0],
  1372.                                        pre_input.f->linesize[0],
  1373.                                        c->width, c->height);
  1374.             s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[1],
  1375.                                        s->tmp_frames[i]->linesize[1],
  1376.                                        data[1],
  1377.                                        pre_input.f->linesize[1],
  1378.                                        c->width >> 1, c->height >> 1);
  1379.             s->mpvencdsp.shrink[scale](s->tmp_frames[i]->data[2],
  1380.                                        s->tmp_frames[i]->linesize[2],
  1381.                                        data[2],
  1382.                                        pre_input.f->linesize[2],
  1383.                                        c->width >> 1, c->height >> 1);
  1384.         }
  1385.     }
  1386.  
  1387.     for (j = 0; j < s->max_b_frames + 1; j++) {
  1388.         int64_t rd = 0;
  1389.  
  1390.         if (!s->input_picture[j])
  1391.             break;
  1392.  
  1393.         c->error[0] = c->error[1] = c->error[2] = 0;
  1394.  
  1395.         s->tmp_frames[0]->pict_type = AV_PICTURE_TYPE_I;
  1396.         s->tmp_frames[0]->quality   = 1 * FF_QP2LAMBDA;
  1397.  
  1398.         out_size = encode_frame(c, s->tmp_frames[0]);
  1399.  
  1400.         //rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;
  1401.  
  1402.         for (i = 0; i < s->max_b_frames + 1; i++) {
  1403.             int is_p = i % (j + 1) == j || i == s->max_b_frames;
  1404.  
  1405.             s->tmp_frames[i + 1]->pict_type = is_p ?
  1406.                                      AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;
  1407.             s->tmp_frames[i + 1]->quality   = is_p ? p_lambda : b_lambda;
  1408.  
  1409.             out_size = encode_frame(c, s->tmp_frames[i + 1]);
  1410.  
  1411.             rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  1412.         }
  1413.  
  1414.         /* get the delayed frames */
  1415.         while (out_size) {
  1416.             out_size = encode_frame(c, NULL);
  1417.             rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);
  1418.         }
  1419.  
  1420.         rd += c->error[0] + c->error[1] + c->error[2];
  1421.  
  1422.         if (rd < best_rd) {
  1423.             best_rd = rd;
  1424.             best_b_count = j;
  1425.         }
  1426.     }
  1427.  
  1428.     avcodec_close(c);
  1429.     av_freep(&c);
  1430.  
  1431.     return best_b_count;
  1432. }
  1433.  
  1434. static int select_input_picture(MpegEncContext *s)
  1435. {
  1436.     int i, ret;
  1437.  
  1438.     for (i = 1; i < MAX_PICTURE_COUNT; i++)
  1439.         s->reordered_input_picture[i - 1] = s->reordered_input_picture[i];
  1440.     s->reordered_input_picture[MAX_PICTURE_COUNT - 1] = NULL;
  1441.  
  1442.     /* set next picture type & ordering */
  1443.     if (!s->reordered_input_picture[0] && s->input_picture[0]) {
  1444.         if (s->avctx->frame_skip_threshold || s->avctx->frame_skip_factor) {
  1445.             if (s->picture_in_gop_number < s->gop_size &&
  1446.                 s->next_picture_ptr &&
  1447.                 skip_check(s, s->input_picture[0], s->next_picture_ptr)) {
  1448.                 // FIXME check that te gop check above is +-1 correct
  1449.                 av_frame_unref(s->input_picture[0]->f);
  1450.  
  1451.                 ff_vbv_update(s, 0);
  1452.  
  1453.                 goto no_output_pic;
  1454.             }
  1455.         }
  1456.  
  1457.         if (/*s->picture_in_gop_number >= s->gop_size ||*/
  1458.             !s->next_picture_ptr || s->intra_only) {
  1459.             s->reordered_input_picture[0] = s->input_picture[0];
  1460.             s->reordered_input_picture[0]->f->pict_type = AV_PICTURE_TYPE_I;
  1461.             s->reordered_input_picture[0]->f->coded_picture_number =
  1462.                 s->coded_picture_number++;
  1463.         } else {
  1464.             int b_frames;
  1465.  
  1466.             if (s->avctx->flags & AV_CODEC_FLAG_PASS2) {
  1467.                 for (i = 0; i < s->max_b_frames + 1; i++) {
  1468.                     int pict_num = s->input_picture[0]->f->display_picture_number + i;
  1469.  
  1470.                     if (pict_num >= s->rc_context.num_entries)
  1471.                         break;
  1472.                     if (!s->input_picture[i]) {
  1473.                         s->rc_context.entry[pict_num - 1].new_pict_type = AV_PICTURE_TYPE_P;
  1474.                         break;
  1475.                     }
  1476.  
  1477.                     s->input_picture[i]->f->pict_type =
  1478.                         s->rc_context.entry[pict_num].new_pict_type;
  1479.                 }
  1480.             }
  1481.  
  1482.             if (s->avctx->b_frame_strategy == 0) {
  1483.                 b_frames = s->max_b_frames;
  1484.                 while (b_frames && !s->input_picture[b_frames])
  1485.                     b_frames--;
  1486.             } else if (s->avctx->b_frame_strategy == 1) {
  1487.                 for (i = 1; i < s->max_b_frames + 1; i++) {
  1488.                     if (s->input_picture[i] &&
  1489.                         s->input_picture[i]->b_frame_score == 0) {
  1490.                         s->input_picture[i]->b_frame_score =
  1491.                             get_intra_count(s,
  1492.                                             s->input_picture[i    ]->f->data[0],
  1493.                                             s->input_picture[i - 1]->f->data[0],
  1494.                                             s->linesize) + 1;
  1495.                     }
  1496.                 }
  1497.                 for (i = 0; i < s->max_b_frames + 1; i++) {
  1498.                     if (!s->input_picture[i] ||
  1499.                         s->input_picture[i]->b_frame_score - 1 >
  1500.                             s->mb_num / s->avctx->b_sensitivity)
  1501.                         break;
  1502.                 }
  1503.  
  1504.                 b_frames = FFMAX(0, i - 1);
  1505.  
  1506.                 /* reset scores */
  1507.                 for (i = 0; i < b_frames + 1; i++) {
  1508.                     s->input_picture[i]->b_frame_score = 0;
  1509.                 }
  1510.             } else if (s->avctx->b_frame_strategy == 2) {
  1511.                 b_frames = estimate_best_b_count(s);
  1512.             } else {
  1513.                 av_log(s->avctx, AV_LOG_ERROR, "illegal b frame strategy\n");
  1514.                 b_frames = 0;
  1515.             }
  1516.  
  1517.             emms_c();
  1518.  
  1519.             for (i = b_frames - 1; i >= 0; i--) {
  1520.                 int type = s->input_picture[i]->f->pict_type;
  1521.                 if (type && type != AV_PICTURE_TYPE_B)
  1522.                     b_frames = i;
  1523.             }
  1524.             if (s->input_picture[b_frames]->f->pict_type == AV_PICTURE_TYPE_B &&
  1525.                 b_frames == s->max_b_frames) {
  1526.                 av_log(s->avctx, AV_LOG_ERROR,
  1527.                        "warning, too many b frames in a row\n");
  1528.             }
  1529.  
  1530.             if (s->picture_in_gop_number + b_frames >= s->gop_size) {
  1531.                 if ((s->mpv_flags & FF_MPV_FLAG_STRICT_GOP) &&
  1532.                     s->gop_size > s->picture_in_gop_number) {
  1533.                     b_frames = s->gop_size - s->picture_in_gop_number - 1;
  1534.                 } else {
  1535.                     if (s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)
  1536.                         b_frames = 0;
  1537.                     s->input_picture[b_frames]->f->pict_type = AV_PICTURE_TYPE_I;
  1538.                 }
  1539.             }
  1540.  
  1541.             if ((s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP) && b_frames &&
  1542.                 s->input_picture[b_frames]->f->pict_type == AV_PICTURE_TYPE_I)
  1543.                 b_frames--;
  1544.  
  1545.             s->reordered_input_picture[0] = s->input_picture[b_frames];
  1546.             if (s->reordered_input_picture[0]->f->pict_type != AV_PICTURE_TYPE_I)
  1547.                 s->reordered_input_picture[0]->f->pict_type = AV_PICTURE_TYPE_P;
  1548.             s->reordered_input_picture[0]->f->coded_picture_number =
  1549.                 s->coded_picture_number++;
  1550.             for (i = 0; i < b_frames; i++) {
  1551.                 s->reordered_input_picture[i + 1] = s->input_picture[i];
  1552.                 s->reordered_input_picture[i + 1]->f->pict_type =
  1553.                     AV_PICTURE_TYPE_B;
  1554.                 s->reordered_input_picture[i + 1]->f->coded_picture_number =
  1555.                     s->coded_picture_number++;
  1556.             }
  1557.         }
  1558.     }
  1559. no_output_pic:
  1560.     if (s->reordered_input_picture[0]) {
  1561.         s->reordered_input_picture[0]->reference =
  1562.            s->reordered_input_picture[0]->f->pict_type !=
  1563.                AV_PICTURE_TYPE_B ? 3 : 0;
  1564.  
  1565.         ff_mpeg_unref_picture(s->avctx, &s->new_picture);
  1566.         if ((ret = ff_mpeg_ref_picture(s->avctx, &s->new_picture, s->reordered_input_picture[0])))
  1567.             return ret;
  1568.  
  1569.         if (s->reordered_input_picture[0]->shared || s->avctx->rc_buffer_size) {
  1570.             // input is a shared pix, so we can't modifiy it -> alloc a new
  1571.             // one & ensure that the shared one is reuseable
  1572.  
  1573.             Picture *pic;
  1574.             int i = ff_find_unused_picture(s->avctx, s->picture, 0);
  1575.             if (i < 0)
  1576.                 return i;
  1577.             pic = &s->picture[i];
  1578.  
  1579.             pic->reference = s->reordered_input_picture[0]->reference;
  1580.             if (alloc_picture(s, pic, 0) < 0) {
  1581.                 return -1;
  1582.             }
  1583.  
  1584.             ret = av_frame_copy_props(pic->f, s->reordered_input_picture[0]->f);
  1585.             if (ret < 0)
  1586.                 return ret;
  1587.  
  1588.             /* mark us unused / free shared pic */
  1589.             av_frame_unref(s->reordered_input_picture[0]->f);
  1590.             s->reordered_input_picture[0]->shared = 0;
  1591.  
  1592.             s->current_picture_ptr = pic;
  1593.         } else {
  1594.             // input is not a shared pix -> reuse buffer for current_pix
  1595.             s->current_picture_ptr = s->reordered_input_picture[0];
  1596.             for (i = 0; i < 4; i++) {
  1597.                 s->new_picture.f->data[i] += INPLACE_OFFSET;
  1598.             }
  1599.         }
  1600.         ff_mpeg_unref_picture(s->avctx, &s->current_picture);
  1601.         if ((ret = ff_mpeg_ref_picture(s->avctx, &s->current_picture,
  1602.                                        s->current_picture_ptr)) < 0)
  1603.             return ret;
  1604.  
  1605.         s->picture_number = s->new_picture.f->display_picture_number;
  1606.     } else {
  1607.         ff_mpeg_unref_picture(s->avctx, &s->new_picture);
  1608.     }
  1609.     return 0;
  1610. }
  1611.  
  1612. static void frame_end(MpegEncContext *s)
  1613. {
  1614.     if (s->unrestricted_mv &&
  1615.         s->current_picture.reference &&
  1616.         !s->intra_only) {
  1617.         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(s->avctx->pix_fmt);
  1618.         int hshift = desc->log2_chroma_w;
  1619.         int vshift = desc->log2_chroma_h;
  1620.         s->mpvencdsp.draw_edges(s->current_picture.f->data[0],
  1621.                                 s->current_picture.f->linesize[0],
  1622.                                 s->h_edge_pos, s->v_edge_pos,
  1623.                                 EDGE_WIDTH, EDGE_WIDTH,
  1624.                                 EDGE_TOP | EDGE_BOTTOM);
  1625.         s->mpvencdsp.draw_edges(s->current_picture.f->data[1],
  1626.                                 s->current_picture.f->linesize[1],
  1627.                                 s->h_edge_pos >> hshift,
  1628.                                 s->v_edge_pos >> vshift,
  1629.                                 EDGE_WIDTH >> hshift,
  1630.                                 EDGE_WIDTH >> vshift,
  1631.                                 EDGE_TOP | EDGE_BOTTOM);
  1632.         s->mpvencdsp.draw_edges(s->current_picture.f->data[2],
  1633.                                 s->current_picture.f->linesize[2],
  1634.                                 s->h_edge_pos >> hshift,
  1635.                                 s->v_edge_pos >> vshift,
  1636.                                 EDGE_WIDTH >> hshift,
  1637.                                 EDGE_WIDTH >> vshift,
  1638.                                 EDGE_TOP | EDGE_BOTTOM);
  1639.     }
  1640.  
  1641.     emms_c();
  1642.  
  1643.     s->last_pict_type                 = s->pict_type;
  1644.     s->last_lambda_for [s->pict_type] = s->current_picture_ptr->f->quality;
  1645.     if (s->pict_type!= AV_PICTURE_TYPE_B)
  1646.         s->last_non_b_pict_type = s->pict_type;
  1647.  
  1648. #if FF_API_CODED_FRAME
  1649. FF_DISABLE_DEPRECATION_WARNINGS
  1650.     av_frame_copy_props(s->avctx->coded_frame, s->current_picture.f);
  1651. FF_ENABLE_DEPRECATION_WARNINGS
  1652. #endif
  1653. }
  1654.  
  1655. static void update_noise_reduction(MpegEncContext *s)
  1656. {
  1657.     int intra, i;
  1658.  
  1659.     for (intra = 0; intra < 2; intra++) {
  1660.         if (s->dct_count[intra] > (1 << 16)) {
  1661.             for (i = 0; i < 64; i++) {
  1662.                 s->dct_error_sum[intra][i] >>= 1;
  1663.             }
  1664.             s->dct_count[intra] >>= 1;
  1665.         }
  1666.  
  1667.         for (i = 0; i < 64; i++) {
  1668.             s->dct_offset[intra][i] = (s->avctx->noise_reduction *
  1669.                                        s->dct_count[intra] +
  1670.                                        s->dct_error_sum[intra][i] / 2) /
  1671.                                       (s->dct_error_sum[intra][i] + 1);
  1672.         }
  1673.     }
  1674. }
  1675.  
  1676. static int frame_start(MpegEncContext *s)
  1677. {
  1678.     int ret;
  1679.  
  1680.     /* mark & release old frames */
  1681.     if (s->pict_type != AV_PICTURE_TYPE_B && s->last_picture_ptr &&
  1682.         s->last_picture_ptr != s->next_picture_ptr &&
  1683.         s->last_picture_ptr->f->buf[0]) {
  1684.         ff_mpeg_unref_picture(s->avctx, s->last_picture_ptr);
  1685.     }
  1686.  
  1687.     s->current_picture_ptr->f->pict_type = s->pict_type;
  1688.     s->current_picture_ptr->f->key_frame = s->pict_type == AV_PICTURE_TYPE_I;
  1689.  
  1690.     ff_mpeg_unref_picture(s->avctx, &s->current_picture);
  1691.     if ((ret = ff_mpeg_ref_picture(s->avctx, &s->current_picture,
  1692.                                    s->current_picture_ptr)) < 0)
  1693.         return ret;
  1694.  
  1695.     if (s->pict_type != AV_PICTURE_TYPE_B) {
  1696.         s->last_picture_ptr = s->next_picture_ptr;
  1697.         if (!s->droppable)
  1698.             s->next_picture_ptr = s->current_picture_ptr;
  1699.     }
  1700.  
  1701.     if (s->last_picture_ptr) {
  1702.         ff_mpeg_unref_picture(s->avctx, &s->last_picture);
  1703.         if (s->last_picture_ptr->f->buf[0] &&
  1704.             (ret = ff_mpeg_ref_picture(s->avctx, &s->last_picture,
  1705.                                        s->last_picture_ptr)) < 0)
  1706.             return ret;
  1707.     }
  1708.     if (s->next_picture_ptr) {
  1709.         ff_mpeg_unref_picture(s->avctx, &s->next_picture);
  1710.         if (s->next_picture_ptr->f->buf[0] &&
  1711.             (ret = ff_mpeg_ref_picture(s->avctx, &s->next_picture,
  1712.                                        s->next_picture_ptr)) < 0)
  1713.             return ret;
  1714.     }
  1715.  
  1716.     if (s->picture_structure!= PICT_FRAME) {
  1717.         int i;
  1718.         for (i = 0; i < 4; i++) {
  1719.             if (s->picture_structure == PICT_BOTTOM_FIELD) {
  1720.                 s->current_picture.f->data[i] +=
  1721.                     s->current_picture.f->linesize[i];
  1722.             }
  1723.             s->current_picture.f->linesize[i] *= 2;
  1724.             s->last_picture.f->linesize[i]    *= 2;
  1725.             s->next_picture.f->linesize[i]    *= 2;
  1726.         }
  1727.     }
  1728.  
  1729.     if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  1730.         s->dct_unquantize_intra = s->dct_unquantize_mpeg2_intra;
  1731.         s->dct_unquantize_inter = s->dct_unquantize_mpeg2_inter;
  1732.     } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {
  1733.         s->dct_unquantize_intra = s->dct_unquantize_h263_intra;
  1734.         s->dct_unquantize_inter = s->dct_unquantize_h263_inter;
  1735.     } else {
  1736.         s->dct_unquantize_intra = s->dct_unquantize_mpeg1_intra;
  1737.         s->dct_unquantize_inter = s->dct_unquantize_mpeg1_inter;
  1738.     }
  1739.  
  1740.     if (s->dct_error_sum) {
  1741.         av_assert2(s->avctx->noise_reduction && s->encoding);
  1742.         update_noise_reduction(s);
  1743.     }
  1744.  
  1745.     return 0;
  1746. }
  1747.  
  1748. int ff_mpv_encode_picture(AVCodecContext *avctx, AVPacket *pkt,
  1749.                           const AVFrame *pic_arg, int *got_packet)
  1750. {
  1751.     MpegEncContext *s = avctx->priv_data;
  1752.     int i, stuffing_count, ret;
  1753.     int context_count = s->slice_context_count;
  1754.  
  1755.     s->vbv_ignore_qmax = 0;
  1756.  
  1757.     s->picture_in_gop_number++;
  1758.  
  1759.     if (load_input_picture(s, pic_arg) < 0)
  1760.         return -1;
  1761.  
  1762.     if (select_input_picture(s) < 0) {
  1763.         return -1;
  1764.     }
  1765.  
  1766.     /* output? */
  1767.     if (s->new_picture.f->data[0]) {
  1768.         int growing_buffer = context_count == 1 && !pkt->data && !s->data_partitioning;
  1769.         int pkt_size = growing_buffer ? FFMAX(s->mb_width*s->mb_height*64+10000, avctx->internal->byte_buffer_size) - AV_INPUT_BUFFER_PADDING_SIZE
  1770.                                               :
  1771.                                               s->mb_width*s->mb_height*(MAX_MB_BYTES+100)+10000;
  1772.         if ((ret = ff_alloc_packet2(avctx, pkt, pkt_size, 0)) < 0)
  1773.             return ret;
  1774.         if (s->mb_info) {
  1775.             s->mb_info_ptr = av_packet_new_side_data(pkt,
  1776.                                  AV_PKT_DATA_H263_MB_INFO,
  1777.                                  s->mb_width*s->mb_height*12);
  1778.             s->prev_mb_info = s->last_mb_info = s->mb_info_size = 0;
  1779.         }
  1780.  
  1781.         for (i = 0; i < context_count; i++) {
  1782.             int start_y = s->thread_context[i]->start_mb_y;
  1783.             int   end_y = s->thread_context[i]->  end_mb_y;
  1784.             int h       = s->mb_height;
  1785.             uint8_t *start = pkt->data + (size_t)(((int64_t) pkt->size) * start_y / h);
  1786.             uint8_t *end   = pkt->data + (size_t)(((int64_t) pkt->size) *   end_y / h);
  1787.  
  1788.             init_put_bits(&s->thread_context[i]->pb, start, end - start);
  1789.         }
  1790.  
  1791.         s->pict_type = s->new_picture.f->pict_type;
  1792.         //emms_c();
  1793.         ret = frame_start(s);
  1794.         if (ret < 0)
  1795.             return ret;
  1796. vbv_retry:
  1797.         ret = encode_picture(s, s->picture_number);
  1798.         if (growing_buffer) {
  1799.             av_assert0(s->pb.buf == avctx->internal->byte_buffer);
  1800.             pkt->data = s->pb.buf;
  1801.             pkt->size = avctx->internal->byte_buffer_size;
  1802.         }
  1803.         if (ret < 0)
  1804.             return -1;
  1805.  
  1806.         avctx->header_bits = s->header_bits;
  1807.         avctx->mv_bits     = s->mv_bits;
  1808.         avctx->misc_bits   = s->misc_bits;
  1809.         avctx->i_tex_bits  = s->i_tex_bits;
  1810.         avctx->p_tex_bits  = s->p_tex_bits;
  1811.         avctx->i_count     = s->i_count;
  1812.         // FIXME f/b_count in avctx
  1813.         avctx->p_count     = s->mb_num - s->i_count - s->skip_count;
  1814.         avctx->skip_count  = s->skip_count;
  1815.  
  1816.         frame_end(s);
  1817.  
  1818.         if (CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG)
  1819.             ff_mjpeg_encode_picture_trailer(&s->pb, s->header_bits);
  1820.  
  1821.         if (avctx->rc_buffer_size) {
  1822.             RateControlContext *rcc = &s->rc_context;
  1823.             int max_size = FFMAX(rcc->buffer_index * avctx->rc_max_available_vbv_use, rcc->buffer_index - 500);
  1824.  
  1825.             if (put_bits_count(&s->pb) > max_size &&
  1826.                 s->lambda < s->lmax) {
  1827.                 s->next_lambda = FFMAX(s->lambda + 1, s->lambda *
  1828.                                        (s->qscale + 1) / s->qscale);
  1829.                 if (s->adaptive_quant) {
  1830.                     int i;
  1831.                     for (i = 0; i < s->mb_height * s->mb_stride; i++)
  1832.                         s->lambda_table[i] =
  1833.                             FFMAX(s->lambda_table[i] + 1,
  1834.                                   s->lambda_table[i] * (s->qscale + 1) /
  1835.                                   s->qscale);
  1836.                 }
  1837.                 s->mb_skipped = 0;        // done in frame_start()
  1838.                 // done in encode_picture() so we must undo it
  1839.                 if (s->pict_type == AV_PICTURE_TYPE_P) {
  1840.                     if (s->flipflop_rounding          ||
  1841.                         s->codec_id == AV_CODEC_ID_H263P ||
  1842.                         s->codec_id == AV_CODEC_ID_MPEG4)
  1843.                         s->no_rounding ^= 1;
  1844.                 }
  1845.                 if (s->pict_type != AV_PICTURE_TYPE_B) {
  1846.                     s->time_base       = s->last_time_base;
  1847.                     s->last_non_b_time = s->time - s->pp_time;
  1848.                 }
  1849.                 for (i = 0; i < context_count; i++) {
  1850.                     PutBitContext *pb = &s->thread_context[i]->pb;
  1851.                     init_put_bits(pb, pb->buf, pb->buf_end - pb->buf);
  1852.                 }
  1853.                 s->vbv_ignore_qmax = 1;
  1854.                 av_log(s->avctx, AV_LOG_VERBOSE, "reencoding frame due to VBV\n");
  1855.                 goto vbv_retry;
  1856.             }
  1857.  
  1858.             av_assert0(s->avctx->rc_max_rate);
  1859.         }
  1860.  
  1861.         if (s->avctx->flags & AV_CODEC_FLAG_PASS1)
  1862.             ff_write_pass1_stats(s);
  1863.  
  1864.         for (i = 0; i < 4; i++) {
  1865.             s->current_picture_ptr->f->error[i] =
  1866.             s->current_picture.f->error[i] =
  1867.                 s->current_picture.error[i];
  1868.             avctx->error[i] += s->current_picture_ptr->f->error[i];
  1869.         }
  1870.         ff_side_data_set_encoder_stats(pkt, s->current_picture.f->quality,
  1871.                                        s->current_picture_ptr->f->error,
  1872.                                        (s->avctx->flags&AV_CODEC_FLAG_PSNR) ? 4 : 0,
  1873.                                        s->pict_type);
  1874.  
  1875.         if (s->avctx->flags & AV_CODEC_FLAG_PASS1)
  1876.             assert(avctx->header_bits + avctx->mv_bits + avctx->misc_bits +
  1877.                    avctx->i_tex_bits + avctx->p_tex_bits ==
  1878.                        put_bits_count(&s->pb));
  1879.         flush_put_bits(&s->pb);
  1880.         s->frame_bits  = put_bits_count(&s->pb);
  1881.  
  1882.         stuffing_count = ff_vbv_update(s, s->frame_bits);
  1883.         s->stuffing_bits = 8*stuffing_count;
  1884.         if (stuffing_count) {
  1885.             if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb) >> 3) <
  1886.                     stuffing_count + 50) {
  1887.                 av_log(s->avctx, AV_LOG_ERROR, "stuffing too large\n");
  1888.                 return -1;
  1889.             }
  1890.  
  1891.             switch (s->codec_id) {
  1892.             case AV_CODEC_ID_MPEG1VIDEO:
  1893.             case AV_CODEC_ID_MPEG2VIDEO:
  1894.                 while (stuffing_count--) {
  1895.                     put_bits(&s->pb, 8, 0);
  1896.                 }
  1897.             break;
  1898.             case AV_CODEC_ID_MPEG4:
  1899.                 put_bits(&s->pb, 16, 0);
  1900.                 put_bits(&s->pb, 16, 0x1C3);
  1901.                 stuffing_count -= 4;
  1902.                 while (stuffing_count--) {
  1903.                     put_bits(&s->pb, 8, 0xFF);
  1904.                 }
  1905.             break;
  1906.             default:
  1907.                 av_log(s->avctx, AV_LOG_ERROR, "vbv buffer overflow\n");
  1908.             }
  1909.             flush_put_bits(&s->pb);
  1910.             s->frame_bits  = put_bits_count(&s->pb);
  1911.         }
  1912.  
  1913.         /* update mpeg1/2 vbv_delay for CBR */
  1914.         if (s->avctx->rc_max_rate                          &&
  1915.             s->avctx->rc_min_rate == s->avctx->rc_max_rate &&
  1916.             s->out_format == FMT_MPEG1                     &&
  1917.             90000LL * (avctx->rc_buffer_size - 1) <=
  1918.                 s->avctx->rc_max_rate * 0xFFFFLL) {
  1919.             int vbv_delay, min_delay;
  1920.             double inbits  = s->avctx->rc_max_rate *
  1921.                              av_q2d(s->avctx->time_base);
  1922.             int    minbits = s->frame_bits - 8 *
  1923.                              (s->vbv_delay_ptr - s->pb.buf - 1);
  1924.             double bits    = s->rc_context.buffer_index + minbits - inbits;
  1925.  
  1926.             if (bits < 0)
  1927.                 av_log(s->avctx, AV_LOG_ERROR,
  1928.                        "Internal error, negative bits\n");
  1929.  
  1930.             assert(s->repeat_first_field == 0);
  1931.  
  1932.             vbv_delay = bits * 90000 / s->avctx->rc_max_rate;
  1933.             min_delay = (minbits * 90000LL + s->avctx->rc_max_rate - 1) /
  1934.                         s->avctx->rc_max_rate;
  1935.  
  1936.             vbv_delay = FFMAX(vbv_delay, min_delay);
  1937.  
  1938.             av_assert0(vbv_delay < 0xFFFF);
  1939.  
  1940.             s->vbv_delay_ptr[0] &= 0xF8;
  1941.             s->vbv_delay_ptr[0] |= vbv_delay >> 13;
  1942.             s->vbv_delay_ptr[1]  = vbv_delay >> 5;
  1943.             s->vbv_delay_ptr[2] &= 0x07;
  1944.             s->vbv_delay_ptr[2] |= vbv_delay << 3;
  1945.             avctx->vbv_delay     = vbv_delay * 300;
  1946.         }
  1947.         s->total_bits     += s->frame_bits;
  1948.         avctx->frame_bits  = s->frame_bits;
  1949.  
  1950.         pkt->pts = s->current_picture.f->pts;
  1951.         if (!s->low_delay && s->pict_type != AV_PICTURE_TYPE_B) {
  1952.             if (!s->current_picture.f->coded_picture_number)
  1953.                 pkt->dts = pkt->pts - s->dts_delta;
  1954.             else
  1955.                 pkt->dts = s->reordered_pts;
  1956.             s->reordered_pts = pkt->pts;
  1957.         } else
  1958.             pkt->dts = pkt->pts;
  1959.         if (s->current_picture.f->key_frame)
  1960.             pkt->flags |= AV_PKT_FLAG_KEY;
  1961.         if (s->mb_info)
  1962.             av_packet_shrink_side_data(pkt, AV_PKT_DATA_H263_MB_INFO, s->mb_info_size);
  1963.     } else {
  1964.         s->frame_bits = 0;
  1965.     }
  1966.  
  1967.     /* release non-reference frames */
  1968.     for (i = 0; i < MAX_PICTURE_COUNT; i++) {
  1969.         if (!s->picture[i].reference)
  1970.             ff_mpeg_unref_picture(s->avctx, &s->picture[i]);
  1971.     }
  1972.  
  1973.     av_assert1((s->frame_bits & 7) == 0);
  1974.  
  1975.     pkt->size = s->frame_bits / 8;
  1976.     *got_packet = !!pkt->size;
  1977.     return 0;
  1978. }
  1979.  
  1980. static inline void dct_single_coeff_elimination(MpegEncContext *s,
  1981.                                                 int n, int threshold)
  1982. {
  1983.     static const char tab[64] = {
  1984.         3, 2, 2, 1, 1, 1, 1, 1,
  1985.         1, 1, 1, 1, 1, 1, 1, 1,
  1986.         1, 1, 1, 1, 1, 1, 1, 1,
  1987.         0, 0, 0, 0, 0, 0, 0, 0,
  1988.         0, 0, 0, 0, 0, 0, 0, 0,
  1989.         0, 0, 0, 0, 0, 0, 0, 0,
  1990.         0, 0, 0, 0, 0, 0, 0, 0,
  1991.         0, 0, 0, 0, 0, 0, 0, 0
  1992.     };
  1993.     int score = 0;
  1994.     int run = 0;
  1995.     int i;
  1996.     int16_t *block = s->block[n];
  1997.     const int last_index = s->block_last_index[n];
  1998.     int skip_dc;
  1999.  
  2000.     if (threshold < 0) {
  2001.         skip_dc = 0;
  2002.         threshold = -threshold;
  2003.     } else
  2004.         skip_dc = 1;
  2005.  
  2006.     /* Are all we could set to zero already zero? */
  2007.     if (last_index <= skip_dc - 1)
  2008.         return;
  2009.  
  2010.     for (i = 0; i <= last_index; i++) {
  2011.         const int j = s->intra_scantable.permutated[i];
  2012.         const int level = FFABS(block[j]);
  2013.         if (level == 1) {
  2014.             if (skip_dc && i == 0)
  2015.                 continue;
  2016.             score += tab[run];
  2017.             run = 0;
  2018.         } else if (level > 1) {
  2019.             return;
  2020.         } else {
  2021.             run++;
  2022.         }
  2023.     }
  2024.     if (score >= threshold)
  2025.         return;
  2026.     for (i = skip_dc; i <= last_index; i++) {
  2027.         const int j = s->intra_scantable.permutated[i];
  2028.         block[j] = 0;
  2029.     }
  2030.     if (block[0])
  2031.         s->block_last_index[n] = 0;
  2032.     else
  2033.         s->block_last_index[n] = -1;
  2034. }
  2035.  
  2036. static inline void clip_coeffs(MpegEncContext *s, int16_t *block,
  2037.                                int last_index)
  2038. {
  2039.     int i;
  2040.     const int maxlevel = s->max_qcoeff;
  2041.     const int minlevel = s->min_qcoeff;
  2042.     int overflow = 0;
  2043.  
  2044.     if (s->mb_intra) {
  2045.         i = 1; // skip clipping of intra dc
  2046.     } else
  2047.         i = 0;
  2048.  
  2049.     for (; i <= last_index; i++) {
  2050.         const int j = s->intra_scantable.permutated[i];
  2051.         int level = block[j];
  2052.  
  2053.         if (level > maxlevel) {
  2054.             level = maxlevel;
  2055.             overflow++;
  2056.         } else if (level < minlevel) {
  2057.             level = minlevel;
  2058.             overflow++;
  2059.         }
  2060.  
  2061.         block[j] = level;
  2062.     }
  2063.  
  2064.     if (overflow && s->avctx->mb_decision == FF_MB_DECISION_SIMPLE)
  2065.         av_log(s->avctx, AV_LOG_INFO,
  2066.                "warning, clipping %d dct coefficients to %d..%d\n",
  2067.                overflow, minlevel, maxlevel);
  2068. }
  2069.  
  2070. static void get_visual_weight(int16_t *weight, uint8_t *ptr, int stride)
  2071. {
  2072.     int x, y;
  2073.     // FIXME optimize
  2074.     for (y = 0; y < 8; y++) {
  2075.         for (x = 0; x < 8; x++) {
  2076.             int x2, y2;
  2077.             int sum = 0;
  2078.             int sqr = 0;
  2079.             int count = 0;
  2080.  
  2081.             for (y2 = FFMAX(y - 1, 0); y2 < FFMIN(8, y + 2); y2++) {
  2082.                 for (x2= FFMAX(x - 1, 0); x2 < FFMIN(8, x + 2); x2++) {
  2083.                     int v = ptr[x2 + y2 * stride];
  2084.                     sum += v;
  2085.                     sqr += v * v;
  2086.                     count++;
  2087.                 }
  2088.             }
  2089.             weight[x + 8 * y]= (36 * ff_sqrt(count * sqr - sum * sum)) / count;
  2090.         }
  2091.     }
  2092. }
  2093.  
  2094. static av_always_inline void encode_mb_internal(MpegEncContext *s,
  2095.                                                 int motion_x, int motion_y,
  2096.                                                 int mb_block_height,
  2097.                                                 int mb_block_width,
  2098.                                                 int mb_block_count)
  2099. {
  2100.     int16_t weight[12][64];
  2101.     int16_t orig[12][64];
  2102.     const int mb_x = s->mb_x;
  2103.     const int mb_y = s->mb_y;
  2104.     int i;
  2105.     int skip_dct[12];
  2106.     int dct_offset = s->linesize * 8; // default for progressive frames
  2107.     int uv_dct_offset = s->uvlinesize * 8;
  2108.     uint8_t *ptr_y, *ptr_cb, *ptr_cr;
  2109.     ptrdiff_t wrap_y, wrap_c;
  2110.  
  2111.     for (i = 0; i < mb_block_count; i++)
  2112.         skip_dct[i] = s->skipdct;
  2113.  
  2114.     if (s->adaptive_quant) {
  2115.         const int last_qp = s->qscale;
  2116.         const int mb_xy = mb_x + mb_y * s->mb_stride;
  2117.  
  2118.         s->lambda = s->lambda_table[mb_xy];
  2119.         update_qscale(s);
  2120.  
  2121.         if (!(s->mpv_flags & FF_MPV_FLAG_QP_RD)) {
  2122.             s->qscale = s->current_picture_ptr->qscale_table[mb_xy];
  2123.             s->dquant = s->qscale - last_qp;
  2124.  
  2125.             if (s->out_format == FMT_H263) {
  2126.                 s->dquant = av_clip(s->dquant, -2, 2);
  2127.  
  2128.                 if (s->codec_id == AV_CODEC_ID_MPEG4) {
  2129.                     if (!s->mb_intra) {
  2130.                         if (s->pict_type == AV_PICTURE_TYPE_B) {
  2131.                             if (s->dquant & 1 || s->mv_dir & MV_DIRECT)
  2132.                                 s->dquant = 0;
  2133.                         }
  2134.                         if (s->mv_type == MV_TYPE_8X8)
  2135.                             s->dquant = 0;
  2136.                     }
  2137.                 }
  2138.             }
  2139.         }
  2140.         ff_set_qscale(s, last_qp + s->dquant);
  2141.     } else if (s->mpv_flags & FF_MPV_FLAG_QP_RD)
  2142.         ff_set_qscale(s, s->qscale + s->dquant);
  2143.  
  2144.     wrap_y = s->linesize;
  2145.     wrap_c = s->uvlinesize;
  2146.     ptr_y  = s->new_picture.f->data[0] +
  2147.              (mb_y * 16 * wrap_y)              + mb_x * 16;
  2148.     ptr_cb = s->new_picture.f->data[1] +
  2149.              (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;
  2150.     ptr_cr = s->new_picture.f->data[2] +
  2151.              (mb_y * mb_block_height * wrap_c) + mb_x * mb_block_width;
  2152.  
  2153.     if((mb_x * 16 + 16 > s->width || mb_y * 16 + 16 > s->height) && s->codec_id != AV_CODEC_ID_AMV){
  2154.         uint8_t *ebuf = s->sc.edge_emu_buffer + 36 * wrap_y;
  2155.         int cw = (s->width  + s->chroma_x_shift) >> s->chroma_x_shift;
  2156.         int ch = (s->height + s->chroma_y_shift) >> s->chroma_y_shift;
  2157.         s->vdsp.emulated_edge_mc(ebuf, ptr_y,
  2158.                                  wrap_y, wrap_y,
  2159.                                  16, 16, mb_x * 16, mb_y * 16,
  2160.                                  s->width, s->height);
  2161.         ptr_y = ebuf;
  2162.         s->vdsp.emulated_edge_mc(ebuf + 16 * wrap_y, ptr_cb,
  2163.                                  wrap_c, wrap_c,
  2164.                                  mb_block_width, mb_block_height,
  2165.                                  mb_x * mb_block_width, mb_y * mb_block_height,
  2166.                                  cw, ch);
  2167.         ptr_cb = ebuf + 16 * wrap_y;
  2168.         s->vdsp.emulated_edge_mc(ebuf + 16 * wrap_y + 16, ptr_cr,
  2169.                                  wrap_c, wrap_c,
  2170.                                  mb_block_width, mb_block_height,
  2171.                                  mb_x * mb_block_width, mb_y * mb_block_height,
  2172.                                  cw, ch);
  2173.         ptr_cr = ebuf + 16 * wrap_y + 16;
  2174.     }
  2175.  
  2176.     if (s->mb_intra) {
  2177.         if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  2178.             int progressive_score, interlaced_score;
  2179.  
  2180.             s->interlaced_dct = 0;
  2181.             progressive_score = s->mecc.ildct_cmp[4](s, ptr_y, NULL, wrap_y, 8) +
  2182.                                 s->mecc.ildct_cmp[4](s, ptr_y + wrap_y * 8,
  2183.                                                      NULL, wrap_y, 8) - 400;
  2184.  
  2185.             if (progressive_score > 0) {
  2186.                 interlaced_score = s->mecc.ildct_cmp[4](s, ptr_y,
  2187.                                                         NULL, wrap_y * 2, 8) +
  2188.                                    s->mecc.ildct_cmp[4](s, ptr_y + wrap_y,
  2189.                                                         NULL, wrap_y * 2, 8);
  2190.                 if (progressive_score > interlaced_score) {
  2191.                     s->interlaced_dct = 1;
  2192.  
  2193.                     dct_offset = wrap_y;
  2194.                     uv_dct_offset = wrap_c;
  2195.                     wrap_y <<= 1;
  2196.                     if (s->chroma_format == CHROMA_422 ||
  2197.                         s->chroma_format == CHROMA_444)
  2198.                         wrap_c <<= 1;
  2199.                 }
  2200.             }
  2201.         }
  2202.  
  2203.         s->pdsp.get_pixels(s->block[0], ptr_y,                  wrap_y);
  2204.         s->pdsp.get_pixels(s->block[1], ptr_y + 8,              wrap_y);
  2205.         s->pdsp.get_pixels(s->block[2], ptr_y + dct_offset,     wrap_y);
  2206.         s->pdsp.get_pixels(s->block[3], ptr_y + dct_offset + 8, wrap_y);
  2207.  
  2208.         if (s->avctx->flags & AV_CODEC_FLAG_GRAY) {
  2209.             skip_dct[4] = 1;
  2210.             skip_dct[5] = 1;
  2211.         } else {
  2212.             s->pdsp.get_pixels(s->block[4], ptr_cb, wrap_c);
  2213.             s->pdsp.get_pixels(s->block[5], ptr_cr, wrap_c);
  2214.             if (!s->chroma_y_shift && s->chroma_x_shift) { /* 422 */
  2215.                 s->pdsp.get_pixels(s->block[6], ptr_cb + uv_dct_offset, wrap_c);
  2216.                 s->pdsp.get_pixels(s->block[7], ptr_cr + uv_dct_offset, wrap_c);
  2217.             } else if (!s->chroma_y_shift && !s->chroma_x_shift) { /* 444 */
  2218.                 s->pdsp.get_pixels(s->block[ 6], ptr_cb + 8, wrap_c);
  2219.                 s->pdsp.get_pixels(s->block[ 7], ptr_cr + 8, wrap_c);
  2220.                 s->pdsp.get_pixels(s->block[ 8], ptr_cb + uv_dct_offset, wrap_c);
  2221.                 s->pdsp.get_pixels(s->block[ 9], ptr_cr + uv_dct_offset, wrap_c);
  2222.                 s->pdsp.get_pixels(s->block[10], ptr_cb + uv_dct_offset + 8, wrap_c);
  2223.                 s->pdsp.get_pixels(s->block[11], ptr_cr + uv_dct_offset + 8, wrap_c);
  2224.             }
  2225.         }
  2226.     } else {
  2227.         op_pixels_func (*op_pix)[4];
  2228.         qpel_mc_func (*op_qpix)[16];
  2229.         uint8_t *dest_y, *dest_cb, *dest_cr;
  2230.  
  2231.         dest_y  = s->dest[0];
  2232.         dest_cb = s->dest[1];
  2233.         dest_cr = s->dest[2];
  2234.  
  2235.         if ((!s->no_rounding) || s->pict_type == AV_PICTURE_TYPE_B) {
  2236.             op_pix  = s->hdsp.put_pixels_tab;
  2237.             op_qpix = s->qdsp.put_qpel_pixels_tab;
  2238.         } else {
  2239.             op_pix  = s->hdsp.put_no_rnd_pixels_tab;
  2240.             op_qpix = s->qdsp.put_no_rnd_qpel_pixels_tab;
  2241.         }
  2242.  
  2243.         if (s->mv_dir & MV_DIR_FORWARD) {
  2244.             ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 0,
  2245.                           s->last_picture.f->data,
  2246.                           op_pix, op_qpix);
  2247.             op_pix  = s->hdsp.avg_pixels_tab;
  2248.             op_qpix = s->qdsp.avg_qpel_pixels_tab;
  2249.         }
  2250.         if (s->mv_dir & MV_DIR_BACKWARD) {
  2251.             ff_mpv_motion(s, dest_y, dest_cb, dest_cr, 1,
  2252.                           s->next_picture.f->data,
  2253.                           op_pix, op_qpix);
  2254.         }
  2255.  
  2256.         if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  2257.             int progressive_score, interlaced_score;
  2258.  
  2259.             s->interlaced_dct = 0;
  2260.             progressive_score = s->mecc.ildct_cmp[0](s, dest_y, ptr_y, wrap_y, 8) +
  2261.                                 s->mecc.ildct_cmp[0](s, dest_y + wrap_y * 8,
  2262.                                                      ptr_y + wrap_y * 8,
  2263.                                                      wrap_y, 8) - 400;
  2264.  
  2265.             if (s->avctx->ildct_cmp == FF_CMP_VSSE)
  2266.                 progressive_score -= 400;
  2267.  
  2268.             if (progressive_score > 0) {
  2269.                 interlaced_score = s->mecc.ildct_cmp[0](s, dest_y, ptr_y,
  2270.                                                         wrap_y * 2, 8) +
  2271.                                    s->mecc.ildct_cmp[0](s, dest_y + wrap_y,
  2272.                                                         ptr_y + wrap_y,
  2273.                                                         wrap_y * 2, 8);
  2274.  
  2275.                 if (progressive_score > interlaced_score) {
  2276.                     s->interlaced_dct = 1;
  2277.  
  2278.                     dct_offset = wrap_y;
  2279.                     uv_dct_offset = wrap_c;
  2280.                     wrap_y <<= 1;
  2281.                     if (s->chroma_format == CHROMA_422)
  2282.                         wrap_c <<= 1;
  2283.                 }
  2284.             }
  2285.         }
  2286.  
  2287.         s->pdsp.diff_pixels(s->block[0], ptr_y, dest_y, wrap_y);
  2288.         s->pdsp.diff_pixels(s->block[1], ptr_y + 8, dest_y + 8, wrap_y);
  2289.         s->pdsp.diff_pixels(s->block[2], ptr_y + dct_offset,
  2290.                             dest_y + dct_offset, wrap_y);
  2291.         s->pdsp.diff_pixels(s->block[3], ptr_y + dct_offset + 8,
  2292.                             dest_y + dct_offset + 8, wrap_y);
  2293.  
  2294.         if (s->avctx->flags & AV_CODEC_FLAG_GRAY) {
  2295.             skip_dct[4] = 1;
  2296.             skip_dct[5] = 1;
  2297.         } else {
  2298.             s->pdsp.diff_pixels(s->block[4], ptr_cb, dest_cb, wrap_c);
  2299.             s->pdsp.diff_pixels(s->block[5], ptr_cr, dest_cr, wrap_c);
  2300.             if (!s->chroma_y_shift) { /* 422 */
  2301.                 s->pdsp.diff_pixels(s->block[6], ptr_cb + uv_dct_offset,
  2302.                                     dest_cb + uv_dct_offset, wrap_c);
  2303.                 s->pdsp.diff_pixels(s->block[7], ptr_cr + uv_dct_offset,
  2304.                                     dest_cr + uv_dct_offset, wrap_c);
  2305.             }
  2306.         }
  2307.         /* pre quantization */
  2308.         if (s->current_picture.mc_mb_var[s->mb_stride * mb_y + mb_x] <
  2309.                 2 * s->qscale * s->qscale) {
  2310.             // FIXME optimize
  2311.             if (s->mecc.sad[1](NULL, ptr_y, dest_y, wrap_y, 8) < 20 * s->qscale)
  2312.                 skip_dct[0] = 1;
  2313.             if (s->mecc.sad[1](NULL, ptr_y + 8, dest_y + 8, wrap_y, 8) < 20 * s->qscale)
  2314.                 skip_dct[1] = 1;
  2315.             if (s->mecc.sad[1](NULL, ptr_y + dct_offset, dest_y + dct_offset,
  2316.                                wrap_y, 8) < 20 * s->qscale)
  2317.                 skip_dct[2] = 1;
  2318.             if (s->mecc.sad[1](NULL, ptr_y + dct_offset + 8, dest_y + dct_offset + 8,
  2319.                                wrap_y, 8) < 20 * s->qscale)
  2320.                 skip_dct[3] = 1;
  2321.             if (s->mecc.sad[1](NULL, ptr_cb, dest_cb, wrap_c, 8) < 20 * s->qscale)
  2322.                 skip_dct[4] = 1;
  2323.             if (s->mecc.sad[1](NULL, ptr_cr, dest_cr, wrap_c, 8) < 20 * s->qscale)
  2324.                 skip_dct[5] = 1;
  2325.             if (!s->chroma_y_shift) { /* 422 */
  2326.                 if (s->mecc.sad[1](NULL, ptr_cb + uv_dct_offset,
  2327.                                    dest_cb + uv_dct_offset,
  2328.                                    wrap_c, 8) < 20 * s->qscale)
  2329.                     skip_dct[6] = 1;
  2330.                 if (s->mecc.sad[1](NULL, ptr_cr + uv_dct_offset,
  2331.                                    dest_cr + uv_dct_offset,
  2332.                                    wrap_c, 8) < 20 * s->qscale)
  2333.                     skip_dct[7] = 1;
  2334.             }
  2335.         }
  2336.     }
  2337.  
  2338.     if (s->quantizer_noise_shaping) {
  2339.         if (!skip_dct[0])
  2340.             get_visual_weight(weight[0], ptr_y                 , wrap_y);
  2341.         if (!skip_dct[1])
  2342.             get_visual_weight(weight[1], ptr_y              + 8, wrap_y);
  2343.         if (!skip_dct[2])
  2344.             get_visual_weight(weight[2], ptr_y + dct_offset    , wrap_y);
  2345.         if (!skip_dct[3])
  2346.             get_visual_weight(weight[3], ptr_y + dct_offset + 8, wrap_y);
  2347.         if (!skip_dct[4])
  2348.             get_visual_weight(weight[4], ptr_cb                , wrap_c);
  2349.         if (!skip_dct[5])
  2350.             get_visual_weight(weight[5], ptr_cr                , wrap_c);
  2351.         if (!s->chroma_y_shift) { /* 422 */
  2352.             if (!skip_dct[6])
  2353.                 get_visual_weight(weight[6], ptr_cb + uv_dct_offset,
  2354.                                   wrap_c);
  2355.             if (!skip_dct[7])
  2356.                 get_visual_weight(weight[7], ptr_cr + uv_dct_offset,
  2357.                                   wrap_c);
  2358.         }
  2359.         memcpy(orig[0], s->block[0], sizeof(int16_t) * 64 * mb_block_count);
  2360.     }
  2361.  
  2362.     /* DCT & quantize */
  2363.     av_assert2(s->out_format != FMT_MJPEG || s->qscale == 8);
  2364.     {
  2365.         for (i = 0; i < mb_block_count; i++) {
  2366.             if (!skip_dct[i]) {
  2367.                 int overflow;
  2368.                 s->block_last_index[i] = s->dct_quantize(s, s->block[i], i, s->qscale, &overflow);
  2369.                 // FIXME we could decide to change to quantizer instead of
  2370.                 // clipping
  2371.                 // JS: I don't think that would be a good idea it could lower
  2372.                 //     quality instead of improve it. Just INTRADC clipping
  2373.                 //     deserves changes in quantizer
  2374.                 if (overflow)
  2375.                     clip_coeffs(s, s->block[i], s->block_last_index[i]);
  2376.             } else
  2377.                 s->block_last_index[i] = -1;
  2378.         }
  2379.         if (s->quantizer_noise_shaping) {
  2380.             for (i = 0; i < mb_block_count; i++) {
  2381.                 if (!skip_dct[i]) {
  2382.                     s->block_last_index[i] =
  2383.                         dct_quantize_refine(s, s->block[i], weight[i],
  2384.                                             orig[i], i, s->qscale);
  2385.                 }
  2386.             }
  2387.         }
  2388.  
  2389.         if (s->luma_elim_threshold && !s->mb_intra)
  2390.             for (i = 0; i < 4; i++)
  2391.                 dct_single_coeff_elimination(s, i, s->luma_elim_threshold);
  2392.         if (s->chroma_elim_threshold && !s->mb_intra)
  2393.             for (i = 4; i < mb_block_count; i++)
  2394.                 dct_single_coeff_elimination(s, i, s->chroma_elim_threshold);
  2395.  
  2396.         if (s->mpv_flags & FF_MPV_FLAG_CBP_RD) {
  2397.             for (i = 0; i < mb_block_count; i++) {
  2398.                 if (s->block_last_index[i] == -1)
  2399.                     s->coded_score[i] = INT_MAX / 256;
  2400.             }
  2401.         }
  2402.     }
  2403.  
  2404.     if ((s->avctx->flags & AV_CODEC_FLAG_GRAY) && s->mb_intra) {
  2405.         s->block_last_index[4] =
  2406.         s->block_last_index[5] = 0;
  2407.         s->block[4][0] =
  2408.         s->block[5][0] = (1024 + s->c_dc_scale / 2) / s->c_dc_scale;
  2409.         if (!s->chroma_y_shift) { /* 422 / 444 */
  2410.             for (i=6; i<12; i++) {
  2411.                 s->block_last_index[i] = 0;
  2412.                 s->block[i][0] = s->block[4][0];
  2413.             }
  2414.         }
  2415.     }
  2416.  
  2417.     // non c quantize code returns incorrect block_last_index FIXME
  2418.     if (s->alternate_scan && s->dct_quantize != ff_dct_quantize_c) {
  2419.         for (i = 0; i < mb_block_count; i++) {
  2420.             int j;
  2421.             if (s->block_last_index[i] > 0) {
  2422.                 for (j = 63; j > 0; j--) {
  2423.                     if (s->block[i][s->intra_scantable.permutated[j]])
  2424.                         break;
  2425.                 }
  2426.                 s->block_last_index[i] = j;
  2427.             }
  2428.         }
  2429.     }
  2430.  
  2431.     /* huffman encode */
  2432.     switch(s->codec_id){ //FIXME funct ptr could be slightly faster
  2433.     case AV_CODEC_ID_MPEG1VIDEO:
  2434.     case AV_CODEC_ID_MPEG2VIDEO:
  2435.         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  2436.             ff_mpeg1_encode_mb(s, s->block, motion_x, motion_y);
  2437.         break;
  2438.     case AV_CODEC_ID_MPEG4:
  2439.         if (CONFIG_MPEG4_ENCODER)
  2440.             ff_mpeg4_encode_mb(s, s->block, motion_x, motion_y);
  2441.         break;
  2442.     case AV_CODEC_ID_MSMPEG4V2:
  2443.     case AV_CODEC_ID_MSMPEG4V3:
  2444.     case AV_CODEC_ID_WMV1:
  2445.         if (CONFIG_MSMPEG4_ENCODER)
  2446.             ff_msmpeg4_encode_mb(s, s->block, motion_x, motion_y);
  2447.         break;
  2448.     case AV_CODEC_ID_WMV2:
  2449.         if (CONFIG_WMV2_ENCODER)
  2450.             ff_wmv2_encode_mb(s, s->block, motion_x, motion_y);
  2451.         break;
  2452.     case AV_CODEC_ID_H261:
  2453.         if (CONFIG_H261_ENCODER)
  2454.             ff_h261_encode_mb(s, s->block, motion_x, motion_y);
  2455.         break;
  2456.     case AV_CODEC_ID_H263:
  2457.     case AV_CODEC_ID_H263P:
  2458.     case AV_CODEC_ID_FLV1:
  2459.     case AV_CODEC_ID_RV10:
  2460.     case AV_CODEC_ID_RV20:
  2461.         if (CONFIG_H263_ENCODER)
  2462.             ff_h263_encode_mb(s, s->block, motion_x, motion_y);
  2463.         break;
  2464.     case AV_CODEC_ID_MJPEG:
  2465.     case AV_CODEC_ID_AMV:
  2466.         if (CONFIG_MJPEG_ENCODER)
  2467.             ff_mjpeg_encode_mb(s, s->block);
  2468.         break;
  2469.     default:
  2470.         av_assert1(0);
  2471.     }
  2472. }
  2473.  
  2474. static av_always_inline void encode_mb(MpegEncContext *s, int motion_x, int motion_y)
  2475. {
  2476.     if (s->chroma_format == CHROMA_420) encode_mb_internal(s, motion_x, motion_y,  8, 8, 6);
  2477.     else if (s->chroma_format == CHROMA_422) encode_mb_internal(s, motion_x, motion_y, 16, 8, 8);
  2478.     else encode_mb_internal(s, motion_x, motion_y, 16, 16, 12);
  2479. }
  2480.  
  2481. static inline void copy_context_before_encode(MpegEncContext *d, MpegEncContext *s, int type){
  2482.     int i;
  2483.  
  2484.     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  2485.  
  2486.     /* mpeg1 */
  2487.     d->mb_skip_run= s->mb_skip_run;
  2488.     for(i=0; i<3; i++)
  2489.         d->last_dc[i] = s->last_dc[i];
  2490.  
  2491.     /* statistics */
  2492.     d->mv_bits= s->mv_bits;
  2493.     d->i_tex_bits= s->i_tex_bits;
  2494.     d->p_tex_bits= s->p_tex_bits;
  2495.     d->i_count= s->i_count;
  2496.     d->f_count= s->f_count;
  2497.     d->b_count= s->b_count;
  2498.     d->skip_count= s->skip_count;
  2499.     d->misc_bits= s->misc_bits;
  2500.     d->last_bits= 0;
  2501.  
  2502.     d->mb_skipped= 0;
  2503.     d->qscale= s->qscale;
  2504.     d->dquant= s->dquant;
  2505.  
  2506.     d->esc3_level_length= s->esc3_level_length;
  2507. }
  2508.  
  2509. static inline void copy_context_after_encode(MpegEncContext *d, MpegEncContext *s, int type){
  2510.     int i;
  2511.  
  2512.     memcpy(d->mv, s->mv, 2*4*2*sizeof(int));
  2513.     memcpy(d->last_mv, s->last_mv, 2*2*2*sizeof(int)); //FIXME is memcpy faster than a loop?
  2514.  
  2515.     /* mpeg1 */
  2516.     d->mb_skip_run= s->mb_skip_run;
  2517.     for(i=0; i<3; i++)
  2518.         d->last_dc[i] = s->last_dc[i];
  2519.  
  2520.     /* statistics */
  2521.     d->mv_bits= s->mv_bits;
  2522.     d->i_tex_bits= s->i_tex_bits;
  2523.     d->p_tex_bits= s->p_tex_bits;
  2524.     d->i_count= s->i_count;
  2525.     d->f_count= s->f_count;
  2526.     d->b_count= s->b_count;
  2527.     d->skip_count= s->skip_count;
  2528.     d->misc_bits= s->misc_bits;
  2529.  
  2530.     d->mb_intra= s->mb_intra;
  2531.     d->mb_skipped= s->mb_skipped;
  2532.     d->mv_type= s->mv_type;
  2533.     d->mv_dir= s->mv_dir;
  2534.     d->pb= s->pb;
  2535.     if(s->data_partitioning){
  2536.         d->pb2= s->pb2;
  2537.         d->tex_pb= s->tex_pb;
  2538.     }
  2539.     d->block= s->block;
  2540.     for(i=0; i<8; i++)
  2541.         d->block_last_index[i]= s->block_last_index[i];
  2542.     d->interlaced_dct= s->interlaced_dct;
  2543.     d->qscale= s->qscale;
  2544.  
  2545.     d->esc3_level_length= s->esc3_level_length;
  2546. }
  2547.  
  2548. static inline void encode_mb_hq(MpegEncContext *s, MpegEncContext *backup, MpegEncContext *best, int type,
  2549.                            PutBitContext pb[2], PutBitContext pb2[2], PutBitContext tex_pb[2],
  2550.                            int *dmin, int *next_block, int motion_x, int motion_y)
  2551. {
  2552.     int score;
  2553.     uint8_t *dest_backup[3];
  2554.  
  2555.     copy_context_before_encode(s, backup, type);
  2556.  
  2557.     s->block= s->blocks[*next_block];
  2558.     s->pb= pb[*next_block];
  2559.     if(s->data_partitioning){
  2560.         s->pb2   = pb2   [*next_block];
  2561.         s->tex_pb= tex_pb[*next_block];
  2562.     }
  2563.  
  2564.     if(*next_block){
  2565.         memcpy(dest_backup, s->dest, sizeof(s->dest));
  2566.         s->dest[0] = s->sc.rd_scratchpad;
  2567.         s->dest[1] = s->sc.rd_scratchpad + 16*s->linesize;
  2568.         s->dest[2] = s->sc.rd_scratchpad + 16*s->linesize + 8;
  2569.         av_assert0(s->linesize >= 32); //FIXME
  2570.     }
  2571.  
  2572.     encode_mb(s, motion_x, motion_y);
  2573.  
  2574.     score= put_bits_count(&s->pb);
  2575.     if(s->data_partitioning){
  2576.         score+= put_bits_count(&s->pb2);
  2577.         score+= put_bits_count(&s->tex_pb);
  2578.     }
  2579.  
  2580.     if(s->avctx->mb_decision == FF_MB_DECISION_RD){
  2581.         ff_mpv_decode_mb(s, s->block);
  2582.  
  2583.         score *= s->lambda2;
  2584.         score += sse_mb(s) << FF_LAMBDA_SHIFT;
  2585.     }
  2586.  
  2587.     if(*next_block){
  2588.         memcpy(s->dest, dest_backup, sizeof(s->dest));
  2589.     }
  2590.  
  2591.     if(score<*dmin){
  2592.         *dmin= score;
  2593.         *next_block^=1;
  2594.  
  2595.         copy_context_after_encode(best, s, type);
  2596.     }
  2597. }
  2598.  
  2599. static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride){
  2600.     uint32_t *sq = ff_square_tab + 256;
  2601.     int acc=0;
  2602.     int x,y;
  2603.  
  2604.     if(w==16 && h==16)
  2605.         return s->mecc.sse[0](NULL, src1, src2, stride, 16);
  2606.     else if(w==8 && h==8)
  2607.         return s->mecc.sse[1](NULL, src1, src2, stride, 8);
  2608.  
  2609.     for(y=0; y<h; y++){
  2610.         for(x=0; x<w; x++){
  2611.             acc+= sq[src1[x + y*stride] - src2[x + y*stride]];
  2612.         }
  2613.     }
  2614.  
  2615.     av_assert2(acc>=0);
  2616.  
  2617.     return acc;
  2618. }
  2619.  
  2620. static int sse_mb(MpegEncContext *s){
  2621.     int w= 16;
  2622.     int h= 16;
  2623.  
  2624.     if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  2625.     if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  2626.  
  2627.     if(w==16 && h==16)
  2628.       if(s->avctx->mb_cmp == FF_CMP_NSSE){
  2629.         return s->mecc.nsse[0](s, s->new_picture.f->data[0] + s->mb_x * 16 + s->mb_y * s->linesize   * 16, s->dest[0], s->linesize,   16) +
  2630.                s->mecc.nsse[1](s, s->new_picture.f->data[1] + s->mb_x *  8 + s->mb_y * s->uvlinesize *  8, s->dest[1], s->uvlinesize,  8) +
  2631.                s->mecc.nsse[1](s, s->new_picture.f->data[2] + s->mb_x *  8 + s->mb_y * s->uvlinesize *  8, s->dest[2], s->uvlinesize,  8);
  2632.       }else{
  2633.         return s->mecc.sse[0](NULL, s->new_picture.f->data[0] + s->mb_x * 16 + s->mb_y * s->linesize   * 16, s->dest[0], s->linesize,   16) +
  2634.                s->mecc.sse[1](NULL, s->new_picture.f->data[1] + s->mb_x *  8 + s->mb_y * s->uvlinesize *  8, s->dest[1], s->uvlinesize,  8) +
  2635.                s->mecc.sse[1](NULL, s->new_picture.f->data[2] + s->mb_x *  8 + s->mb_y * s->uvlinesize *  8, s->dest[2], s->uvlinesize,  8);
  2636.       }
  2637.     else
  2638.         return  sse(s, s->new_picture.f->data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], w, h, s->linesize)
  2639.                +sse(s, s->new_picture.f->data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], w>>1, h>>1, s->uvlinesize)
  2640.                +sse(s, s->new_picture.f->data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], w>>1, h>>1, s->uvlinesize);
  2641. }
  2642.  
  2643. static int pre_estimate_motion_thread(AVCodecContext *c, void *arg){
  2644.     MpegEncContext *s= *(void**)arg;
  2645.  
  2646.  
  2647.     s->me.pre_pass=1;
  2648.     s->me.dia_size= s->avctx->pre_dia_size;
  2649.     s->first_slice_line=1;
  2650.     for(s->mb_y= s->end_mb_y-1; s->mb_y >= s->start_mb_y; s->mb_y--) {
  2651.         for(s->mb_x=s->mb_width-1; s->mb_x >=0 ;s->mb_x--) {
  2652.             ff_pre_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  2653.         }
  2654.         s->first_slice_line=0;
  2655.     }
  2656.  
  2657.     s->me.pre_pass=0;
  2658.  
  2659.     return 0;
  2660. }
  2661.  
  2662. static int estimate_motion_thread(AVCodecContext *c, void *arg){
  2663.     MpegEncContext *s= *(void**)arg;
  2664.  
  2665.     ff_check_alignment();
  2666.  
  2667.     s->me.dia_size= s->avctx->dia_size;
  2668.     s->first_slice_line=1;
  2669.     for(s->mb_y= s->start_mb_y; s->mb_y < s->end_mb_y; s->mb_y++) {
  2670.         s->mb_x=0; //for block init below
  2671.         ff_init_block_index(s);
  2672.         for(s->mb_x=0; s->mb_x < s->mb_width; s->mb_x++) {
  2673.             s->block_index[0]+=2;
  2674.             s->block_index[1]+=2;
  2675.             s->block_index[2]+=2;
  2676.             s->block_index[3]+=2;
  2677.  
  2678.             /* compute motion vector & mb_type and store in context */
  2679.             if(s->pict_type==AV_PICTURE_TYPE_B)
  2680.                 ff_estimate_b_frame_motion(s, s->mb_x, s->mb_y);
  2681.             else
  2682.                 ff_estimate_p_frame_motion(s, s->mb_x, s->mb_y);
  2683.         }
  2684.         s->first_slice_line=0;
  2685.     }
  2686.     return 0;
  2687. }
  2688.  
  2689. static int mb_var_thread(AVCodecContext *c, void *arg){
  2690.     MpegEncContext *s= *(void**)arg;
  2691.     int mb_x, mb_y;
  2692.  
  2693.     ff_check_alignment();
  2694.  
  2695.     for(mb_y=s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  2696.         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2697.             int xx = mb_x * 16;
  2698.             int yy = mb_y * 16;
  2699.             uint8_t *pix = s->new_picture.f->data[0] + (yy * s->linesize) + xx;
  2700.             int varc;
  2701.             int sum = s->mpvencdsp.pix_sum(pix, s->linesize);
  2702.  
  2703.             varc = (s->mpvencdsp.pix_norm1(pix, s->linesize) -
  2704.                     (((unsigned) sum * sum) >> 8) + 500 + 128) >> 8;
  2705.  
  2706.             s->current_picture.mb_var [s->mb_stride * mb_y + mb_x] = varc;
  2707.             s->current_picture.mb_mean[s->mb_stride * mb_y + mb_x] = (sum+128)>>8;
  2708.             s->me.mb_var_sum_temp    += varc;
  2709.         }
  2710.     }
  2711.     return 0;
  2712. }
  2713.  
  2714. static void write_slice_end(MpegEncContext *s){
  2715.     if(CONFIG_MPEG4_ENCODER && s->codec_id==AV_CODEC_ID_MPEG4){
  2716.         if(s->partitioned_frame){
  2717.             ff_mpeg4_merge_partitions(s);
  2718.         }
  2719.  
  2720.         ff_mpeg4_stuffing(&s->pb);
  2721.     }else if(CONFIG_MJPEG_ENCODER && s->out_format == FMT_MJPEG){
  2722.         ff_mjpeg_encode_stuffing(s);
  2723.     }
  2724.  
  2725.     avpriv_align_put_bits(&s->pb);
  2726.     flush_put_bits(&s->pb);
  2727.  
  2728.     if ((s->avctx->flags & AV_CODEC_FLAG_PASS1) && !s->partitioned_frame)
  2729.         s->misc_bits+= get_bits_diff(s);
  2730. }
  2731.  
  2732. static void write_mb_info(MpegEncContext *s)
  2733. {
  2734.     uint8_t *ptr = s->mb_info_ptr + s->mb_info_size - 12;
  2735.     int offset = put_bits_count(&s->pb);
  2736.     int mba  = s->mb_x + s->mb_width * (s->mb_y % s->gob_index);
  2737.     int gobn = s->mb_y / s->gob_index;
  2738.     int pred_x, pred_y;
  2739.     if (CONFIG_H263_ENCODER)
  2740.         ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
  2741.     bytestream_put_le32(&ptr, offset);
  2742.     bytestream_put_byte(&ptr, s->qscale);
  2743.     bytestream_put_byte(&ptr, gobn);
  2744.     bytestream_put_le16(&ptr, mba);
  2745.     bytestream_put_byte(&ptr, pred_x); /* hmv1 */
  2746.     bytestream_put_byte(&ptr, pred_y); /* vmv1 */
  2747.     /* 4MV not implemented */
  2748.     bytestream_put_byte(&ptr, 0); /* hmv2 */
  2749.     bytestream_put_byte(&ptr, 0); /* vmv2 */
  2750. }
  2751.  
  2752. static void update_mb_info(MpegEncContext *s, int startcode)
  2753. {
  2754.     if (!s->mb_info)
  2755.         return;
  2756.     if (put_bits_count(&s->pb) - s->prev_mb_info*8 >= s->mb_info*8) {
  2757.         s->mb_info_size += 12;
  2758.         s->prev_mb_info = s->last_mb_info;
  2759.     }
  2760.     if (startcode) {
  2761.         s->prev_mb_info = put_bits_count(&s->pb)/8;
  2762.         /* This might have incremented mb_info_size above, and we return without
  2763.          * actually writing any info into that slot yet. But in that case,
  2764.          * this will be called again at the start of the after writing the
  2765.          * start code, actually writing the mb info. */
  2766.         return;
  2767.     }
  2768.  
  2769.     s->last_mb_info = put_bits_count(&s->pb)/8;
  2770.     if (!s->mb_info_size)
  2771.         s->mb_info_size += 12;
  2772.     write_mb_info(s);
  2773. }
  2774.  
  2775. int ff_mpv_reallocate_putbitbuffer(MpegEncContext *s, size_t threshold, size_t size_increase)
  2776. {
  2777.     if (   s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < threshold
  2778.         && s->slice_context_count == 1
  2779.         && s->pb.buf == s->avctx->internal->byte_buffer) {
  2780.         int lastgob_pos = s->ptr_lastgob - s->pb.buf;
  2781.         int vbv_pos     = s->vbv_delay_ptr - s->pb.buf;
  2782.  
  2783.         uint8_t *new_buffer = NULL;
  2784.         int new_buffer_size = 0;
  2785.  
  2786.         av_fast_padded_malloc(&new_buffer, &new_buffer_size,
  2787.                               s->avctx->internal->byte_buffer_size + size_increase);
  2788.         if (!new_buffer)
  2789.             return AVERROR(ENOMEM);
  2790.  
  2791.         memcpy(new_buffer, s->avctx->internal->byte_buffer, s->avctx->internal->byte_buffer_size);
  2792.         av_free(s->avctx->internal->byte_buffer);
  2793.         s->avctx->internal->byte_buffer      = new_buffer;
  2794.         s->avctx->internal->byte_buffer_size = new_buffer_size;
  2795.         rebase_put_bits(&s->pb, new_buffer, new_buffer_size);
  2796.         s->ptr_lastgob   = s->pb.buf + lastgob_pos;
  2797.         s->vbv_delay_ptr = s->pb.buf + vbv_pos;
  2798.     }
  2799.     if (s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < threshold)
  2800.         return AVERROR(EINVAL);
  2801.     return 0;
  2802. }
  2803.  
  2804. static int encode_thread(AVCodecContext *c, void *arg){
  2805.     MpegEncContext *s= *(void**)arg;
  2806.     int mb_x, mb_y, pdif = 0;
  2807.     int chr_h= 16>>s->chroma_y_shift;
  2808.     int i, j;
  2809.     MpegEncContext best_s = { 0 }, backup_s;
  2810.     uint8_t bit_buf[2][MAX_MB_BYTES];
  2811.     uint8_t bit_buf2[2][MAX_MB_BYTES];
  2812.     uint8_t bit_buf_tex[2][MAX_MB_BYTES];
  2813.     PutBitContext pb[2], pb2[2], tex_pb[2];
  2814.  
  2815.     ff_check_alignment();
  2816.  
  2817.     for(i=0; i<2; i++){
  2818.         init_put_bits(&pb    [i], bit_buf    [i], MAX_MB_BYTES);
  2819.         init_put_bits(&pb2   [i], bit_buf2   [i], MAX_MB_BYTES);
  2820.         init_put_bits(&tex_pb[i], bit_buf_tex[i], MAX_MB_BYTES);
  2821.     }
  2822.  
  2823.     s->last_bits= put_bits_count(&s->pb);
  2824.     s->mv_bits=0;
  2825.     s->misc_bits=0;
  2826.     s->i_tex_bits=0;
  2827.     s->p_tex_bits=0;
  2828.     s->i_count=0;
  2829.     s->f_count=0;
  2830.     s->b_count=0;
  2831.     s->skip_count=0;
  2832.  
  2833.     for(i=0; i<3; i++){
  2834.         /* init last dc values */
  2835.         /* note: quant matrix value (8) is implied here */
  2836.         s->last_dc[i] = 128 << s->intra_dc_precision;
  2837.  
  2838.         s->current_picture.error[i] = 0;
  2839.     }
  2840.     if(s->codec_id==AV_CODEC_ID_AMV){
  2841.         s->last_dc[0] = 128*8/13;
  2842.         s->last_dc[1] = 128*8/14;
  2843.         s->last_dc[2] = 128*8/14;
  2844.     }
  2845.     s->mb_skip_run = 0;
  2846.     memset(s->last_mv, 0, sizeof(s->last_mv));
  2847.  
  2848.     s->last_mv_dir = 0;
  2849.  
  2850.     switch(s->codec_id){
  2851.     case AV_CODEC_ID_H263:
  2852.     case AV_CODEC_ID_H263P:
  2853.     case AV_CODEC_ID_FLV1:
  2854.         if (CONFIG_H263_ENCODER)
  2855.             s->gob_index = H263_GOB_HEIGHT(s->height);
  2856.         break;
  2857.     case AV_CODEC_ID_MPEG4:
  2858.         if(CONFIG_MPEG4_ENCODER && s->partitioned_frame)
  2859.             ff_mpeg4_init_partitions(s);
  2860.         break;
  2861.     }
  2862.  
  2863.     s->resync_mb_x=0;
  2864.     s->resync_mb_y=0;
  2865.     s->first_slice_line = 1;
  2866.     s->ptr_lastgob = s->pb.buf;
  2867.     for(mb_y= s->start_mb_y; mb_y < s->end_mb_y; mb_y++) {
  2868.         s->mb_x=0;
  2869.         s->mb_y= mb_y;
  2870.  
  2871.         ff_set_qscale(s, s->qscale);
  2872.         ff_init_block_index(s);
  2873.  
  2874.         for(mb_x=0; mb_x < s->mb_width; mb_x++) {
  2875.             int xy= mb_y*s->mb_stride + mb_x; // removed const, H261 needs to adjust this
  2876.             int mb_type= s->mb_type[xy];
  2877. //            int d;
  2878.             int dmin= INT_MAX;
  2879.             int dir;
  2880.             int size_increase =  s->avctx->internal->byte_buffer_size/4
  2881.                                + s->mb_width*MAX_MB_BYTES;
  2882.  
  2883.             ff_mpv_reallocate_putbitbuffer(s, MAX_MB_BYTES, size_increase);
  2884.             if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < MAX_MB_BYTES){
  2885.                 av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
  2886.                 return -1;
  2887.             }
  2888.             if(s->data_partitioning){
  2889.                 if(   s->pb2   .buf_end - s->pb2   .buf - (put_bits_count(&s->    pb2)>>3) < MAX_MB_BYTES
  2890.                    || s->tex_pb.buf_end - s->tex_pb.buf - (put_bits_count(&s->tex_pb )>>3) < MAX_MB_BYTES){
  2891.                     av_log(s->avctx, AV_LOG_ERROR, "encoded partitioned frame too large\n");
  2892.                     return -1;
  2893.                 }
  2894.             }
  2895.  
  2896.             s->mb_x = mb_x;
  2897.             s->mb_y = mb_y;  // moved into loop, can get changed by H.261
  2898.             ff_update_block_index(s);
  2899.  
  2900.             if(CONFIG_H261_ENCODER && s->codec_id == AV_CODEC_ID_H261){
  2901.                 ff_h261_reorder_mb_index(s);
  2902.                 xy= s->mb_y*s->mb_stride + s->mb_x;
  2903.                 mb_type= s->mb_type[xy];
  2904.             }
  2905.  
  2906.             /* write gob / video packet header  */
  2907.             if(s->rtp_mode){
  2908.                 int current_packet_size, is_gob_start;
  2909.  
  2910.                 current_packet_size= ((put_bits_count(&s->pb)+7)>>3) - (s->ptr_lastgob - s->pb.buf);
  2911.  
  2912.                 is_gob_start= s->avctx->rtp_payload_size && current_packet_size >= s->avctx->rtp_payload_size && mb_y + mb_x>0;
  2913.  
  2914.                 if(s->start_mb_y == mb_y && mb_y > 0 && mb_x==0) is_gob_start=1;
  2915.  
  2916.                 switch(s->codec_id){
  2917.                 case AV_CODEC_ID_H263:
  2918.                 case AV_CODEC_ID_H263P:
  2919.                     if(!s->h263_slice_structured)
  2920.                         if(s->mb_x || s->mb_y%s->gob_index) is_gob_start=0;
  2921.                     break;
  2922.                 case AV_CODEC_ID_MPEG2VIDEO:
  2923.                     if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
  2924.                 case AV_CODEC_ID_MPEG1VIDEO:
  2925.                     if(s->mb_skip_run) is_gob_start=0;
  2926.                     break;
  2927.                 case AV_CODEC_ID_MJPEG:
  2928.                     if(s->mb_x==0 && s->mb_y!=0) is_gob_start=1;
  2929.                     break;
  2930.                 }
  2931.  
  2932.                 if(is_gob_start){
  2933.                     if(s->start_mb_y != mb_y || mb_x!=0){
  2934.                         write_slice_end(s);
  2935.  
  2936.                         if(CONFIG_MPEG4_ENCODER && s->codec_id==AV_CODEC_ID_MPEG4 && s->partitioned_frame){
  2937.                             ff_mpeg4_init_partitions(s);
  2938.                         }
  2939.                     }
  2940.  
  2941.                     av_assert2((put_bits_count(&s->pb)&7) == 0);
  2942.                     current_packet_size= put_bits_ptr(&s->pb) - s->ptr_lastgob;
  2943.  
  2944.                     if (s->error_rate && s->resync_mb_x + s->resync_mb_y > 0) {
  2945.                         int r= put_bits_count(&s->pb)/8 + s->picture_number + 16 + s->mb_x + s->mb_y;
  2946.                         int d = 100 / s->error_rate;
  2947.                         if(r % d == 0){
  2948.                             current_packet_size=0;
  2949.                             s->pb.buf_ptr= s->ptr_lastgob;
  2950.                             assert(put_bits_ptr(&s->pb) == s->ptr_lastgob);
  2951.                         }
  2952.                     }
  2953.  
  2954.                     if (s->avctx->rtp_callback){
  2955.                         int number_mb = (mb_y - s->resync_mb_y)*s->mb_width + mb_x - s->resync_mb_x;
  2956.                         s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, current_packet_size, number_mb);
  2957.                     }
  2958.                     update_mb_info(s, 1);
  2959.  
  2960.                     switch(s->codec_id){
  2961.                     case AV_CODEC_ID_MPEG4:
  2962.                         if (CONFIG_MPEG4_ENCODER) {
  2963.                             ff_mpeg4_encode_video_packet_header(s);
  2964.                             ff_mpeg4_clean_buffers(s);
  2965.                         }
  2966.                     break;
  2967.                     case AV_CODEC_ID_MPEG1VIDEO:
  2968.                     case AV_CODEC_ID_MPEG2VIDEO:
  2969.                         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER) {
  2970.                             ff_mpeg1_encode_slice_header(s);
  2971.                             ff_mpeg1_clean_buffers(s);
  2972.                         }
  2973.                     break;
  2974.                     case AV_CODEC_ID_H263:
  2975.                     case AV_CODEC_ID_H263P:
  2976.                         if (CONFIG_H263_ENCODER)
  2977.                             ff_h263_encode_gob_header(s, mb_y);
  2978.                     break;
  2979.                     }
  2980.  
  2981.                     if (s->avctx->flags & AV_CODEC_FLAG_PASS1) {
  2982.                         int bits= put_bits_count(&s->pb);
  2983.                         s->misc_bits+= bits - s->last_bits;
  2984.                         s->last_bits= bits;
  2985.                     }
  2986.  
  2987.                     s->ptr_lastgob += current_packet_size;
  2988.                     s->first_slice_line=1;
  2989.                     s->resync_mb_x=mb_x;
  2990.                     s->resync_mb_y=mb_y;
  2991.                 }
  2992.             }
  2993.  
  2994.             if(  (s->resync_mb_x   == s->mb_x)
  2995.                && s->resync_mb_y+1 == s->mb_y){
  2996.                 s->first_slice_line=0;
  2997.             }
  2998.  
  2999.             s->mb_skipped=0;
  3000.             s->dquant=0; //only for QP_RD
  3001.  
  3002.             update_mb_info(s, 0);
  3003.  
  3004.             if (mb_type & (mb_type-1) || (s->mpv_flags & FF_MPV_FLAG_QP_RD)) { // more than 1 MB type possible or FF_MPV_FLAG_QP_RD
  3005.                 int next_block=0;
  3006.                 int pb_bits_count, pb2_bits_count, tex_pb_bits_count;
  3007.  
  3008.                 copy_context_before_encode(&backup_s, s, -1);
  3009.                 backup_s.pb= s->pb;
  3010.                 best_s.data_partitioning= s->data_partitioning;
  3011.                 best_s.partitioned_frame= s->partitioned_frame;
  3012.                 if(s->data_partitioning){
  3013.                     backup_s.pb2= s->pb2;
  3014.                     backup_s.tex_pb= s->tex_pb;
  3015.                 }
  3016.  
  3017.                 if(mb_type&CANDIDATE_MB_TYPE_INTER){
  3018.                     s->mv_dir = MV_DIR_FORWARD;
  3019.                     s->mv_type = MV_TYPE_16X16;
  3020.                     s->mb_intra= 0;
  3021.                     s->mv[0][0][0] = s->p_mv_table[xy][0];
  3022.                     s->mv[0][0][1] = s->p_mv_table[xy][1];
  3023.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER, pb, pb2, tex_pb,
  3024.                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  3025.                 }
  3026.                 if(mb_type&CANDIDATE_MB_TYPE_INTER_I){
  3027.                     s->mv_dir = MV_DIR_FORWARD;
  3028.                     s->mv_type = MV_TYPE_FIELD;
  3029.                     s->mb_intra= 0;
  3030.                     for(i=0; i<2; i++){
  3031.                         j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  3032.                         s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  3033.                         s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  3034.                     }
  3035.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER_I, pb, pb2, tex_pb,
  3036.                                  &dmin, &next_block, 0, 0);
  3037.                 }
  3038.                 if(mb_type&CANDIDATE_MB_TYPE_SKIPPED){
  3039.                     s->mv_dir = MV_DIR_FORWARD;
  3040.                     s->mv_type = MV_TYPE_16X16;
  3041.                     s->mb_intra= 0;
  3042.                     s->mv[0][0][0] = 0;
  3043.                     s->mv[0][0][1] = 0;
  3044.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_SKIPPED, pb, pb2, tex_pb,
  3045.                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  3046.                 }
  3047.                 if(mb_type&CANDIDATE_MB_TYPE_INTER4V){
  3048.                     s->mv_dir = MV_DIR_FORWARD;
  3049.                     s->mv_type = MV_TYPE_8X8;
  3050.                     s->mb_intra= 0;
  3051.                     for(i=0; i<4; i++){
  3052.                         s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  3053.                         s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  3054.                     }
  3055.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER4V, pb, pb2, tex_pb,
  3056.                                  &dmin, &next_block, 0, 0);
  3057.                 }
  3058.                 if(mb_type&CANDIDATE_MB_TYPE_FORWARD){
  3059.                     s->mv_dir = MV_DIR_FORWARD;
  3060.                     s->mv_type = MV_TYPE_16X16;
  3061.                     s->mb_intra= 0;
  3062.                     s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  3063.                     s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  3064.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD, pb, pb2, tex_pb,
  3065.                                  &dmin, &next_block, s->mv[0][0][0], s->mv[0][0][1]);
  3066.                 }
  3067.                 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD){
  3068.                     s->mv_dir = MV_DIR_BACKWARD;
  3069.                     s->mv_type = MV_TYPE_16X16;
  3070.                     s->mb_intra= 0;
  3071.                     s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  3072.                     s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  3073.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD, pb, pb2, tex_pb,
  3074.                                  &dmin, &next_block, s->mv[1][0][0], s->mv[1][0][1]);
  3075.                 }
  3076.                 if(mb_type&CANDIDATE_MB_TYPE_BIDIR){
  3077.                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  3078.                     s->mv_type = MV_TYPE_16X16;
  3079.                     s->mb_intra= 0;
  3080.                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  3081.                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  3082.                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  3083.                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  3084.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR, pb, pb2, tex_pb,
  3085.                                  &dmin, &next_block, 0, 0);
  3086.                 }
  3087.                 if(mb_type&CANDIDATE_MB_TYPE_FORWARD_I){
  3088.                     s->mv_dir = MV_DIR_FORWARD;
  3089.                     s->mv_type = MV_TYPE_FIELD;
  3090.                     s->mb_intra= 0;
  3091.                     for(i=0; i<2; i++){
  3092.                         j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  3093.                         s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  3094.                         s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  3095.                     }
  3096.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_FORWARD_I, pb, pb2, tex_pb,
  3097.                                  &dmin, &next_block, 0, 0);
  3098.                 }
  3099.                 if(mb_type&CANDIDATE_MB_TYPE_BACKWARD_I){
  3100.                     s->mv_dir = MV_DIR_BACKWARD;
  3101.                     s->mv_type = MV_TYPE_FIELD;
  3102.                     s->mb_intra= 0;
  3103.                     for(i=0; i<2; i++){
  3104.                         j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  3105.                         s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  3106.                         s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  3107.                     }
  3108.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BACKWARD_I, pb, pb2, tex_pb,
  3109.                                  &dmin, &next_block, 0, 0);
  3110.                 }
  3111.                 if(mb_type&CANDIDATE_MB_TYPE_BIDIR_I){
  3112.                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  3113.                     s->mv_type = MV_TYPE_FIELD;
  3114.                     s->mb_intra= 0;
  3115.                     for(dir=0; dir<2; dir++){
  3116.                         for(i=0; i<2; i++){
  3117.                             j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  3118.                             s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  3119.                             s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  3120.                         }
  3121.                     }
  3122.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_BIDIR_I, pb, pb2, tex_pb,
  3123.                                  &dmin, &next_block, 0, 0);
  3124.                 }
  3125.                 if(mb_type&CANDIDATE_MB_TYPE_INTRA){
  3126.                     s->mv_dir = 0;
  3127.                     s->mv_type = MV_TYPE_16X16;
  3128.                     s->mb_intra= 1;
  3129.                     s->mv[0][0][0] = 0;
  3130.                     s->mv[0][0][1] = 0;
  3131.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTRA, pb, pb2, tex_pb,
  3132.                                  &dmin, &next_block, 0, 0);
  3133.                     if(s->h263_pred || s->h263_aic){
  3134.                         if(best_s.mb_intra)
  3135.                             s->mbintra_table[mb_x + mb_y*s->mb_stride]=1;
  3136.                         else
  3137.                             ff_clean_intra_table_entries(s); //old mode?
  3138.                     }
  3139.                 }
  3140.  
  3141.                 if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) && dmin < INT_MAX) {
  3142.                     if(best_s.mv_type==MV_TYPE_16X16){ //FIXME move 4mv after QPRD
  3143.                         const int last_qp= backup_s.qscale;
  3144.                         int qpi, qp, dc[6];
  3145.                         int16_t ac[6][16];
  3146.                         const int mvdir= (best_s.mv_dir&MV_DIR_BACKWARD) ? 1 : 0;
  3147.                         static const int dquant_tab[4]={-1,1,-2,2};
  3148.                         int storecoefs = s->mb_intra && s->dc_val[0];
  3149.  
  3150.                         av_assert2(backup_s.dquant == 0);
  3151.  
  3152.                         //FIXME intra
  3153.                         s->mv_dir= best_s.mv_dir;
  3154.                         s->mv_type = MV_TYPE_16X16;
  3155.                         s->mb_intra= best_s.mb_intra;
  3156.                         s->mv[0][0][0] = best_s.mv[0][0][0];
  3157.                         s->mv[0][0][1] = best_s.mv[0][0][1];
  3158.                         s->mv[1][0][0] = best_s.mv[1][0][0];
  3159.                         s->mv[1][0][1] = best_s.mv[1][0][1];
  3160.  
  3161.                         qpi = s->pict_type == AV_PICTURE_TYPE_B ? 2 : 0;
  3162.                         for(; qpi<4; qpi++){
  3163.                             int dquant= dquant_tab[qpi];
  3164.                             qp= last_qp + dquant;
  3165.                             if(qp < s->avctx->qmin || qp > s->avctx->qmax)
  3166.                                 continue;
  3167.                             backup_s.dquant= dquant;
  3168.                             if(storecoefs){
  3169.                                 for(i=0; i<6; i++){
  3170.                                     dc[i]= s->dc_val[0][ s->block_index[i] ];
  3171.                                     memcpy(ac[i], s->ac_val[0][s->block_index[i]], sizeof(int16_t)*16);
  3172.                                 }
  3173.                             }
  3174.  
  3175.                             encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  3176.                                          &dmin, &next_block, s->mv[mvdir][0][0], s->mv[mvdir][0][1]);
  3177.                             if(best_s.qscale != qp){
  3178.                                 if(storecoefs){
  3179.                                     for(i=0; i<6; i++){
  3180.                                         s->dc_val[0][ s->block_index[i] ]= dc[i];
  3181.                                         memcpy(s->ac_val[0][s->block_index[i]], ac[i], sizeof(int16_t)*16);
  3182.                                     }
  3183.                                 }
  3184.                             }
  3185.                         }
  3186.                     }
  3187.                 }
  3188.                 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT){
  3189.                     int mx= s->b_direct_mv_table[xy][0];
  3190.                     int my= s->b_direct_mv_table[xy][1];
  3191.  
  3192.                     backup_s.dquant = 0;
  3193.                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  3194.                     s->mb_intra= 0;
  3195.                     ff_mpeg4_set_direct_mv(s, mx, my);
  3196.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  3197.                                  &dmin, &next_block, mx, my);
  3198.                 }
  3199.                 if(CONFIG_MPEG4_ENCODER && mb_type&CANDIDATE_MB_TYPE_DIRECT0){
  3200.                     backup_s.dquant = 0;
  3201.                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
  3202.                     s->mb_intra= 0;
  3203.                     ff_mpeg4_set_direct_mv(s, 0, 0);
  3204.                     encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_DIRECT, pb, pb2, tex_pb,
  3205.                                  &dmin, &next_block, 0, 0);
  3206.                 }
  3207.                 if (!best_s.mb_intra && s->mpv_flags & FF_MPV_FLAG_SKIP_RD) {
  3208.                     int coded=0;
  3209.                     for(i=0; i<6; i++)
  3210.                         coded |= s->block_last_index[i];
  3211.                     if(coded){
  3212.                         int mx,my;
  3213.                         memcpy(s->mv, best_s.mv, sizeof(s->mv));
  3214.                         if(CONFIG_MPEG4_ENCODER && best_s.mv_dir & MV_DIRECT){
  3215.                             mx=my=0; //FIXME find the one we actually used
  3216.                             ff_mpeg4_set_direct_mv(s, mx, my);
  3217.                         }else if(best_s.mv_dir&MV_DIR_BACKWARD){
  3218.                             mx= s->mv[1][0][0];
  3219.                             my= s->mv[1][0][1];
  3220.                         }else{
  3221.                             mx= s->mv[0][0][0];
  3222.                             my= s->mv[0][0][1];
  3223.                         }
  3224.  
  3225.                         s->mv_dir= best_s.mv_dir;
  3226.                         s->mv_type = best_s.mv_type;
  3227.                         s->mb_intra= 0;
  3228. /*                        s->mv[0][0][0] = best_s.mv[0][0][0];
  3229.                         s->mv[0][0][1] = best_s.mv[0][0][1];
  3230.                         s->mv[1][0][0] = best_s.mv[1][0][0];
  3231.                         s->mv[1][0][1] = best_s.mv[1][0][1];*/
  3232.                         backup_s.dquant= 0;
  3233.                         s->skipdct=1;
  3234.                         encode_mb_hq(s, &backup_s, &best_s, CANDIDATE_MB_TYPE_INTER /* wrong but unused */, pb, pb2, tex_pb,
  3235.                                         &dmin, &next_block, mx, my);
  3236.                         s->skipdct=0;
  3237.                     }
  3238.                 }
  3239.  
  3240.                 s->current_picture.qscale_table[xy] = best_s.qscale;
  3241.  
  3242.                 copy_context_after_encode(s, &best_s, -1);
  3243.  
  3244.                 pb_bits_count= put_bits_count(&s->pb);
  3245.                 flush_put_bits(&s->pb);
  3246.                 avpriv_copy_bits(&backup_s.pb, bit_buf[next_block^1], pb_bits_count);
  3247.                 s->pb= backup_s.pb;
  3248.  
  3249.                 if(s->data_partitioning){
  3250.                     pb2_bits_count= put_bits_count(&s->pb2);
  3251.                     flush_put_bits(&s->pb2);
  3252.                     avpriv_copy_bits(&backup_s.pb2, bit_buf2[next_block^1], pb2_bits_count);
  3253.                     s->pb2= backup_s.pb2;
  3254.  
  3255.                     tex_pb_bits_count= put_bits_count(&s->tex_pb);
  3256.                     flush_put_bits(&s->tex_pb);
  3257.                     avpriv_copy_bits(&backup_s.tex_pb, bit_buf_tex[next_block^1], tex_pb_bits_count);
  3258.                     s->tex_pb= backup_s.tex_pb;
  3259.                 }
  3260.                 s->last_bits= put_bits_count(&s->pb);
  3261.  
  3262.                 if (CONFIG_H263_ENCODER &&
  3263.                     s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  3264.                     ff_h263_update_motion_val(s);
  3265.  
  3266.                 if(next_block==0){ //FIXME 16 vs linesize16
  3267.                     s->hdsp.put_pixels_tab[0][0](s->dest[0], s->sc.rd_scratchpad                     , s->linesize  ,16);
  3268.                     s->hdsp.put_pixels_tab[1][0](s->dest[1], s->sc.rd_scratchpad + 16*s->linesize    , s->uvlinesize, 8);
  3269.                     s->hdsp.put_pixels_tab[1][0](s->dest[2], s->sc.rd_scratchpad + 16*s->linesize + 8, s->uvlinesize, 8);
  3270.                 }
  3271.  
  3272.                 if(s->avctx->mb_decision == FF_MB_DECISION_BITS)
  3273.                     ff_mpv_decode_mb(s, s->block);
  3274.             } else {
  3275.                 int motion_x = 0, motion_y = 0;
  3276.                 s->mv_type=MV_TYPE_16X16;
  3277.                 // only one MB-Type possible
  3278.  
  3279.                 switch(mb_type){
  3280.                 case CANDIDATE_MB_TYPE_INTRA:
  3281.                     s->mv_dir = 0;
  3282.                     s->mb_intra= 1;
  3283.                     motion_x= s->mv[0][0][0] = 0;
  3284.                     motion_y= s->mv[0][0][1] = 0;
  3285.                     break;
  3286.                 case CANDIDATE_MB_TYPE_INTER:
  3287.                     s->mv_dir = MV_DIR_FORWARD;
  3288.                     s->mb_intra= 0;
  3289.                     motion_x= s->mv[0][0][0] = s->p_mv_table[xy][0];
  3290.                     motion_y= s->mv[0][0][1] = s->p_mv_table[xy][1];
  3291.                     break;
  3292.                 case CANDIDATE_MB_TYPE_INTER_I:
  3293.                     s->mv_dir = MV_DIR_FORWARD;
  3294.                     s->mv_type = MV_TYPE_FIELD;
  3295.                     s->mb_intra= 0;
  3296.                     for(i=0; i<2; i++){
  3297.                         j= s->field_select[0][i] = s->p_field_select_table[i][xy];
  3298.                         s->mv[0][i][0] = s->p_field_mv_table[i][j][xy][0];
  3299.                         s->mv[0][i][1] = s->p_field_mv_table[i][j][xy][1];
  3300.                     }
  3301.                     break;
  3302.                 case CANDIDATE_MB_TYPE_INTER4V:
  3303.                     s->mv_dir = MV_DIR_FORWARD;
  3304.                     s->mv_type = MV_TYPE_8X8;
  3305.                     s->mb_intra= 0;
  3306.                     for(i=0; i<4; i++){
  3307.                         s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
  3308.                         s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
  3309.                     }
  3310.                     break;
  3311.                 case CANDIDATE_MB_TYPE_DIRECT:
  3312.                     if (CONFIG_MPEG4_ENCODER) {
  3313.                         s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  3314.                         s->mb_intra= 0;
  3315.                         motion_x=s->b_direct_mv_table[xy][0];
  3316.                         motion_y=s->b_direct_mv_table[xy][1];
  3317.                         ff_mpeg4_set_direct_mv(s, motion_x, motion_y);
  3318.                     }
  3319.                     break;
  3320.                 case CANDIDATE_MB_TYPE_DIRECT0:
  3321.                     if (CONFIG_MPEG4_ENCODER) {
  3322.                         s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD|MV_DIRECT;
  3323.                         s->mb_intra= 0;
  3324.                         ff_mpeg4_set_direct_mv(s, 0, 0);
  3325.                     }
  3326.                     break;
  3327.                 case CANDIDATE_MB_TYPE_BIDIR:
  3328.                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  3329.                     s->mb_intra= 0;
  3330.                     s->mv[0][0][0] = s->b_bidir_forw_mv_table[xy][0];
  3331.                     s->mv[0][0][1] = s->b_bidir_forw_mv_table[xy][1];
  3332.                     s->mv[1][0][0] = s->b_bidir_back_mv_table[xy][0];
  3333.                     s->mv[1][0][1] = s->b_bidir_back_mv_table[xy][1];
  3334.                     break;
  3335.                 case CANDIDATE_MB_TYPE_BACKWARD:
  3336.                     s->mv_dir = MV_DIR_BACKWARD;
  3337.                     s->mb_intra= 0;
  3338.                     motion_x= s->mv[1][0][0] = s->b_back_mv_table[xy][0];
  3339.                     motion_y= s->mv[1][0][1] = s->b_back_mv_table[xy][1];
  3340.                     break;
  3341.                 case CANDIDATE_MB_TYPE_FORWARD:
  3342.                     s->mv_dir = MV_DIR_FORWARD;
  3343.                     s->mb_intra= 0;
  3344.                     motion_x= s->mv[0][0][0] = s->b_forw_mv_table[xy][0];
  3345.                     motion_y= s->mv[0][0][1] = s->b_forw_mv_table[xy][1];
  3346.                     break;
  3347.                 case CANDIDATE_MB_TYPE_FORWARD_I:
  3348.                     s->mv_dir = MV_DIR_FORWARD;
  3349.                     s->mv_type = MV_TYPE_FIELD;
  3350.                     s->mb_intra= 0;
  3351.                     for(i=0; i<2; i++){
  3352.                         j= s->field_select[0][i] = s->b_field_select_table[0][i][xy];
  3353.                         s->mv[0][i][0] = s->b_field_mv_table[0][i][j][xy][0];
  3354.                         s->mv[0][i][1] = s->b_field_mv_table[0][i][j][xy][1];
  3355.                     }
  3356.                     break;
  3357.                 case CANDIDATE_MB_TYPE_BACKWARD_I:
  3358.                     s->mv_dir = MV_DIR_BACKWARD;
  3359.                     s->mv_type = MV_TYPE_FIELD;
  3360.                     s->mb_intra= 0;
  3361.                     for(i=0; i<2; i++){
  3362.                         j= s->field_select[1][i] = s->b_field_select_table[1][i][xy];
  3363.                         s->mv[1][i][0] = s->b_field_mv_table[1][i][j][xy][0];
  3364.                         s->mv[1][i][1] = s->b_field_mv_table[1][i][j][xy][1];
  3365.                     }
  3366.                     break;
  3367.                 case CANDIDATE_MB_TYPE_BIDIR_I:
  3368.                     s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD;
  3369.                     s->mv_type = MV_TYPE_FIELD;
  3370.                     s->mb_intra= 0;
  3371.                     for(dir=0; dir<2; dir++){
  3372.                         for(i=0; i<2; i++){
  3373.                             j= s->field_select[dir][i] = s->b_field_select_table[dir][i][xy];
  3374.                             s->mv[dir][i][0] = s->b_field_mv_table[dir][i][j][xy][0];
  3375.                             s->mv[dir][i][1] = s->b_field_mv_table[dir][i][j][xy][1];
  3376.                         }
  3377.                     }
  3378.                     break;
  3379.                 default:
  3380.                     av_log(s->avctx, AV_LOG_ERROR, "illegal MB type\n");
  3381.                 }
  3382.  
  3383.                 encode_mb(s, motion_x, motion_y);
  3384.  
  3385.                 // RAL: Update last macroblock type
  3386.                 s->last_mv_dir = s->mv_dir;
  3387.  
  3388.                 if (CONFIG_H263_ENCODER &&
  3389.                     s->out_format == FMT_H263 && s->pict_type!=AV_PICTURE_TYPE_B)
  3390.                     ff_h263_update_motion_val(s);
  3391.  
  3392.                 ff_mpv_decode_mb(s, s->block);
  3393.             }
  3394.  
  3395.             /* clean the MV table in IPS frames for direct mode in B frames */
  3396.             if(s->mb_intra /* && I,P,S_TYPE */){
  3397.                 s->p_mv_table[xy][0]=0;
  3398.                 s->p_mv_table[xy][1]=0;
  3399.             }
  3400.  
  3401.             if (s->avctx->flags & AV_CODEC_FLAG_PSNR) {
  3402.                 int w= 16;
  3403.                 int h= 16;
  3404.  
  3405.                 if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;
  3406.                 if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;
  3407.  
  3408.                 s->current_picture.error[0] += sse(
  3409.                     s, s->new_picture.f->data[0] + s->mb_x*16 + s->mb_y*s->linesize*16,
  3410.                     s->dest[0], w, h, s->linesize);
  3411.                 s->current_picture.error[1] += sse(
  3412.                     s, s->new_picture.f->data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
  3413.                     s->dest[1], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  3414.                 s->current_picture.error[2] += sse(
  3415.                     s, s->new_picture.f->data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*chr_h,
  3416.                     s->dest[2], w>>1, h>>s->chroma_y_shift, s->uvlinesize);
  3417.             }
  3418.             if(s->loop_filter){
  3419.                 if(CONFIG_H263_ENCODER && s->out_format == FMT_H263)
  3420.                     ff_h263_loop_filter(s);
  3421.             }
  3422.             ff_dlog(s->avctx, "MB %d %d bits\n",
  3423.                     s->mb_x + s->mb_y * s->mb_stride, put_bits_count(&s->pb));
  3424.         }
  3425.     }
  3426.  
  3427.     //not beautiful here but we must write it before flushing so it has to be here
  3428.     if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version && s->msmpeg4_version<4 && s->pict_type == AV_PICTURE_TYPE_I)
  3429.         ff_msmpeg4_encode_ext_header(s);
  3430.  
  3431.     write_slice_end(s);
  3432.  
  3433.     /* Send the last GOB if RTP */
  3434.     if (s->avctx->rtp_callback) {
  3435.         int number_mb = (mb_y - s->resync_mb_y)*s->mb_width - s->resync_mb_x;
  3436.         pdif = put_bits_ptr(&s->pb) - s->ptr_lastgob;
  3437.         /* Call the RTP callback to send the last GOB */
  3438.         emms_c();
  3439.         s->avctx->rtp_callback(s->avctx, s->ptr_lastgob, pdif, number_mb);
  3440.     }
  3441.  
  3442.     return 0;
  3443. }
  3444.  
  3445. #define MERGE(field) dst->field += src->field; src->field=0
  3446. static void merge_context_after_me(MpegEncContext *dst, MpegEncContext *src){
  3447.     MERGE(me.scene_change_score);
  3448.     MERGE(me.mc_mb_var_sum_temp);
  3449.     MERGE(me.mb_var_sum_temp);
  3450. }
  3451.  
  3452. static void merge_context_after_encode(MpegEncContext *dst, MpegEncContext *src){
  3453.     int i;
  3454.  
  3455.     MERGE(dct_count[0]); //note, the other dct vars are not part of the context
  3456.     MERGE(dct_count[1]);
  3457.     MERGE(mv_bits);
  3458.     MERGE(i_tex_bits);
  3459.     MERGE(p_tex_bits);
  3460.     MERGE(i_count);
  3461.     MERGE(f_count);
  3462.     MERGE(b_count);
  3463.     MERGE(skip_count);
  3464.     MERGE(misc_bits);
  3465.     MERGE(er.error_count);
  3466.     MERGE(padding_bug_score);
  3467.     MERGE(current_picture.error[0]);
  3468.     MERGE(current_picture.error[1]);
  3469.     MERGE(current_picture.error[2]);
  3470.  
  3471.     if(dst->avctx->noise_reduction){
  3472.         for(i=0; i<64; i++){
  3473.             MERGE(dct_error_sum[0][i]);
  3474.             MERGE(dct_error_sum[1][i]);
  3475.         }
  3476.     }
  3477.  
  3478.     assert(put_bits_count(&src->pb) % 8 ==0);
  3479.     assert(put_bits_count(&dst->pb) % 8 ==0);
  3480.     avpriv_copy_bits(&dst->pb, src->pb.buf, put_bits_count(&src->pb));
  3481.     flush_put_bits(&dst->pb);
  3482. }
  3483.  
  3484. static int estimate_qp(MpegEncContext *s, int dry_run){
  3485.     if (s->next_lambda){
  3486.         s->current_picture_ptr->f->quality =
  3487.         s->current_picture.f->quality = s->next_lambda;
  3488.         if(!dry_run) s->next_lambda= 0;
  3489.     } else if (!s->fixed_qscale) {
  3490.         s->current_picture_ptr->f->quality =
  3491.         s->current_picture.f->quality = ff_rate_estimate_qscale(s, dry_run);
  3492.         if (s->current_picture.f->quality < 0)
  3493.             return -1;
  3494.     }
  3495.  
  3496.     if(s->adaptive_quant){
  3497.         switch(s->codec_id){
  3498.         case AV_CODEC_ID_MPEG4:
  3499.             if (CONFIG_MPEG4_ENCODER)
  3500.                 ff_clean_mpeg4_qscales(s);
  3501.             break;
  3502.         case AV_CODEC_ID_H263:
  3503.         case AV_CODEC_ID_H263P:
  3504.         case AV_CODEC_ID_FLV1:
  3505.             if (CONFIG_H263_ENCODER)
  3506.                 ff_clean_h263_qscales(s);
  3507.             break;
  3508.         default:
  3509.             ff_init_qscale_tab(s);
  3510.         }
  3511.  
  3512.         s->lambda= s->lambda_table[0];
  3513.         //FIXME broken
  3514.     }else
  3515.         s->lambda = s->current_picture.f->quality;
  3516.     update_qscale(s);
  3517.     return 0;
  3518. }
  3519.  
  3520. /* must be called before writing the header */
  3521. static void set_frame_distances(MpegEncContext * s){
  3522.     av_assert1(s->current_picture_ptr->f->pts != AV_NOPTS_VALUE);
  3523.     s->time = s->current_picture_ptr->f->pts * s->avctx->time_base.num;
  3524.  
  3525.     if(s->pict_type==AV_PICTURE_TYPE_B){
  3526.         s->pb_time= s->pp_time - (s->last_non_b_time - s->time);
  3527.         assert(s->pb_time > 0 && s->pb_time < s->pp_time);
  3528.     }else{
  3529.         s->pp_time= s->time - s->last_non_b_time;
  3530.         s->last_non_b_time= s->time;
  3531.         assert(s->picture_number==0 || s->pp_time > 0);
  3532.     }
  3533. }
  3534.  
  3535. static int encode_picture(MpegEncContext *s, int picture_number)
  3536. {
  3537.     int i, ret;
  3538.     int bits;
  3539.     int context_count = s->slice_context_count;
  3540.  
  3541.     s->picture_number = picture_number;
  3542.  
  3543.     /* Reset the average MB variance */
  3544.     s->me.mb_var_sum_temp    =
  3545.     s->me.mc_mb_var_sum_temp = 0;
  3546.  
  3547.     /* we need to initialize some time vars before we can encode b-frames */
  3548.     // RAL: Condition added for MPEG1VIDEO
  3549.     if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO || s->codec_id == AV_CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))
  3550.         set_frame_distances(s);
  3551.     if(CONFIG_MPEG4_ENCODER && s->codec_id == AV_CODEC_ID_MPEG4)
  3552.         ff_set_mpeg4_time(s);
  3553.  
  3554.     s->me.scene_change_score=0;
  3555.  
  3556. //    s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion
  3557.  
  3558.     if(s->pict_type==AV_PICTURE_TYPE_I){
  3559.         if(s->msmpeg4_version >= 3) s->no_rounding=1;
  3560.         else                        s->no_rounding=0;
  3561.     }else if(s->pict_type!=AV_PICTURE_TYPE_B){
  3562.         if(s->flipflop_rounding || s->codec_id == AV_CODEC_ID_H263P || s->codec_id == AV_CODEC_ID_MPEG4)
  3563.             s->no_rounding ^= 1;
  3564.     }
  3565.  
  3566.     if (s->avctx->flags & AV_CODEC_FLAG_PASS2) {
  3567.         if (estimate_qp(s,1) < 0)
  3568.             return -1;
  3569.         ff_get_2pass_fcode(s);
  3570.     } else if (!(s->avctx->flags & AV_CODEC_FLAG_QSCALE)) {
  3571.         if(s->pict_type==AV_PICTURE_TYPE_B)
  3572.             s->lambda= s->last_lambda_for[s->pict_type];
  3573.         else
  3574.             s->lambda= s->last_lambda_for[s->last_non_b_pict_type];
  3575.         update_qscale(s);
  3576.     }
  3577.  
  3578.     if(s->codec_id != AV_CODEC_ID_AMV && s->codec_id != AV_CODEC_ID_MJPEG){
  3579.         if(s->q_chroma_intra_matrix   != s->q_intra_matrix  ) av_freep(&s->q_chroma_intra_matrix);
  3580.         if(s->q_chroma_intra_matrix16 != s->q_intra_matrix16) av_freep(&s->q_chroma_intra_matrix16);
  3581.         s->q_chroma_intra_matrix   = s->q_intra_matrix;
  3582.         s->q_chroma_intra_matrix16 = s->q_intra_matrix16;
  3583.     }
  3584.  
  3585.     s->mb_intra=0; //for the rate distortion & bit compare functions
  3586.     for(i=1; i<context_count; i++){
  3587.         ret = ff_update_duplicate_context(s->thread_context[i], s);
  3588.         if (ret < 0)
  3589.             return ret;
  3590.     }
  3591.  
  3592.     if(ff_init_me(s)<0)
  3593.         return -1;
  3594.  
  3595.     /* Estimate motion for every MB */
  3596.     if(s->pict_type != AV_PICTURE_TYPE_I){
  3597.         s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;
  3598.         s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;
  3599.         if (s->pict_type != AV_PICTURE_TYPE_B) {
  3600.             if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){
  3601.                 s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  3602.             }
  3603.         }
  3604.  
  3605.         s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  3606.     }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{
  3607.         /* I-Frame */
  3608.         for(i=0; i<s->mb_stride*s->mb_height; i++)
  3609.             s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  3610.  
  3611.         if(!s->fixed_qscale){
  3612.             /* finding spatial complexity for I-frame rate control */
  3613.             s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  3614.         }
  3615.     }
  3616.     for(i=1; i<context_count; i++){
  3617.         merge_context_after_me(s, s->thread_context[i]);
  3618.     }
  3619.     s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;
  3620.     s->current_picture.   mb_var_sum= s->current_picture_ptr->   mb_var_sum= s->me.   mb_var_sum_temp;
  3621.     emms_c();
  3622.  
  3623.     if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){
  3624.         s->pict_type= AV_PICTURE_TYPE_I;
  3625.         for(i=0; i<s->mb_stride*s->mb_height; i++)
  3626.             s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;
  3627.         if(s->msmpeg4_version >= 3)
  3628.             s->no_rounding=1;
  3629.         ff_dlog(s, "Scene change detected, encoding as I Frame %"PRId64" %"PRId64"\n",
  3630.                 s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);
  3631.     }
  3632.  
  3633.     if(!s->umvplus){
  3634.         if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {
  3635.             s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);
  3636.  
  3637.             if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
  3638.                 int a,b;
  3639.                 a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select
  3640.                 b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);
  3641.                 s->f_code= FFMAX3(s->f_code, a, b);
  3642.             }
  3643.  
  3644.             ff_fix_long_p_mvs(s);
  3645.             ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);
  3646.             if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
  3647.                 int j;
  3648.                 for(i=0; i<2; i++){
  3649.                     for(j=0; j<2; j++)
  3650.                         ff_fix_long_mvs(s, s->p_field_select_table[i], j,
  3651.                                         s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);
  3652.                 }
  3653.             }
  3654.         }
  3655.  
  3656.         if(s->pict_type==AV_PICTURE_TYPE_B){
  3657.             int a, b;
  3658.  
  3659.             a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);
  3660.             b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  3661.             s->f_code = FFMAX(a, b);
  3662.  
  3663.             a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);
  3664.             b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);
  3665.             s->b_code = FFMAX(a, b);
  3666.  
  3667.             ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);
  3668.             ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);
  3669.             ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  3670.             ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);
  3671.             if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {
  3672.                 int dir, j;
  3673.                 for(dir=0; dir<2; dir++){
  3674.                     for(i=0; i<2; i++){
  3675.                         for(j=0; j<2; j++){
  3676.                             int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)
  3677.                                           : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);
  3678.                             ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,
  3679.                                             s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);
  3680.                         }
  3681.                     }
  3682.                 }
  3683.             }
  3684.         }
  3685.     }
  3686.  
  3687.     if (estimate_qp(s, 0) < 0)
  3688.         return -1;
  3689.  
  3690.     if (s->qscale < 3 && s->max_qcoeff <= 128 &&
  3691.         s->pict_type == AV_PICTURE_TYPE_I &&
  3692.         !(s->avctx->flags & AV_CODEC_FLAG_QSCALE))
  3693.         s->qscale= 3; //reduce clipping problems
  3694.  
  3695.     if (s->out_format == FMT_MJPEG) {
  3696.         const uint16_t *  luma_matrix = ff_mpeg1_default_intra_matrix;
  3697.         const uint16_t *chroma_matrix = ff_mpeg1_default_intra_matrix;
  3698.  
  3699.         if (s->avctx->intra_matrix) {
  3700.             chroma_matrix =
  3701.             luma_matrix = s->avctx->intra_matrix;
  3702.         }
  3703.         if (s->avctx->chroma_intra_matrix)
  3704.             chroma_matrix = s->avctx->chroma_intra_matrix;
  3705.  
  3706.         /* for mjpeg, we do include qscale in the matrix */
  3707.         for(i=1;i<64;i++){
  3708.             int j = s->idsp.idct_permutation[i];
  3709.  
  3710.             s->chroma_intra_matrix[j] = av_clip_uint8((chroma_matrix[i] * s->qscale) >> 3);
  3711.             s->       intra_matrix[j] = av_clip_uint8((  luma_matrix[i] * s->qscale) >> 3);
  3712.         }
  3713.         s->y_dc_scale_table=
  3714.         s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];
  3715.         s->chroma_intra_matrix[0] =
  3716.         s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];
  3717.         ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,
  3718.                        s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  3719.         ff_convert_matrix(s, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,
  3720.                        s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);
  3721.         s->qscale= 8;
  3722.     }
  3723.     if(s->codec_id == AV_CODEC_ID_AMV){
  3724.         static const uint8_t y[32]={13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13};
  3725.         static const uint8_t c[32]={14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14};
  3726.         for(i=1;i<64;i++){
  3727.             int j= s->idsp.idct_permutation[ff_zigzag_direct[i]];
  3728.  
  3729.             s->intra_matrix[j] = sp5x_quant_table[5*2+0][i];
  3730.             s->chroma_intra_matrix[j] = sp5x_quant_table[5*2+1][i];
  3731.         }
  3732.         s->y_dc_scale_table= y;
  3733.         s->c_dc_scale_table= c;
  3734.         s->intra_matrix[0] = 13;
  3735.         s->chroma_intra_matrix[0] = 14;
  3736.         ff_convert_matrix(s, s->q_intra_matrix, s->q_intra_matrix16,
  3737.                        s->intra_matrix, s->intra_quant_bias, 8, 8, 1);
  3738.         ff_convert_matrix(s, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,
  3739.                        s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);
  3740.         s->qscale= 8;
  3741.     }
  3742.  
  3743.     //FIXME var duplication
  3744.     s->current_picture_ptr->f->key_frame =
  3745.     s->current_picture.f->key_frame = s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr
  3746.     s->current_picture_ptr->f->pict_type =
  3747.     s->current_picture.f->pict_type = s->pict_type;
  3748.  
  3749.     if (s->current_picture.f->key_frame)
  3750.         s->picture_in_gop_number=0;
  3751.  
  3752.     s->mb_x = s->mb_y = 0;
  3753.     s->last_bits= put_bits_count(&s->pb);
  3754.     switch(s->out_format) {
  3755.     case FMT_MJPEG:
  3756.         if (CONFIG_MJPEG_ENCODER)
  3757.             ff_mjpeg_encode_picture_header(s->avctx, &s->pb, &s->intra_scantable,
  3758.                                            s->intra_matrix, s->chroma_intra_matrix);
  3759.         break;
  3760.     case FMT_H261:
  3761.         if (CONFIG_H261_ENCODER)
  3762.             ff_h261_encode_picture_header(s, picture_number);
  3763.         break;
  3764.     case FMT_H263:
  3765.         if (CONFIG_WMV2_ENCODER && s->codec_id == AV_CODEC_ID_WMV2)
  3766.             ff_wmv2_encode_picture_header(s, picture_number);
  3767.         else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)
  3768.             ff_msmpeg4_encode_picture_header(s, picture_number);
  3769.         else if (CONFIG_MPEG4_ENCODER && s->h263_pred) {
  3770.             ret = ff_mpeg4_encode_picture_header(s, picture_number);
  3771.             if (ret < 0)
  3772.                 return ret;
  3773.         } else if (CONFIG_RV10_ENCODER && s->codec_id == AV_CODEC_ID_RV10) {
  3774.             ret = ff_rv10_encode_picture_header(s, picture_number);
  3775.             if (ret < 0)
  3776.                 return ret;
  3777.         }
  3778.         else if (CONFIG_RV20_ENCODER && s->codec_id == AV_CODEC_ID_RV20)
  3779.             ff_rv20_encode_picture_header(s, picture_number);
  3780.         else if (CONFIG_FLV_ENCODER && s->codec_id == AV_CODEC_ID_FLV1)
  3781.             ff_flv_encode_picture_header(s, picture_number);
  3782.         else if (CONFIG_H263_ENCODER)
  3783.             ff_h263_encode_picture_header(s, picture_number);
  3784.         break;
  3785.     case FMT_MPEG1:
  3786.         if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)
  3787.             ff_mpeg1_encode_picture_header(s, picture_number);
  3788.         break;
  3789.     default:
  3790.         av_assert0(0);
  3791.     }
  3792.     bits= put_bits_count(&s->pb);
  3793.     s->header_bits= bits - s->last_bits;
  3794.  
  3795.     for(i=1; i<context_count; i++){
  3796.         update_duplicate_context_after_me(s->thread_context[i], s);
  3797.     }
  3798.     s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));
  3799.     for(i=1; i<context_count; i++){
  3800.         if (s->pb.buf_end == s->thread_context[i]->pb.buf)
  3801.             set_put_bits_buffer_size(&s->pb, FFMIN(s->thread_context[i]->pb.buf_end - s->pb.buf, INT_MAX/8-32));
  3802.         merge_context_after_encode(s, s->thread_context[i]);
  3803.     }
  3804.     emms_c();
  3805.     return 0;
  3806. }
  3807.  
  3808. static void denoise_dct_c(MpegEncContext *s, int16_t *block){
  3809.     const int intra= s->mb_intra;
  3810.     int i;
  3811.  
  3812.     s->dct_count[intra]++;
  3813.  
  3814.     for(i=0; i<64; i++){
  3815.         int level= block[i];
  3816.  
  3817.         if(level){
  3818.             if(level>0){
  3819.                 s->dct_error_sum[intra][i] += level;
  3820.                 level -= s->dct_offset[intra][i];
  3821.                 if(level<0) level=0;
  3822.             }else{
  3823.                 s->dct_error_sum[intra][i] -= level;
  3824.                 level += s->dct_offset[intra][i];
  3825.                 if(level>0) level=0;
  3826.             }
  3827.             block[i]= level;
  3828.         }
  3829.     }
  3830. }
  3831.  
  3832. static int dct_quantize_trellis_c(MpegEncContext *s,
  3833.                                   int16_t *block, int n,
  3834.                                   int qscale, int *overflow){
  3835.     const int *qmat;
  3836.     const uint16_t *matrix;
  3837.     const uint8_t *scantable= s->intra_scantable.scantable;
  3838.     const uint8_t *perm_scantable= s->intra_scantable.permutated;
  3839.     int max=0;
  3840.     unsigned int threshold1, threshold2;
  3841.     int bias=0;
  3842.     int run_tab[65];
  3843.     int level_tab[65];
  3844.     int score_tab[65];
  3845.     int survivor[65];
  3846.     int survivor_count;
  3847.     int last_run=0;
  3848.     int last_level=0;
  3849.     int last_score= 0;
  3850.     int last_i;
  3851.     int coeff[2][64];
  3852.     int coeff_count[64];
  3853.     int qmul, qadd, start_i, last_non_zero, i, dc;
  3854.     const int esc_length= s->ac_esc_length;
  3855.     uint8_t * length;
  3856.     uint8_t * last_length;
  3857.     const int lambda= s->lambda2 >> (FF_LAMBDA_SHIFT - 6);
  3858.  
  3859.     s->fdsp.fdct(block);
  3860.  
  3861.     if(s->dct_error_sum)
  3862.         s->denoise_dct(s, block);
  3863.     qmul= qscale*16;
  3864.     qadd= ((qscale-1)|1)*8;
  3865.  
  3866.     if (s->mb_intra) {
  3867.         int q;
  3868.         if (!s->h263_aic) {
  3869.             if (n < 4)
  3870.                 q = s->y_dc_scale;
  3871.             else
  3872.                 q = s->c_dc_scale;
  3873.             q = q << 3;
  3874.         } else{
  3875.             /* For AIC we skip quant/dequant of INTRADC */
  3876.             q = 1 << 3;
  3877.             qadd=0;
  3878.         }
  3879.  
  3880.         /* note: block[0] is assumed to be positive */
  3881.         block[0] = (block[0] + (q >> 1)) / q;
  3882.         start_i = 1;
  3883.         last_non_zero = 0;
  3884.         qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
  3885.         matrix = n < 4 ? s->intra_matrix : s->chroma_intra_matrix;
  3886.         if(s->mpeg_quant || s->out_format == FMT_MPEG1 || s->out_format == FMT_MJPEG)
  3887.             bias= 1<<(QMAT_SHIFT-1);
  3888.  
  3889.         if (n > 3 && s->intra_chroma_ac_vlc_length) {
  3890.             length     = s->intra_chroma_ac_vlc_length;
  3891.             last_length= s->intra_chroma_ac_vlc_last_length;
  3892.         } else {
  3893.             length     = s->intra_ac_vlc_length;
  3894.             last_length= s->intra_ac_vlc_last_length;
  3895.         }
  3896.     } else {
  3897.         start_i = 0;
  3898.         last_non_zero = -1;
  3899.         qmat = s->q_inter_matrix[qscale];
  3900.         matrix = s->inter_matrix;
  3901.         length     = s->inter_ac_vlc_length;
  3902.         last_length= s->inter_ac_vlc_last_length;
  3903.     }
  3904.     last_i= start_i;
  3905.  
  3906.     threshold1= (1<<QMAT_SHIFT) - bias - 1;
  3907.     threshold2= (threshold1<<1);
  3908.  
  3909.     for(i=63; i>=start_i; i--) {
  3910.         const int j = scantable[i];
  3911.         int level = block[j] * qmat[j];
  3912.  
  3913.         if(((unsigned)(level+threshold1))>threshold2){
  3914.             last_non_zero = i;
  3915.             break;
  3916.         }
  3917.     }
  3918.  
  3919.     for(i=start_i; i<=last_non_zero; i++) {
  3920.         const int j = scantable[i];
  3921.         int level = block[j] * qmat[j];
  3922.  
  3923. //        if(   bias+level >= (1<<(QMAT_SHIFT - 3))
  3924. //           || bias-level >= (1<<(QMAT_SHIFT - 3))){
  3925.         if(((unsigned)(level+threshold1))>threshold2){
  3926.             if(level>0){
  3927.                 level= (bias + level)>>QMAT_SHIFT;
  3928.                 coeff[0][i]= level;
  3929.                 coeff[1][i]= level-1;
  3930. //                coeff[2][k]= level-2;
  3931.             }else{
  3932.                 level= (bias - level)>>QMAT_SHIFT;
  3933.                 coeff[0][i]= -level;
  3934.                 coeff[1][i]= -level+1;
  3935. //                coeff[2][k]= -level+2;
  3936.             }
  3937.             coeff_count[i]= FFMIN(level, 2);
  3938.             av_assert2(coeff_count[i]);
  3939.             max |=level;
  3940.         }else{
  3941.             coeff[0][i]= (level>>31)|1;
  3942.             coeff_count[i]= 1;
  3943.         }
  3944.     }
  3945.  
  3946.     *overflow= s->max_qcoeff < max; //overflow might have happened
  3947.  
  3948.     if(last_non_zero < start_i){
  3949.         memset(block + start_i, 0, (64-start_i)*sizeof(int16_t));
  3950.         return last_non_zero;
  3951.     }
  3952.  
  3953.     score_tab[start_i]= 0;
  3954.     survivor[0]= start_i;
  3955.     survivor_count= 1;
  3956.  
  3957.     for(i=start_i; i<=last_non_zero; i++){
  3958.         int level_index, j, zero_distortion;
  3959.         int dct_coeff= FFABS(block[ scantable[i] ]);
  3960.         int best_score=256*256*256*120;
  3961.  
  3962.         if (s->fdsp.fdct == ff_fdct_ifast)
  3963.             dct_coeff= (dct_coeff*ff_inv_aanscales[ scantable[i] ]) >> 12;
  3964.         zero_distortion= dct_coeff*dct_coeff;
  3965.  
  3966.         for(level_index=0; level_index < coeff_count[i]; level_index++){
  3967.             int distortion;
  3968.             int level= coeff[level_index][i];
  3969.             const int alevel= FFABS(level);
  3970.             int unquant_coeff;
  3971.  
  3972.             av_assert2(level);
  3973.  
  3974.             if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
  3975.                 unquant_coeff= alevel*qmul + qadd;
  3976.             } else if(s->out_format == FMT_MJPEG) {
  3977.                 j = s->idsp.idct_permutation[scantable[i]];
  3978.                 unquant_coeff = alevel * matrix[j] * 8;
  3979.             }else{ //MPEG1
  3980.                 j = s->idsp.idct_permutation[scantable[i]]; // FIXME: optimize
  3981.                 if(s->mb_intra){
  3982.                         unquant_coeff = (int)(  alevel  * qscale * matrix[j]) >> 3;
  3983.                         unquant_coeff =   (unquant_coeff - 1) | 1;
  3984.                 }else{
  3985.                         unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) matrix[j])) >> 4;
  3986.                         unquant_coeff =   (unquant_coeff - 1) | 1;
  3987.                 }
  3988.                 unquant_coeff<<= 3;
  3989.             }
  3990.  
  3991.             distortion= (unquant_coeff - dct_coeff) * (unquant_coeff - dct_coeff) - zero_distortion;
  3992.             level+=64;
  3993.             if((level&(~127)) == 0){
  3994.                 for(j=survivor_count-1; j>=0; j--){
  3995.                     int run= i - survivor[j];
  3996.                     int score= distortion + length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  3997.                     score += score_tab[i-run];
  3998.  
  3999.                     if(score < best_score){
  4000.                         best_score= score;
  4001.                         run_tab[i+1]= run;
  4002.                         level_tab[i+1]= level-64;
  4003.                     }
  4004.                 }
  4005.  
  4006.                 if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
  4007.                     for(j=survivor_count-1; j>=0; j--){
  4008.                         int run= i - survivor[j];
  4009.                         int score= distortion + last_length[UNI_AC_ENC_INDEX(run, level)]*lambda;
  4010.                         score += score_tab[i-run];
  4011.                         if(score < last_score){
  4012.                             last_score= score;
  4013.                             last_run= run;
  4014.                             last_level= level-64;
  4015.                             last_i= i+1;
  4016.                         }
  4017.                     }
  4018.                 }
  4019.             }else{
  4020.                 distortion += esc_length*lambda;
  4021.                 for(j=survivor_count-1; j>=0; j--){
  4022.                     int run= i - survivor[j];
  4023.                     int score= distortion + score_tab[i-run];
  4024.  
  4025.                     if(score < best_score){
  4026.                         best_score= score;
  4027.                         run_tab[i+1]= run;
  4028.                         level_tab[i+1]= level-64;
  4029.                     }
  4030.                 }
  4031.  
  4032.                 if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
  4033.                   for(j=survivor_count-1; j>=0; j--){
  4034.                         int run= i - survivor[j];
  4035.                         int score= distortion + score_tab[i-run];
  4036.                         if(score < last_score){
  4037.                             last_score= score;
  4038.                             last_run= run;
  4039.                             last_level= level-64;
  4040.                             last_i= i+1;
  4041.                         }
  4042.                     }
  4043.                 }
  4044.             }
  4045.         }
  4046.  
  4047.         score_tab[i+1]= best_score;
  4048.  
  4049.         //Note: there is a vlc code in mpeg4 which is 1 bit shorter then another one with a shorter run and the same level
  4050.         if(last_non_zero <= 27){
  4051.             for(; survivor_count; survivor_count--){
  4052.                 if(score_tab[ survivor[survivor_count-1] ] <= best_score)
  4053.                     break;
  4054.             }
  4055.         }else{
  4056.             for(; survivor_count; survivor_count--){
  4057.                 if(score_tab[ survivor[survivor_count-1] ] <= best_score + lambda)
  4058.                     break;
  4059.             }
  4060.         }
  4061.  
  4062.         survivor[ survivor_count++ ]= i+1;
  4063.     }
  4064.  
  4065.     if(s->out_format != FMT_H263 && s->out_format != FMT_H261){
  4066.         last_score= 256*256*256*120;
  4067.         for(i= survivor[0]; i<=last_non_zero + 1; i++){
  4068.             int score= score_tab[i];
  4069.             if(i) score += lambda*2; //FIXME exacter?
  4070.  
  4071.             if(score < last_score){
  4072.                 last_score= score;
  4073.                 last_i= i;
  4074.                 last_level= level_tab[i];
  4075.                 last_run= run_tab[i];
  4076.             }
  4077.         }
  4078.     }
  4079.  
  4080.     s->coded_score[n] = last_score;
  4081.  
  4082.     dc= FFABS(block[0]);
  4083.     last_non_zero= last_i - 1;
  4084.     memset(block + start_i, 0, (64-start_i)*sizeof(int16_t));
  4085.  
  4086.     if(last_non_zero < start_i)
  4087.         return last_non_zero;
  4088.  
  4089.     if(last_non_zero == 0 && start_i == 0){
  4090.         int best_level= 0;
  4091.         int best_score= dc * dc;
  4092.  
  4093.         for(i=0; i<coeff_count[0]; i++){
  4094.             int level= coeff[i][0];
  4095.             int alevel= FFABS(level);
  4096.             int unquant_coeff, score, distortion;
  4097.  
  4098.             if(s->out_format == FMT_H263 || s->out_format == FMT_H261){
  4099.                     unquant_coeff= (alevel*qmul + qadd)>>3;
  4100.             }else{ //MPEG1
  4101.                     unquant_coeff = (((  alevel  << 1) + 1) * qscale * ((int) matrix[0])) >> 4;
  4102.                     unquant_coeff =   (unquant_coeff - 1) | 1;
  4103.             }
  4104.             unquant_coeff = (unquant_coeff + 4) >> 3;
  4105.             unquant_coeff<<= 3 + 3;
  4106.  
  4107.             distortion= (unquant_coeff - dc) * (unquant_coeff - dc);
  4108.             level+=64;
  4109.             if((level&(~127)) == 0) score= distortion + last_length[UNI_AC_ENC_INDEX(0, level)]*lambda;
  4110.             else                    score= distortion + esc_length*lambda;
  4111.  
  4112.             if(score < best_score){
  4113.                 best_score= score;
  4114.                 best_level= level - 64;
  4115.             }
  4116.         }
  4117.         block[0]= best_level;
  4118.         s->coded_score[n] = best_score - dc*dc;
  4119.         if(best_level == 0) return -1;
  4120.         else                return last_non_zero;
  4121.     }
  4122.  
  4123.     i= last_i;
  4124.     av_assert2(last_level);
  4125.  
  4126.     block[ perm_scantable[last_non_zero] ]= last_level;
  4127.     i -= last_run + 1;
  4128.  
  4129.     for(; i>start_i; i -= run_tab[i] + 1){
  4130.         block[ perm_scantable[i-1] ]= level_tab[i];
  4131.     }
  4132.  
  4133.     return last_non_zero;
  4134. }
  4135.  
  4136. //#define REFINE_STATS 1
  4137. static int16_t basis[64][64];
  4138.  
  4139. static void build_basis(uint8_t *perm){
  4140.     int i, j, x, y;
  4141.     emms_c();
  4142.     for(i=0; i<8; i++){
  4143.         for(j=0; j<8; j++){
  4144.             for(y=0; y<8; y++){
  4145.                 for(x=0; x<8; x++){
  4146.                     double s= 0.25*(1<<BASIS_SHIFT);
  4147.                     int index= 8*i + j;
  4148.                     int perm_index= perm[index];
  4149.                     if(i==0) s*= sqrt(0.5);
  4150.                     if(j==0) s*= sqrt(0.5);
  4151.                     basis[perm_index][8*x + y]= lrintf(s * cos((M_PI/8.0)*i*(x+0.5)) * cos((M_PI/8.0)*j*(y+0.5)));
  4152.                 }
  4153.             }
  4154.         }
  4155.     }
  4156. }
  4157.  
  4158. static int dct_quantize_refine(MpegEncContext *s, //FIXME breaks denoise?
  4159.                         int16_t *block, int16_t *weight, int16_t *orig,
  4160.                         int n, int qscale){
  4161.     int16_t rem[64];
  4162.     LOCAL_ALIGNED_16(int16_t, d1, [64]);
  4163.     const uint8_t *scantable= s->intra_scantable.scantable;
  4164.     const uint8_t *perm_scantable= s->intra_scantable.permutated;
  4165. //    unsigned int threshold1, threshold2;
  4166. //    int bias=0;
  4167.     int run_tab[65];
  4168.     int prev_run=0;
  4169.     int prev_level=0;
  4170.     int qmul, qadd, start_i, last_non_zero, i, dc;
  4171.     uint8_t * length;
  4172.     uint8_t * last_length;
  4173.     int lambda;
  4174.     int rle_index, run, q = 1, sum; //q is only used when s->mb_intra is true
  4175. #ifdef REFINE_STATS
  4176. static int count=0;
  4177. static int after_last=0;
  4178. static int to_zero=0;
  4179. static int from_zero=0;
  4180. static int raise=0;
  4181. static int lower=0;
  4182. static int messed_sign=0;
  4183. #endif
  4184.  
  4185.     if(basis[0][0] == 0)
  4186.         build_basis(s->idsp.idct_permutation);
  4187.  
  4188.     qmul= qscale*2;
  4189.     qadd= (qscale-1)|1;
  4190.     if (s->mb_intra) {
  4191.         if (!s->h263_aic) {
  4192.             if (n < 4)
  4193.                 q = s->y_dc_scale;
  4194.             else
  4195.                 q = s->c_dc_scale;
  4196.         } else{
  4197.             /* For AIC we skip quant/dequant of INTRADC */
  4198.             q = 1;
  4199.             qadd=0;
  4200.         }
  4201.         q <<= RECON_SHIFT-3;
  4202.         /* note: block[0] is assumed to be positive */
  4203.         dc= block[0]*q;
  4204. //        block[0] = (block[0] + (q >> 1)) / q;
  4205.         start_i = 1;
  4206. //        if(s->mpeg_quant || s->out_format == FMT_MPEG1)
  4207. //            bias= 1<<(QMAT_SHIFT-1);
  4208.         if (n > 3 && s->intra_chroma_ac_vlc_length) {
  4209.             length     = s->intra_chroma_ac_vlc_length;
  4210.             last_length= s->intra_chroma_ac_vlc_last_length;
  4211.         } else {
  4212.             length     = s->intra_ac_vlc_length;
  4213.             last_length= s->intra_ac_vlc_last_length;
  4214.         }
  4215.     } else {
  4216.         dc= 0;
  4217.         start_i = 0;
  4218.         length     = s->inter_ac_vlc_length;
  4219.         last_length= s->inter_ac_vlc_last_length;
  4220.     }
  4221.     last_non_zero = s->block_last_index[n];
  4222.  
  4223. #ifdef REFINE_STATS
  4224. {START_TIMER
  4225. #endif
  4226.     dc += (1<<(RECON_SHIFT-1));
  4227.     for(i=0; i<64; i++){
  4228.         rem[i]= dc - (orig[i]<<RECON_SHIFT); //FIXME  use orig dirrectly instead of copying to rem[]
  4229.     }
  4230. #ifdef REFINE_STATS
  4231. STOP_TIMER("memset rem[]")}
  4232. #endif
  4233.     sum=0;
  4234.     for(i=0; i<64; i++){
  4235.         int one= 36;
  4236.         int qns=4;
  4237.         int w;
  4238.  
  4239.         w= FFABS(weight[i]) + qns*one;
  4240.         w= 15 + (48*qns*one + w/2)/w; // 16 .. 63
  4241.  
  4242.         weight[i] = w;
  4243. //        w=weight[i] = (63*qns + (w/2)) / w;
  4244.  
  4245.         av_assert2(w>0);
  4246.         av_assert2(w<(1<<6));
  4247.         sum += w*w;
  4248.     }
  4249.     lambda= sum*(uint64_t)s->lambda2 >> (FF_LAMBDA_SHIFT - 6 + 6 + 6 + 6);
  4250. #ifdef REFINE_STATS
  4251. {START_TIMER
  4252. #endif
  4253.     run=0;
  4254.     rle_index=0;
  4255.     for(i=start_i; i<=last_non_zero; i++){
  4256.         int j= perm_scantable[i];
  4257.         const int level= block[j];
  4258.         int coeff;
  4259.  
  4260.         if(level){
  4261.             if(level<0) coeff= qmul*level - qadd;
  4262.             else        coeff= qmul*level + qadd;
  4263.             run_tab[rle_index++]=run;
  4264.             run=0;
  4265.  
  4266.             s->mpvencdsp.add_8x8basis(rem, basis[j], coeff);
  4267.         }else{
  4268.             run++;
  4269.         }
  4270.     }
  4271. #ifdef REFINE_STATS
  4272. if(last_non_zero>0){
  4273. STOP_TIMER("init rem[]")
  4274. }
  4275. }
  4276.  
  4277. {START_TIMER
  4278. #endif
  4279.     for(;;){
  4280.         int best_score = s->mpvencdsp.try_8x8basis(rem, weight, basis[0], 0);
  4281.         int best_coeff=0;
  4282.         int best_change=0;
  4283.         int run2, best_unquant_change=0, analyze_gradient;
  4284. #ifdef REFINE_STATS
  4285. {START_TIMER
  4286. #endif
  4287.         analyze_gradient = last_non_zero > 2 || s->quantizer_noise_shaping >= 3;
  4288.  
  4289.         if(analyze_gradient){
  4290. #ifdef REFINE_STATS
  4291. {START_TIMER
  4292. #endif
  4293.             for(i=0; i<64; i++){
  4294.                 int w= weight[i];
  4295.  
  4296.                 d1[i] = (rem[i]*w*w + (1<<(RECON_SHIFT+12-1)))>>(RECON_SHIFT+12);
  4297.             }
  4298. #ifdef REFINE_STATS
  4299. STOP_TIMER("rem*w*w")}
  4300. {START_TIMER
  4301. #endif
  4302.             s->fdsp.fdct(d1);
  4303. #ifdef REFINE_STATS
  4304. STOP_TIMER("dct")}
  4305. #endif
  4306.         }
  4307.  
  4308.         if(start_i){
  4309.             const int level= block[0];
  4310.             int change, old_coeff;
  4311.  
  4312.             av_assert2(s->mb_intra);
  4313.  
  4314.             old_coeff= q*level;
  4315.  
  4316.             for(change=-1; change<=1; change+=2){
  4317.                 int new_level= level + change;
  4318.                 int score, new_coeff;
  4319.  
  4320.                 new_coeff= q*new_level;
  4321.                 if(new_coeff >= 2048 || new_coeff < 0)
  4322.                     continue;
  4323.  
  4324.                 score = s->mpvencdsp.try_8x8basis(rem, weight, basis[0],
  4325.                                                   new_coeff - old_coeff);
  4326.                 if(score<best_score){
  4327.                     best_score= score;
  4328.                     best_coeff= 0;
  4329.                     best_change= change;
  4330.                     best_unquant_change= new_coeff - old_coeff;
  4331.                 }
  4332.             }
  4333.         }
  4334.  
  4335.         run=0;
  4336.         rle_index=0;
  4337.         run2= run_tab[rle_index++];
  4338.         prev_level=0;
  4339.         prev_run=0;
  4340.  
  4341.         for(i=start_i; i<64; i++){
  4342.             int j= perm_scantable[i];
  4343.             const int level= block[j];
  4344.             int change, old_coeff;
  4345.  
  4346.             if(s->quantizer_noise_shaping < 3 && i > last_non_zero + 1)
  4347.                 break;
  4348.  
  4349.             if(level){
  4350.                 if(level<0) old_coeff= qmul*level - qadd;
  4351.                 else        old_coeff= qmul*level + qadd;
  4352.                 run2= run_tab[rle_index++]; //FIXME ! maybe after last
  4353.             }else{
  4354.                 old_coeff=0;
  4355.                 run2--;
  4356.                 av_assert2(run2>=0 || i >= last_non_zero );
  4357.             }
  4358.  
  4359.             for(change=-1; change<=1; change+=2){
  4360.                 int new_level= level + change;
  4361.                 int score, new_coeff, unquant_change;
  4362.  
  4363.                 score=0;
  4364.                 if(s->quantizer_noise_shaping < 2 && FFABS(new_level) > FFABS(level))
  4365.                    continue;
  4366.  
  4367.                 if(new_level){
  4368.                     if(new_level<0) new_coeff= qmul*new_level - qadd;
  4369.                     else            new_coeff= qmul*new_level + qadd;
  4370.                     if(new_coeff >= 2048 || new_coeff <= -2048)
  4371.                         continue;
  4372.                     //FIXME check for overflow
  4373.  
  4374.                     if(level){
  4375.                         if(level < 63 && level > -63){
  4376.                             if(i < last_non_zero)
  4377.                                 score +=   length[UNI_AC_ENC_INDEX(run, new_level+64)]
  4378.                                          - length[UNI_AC_ENC_INDEX(run, level+64)];
  4379.                             else
  4380.                                 score +=   last_length[UNI_AC_ENC_INDEX(run, new_level+64)]
  4381.                                          - last_length[UNI_AC_ENC_INDEX(run, level+64)];
  4382.                         }
  4383.                     }else{
  4384.                         av_assert2(FFABS(new_level)==1);
  4385.  
  4386.                         if(analyze_gradient){
  4387.                             int g= d1[ scantable[i] ];
  4388.                             if(g && (g^new_level) >= 0)
  4389.                                 continue;
  4390.                         }
  4391.  
  4392.                         if(i < last_non_zero){
  4393.                             int next_i= i + run2 + 1;
  4394.                             int next_level= block[ perm_scantable[next_i] ] + 64;
  4395.  
  4396.                             if(next_level&(~127))
  4397.                                 next_level= 0;
  4398.  
  4399.                             if(next_i < last_non_zero)
  4400.                                 score +=   length[UNI_AC_ENC_INDEX(run, 65)]
  4401.                                          + length[UNI_AC_ENC_INDEX(run2, next_level)]
  4402.                                          - length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  4403.                             else
  4404.                                 score +=  length[UNI_AC_ENC_INDEX(run, 65)]
  4405.                                         + last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  4406.                                         - last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)];
  4407.                         }else{
  4408.                             score += last_length[UNI_AC_ENC_INDEX(run, 65)];
  4409.                             if(prev_level){
  4410.                                 score +=  length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  4411.                                         - last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  4412.                             }
  4413.                         }
  4414.                     }
  4415.                 }else{
  4416.                     new_coeff=0;
  4417.                     av_assert2(FFABS(level)==1);
  4418.  
  4419.                     if(i < last_non_zero){
  4420.                         int next_i= i + run2 + 1;
  4421.                         int next_level= block[ perm_scantable[next_i] ] + 64;
  4422.  
  4423.                         if(next_level&(~127))
  4424.                             next_level= 0;
  4425.  
  4426.                         if(next_i < last_non_zero)
  4427.                             score +=   length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  4428.                                      - length[UNI_AC_ENC_INDEX(run2, next_level)]
  4429.                                      - length[UNI_AC_ENC_INDEX(run, 65)];
  4430.                         else
  4431.                             score +=   last_length[UNI_AC_ENC_INDEX(run + run2 + 1, next_level)]
  4432.                                      - last_length[UNI_AC_ENC_INDEX(run2, next_level)]
  4433.                                      - length[UNI_AC_ENC_INDEX(run, 65)];
  4434.                     }else{
  4435.                         score += -last_length[UNI_AC_ENC_INDEX(run, 65)];
  4436.                         if(prev_level){
  4437.                             score +=  last_length[UNI_AC_ENC_INDEX(prev_run, prev_level)]
  4438.                                     - length[UNI_AC_ENC_INDEX(prev_run, prev_level)];
  4439.                         }
  4440.                     }
  4441.                 }
  4442.  
  4443.                 score *= lambda;
  4444.  
  4445.                 unquant_change= new_coeff - old_coeff;
  4446.                 av_assert2((score < 100*lambda && score > -100*lambda) || lambda==0);
  4447.  
  4448.                 score += s->mpvencdsp.try_8x8basis(rem, weight, basis[j],
  4449.                                                    unquant_change);
  4450.                 if(score<best_score){
  4451.                     best_score= score;
  4452.                     best_coeff= i;
  4453.                     best_change= change;
  4454.                     best_unquant_change= unquant_change;
  4455.                 }
  4456.             }
  4457.             if(level){
  4458.                 prev_level= level + 64;
  4459.                 if(prev_level&(~127))
  4460.                     prev_level= 0;
  4461.                 prev_run= run;
  4462.                 run=0;
  4463.             }else{
  4464.                 run++;
  4465.             }
  4466.         }
  4467. #ifdef REFINE_STATS
  4468. STOP_TIMER("iterative step")}
  4469. #endif
  4470.  
  4471.         if(best_change){
  4472.             int j= perm_scantable[ best_coeff ];
  4473.  
  4474.             block[j] += best_change;
  4475.  
  4476.             if(best_coeff > last_non_zero){
  4477.                 last_non_zero= best_coeff;
  4478.                 av_assert2(block[j]);
  4479. #ifdef REFINE_STATS
  4480. after_last++;
  4481. #endif
  4482.             }else{
  4483. #ifdef REFINE_STATS
  4484. if(block[j]){
  4485.     if(block[j] - best_change){
  4486.         if(FFABS(block[j]) > FFABS(block[j] - best_change)){
  4487.             raise++;
  4488.         }else{
  4489.             lower++;
  4490.         }
  4491.     }else{
  4492.         from_zero++;
  4493.     }
  4494. }else{
  4495.     to_zero++;
  4496. }
  4497. #endif
  4498.                 for(; last_non_zero>=start_i; last_non_zero--){
  4499.                     if(block[perm_scantable[last_non_zero]])
  4500.                         break;
  4501.                 }
  4502.             }
  4503. #ifdef REFINE_STATS
  4504. count++;
  4505. if(256*256*256*64 % count == 0){
  4506.     av_log(s->avctx, AV_LOG_DEBUG, "after_last:%d to_zero:%d from_zero:%d raise:%d lower:%d sign:%d xyp:%d/%d/%d\n", after_last, to_zero, from_zero, raise, lower, messed_sign, s->mb_x, s->mb_y, s->picture_number);
  4507. }
  4508. #endif
  4509.             run=0;
  4510.             rle_index=0;
  4511.             for(i=start_i; i<=last_non_zero; i++){
  4512.                 int j= perm_scantable[i];
  4513.                 const int level= block[j];
  4514.  
  4515.                  if(level){
  4516.                      run_tab[rle_index++]=run;
  4517.                      run=0;
  4518.                  }else{
  4519.                      run++;
  4520.                  }
  4521.             }
  4522.  
  4523.             s->mpvencdsp.add_8x8basis(rem, basis[j], best_unquant_change);
  4524.         }else{
  4525.             break;
  4526.         }
  4527.     }
  4528. #ifdef REFINE_STATS
  4529. if(last_non_zero>0){
  4530. STOP_TIMER("iterative search")
  4531. }
  4532. }
  4533. #endif
  4534.  
  4535.     return last_non_zero;
  4536. }
  4537.  
  4538. /**
  4539.  * Permute an 8x8 block according to permuatation.
  4540.  * @param block the block which will be permuted according to
  4541.  *              the given permutation vector
  4542.  * @param permutation the permutation vector
  4543.  * @param last the last non zero coefficient in scantable order, used to
  4544.  *             speed the permutation up
  4545.  * @param scantable the used scantable, this is only used to speed the
  4546.  *                  permutation up, the block is not (inverse) permutated
  4547.  *                  to scantable order!
  4548.  */
  4549. static void block_permute(int16_t *block, uint8_t *permutation,
  4550.                           const uint8_t *scantable, int last)
  4551. {
  4552.     int i;
  4553.     int16_t temp[64];
  4554.  
  4555.     if (last <= 0)
  4556.         return;
  4557.     //FIXME it is ok but not clean and might fail for some permutations
  4558.     // if (permutation[1] == 1)
  4559.     // return;
  4560.  
  4561.     for (i = 0; i <= last; i++) {
  4562.         const int j = scantable[i];
  4563.         temp[j] = block[j];
  4564.         block[j] = 0;
  4565.     }
  4566.  
  4567.     for (i = 0; i <= last; i++) {
  4568.         const int j = scantable[i];
  4569.         const int perm_j = permutation[j];
  4570.         block[perm_j] = temp[j];
  4571.     }
  4572. }
  4573.  
  4574. int ff_dct_quantize_c(MpegEncContext *s,
  4575.                         int16_t *block, int n,
  4576.                         int qscale, int *overflow)
  4577. {
  4578.     int i, j, level, last_non_zero, q, start_i;
  4579.     const int *qmat;
  4580.     const uint8_t *scantable= s->intra_scantable.scantable;
  4581.     int bias;
  4582.     int max=0;
  4583.     unsigned int threshold1, threshold2;
  4584.  
  4585.     s->fdsp.fdct(block);
  4586.  
  4587.     if(s->dct_error_sum)
  4588.         s->denoise_dct(s, block);
  4589.  
  4590.     if (s->mb_intra) {
  4591.         if (!s->h263_aic) {
  4592.             if (n < 4)
  4593.                 q = s->y_dc_scale;
  4594.             else
  4595.                 q = s->c_dc_scale;
  4596.             q = q << 3;
  4597.         } else
  4598.             /* For AIC we skip quant/dequant of INTRADC */
  4599.             q = 1 << 3;
  4600.  
  4601.         /* note: block[0] is assumed to be positive */
  4602.         block[0] = (block[0] + (q >> 1)) / q;
  4603.         start_i = 1;
  4604.         last_non_zero = 0;
  4605.         qmat = n < 4 ? s->q_intra_matrix[qscale] : s->q_chroma_intra_matrix[qscale];
  4606.         bias= s->intra_quant_bias*(1<<(QMAT_SHIFT - QUANT_BIAS_SHIFT));
  4607.     } else {
  4608.         start_i = 0;
  4609.         last_non_zero = -1;
  4610.         qmat = s->q_inter_matrix[qscale];
  4611.         bias= s->inter_quant_bias*(1<<(QMAT_SHIFT - QUANT_BIAS_SHIFT));
  4612.     }
  4613.     threshold1= (1<<QMAT_SHIFT) - bias - 1;
  4614.     threshold2= (threshold1<<1);
  4615.     for(i=63;i>=start_i;i--) {
  4616.         j = scantable[i];
  4617.         level = block[j] * qmat[j];
  4618.  
  4619.         if(((unsigned)(level+threshold1))>threshold2){
  4620.             last_non_zero = i;
  4621.             break;
  4622.         }else{
  4623.             block[j]=0;
  4624.         }
  4625.     }
  4626.     for(i=start_i; i<=last_non_zero; i++) {
  4627.         j = scantable[i];
  4628.         level = block[j] * qmat[j];
  4629.  
  4630. //        if(   bias+level >= (1<<QMAT_SHIFT)
  4631. //           || bias-level >= (1<<QMAT_SHIFT)){
  4632.         if(((unsigned)(level+threshold1))>threshold2){
  4633.             if(level>0){
  4634.                 level= (bias + level)>>QMAT_SHIFT;
  4635.                 block[j]= level;
  4636.             }else{
  4637.                 level= (bias - level)>>QMAT_SHIFT;
  4638.                 block[j]= -level;
  4639.             }
  4640.             max |=level;
  4641.         }else{
  4642.             block[j]=0;
  4643.         }
  4644.     }
  4645.     *overflow= s->max_qcoeff < max; //overflow might have happened
  4646.  
  4647.     /* we need this permutation so that we correct the IDCT, we only permute the !=0 elements */
  4648.     if (s->idsp.perm_type != FF_IDCT_PERM_NONE)
  4649.         block_permute(block, s->idsp.idct_permutation,
  4650.                       scantable, last_non_zero);
  4651.  
  4652.     return last_non_zero;
  4653. }
  4654.  
  4655. #define OFFSET(x) offsetof(MpegEncContext, x)
  4656. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  4657. static const AVOption h263_options[] = {
  4658.     { "obmc",         "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  4659.     { "structured_slices","Write slice start position at every GOB header instead of just GOB number.", OFFSET(h263_slice_structured), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE},
  4660.     { "mb_info",      "emit macroblock info for RFC 2190 packetization, the parameter value is the maximum payload size", OFFSET(mb_info), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
  4661.     FF_MPV_COMMON_OPTS
  4662.     { NULL },
  4663. };
  4664.  
  4665. static const AVClass h263_class = {
  4666.     .class_name = "H.263 encoder",
  4667.     .item_name  = av_default_item_name,
  4668.     .option     = h263_options,
  4669.     .version    = LIBAVUTIL_VERSION_INT,
  4670. };
  4671.  
  4672. AVCodec ff_h263_encoder = {
  4673.     .name           = "h263",
  4674.     .long_name      = NULL_IF_CONFIG_SMALL("H.263 / H.263-1996"),
  4675.     .type           = AVMEDIA_TYPE_VIDEO,
  4676.     .id             = AV_CODEC_ID_H263,
  4677.     .priv_data_size = sizeof(MpegEncContext),
  4678.     .init           = ff_mpv_encode_init,
  4679.     .encode2        = ff_mpv_encode_picture,
  4680.     .close          = ff_mpv_encode_end,
  4681.     .pix_fmts= (const enum AVPixelFormat[]){AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE},
  4682.     .priv_class     = &h263_class,
  4683. };
  4684.  
  4685. static const AVOption h263p_options[] = {
  4686.     { "umv",        "Use unlimited motion vectors.",    OFFSET(umvplus), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  4687.     { "aiv",        "Use alternative inter VLC.",       OFFSET(alt_inter_vlc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  4688.     { "obmc",       "use overlapped block motion compensation.", OFFSET(obmc), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  4689.     { "structured_slices", "Write slice start position at every GOB header instead of just GOB number.", OFFSET(h263_slice_structured), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE},
  4690.     FF_MPV_COMMON_OPTS
  4691.     { NULL },
  4692. };
  4693. static const AVClass h263p_class = {
  4694.     .class_name = "H.263p encoder",
  4695.     .item_name  = av_default_item_name,
  4696.     .option     = h263p_options,
  4697.     .version    = LIBAVUTIL_VERSION_INT,
  4698. };
  4699.  
  4700. AVCodec ff_h263p_encoder = {
  4701.     .name           = "h263p",
  4702.     .long_name      = NULL_IF_CONFIG_SMALL("H.263+ / H.263-1998 / H.263 version 2"),
  4703.     .type           = AVMEDIA_TYPE_VIDEO,
  4704.     .id             = AV_CODEC_ID_H263P,
  4705.     .priv_data_size = sizeof(MpegEncContext),
  4706.     .init           = ff_mpv_encode_init,
  4707.     .encode2        = ff_mpv_encode_picture,
  4708.     .close          = ff_mpv_encode_end,
  4709.     .capabilities   = AV_CODEC_CAP_SLICE_THREADS,
  4710.     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  4711.     .priv_class     = &h263p_class,
  4712. };
  4713.  
  4714. static const AVClass msmpeg4v2_class = {
  4715.     .class_name = "msmpeg4v2 encoder",
  4716.     .item_name  = av_default_item_name,
  4717.     .option     = ff_mpv_generic_options,
  4718.     .version    = LIBAVUTIL_VERSION_INT,
  4719. };
  4720.  
  4721. AVCodec ff_msmpeg4v2_encoder = {
  4722.     .name           = "msmpeg4v2",
  4723.     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 2"),
  4724.     .type           = AVMEDIA_TYPE_VIDEO,
  4725.     .id             = AV_CODEC_ID_MSMPEG4V2,
  4726.     .priv_data_size = sizeof(MpegEncContext),
  4727.     .init           = ff_mpv_encode_init,
  4728.     .encode2        = ff_mpv_encode_picture,
  4729.     .close          = ff_mpv_encode_end,
  4730.     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  4731.     .priv_class     = &msmpeg4v2_class,
  4732. };
  4733.  
  4734. static const AVClass msmpeg4v3_class = {
  4735.     .class_name = "msmpeg4v3 encoder",
  4736.     .item_name  = av_default_item_name,
  4737.     .option     = ff_mpv_generic_options,
  4738.     .version    = LIBAVUTIL_VERSION_INT,
  4739. };
  4740.  
  4741. AVCodec ff_msmpeg4v3_encoder = {
  4742.     .name           = "msmpeg4",
  4743.     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 part 2 Microsoft variant version 3"),
  4744.     .type           = AVMEDIA_TYPE_VIDEO,
  4745.     .id             = AV_CODEC_ID_MSMPEG4V3,
  4746.     .priv_data_size = sizeof(MpegEncContext),
  4747.     .init           = ff_mpv_encode_init,
  4748.     .encode2        = ff_mpv_encode_picture,
  4749.     .close          = ff_mpv_encode_end,
  4750.     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  4751.     .priv_class     = &msmpeg4v3_class,
  4752. };
  4753.  
  4754. static const AVClass wmv1_class = {
  4755.     .class_name = "wmv1 encoder",
  4756.     .item_name  = av_default_item_name,
  4757.     .option     = ff_mpv_generic_options,
  4758.     .version    = LIBAVUTIL_VERSION_INT,
  4759. };
  4760.  
  4761. AVCodec ff_wmv1_encoder = {
  4762.     .name           = "wmv1",
  4763.     .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 7"),
  4764.     .type           = AVMEDIA_TYPE_VIDEO,
  4765.     .id             = AV_CODEC_ID_WMV1,
  4766.     .priv_data_size = sizeof(MpegEncContext),
  4767.     .init           = ff_mpv_encode_init,
  4768.     .encode2        = ff_mpv_encode_picture,
  4769.     .close          = ff_mpv_encode_end,
  4770.     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE },
  4771.     .priv_class     = &wmv1_class,
  4772. };
  4773.