[svn] / trunk / xvidcore / src / encoder.c Repository:
ViewVC logotype

Diff of /trunk/xvidcore/src/encoder.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 152, Wed May 1 13:00:02 2002 UTC revision 1679, Wed Feb 15 20:58:43 2006 UTC
# Line 1  Line 1 
1  /**************************************************************************  /*****************************************************************************
2   *   *
3   *  XVID MPEG-4 VIDEO CODEC   *  XVID MPEG-4 VIDEO CODEC
4   *  -  Encoder main module  -   *  -  Encoder main module  -
5   *   *
6   *  This program is an implementation of a part of one or more MPEG-4   *  Copyright(C) 2002     Michael Militzer <isibaar@xvid.org>
7   *  Video tools as specified in ISO/IEC 14496-2 standard.  Those intending   *                         2002-2003 Peter Ross <pross@xvid.org>
8   *  to use this software module in hardware or software products are   *                         2002   Daniel Smith <danielsmith@astroboymail.com>
  *  advised that its use may infringe existing patents or copyrights, and  
  *  any such use would be at such party's own risk.  The original  
  *  developer of this software module and his/her company, and subsequent  
  *  editors and their companies, will have no liability for use of this  
  *  software or modifications or derivatives thereof.  
9   *   *
10   *  This program is free software; you can redistribute it and/or modify   *  This program is free software; you can redistribute it and/or modify
11   *  it under the terms of the GNU General Public License as published by   *  it under the terms of the GNU General Public License as published by
# Line 26  Line 21 
21   *  along with this program; if not, write to the Free Software   *  along with this program; if not, write to the Free Software
22   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
23   *   *
24   ***************************************************************************/   * $Id: encoder.c,v 1.124 2006-02-15 20:58:43 Isibaar Exp $
   
 /****************************************************************************  
  *  
  *  History  
  *  
  *  14.04.2002 added FrameCodeB()  
  *  
  *  $Id: encoder.c,v 1.32 2002-05-01 13:00:01 suxen_drol Exp $  
25   *   *
26   ***************************************************************************/   ****************************************************************************/
27    
28  #include <stdlib.h>  #include <stdlib.h>
29  #include <stdio.h>  #include <stdio.h>
30  #include <math.h>  #include <math.h>
31    #include <string.h>
32    
33  #include "encoder.h"  #include "encoder.h"
34  #include "prediction/mbprediction.h"  #include "prediction/mbprediction.h"
35  #include "global.h"  #include "global.h"
36  #include "utils/timer.h"  #include "utils/timer.h"
37  #include "image/image.h"  #include "image/image.h"
38    #include "image/font.h"
39    #include "motion/sad.h"
40  #include "motion/motion.h"  #include "motion/motion.h"
41    #include "motion/gmc.h"
42    
43  #include "bitstream/cbp.h"  #include "bitstream/cbp.h"
44  #include "utils/mbfunctions.h"  #include "utils/mbfunctions.h"
45  #include "bitstream/bitstream.h"  #include "bitstream/bitstream.h"
46  #include "bitstream/mbcoding.h"  #include "bitstream/mbcoding.h"
 #include "utils/ratecontrol.h"  
47  #include "utils/emms.h"  #include "utils/emms.h"
48  #include "bitstream/mbcoding.h"  #include "bitstream/mbcoding.h"
 #include "quant/adapt_quant.h"  
49  #include "quant/quant_matrix.h"  #include "quant/quant_matrix.h"
50  #include "utils/mem_align.h"  #include "utils/mem_align.h"
51    
52  #define ENC_CHECK(X) if(!(X)) return XVID_ERR_FORMAT  /*****************************************************************************
53  #define SWAP(A,B)    { void * tmp = A; A = B; B = tmp; }   * Local function prototypes
54     ****************************************************************************/
55    
56    static int FrameCodeI(Encoder * pEnc,
57                                              Bitstream * bs);
58    
59  static int FrameCodeI(Encoder * pEnc, Bitstream * bs, uint32_t *pBits);  static int FrameCodeP(Encoder * pEnc,
60  static int FrameCodeP(Encoder * pEnc, Bitstream * bs, uint32_t *pBits, bool force_inter, bool vol_header);                                            Bitstream * bs);
 static void FrameCodeB(Encoder * pEnc, FRAMEINFO * frame, Bitstream * bs, uint32_t *pBits);  
61    
62  static int DQtab[4] =  static void FrameCodeB(Encoder * pEnc,
63  {                                             FRAMEINFO * frame,
64          -1, -2, 1, 2                                             Bitstream * bs);
 };  
65    
 static int iDQtab[5] =  
 {  
         1, 0, NO_CHANGE, 2, 3  
 };  
66    
67    /*****************************************************************************
68     * Encoder creation
69     *
70     * This function creates an Encoder instance, it allocates all necessary
71     * image buffers (reference, current and bframes) and initialize the internal
72     * xvid encoder paremeters according to the XVID_ENC_PARAM input parameter.
73     *
74     * The code seems to be very long but is very basic, mainly memory allocation
75     * and cleaning code.
76     *
77     * Returned values :
78     *      - 0                             - no errors
79     *      - XVID_ERR_MEMORY - the libc could not allocate memory, the function
80     *                                              cleans the structure before exiting.
81     *                                              pParam->handle is also set to NULL.
82     *
83     ****************************************************************************/
84    
85  void static image_null(IMAGE * image)  /*
86     * Simplify the "fincr/fbase" fraction
87    */
88    static int
89    gcd(int a, int b)
90  {  {
91          image->y = image->u = image->v = NULL;          int r ;
92    
93            if (b > a) {
94                    r = a;
95                    a = b;
96                    b = r;
97  }  }
98    
99            while ((r = a % b)) {
100                    a = b;
101                    b = r;
102            }
103            return b;
104    }
105    
106  int encoder_create(XVID_ENC_PARAM * pParam)  static void
107    simplify_time(int *inc, int *base)
108  {  {
109          Encoder *pEnc;          /* common factor */
110          uint32_t i;          const int s = gcd(*inc, *base);
111      *inc  /= s;
112          pParam->handle = NULL;    *base /= s;
113    
114          ENC_CHECK(pParam);          if (*base > 65535 || *inc > 65535) {
115                    int *biggest;
116                    int *other;
117                    float div;
118    
119          ENC_CHECK(pParam->width > 0 && pParam->width <= 1920);                  if (*base > *inc) {
120          ENC_CHECK(pParam->height > 0 && pParam->height <= 1280);                          biggest = base;
121          ENC_CHECK(!(pParam->width % 2));                          other = inc;
122          ENC_CHECK(!(pParam->height % 2));                  } else {
123                            biggest = inc;
124          if (pParam->fincr <= 0 || pParam->fbase <= 0)                          other = base;
         {  
                 pParam->fincr = 1;  
                 pParam->fbase = 25;  
125          }          }
126    
127          // simplify the "fincr/fbase" fraction                  div = ((float)*biggest)/((float)65535);
128          // (neccessary, since windows supplies us with huge numbers)                  *biggest = (unsigned int)(((float)*biggest)/div);
129                    *other = (unsigned int)(((float)*other)/div);
         i = pParam->fincr;  
         while (i > 1)  
         {  
                 if (pParam->fincr % i == 0 && pParam->fbase % i == 0)  
                 {  
                         pParam->fincr /= i;  
                         pParam->fbase /= i;  
                         i = pParam->fincr;  
                         continue;  
130                  }                  }
                 i--;  
         }  
   
         if (pParam->fbase > 65535)  
         {  
                 float div = (float)pParam->fbase / 65535;  
                 pParam->fbase = (int)(pParam->fbase / div);  
                 pParam->fincr = (int)(pParam->fincr / div);  
131          }          }
132    
         if (pParam->rc_bitrate <= 0)  
                 pParam->rc_bitrate = 900000;  
   
         if (pParam->rc_reaction_delay_factor <= 0)  
                 pParam->rc_reaction_delay_factor = 16;  
133    
134          if (pParam->rc_averaging_period <= 0)  int
135                  pParam->rc_averaging_period = 100;  enc_create(xvid_enc_create_t * create)
136    {
137          if (pParam->rc_buffer <= 0)          Encoder *pEnc;
138                  pParam->rc_buffer = 100;    int n;
139    
140          if ((pParam->min_quantizer <= 0) || (pParam->min_quantizer > 31))          if (XVID_VERSION_MAJOR(create->version) != 1) /* v1.x.x */
141                  pParam->min_quantizer = 1;                  return XVID_ERR_VERSION;
142    
143          if ((pParam->max_quantizer <= 0) || (pParam->max_quantizer > 31))          if (create->width%2 || create->height%2)
144                  pParam->max_quantizer = 31;                  return XVID_ERR_FAIL;
145    
146          if (pParam->max_key_interval == 0)              /* 1 keyframe each 10 seconds */          if (create->width<=0 || create->height<=0)
147                  pParam->max_key_interval = 10 * pParam->fincr / pParam->fbase;                  return XVID_ERR_FAIL;
148    
149          if (pParam->max_quantizer < pParam->min_quantizer)          /* allocate encoder struct */
                 pParam->max_quantizer = pParam->min_quantizer;  
150    
151          if ((pEnc = (Encoder *) xvid_malloc(sizeof(Encoder), CACHE_LINE)) == NULL)          pEnc = (Encoder *) xvid_malloc(sizeof(Encoder), CACHE_LINE);
152            if (pEnc == NULL)
153                  return XVID_ERR_MEMORY;                  return XVID_ERR_MEMORY;
154            memset(pEnc, 0, sizeof(Encoder));
155    
156          /* Fill members of Encoder structure */          pEnc->mbParam.profile = create->profile;
   
         pEnc->mbParam.width = pParam->width;  
         pEnc->mbParam.height = pParam->height;  
157    
158            /* global flags */
159            pEnc->mbParam.global_flags = create->global;
160      if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED))
161        pEnc->mbParam.global_flags |= XVID_GLOBAL_DIVX5_USERDATA;
162    
163            /* width, height */
164            pEnc->mbParam.width = create->width;
165            pEnc->mbParam.height = create->height;
166          pEnc->mbParam.mb_width = (pEnc->mbParam.width + 15) / 16;          pEnc->mbParam.mb_width = (pEnc->mbParam.width + 15) / 16;
167          pEnc->mbParam.mb_height = (pEnc->mbParam.height + 15) / 16;          pEnc->mbParam.mb_height = (pEnc->mbParam.height + 15) / 16;
   
168          pEnc->mbParam.edged_width = 16 * pEnc->mbParam.mb_width + 2 * EDGE_SIZE;          pEnc->mbParam.edged_width = 16 * pEnc->mbParam.mb_width + 2 * EDGE_SIZE;
169          pEnc->mbParam.edged_height = 16 * pEnc->mbParam.mb_height + 2 * EDGE_SIZE;          pEnc->mbParam.edged_height = 16 * pEnc->mbParam.mb_height + 2 * EDGE_SIZE;
170    
171          pEnc->mbParam.fbase = pParam->fbase;          /* framerate */
172          pEnc->mbParam.fincr = pParam->fincr;          pEnc->mbParam.fincr = MAX(create->fincr, 0);
173            pEnc->mbParam.fbase = create->fincr <= 0 ? 25 : create->fbase;
174            if (pEnc->mbParam.fincr>0)
175                    simplify_time((int*)&pEnc->mbParam.fincr, (int*)&pEnc->mbParam.fbase);
176    
177          pEnc->sStat.fMvPrevSigma = -1;          /* zones */
178            if(create->num_zones > 0) {
179                    pEnc->num_zones = create->num_zones;
180                    pEnc->zones = xvid_malloc(sizeof(xvid_enc_zone_t) * pEnc->num_zones, CACHE_LINE);
181                    if (pEnc->zones == NULL)
182                            goto xvid_err_memory0;
183                    memcpy(pEnc->zones, create->zones, sizeof(xvid_enc_zone_t) * pEnc->num_zones);
184            } else {
185                    pEnc->num_zones = 0;
186                    pEnc->zones = NULL;
187            }
188    
189          /* Fill rate control parameters */          /* plugins */
190            if(create->num_plugins > 0) {
191                    pEnc->num_plugins = create->num_plugins;
192                    pEnc->plugins = xvid_malloc(sizeof(xvid_enc_plugin_t) * pEnc->num_plugins, CACHE_LINE);
193                    if (pEnc->plugins == NULL)
194                            goto xvid_err_memory0;
195            } else {
196                    pEnc->num_plugins = 0;
197                    pEnc->plugins = NULL;
198            }
199    
200          pEnc->bitrate = pParam->rc_bitrate;          for (n=0; n<pEnc->num_plugins;n++) {
201                    xvid_plg_create_t pcreate;
202                    xvid_plg_info_t pinfo;
203    
204          pEnc->iFrameNum = 0;                  memset(&pinfo, 0, sizeof(xvid_plg_info_t));
205          pEnc->iMaxKeyInterval = pParam->max_key_interval;                  pinfo.version = XVID_VERSION;
206                    if (create->plugins[n].func(NULL, XVID_PLG_INFO, &pinfo, NULL) >= 0) {
207                            pEnc->mbParam.plugin_flags |= pinfo.flags;
208                    }
209    
210          /* try to allocate frame memory */                  memset(&pcreate, 0, sizeof(xvid_plg_create_t));
211                    pcreate.version = XVID_VERSION;
212                    pcreate.num_zones = pEnc->num_zones;
213                    pcreate.zones = pEnc->zones;
214                    pcreate.width = pEnc->mbParam.width;
215                    pcreate.height = pEnc->mbParam.height;
216                    pcreate.mb_width = pEnc->mbParam.mb_width;
217                    pcreate.mb_height = pEnc->mbParam.mb_height;
218                    pcreate.fincr = pEnc->mbParam.fincr;
219                    pcreate.fbase = pEnc->mbParam.fbase;
220                    pcreate.param = create->plugins[n].param;
221    
222          pEnc->current = NULL;                  pEnc->plugins[n].func = NULL;   /* disable plugins that fail */
223          pEnc->reference = NULL;                  if (create->plugins[n].func(NULL, XVID_PLG_CREATE, &pcreate, &pEnc->plugins[n].param) >= 0) {
224          if ( (pEnc->current = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE)) == NULL ||                          pEnc->plugins[n].func = create->plugins[n].func;
225                   (pEnc->reference = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE)) == NULL)                  }
         {  
                 if (pEnc->current) xvid_free(pEnc->current);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
226          }          }
227    
228          /* try to allocate mb memory */          if ((pEnc->mbParam.global_flags & XVID_GLOBAL_EXTRASTATS_ENABLE) ||
229                    (pEnc->mbParam.plugin_flags & XVID_REQPSNR)) {
230                    pEnc->mbParam.plugin_flags |= XVID_REQORIGINAL; /* psnr calculation requires the original */
231            }
232    
233          pEnc->current->mbs = NULL;          /* temp dquants */
234          pEnc->reference->mbs = NULL;          if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
235                    pEnc->temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width *
236                                                    pEnc->mbParam.mb_height * sizeof(int), CACHE_LINE);
237                    if (pEnc->temp_dquants==NULL)
238                            goto xvid_err_memory1a;
239            }
240    
241          if ((pEnc->current->mbs = xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width * pEnc->mbParam.mb_height, CACHE_LINE)) == NULL ||          /* temp lambdas */
242                  (pEnc->reference->mbs = xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width * pEnc->mbParam.mb_height, CACHE_LINE)) == NULL)          if (pEnc->mbParam.plugin_flags & XVID_REQLAMBDA) {
243          {                  pEnc->temp_lambda = (float *) xvid_malloc(pEnc->mbParam.mb_width *
244                  if (pEnc->current->mbs) xvid_free(pEnc->current->mbs);                                                  pEnc->mbParam.mb_height * 6 * sizeof(float), CACHE_LINE);
245                  xvid_free(pEnc->current);                  if (pEnc->temp_lambda == NULL)
246                  xvid_free(pEnc->reference);                          goto xvid_err_memory1a;
247                  xvid_free(pEnc);          }
248    
249            /* bframes */
250            pEnc->mbParam.max_bframes = MAX(create->max_bframes, 0);
251            pEnc->mbParam.bquant_ratio = MAX(create->bquant_ratio, 0);
252            pEnc->mbParam.bquant_offset = create->bquant_offset;
253    
254            /* min/max quant */
255            for (n=0; n<3; n++) {
256                    pEnc->mbParam.min_quant[n] = create->min_quant[n] > 0 ? create->min_quant[n] : 2;
257                    pEnc->mbParam.max_quant[n] = create->max_quant[n] > 0 ? create->max_quant[n] : 31;
258          }          }
259    
260          /* try to allocate image memory */          /* frame drop ratio */
261            pEnc->mbParam.frame_drop_ratio = MAX(create->frame_drop_ratio, 0);
262    
263            /* max keyframe interval */
264            pEnc->mbParam.iMaxKeyInterval = create->max_key_interval <= 0 ? (10 * (int)pEnc->mbParam.fbase) / (int)pEnc->mbParam.fincr : create->max_key_interval;
265    
266            /* allocate working frame-image memory */
267    
268            pEnc->current = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
269            pEnc->reference = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
270    
271            if (pEnc->current == NULL || pEnc->reference == NULL)
272                    goto xvid_err_memory1;
273    
274            /* allocate macroblock memory */
275    
276            pEnc->current->mbs =
277                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
278                                            pEnc->mbParam.mb_height, CACHE_LINE);
279            pEnc->reference->mbs =
280                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
281                                            pEnc->mbParam.mb_height, CACHE_LINE);
282    
283            if (pEnc->current->mbs == NULL || pEnc->reference->mbs == NULL)
284                    goto xvid_err_memory2;
285    
286  #ifdef _DEBUG          /* allocate quant matrix memory */
287    
288            pEnc->mbParam.mpeg_quant_matrices =
289                    xvid_malloc(sizeof(uint16_t) * 64 * 8, CACHE_LINE);
290    
291            if (pEnc->mbParam.mpeg_quant_matrices == NULL)
292                    goto xvid_err_memory2a;
293    
294            /* allocate interpolation image memory */
295    
296            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
297          image_null(&pEnc->sOriginal);          image_null(&pEnc->sOriginal);
298  #endif                  image_null(&pEnc->sOriginal2);
299  #ifdef BFRAMES          }
300    
301          image_null(&pEnc->f_refh);          image_null(&pEnc->f_refh);
302          image_null(&pEnc->f_refv);          image_null(&pEnc->f_refv);
303          image_null(&pEnc->f_refhv);          image_null(&pEnc->f_refhv);
304  #endif  
305          image_null(&pEnc->current->image);          image_null(&pEnc->current->image);
306          image_null(&pEnc->reference->image);          image_null(&pEnc->reference->image);
307          image_null(&pEnc->vInterH);          image_null(&pEnc->vInterH);
308          image_null(&pEnc->vInterV);          image_null(&pEnc->vInterV);
         image_null(&pEnc->vInterVf);  
309          image_null(&pEnc->vInterHV);          image_null(&pEnc->vInterHV);
         image_null(&pEnc->vInterHVf);  
   
         if (  
 #ifdef _DEBUG  
                 image_create(&pEnc->sOriginal, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
 #endif  
 #ifdef BFRAMES  
                 image_create(&pEnc->f_refh, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
                 image_create(&pEnc->f_refv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
                 image_create(&pEnc->f_refhv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
 #endif  
                 image_create(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
                 image_create(&pEnc->reference->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
                 image_create(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
                 image_create(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
                 image_create(&pEnc->vInterVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
                 image_create(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
                 image_create(&pEnc->vInterHVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)  
         {  
 #ifdef _DEBUG  
                 image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
 #endif  
 #ifdef BFRAMES  
                 image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
 #endif  
                 image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->vInterVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->vInterHVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
   
                 xvid_free(pEnc->current);  
                 xvid_free(pEnc->reference);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
   
 // ==============================================================================  
 #ifdef BFRAMES  
   
         // TODO: handle malloc() == NULL  
         pEnc->max_bframes = pParam->max_bframes;  
         pEnc->bquant_ratio = pParam->bquant_ratio;  
         if (pEnc->max_bframes > 0)  
         {  
                 int n;  
310    
311                  pEnc->bframes = malloc(pEnc->max_bframes * sizeof(FRAMEINFO *));          if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
312                    if (image_create
313                            (&pEnc->sOriginal, pEnc->mbParam.edged_width,
314                             pEnc->mbParam.edged_height) < 0)
315                            goto xvid_err_memory3;
316    
317                    if (image_create
318                            (&pEnc->sOriginal2, pEnc->mbParam.edged_width,
319                             pEnc->mbParam.edged_height) < 0)
320                            goto xvid_err_memory3;
321            }
322    
323            if (image_create
324                    (&pEnc->f_refh, pEnc->mbParam.edged_width,
325                     pEnc->mbParam.edged_height) < 0)
326                    goto xvid_err_memory3;
327            if (image_create
328                    (&pEnc->f_refv, pEnc->mbParam.edged_width,
329                     pEnc->mbParam.edged_height) < 0)
330                    goto xvid_err_memory3;
331            if (image_create
332                    (&pEnc->f_refhv, pEnc->mbParam.edged_width,
333                     pEnc->mbParam.edged_height) < 0)
334                    goto xvid_err_memory3;
335    
336            if (image_create
337                    (&pEnc->current->image, pEnc->mbParam.edged_width,
338                     pEnc->mbParam.edged_height) < 0)
339                    goto xvid_err_memory3;
340            if (image_create
341                    (&pEnc->reference->image, pEnc->mbParam.edged_width,
342                     pEnc->mbParam.edged_height) < 0)
343                    goto xvid_err_memory3;
344            if (image_create
345                    (&pEnc->vInterH, pEnc->mbParam.edged_width,
346                     pEnc->mbParam.edged_height) < 0)
347                    goto xvid_err_memory3;
348            if (image_create
349                    (&pEnc->vInterV, pEnc->mbParam.edged_width,
350                     pEnc->mbParam.edged_height) < 0)
351                    goto xvid_err_memory3;
352            if (image_create
353                    (&pEnc->vInterHV, pEnc->mbParam.edged_width,
354                     pEnc->mbParam.edged_height) < 0)
355                    goto xvid_err_memory3;
356    
357    /* Create full bitplane for GMC, this might be wasteful */
358            if (image_create
359                    (&pEnc->vGMC, pEnc->mbParam.edged_width,
360                     pEnc->mbParam.edged_height) < 0)
361                    goto xvid_err_memory3;
362    
363                  for (n = 0; n < pEnc->max_bframes; n++)          /* init bframe image buffers */
                 {  
                         pEnc->bframes[n] = malloc(sizeof(FRAMEINFO));  
                         pEnc->bframes[n]->mbs = malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width * pEnc->mbParam.mb_height);  
364    
                         if (image_create(&pEnc->bframes[n]->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)  
                         {  
                                 return XVID_ERR_MEMORY;  
                         }  
                 }  
         }  
365          pEnc->bframenum_head = 0;          pEnc->bframenum_head = 0;
366          pEnc->bframenum_tail = 0;          pEnc->bframenum_tail = 0;
367          pEnc->flush_bframes = 0;          pEnc->flush_bframes = 0;
368            pEnc->closed_bframenum = -1;
369    
370          pEnc->mbParam.m_seconds = 0;          /* B Frames specific init */
371          pEnc->mbParam.m_ticks = 0;          pEnc->bframes = NULL;
 #endif  
372    
373            if (pEnc->mbParam.max_bframes > 0) {
374    
375  // ==============================================================================                  pEnc->bframes =
376                            xvid_malloc(pEnc->mbParam.max_bframes * sizeof(FRAMEINFO *),
377                                                    CACHE_LINE);
378    
379                    if (pEnc->bframes == NULL)
380                            goto xvid_err_memory3;
381    
382          pParam->handle = (void *)pEnc;                  for (n = 0; n < pEnc->mbParam.max_bframes; n++)
383                            pEnc->bframes[n] = NULL;
384    
         if (pParam->rc_bitrate)  
         {  
                 RateControlInit(pParam->rc_bitrate, pParam->rc_reaction_delay_factor,  
                         pParam->rc_averaging_period, pParam->rc_buffer, pParam->fbase * 1000 / pParam->fincr,  
                         pParam->max_quantizer, pParam->min_quantizer);  
         }  
385    
386          init_timer();                  for (n = 0; n < pEnc->mbParam.max_bframes; n++) {
387                            pEnc->bframes[n] = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
388    
389          return XVID_ERR_OK;                          if (pEnc->bframes[n] == NULL)
390  }                                  goto xvid_err_memory4;
391    
392                            pEnc->bframes[n]->mbs =
393                                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
394                                                            pEnc->mbParam.mb_height, CACHE_LINE);
395    
396  int encoder_destroy(Encoder * pEnc)                          if (pEnc->bframes[n]->mbs == NULL)
397  {                                  goto xvid_err_memory4;
         ENC_CHECK(pEnc);  
398    
399  // =================================================================                          image_null(&pEnc->bframes[n]->image);
 #ifdef BFRAMES  
         if (pEnc->max_bframes > 0)  
         {  
                 int n;  
                 for (n = 0; n < pEnc->max_bframes; n++)  
                 {  
                         image_destroy(&pEnc->bframes[n]->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                         free(pEnc->bframes[n]->mbs);  
                         free(pEnc->bframes[n]);  
                 }  
                 free(pEnc->bframes);  
         }  
 #endif BFRAMES  
 //====================================================================  
   
         image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->vInterVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->vInterHVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
 #ifdef BFRAMES  
         image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
 #endif  
 #ifdef _DEBUG  
                 image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
 #endif  
         xvid_free(pEnc->current->mbs);  
         xvid_free(pEnc->current);  
400    
401          xvid_free(pEnc->reference->mbs);                          if (image_create
402          xvid_free(pEnc->reference);                                  (&pEnc->bframes[n]->image, pEnc->mbParam.edged_width,
403                                     pEnc->mbParam.edged_height) < 0)
404                                    goto xvid_err_memory4;
405    
406          xvid_free(pEnc);                  }
         return XVID_ERR_OK;  
407  }  }
408    
409            /* init incoming frame queue */
410            pEnc->queue_head = 0;
411            pEnc->queue_tail = 0;
412            pEnc->queue_size = 0;
413    
414            pEnc->queue =
415                    xvid_malloc((pEnc->mbParam.max_bframes+1) * sizeof(QUEUEINFO),
416                                            CACHE_LINE);
417    
418  // ==================================================================          if (pEnc->queue == NULL)
419  #ifdef BFRAMES                  goto xvid_err_memory4;
 int encoder_encode(Encoder * pEnc, XVID_ENC_FRAME * pFrame, XVID_ENC_STATS * pResult)  
 {  
         uint16_t x, y;  
         Bitstream bs;  
         uint32_t bits;  
420    
421          ENC_CHECK(pEnc);          for (n = 0; n < pEnc->mbParam.max_bframes+1; n++)
422          ENC_CHECK(pFrame);                  image_null(&pEnc->queue[n].image);
423    
         start_global_timer();  
424    
425          BitstreamInit(&bs, pFrame->bitstream, 0);          for (n = 0; n < pEnc->mbParam.max_bframes+1; n++) {
426                    if (image_create
427                            (&pEnc->queue[n].image, pEnc->mbParam.edged_width,
428                             pEnc->mbParam.edged_height) < 0)
429                            goto xvid_err_memory5;
430            }
431    
432  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          /* timestamp stuff */
 // bframe "flush" code  
 // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
433    
434          if ((pFrame->image == NULL || pEnc->flush_bframes) &&          pEnc->mbParam.m_stamp = 0;
435                  pEnc->bframenum_head < pEnc->bframenum_tail)          pEnc->m_framenum = 0;
436          {          pEnc->current->stamp = 0;
437            pEnc->reference->stamp = 0;
438    
439                  if (pEnc->flush_bframes == 0)          /* other stuff */
                 {  
                         // we have reached end of stream without getting a future reference  
                         // .. so encode last final frame a pframe  
                         dprintf("--- PFRAME (final frame correction) --- ");  
                         pEnc->bframenum_tail--;  
                         SWAP(pEnc->current, pEnc->reference);  
440    
441                          SWAP(pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);          pEnc->iFrameNum = 0;
442            pEnc->fMvPrevSigma = -1;
443    
444                          FrameCodeP(pEnc, &bs, &bits, 1, 0);          create->handle = (void *) pEnc;
445    
446                          BitstreamPad(&bs);          init_timer();
447                          pFrame->length = BitstreamLength(&bs);          init_mpeg_matrix(pEnc->mbParam.mpeg_quant_matrices);
                         pFrame->input_consumed = 0;  
                         pFrame->intra = 0;  
                         return XVID_ERR_OK;  
                 }  
448    
449                  dprintf("--- BFRAME (flush) --- ");          return 0;   /* ok */
                 FrameCodeB(pEnc,  
                         pEnc->bframes[pEnc->bframenum_head],  
                          &bs, &bits);  
                 pEnc->bframenum_head++;  
450    
451            /*
452             * We handle all XVID_ERR_MEMORY here, this makes the code lighter
453             */
454    
455                  BitstreamPad(&bs);    xvid_err_memory5:
                 pFrame->length = BitstreamLength(&bs);  
                 pFrame->input_consumed = 0;  
                 pFrame->intra = 0;  
                 return XVID_ERR_OK;  
         }  
456    
457          if (pFrame->image == NULL)          for (n = 0; n < pEnc->mbParam.max_bframes+1; n++) {
458          {                          image_destroy(&pEnc->queue[n].image, pEnc->mbParam.edged_width,
459                  pFrame->length = 0;                                                    pEnc->mbParam.edged_height);
                 pFrame->input_consumed = 1;  
                 pFrame->intra = 0;  
                 return XVID_ERR_OK;  
460          }          }
461    
462          if (pEnc->bframenum_head > 0)          xvid_free(pEnc->queue);
         {  
                 pEnc->bframenum_head = pEnc->bframenum_tail = 0;  
         }  
463    
464          pEnc->flush_bframes = 0;    xvid_err_memory4:
465    
466  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          if (pEnc->mbParam.max_bframes > 0) {
467                    int i;
468    
469          SWAP(pEnc->current, pEnc->reference);                  for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
470    
471          pEnc->current->quant = (pFrame->quant == 0) ? RateControlGetQ(0) : pFrame->quant;                          if (pEnc->bframes[i] == NULL)
472          pEnc->current->global_flags = pFrame->general;                                  continue;
         pEnc->current->motion_flags = pFrame->motion;  
         pEnc->current->seconds = pEnc->mbParam.m_seconds;  
         pEnc->current->ticks = pEnc->mbParam.m_ticks;  
         //@@@ TODO: dyanmic fcode (in both directions)  
         pEnc->current->fcode = pEnc->mbParam.m_fcode;  
         pEnc->current->bcode = pEnc->mbParam.m_fcode;  
473    
474          start_timer();                          image_destroy(&pEnc->bframes[i]->image, pEnc->mbParam.edged_width,
475          if (image_input(&pEnc->current->image, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width,                                                    pEnc->mbParam.edged_height);
476                          pFrame->image, pFrame->colorspace))                          xvid_free(pEnc->bframes[i]->mbs);
477          {                          xvid_free(pEnc->bframes[i]);
478                  return XVID_ERR_FORMAT;                  }
479          }  
480          stop_conv_timer();                  xvid_free(pEnc->bframes);
481            }
482    
483      xvid_err_memory3:
484    
485            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
486                    image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width,
487                                              pEnc->mbParam.edged_height);
488                    image_destroy(&pEnc->sOriginal2, pEnc->mbParam.edged_width,
489                                              pEnc->mbParam.edged_height);
490            }
491    
492            image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width,
493                                      pEnc->mbParam.edged_height);
494            image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width,
495                                      pEnc->mbParam.edged_height);
496            image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width,
497                                      pEnc->mbParam.edged_height);
498    
499            image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width,
500                                      pEnc->mbParam.edged_height);
501            image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width,
502                                      pEnc->mbParam.edged_height);
503            image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width,
504                                      pEnc->mbParam.edged_height);
505            image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width,
506                                      pEnc->mbParam.edged_height);
507            image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width,
508                                      pEnc->mbParam.edged_height);
509    
510    /* destroy GMC image */
511            image_destroy(&pEnc->vGMC, pEnc->mbParam.edged_width,
512                                      pEnc->mbParam.edged_height);
513    
514  #ifdef _DEBUG    xvid_err_memory2a:
515          image_copy(&pEnc->sOriginal, &pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.height);          xvid_free(pEnc->mbParam.mpeg_quant_matrices);
 #endif  
516    
517      xvid_err_memory2:
518            xvid_free(pEnc->current->mbs);
519            xvid_free(pEnc->reference->mbs);
520    
521  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    xvid_err_memory1:
522  // lumi masking          xvid_free(pEnc->current);
523  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          xvid_free(pEnc->reference);
524    
525          if ((pEnc->current->global_flags & XVID_LUMIMASKING))    xvid_err_memory1a:
526          {          if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
527                  int * temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * sizeof(int), CACHE_LINE);                  xvid_free(pEnc->temp_dquants);
528            }
529    
530                  pEnc->current->quant = adaptive_quantization(pEnc->current->image.y,          if(pEnc->mbParam.plugin_flags & XVID_REQLAMBDA) {
531                                                              pEnc->mbParam.edged_width,  // stride                  xvid_free(pEnc->temp_lambda);
532                                                              temp_dquants,          }
                                                             pEnc->current->quant,  
                                                             pEnc->current->quant,       // min_quant  
                                                             2*pEnc->current->quant,     // max_quant  
                                                             pEnc->mbParam.mb_width,  
                                                             pEnc->mbParam.mb_height);  
533    
534                  for (y = 0; y < pEnc->mbParam.mb_height; y++)    xvid_err_memory0:
535                          for (x = 0; x < pEnc->mbParam.mb_width; x++)          for (n=0; n<pEnc->num_plugins;n++) {
536                          {                  if (pEnc->plugins[n].func) {
537                                  MACROBLOCK *pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];                          pEnc->plugins[n].func(pEnc->plugins[n].param, XVID_PLG_DESTROY, NULL, NULL);
                                 pMB->dquant = iDQtab[(temp_dquants[y * pEnc->mbParam.mb_width + x] + 2)];  
538                          }                          }
                 xvid_free(temp_dquants);  
539          }          }
540            xvid_free(pEnc->plugins);
541    
542            xvid_free(pEnc->zones);
543    
544  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          xvid_free(pEnc);
 // ivop/pvop/bvop selection  
 // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
545    
546          if (pEnc->iFrameNum == 0 ||          create->handle = NULL;
                 pFrame->intra == 1 ||  
                 (pFrame->intra < 0 && (pEnc->iMaxKeyInterval > 0 && pEnc->iFrameNum >= pEnc->iMaxKeyInterval)) ||  
                 image_mad(&pEnc->reference->image, &pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.width, pEnc->mbParam.height) > 30)  
         {  
                 dprintf("--- IFRAME ---");  
547    
548                  FrameCodeI(pEnc, &bs, &bits);          return XVID_ERR_MEMORY;
549    }
550    
551                  pFrame->intra = 1;  /*****************************************************************************
552                  pEnc->flush_bframes = 1;   * Encoder destruction
553     *
554     * This function destroy the entire encoder structure created by a previous
555     * successful enc_create call.
556     *
557     * Returned values (for now only one returned value) :
558     *      - 0      - no errors
559     *
560     ****************************************************************************/
561    
562                  /* note: sequences like "IIBB" decode fine with msfdam but,  int
563                     go screwy with divx5.00 */  enc_destroy(Encoder * pEnc)
         }  
         else if (pEnc->bframenum_tail >= pEnc->max_bframes)  
564          {          {
565                  dprintf("--- PFRAME ---");          int i;
566    
567                  FrameCodeP(pEnc, &bs, &bits, 1, 0);          /* B Frames specific */
568                  pFrame->intra = 0;          for (i = 0; i < pEnc->mbParam.max_bframes+1; i++) {
569                  pEnc->flush_bframes = 1;                  image_destroy(&pEnc->queue[i].image, pEnc->mbParam.edged_width,
570                                              pEnc->mbParam.edged_height);
571          }          }
         else  
         {  
                 dprintf("--- BFRAME (store) ---  head=%i tail=%i", pEnc->bframenum_head, pEnc->bframenum_tail);  
572    
573                  if (pFrame->bquant < 1)          xvid_free(pEnc->queue);
                 {  
                         pEnc->current->quant = ((pEnc->reference->quant + pEnc->current->quant) * pEnc->bquant_ratio) / 200;  
                 }  
                 else  
                 {  
                         pEnc->current->quant = pFrame->bquant;  
                 }  
574    
575                  // store frame into bframe buffer & swap ref back to current          if (pEnc->mbParam.max_bframes > 0) {
                 SWAP(pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);  
                 SWAP(pEnc->current, pEnc->reference);  
576    
577                  pEnc->bframenum_tail++;                  for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
578    
579                            if (pEnc->bframes[i] == NULL)
580                                    continue;
581    
582                  pFrame->intra = 0;                          image_destroy(&pEnc->bframes[i]->image, pEnc->mbParam.edged_width,
583                  pFrame->length = 0;                                            pEnc->mbParam.edged_height);
584                  pFrame->input_consumed = 1;                          xvid_free(pEnc->bframes[i]->mbs);
585                            xvid_free(pEnc->bframes[i]);
586                    }
587    
588                    xvid_free(pEnc->bframes);
589    
                 pEnc->mbParam.m_ticks += pEnc->mbParam.fincr;  
                 if (pEnc->mbParam.m_ticks > pEnc->mbParam.fbase)  
                 {  
                         pEnc->mbParam.m_seconds++;  
                         pEnc->mbParam.m_ticks = 0;  
590                  }                  }
591                  return XVID_ERR_OK;  
592            /* All images, reference, current etc ... */
593    
594            image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width,
595                                      pEnc->mbParam.edged_height);
596            image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width,
597                                      pEnc->mbParam.edged_height);
598            image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width,
599                                      pEnc->mbParam.edged_height);
600            image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width,
601                                      pEnc->mbParam.edged_height);
602            image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width,
603                                      pEnc->mbParam.edged_height);
604            image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width,
605                                      pEnc->mbParam.edged_height);
606            image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width,
607                                      pEnc->mbParam.edged_height);
608            image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width,
609                                      pEnc->mbParam.edged_height);
610            image_destroy(&pEnc->vGMC, pEnc->mbParam.edged_width,
611                                      pEnc->mbParam.edged_height);
612    
613            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
614                    image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width,
615                                              pEnc->mbParam.edged_height);
616                    image_destroy(&pEnc->sOriginal2, pEnc->mbParam.edged_width,
617                                              pEnc->mbParam.edged_height);
618          }          }
619    
620          BitstreamPad(&bs);          /* Encoder structure */
         pFrame->length = BitstreamLength(&bs);  
621    
622          if (pResult)          xvid_free(pEnc->current->mbs);
623          {          xvid_free(pEnc->current);
624                  pResult->quant = pEnc->current->quant;  
625                  pResult->hlength = pFrame->length - (pEnc->sStat.iTextBits / 8);          xvid_free(pEnc->reference->mbs);
626                  pResult->kblks = pEnc->sStat.kblks;          xvid_free(pEnc->reference);
627                  pResult->mblks = pEnc->sStat.mblks;  
628                  pResult->ublks = pEnc->sStat.ublks;          if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
629                    xvid_free(pEnc->temp_dquants);
630          }          }
631    
 #ifdef _DEBUG  
         psnr = image_psnr(&pEnc->sOriginal, &pEnc->current->image, pEnc->mbParam.edged_width,  
                                 pEnc->mbParam.width, pEnc->mbParam.height);  
632    
633          sprintf(temp, "PSNR: %f\n", psnr);          if (pEnc->num_plugins>0) {
634          DEBUG(temp);                  xvid_plg_destroy_t pdestroy;
635  #endif                  memset(&pdestroy, 0, sizeof(xvid_plg_destroy_t));
636    
637          if (pFrame->quant == 0)                  pdestroy.version = XVID_VERSION;
638          {                  pdestroy.num_frames = pEnc->m_framenum;
                 RateControlUpdate(pEnc->current->quant, pFrame->length, pFrame->intra);  
         }  
639    
640          pEnc->iFrameNum++;                  for (i=0; i<pEnc->num_plugins;i++) {
641          pEnc->mbParam.m_ticks += pEnc->mbParam.fincr;                          if (pEnc->plugins[i].func) {
642          if (pEnc->mbParam.m_ticks > pEnc->mbParam.fbase)                                  pEnc->plugins[i].func(pEnc->plugins[i].param, XVID_PLG_DESTROY, &pdestroy, NULL);
643          {                          }
644                  pEnc->mbParam.m_seconds++;                  }
645                  pEnc->mbParam.m_ticks = 0;                  xvid_free(pEnc->plugins);
646          }          }
         pFrame->input_consumed = 1;  
647    
648          stop_global_timer();          xvid_free(pEnc->mbParam.mpeg_quant_matrices);
         write_timer();  
649    
650          return XVID_ERR_OK;          if (pEnc->num_plugins>0)
651                    xvid_free(pEnc->zones);
652    
653            xvid_free(pEnc);
654    
655            return 0;  /* ok */
656  }  }
 // ==================================================================  
 #else  
 int encoder_encode(Encoder * pEnc, XVID_ENC_FRAME * pFrame, XVID_ENC_STATS * pResult)  
 {  
         uint16_t x, y;  
         Bitstream bs;  
         uint32_t bits;  
         uint16_t write_vol_header = 0;  
 #ifdef _DEBUG  
         float psnr;  
         uint8_t temp[100];  
 #endif  
657    
         start_global_timer();  
658    
659          ENC_CHECK(pEnc);  /*
660          ENC_CHECK(pFrame);    call the plugins
661          ENC_CHECK(pFrame->bitstream);    */
         ENC_CHECK(pFrame->image);  
   
         SWAP(pEnc->current, pEnc->reference);  
   
         pEnc->current->global_flags = pFrame->general;  
         pEnc->current->motion_flags = pFrame->motion;  
         pEnc->mbParam.hint = &pFrame->hint;  
662    
663          start_timer();  static void call_plugins(Encoder * pEnc, FRAMEINFO * frame, IMAGE * original,
664          if (image_input(&pEnc->current->image, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width,                                                   int opt, int * type, int * quant, xvid_enc_stats_t * stats)
                         pFrame->image, pFrame->colorspace))  
665          {          {
666                  return XVID_ERR_FORMAT;          unsigned int i, j, k;
667          }          xvid_plg_data_t data;
         stop_conv_timer();  
668    
669  #ifdef _DEBUG          /* set data struct */
         image_copy(&pEnc->sOriginal, &pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height);  
 #endif  
670    
671          EMMS();          memset(&data, 0, sizeof(xvid_plg_data_t));
672            data.version = XVID_VERSION;
673    
674          BitstreamInit(&bs, pFrame->bitstream, 0);          /* find zone */
675            for(i=0; i<pEnc->num_zones && pEnc->zones[i].frame<=frame->frame_num; i++) ;
676            data.zone = i>0 ? &pEnc->zones[i-1] : NULL;
677    
678          if (pFrame->quant == 0)          data.width = pEnc->mbParam.width;
679          {          data.height = pEnc->mbParam.height;
680                  pEnc->current->quant = RateControlGetQ(0);          data.mb_width = pEnc->mbParam.mb_width;
681          }          data.mb_height = pEnc->mbParam.mb_height;
682          else          data.fincr = frame->fincr;
683          {          data.fbase = pEnc->mbParam.fbase;
684                  pEnc->current->quant = pFrame->quant;          data.bquant_ratio = pEnc->mbParam.bquant_ratio;
685          }          data.bquant_offset = pEnc->mbParam.bquant_offset;
686    
687          if ((pEnc->current->global_flags & XVID_LUMIMASKING))          for (i=0; i<3; i++) {
688          {                  data.min_quant[i] = pEnc->mbParam.min_quant[i];
689                  int * temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * sizeof(int), CACHE_LINE);                  data.max_quant[i] = pEnc->mbParam.max_quant[i];
690            }
691    
692                  pEnc->current->quant = adaptive_quantization(pEnc->current->image.y,          data.reference.csp = XVID_CSP_PLANAR;
693                                                              pEnc->mbParam.edged_width,  // stride          data.reference.plane[0] = pEnc->reference->image.y;
694                                                              temp_dquants,          data.reference.plane[1] = pEnc->reference->image.u;
695                                                              pEnc->current->quant,          data.reference.plane[2] = pEnc->reference->image.v;
696                                                              pEnc->current->quant,       // min_quant          data.reference.stride[0] = pEnc->mbParam.edged_width;
697                                                              2*pEnc->current->quant,     // max_quant          data.reference.stride[1] = pEnc->mbParam.edged_width/2;
698                                                              pEnc->mbParam.mb_width,          data.reference.stride[2] = pEnc->mbParam.edged_width/2;
                                                             pEnc->mbParam.mb_height);  
699    
700                  for (y = 0; y < pEnc->mbParam.mb_height; y++)          data.current.csp = XVID_CSP_PLANAR;
701                          for (x = 0; x < pEnc->mbParam.mb_width; x++)          data.current.plane[0] = frame->image.y;
702                          {          data.current.plane[1] = frame->image.u;
703                                  MACROBLOCK *pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];          data.current.plane[2] = frame->image.v;
704                                  pMB->dquant = iDQtab[(temp_dquants[y * pEnc->mbParam.mb_width + x] + 2)];          data.current.stride[0] = pEnc->mbParam.edged_width;
705                          }          data.current.stride[1] = pEnc->mbParam.edged_width/2;
706                  xvid_free(temp_dquants);          data.current.stride[2] = pEnc->mbParam.edged_width/2;
         }  
707    
708          if (pEnc->current->global_flags & XVID_H263QUANT) {          data.frame_num = frame->frame_num;
                 if(pEnc->mbParam.m_quant_type != H263_QUANT)  
                         write_vol_header = 1;  
                 pEnc->mbParam.m_quant_type = H263_QUANT;  
         }  
         else if(pEnc->current->global_flags & XVID_MPEGQUANT) {  
                 int ret1, ret2;  
709    
710                  ret1 = ret2 = 0;          if (opt == XVID_PLG_BEFORE) {
711                    data.type = *type;
712                    data.quant = *quant;
713    
714                  if(pEnc->mbParam.m_quant_type != MPEG4_QUANT)                  data.vol_flags = frame->vol_flags;
715                          write_vol_header = 1;                  data.vop_flags = frame->vop_flags;
716                    data.motion_flags = frame->motion_flags;
717    
718                  pEnc->mbParam.m_quant_type = MPEG4_QUANT;          } else if (opt == XVID_PLG_FRAME) {
719                    data.type = coding2type(frame->coding_type);
720                    data.quant = frame->quant;
721    
722                  if ((pEnc->current->global_flags & XVID_CUSTOM_QMATRIX) > 0) {                  if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
723                          if(pFrame->quant_intra_matrix != NULL)                          data.dquant = pEnc->temp_dquants;
724                                  ret1 = set_intra_matrix(pFrame->quant_intra_matrix);                          data.dquant_stride = pEnc->mbParam.mb_width;
725                          if(pFrame->quant_inter_matrix != NULL)                          memset(data.dquant, 0, data.mb_width*data.mb_height);
                                 ret2 = set_inter_matrix(pFrame->quant_inter_matrix);  
726                  }                  }
727                  else {  
728                          ret1 = set_intra_matrix(get_default_intra_matrix());                  if(pEnc->mbParam.plugin_flags & XVID_REQLAMBDA) {
729                          ret2 = set_inter_matrix(get_default_inter_matrix());                          int block = 0;
730                            data.lambda = pEnc->temp_lambda;
731                            for(i = 0;i < pEnc->mbParam.mb_height; i++)
732                                    for(j = 0;j < pEnc->mbParam.mb_width; j++)
733                                            for (k = 0; k < 6; k++)
734                                                    data.lambda[block++] = 1.0f;
735                  }                  }
736                  if(write_vol_header == 0)  
737                          write_vol_header = ret1 | ret2;          } else { /* XVID_PLG_AFTER */
738                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
739                            data.original.csp = XVID_CSP_PLANAR;
740                            data.original.plane[0] = original->y;
741                            data.original.plane[1] = original->u;
742                            data.original.plane[2] = original->v;
743                            data.original.stride[0] = pEnc->mbParam.edged_width;
744                            data.original.stride[1] = pEnc->mbParam.edged_width/2;
745                            data.original.stride[2] = pEnc->mbParam.edged_width/2;
746          }          }
747    
748          if (pFrame->intra < 0)                  if ((frame->vol_flags & XVID_VOL_EXTRASTATS) ||
749          {                          (pEnc->mbParam.plugin_flags & XVID_REQPSNR)) {
                 if ((pEnc->iFrameNum == 0) || ((pEnc->iMaxKeyInterval > 0)  
                                                && (pEnc->iFrameNum >= pEnc->iMaxKeyInterval)))  
750    
751                          pFrame->intra = FrameCodeI(pEnc, &bs, &bits);                          data.sse_y =
752                  else                                  plane_sse( original->y, frame->image.y,
753                          pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 0, write_vol_header);                                                     pEnc->mbParam.edged_width, pEnc->mbParam.width,
754          }                                                     pEnc->mbParam.height);
         else  
         {  
                 if (pFrame->intra == 1)  
                         pFrame->intra = FrameCodeI(pEnc, &bs, &bits);  
                 else  
                         pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 1, write_vol_header);  
         }  
755    
756          BitstreamPutBits(&bs, 0xFFFF, 16);                          data.sse_u =
757          BitstreamPutBits(&bs, 0xFFFF, 16);                                  plane_sse( original->u, frame->image.u,
758          BitstreamPad(&bs);                                                     pEnc->mbParam.edged_width/2, pEnc->mbParam.width/2,
759          pFrame->length = BitstreamLength(&bs);                                                     pEnc->mbParam.height/2);
760    
761          if (pResult)                          data.sse_v =
762          {                                  plane_sse( original->v, frame->image.v,
763                  pResult->quant = pEnc->current->quant;                                                     pEnc->mbParam.edged_width/2, pEnc->mbParam.width/2,
764                  pResult->hlength = pFrame->length - (pEnc->sStat.iTextBits / 8);                                                     pEnc->mbParam.height/2);
                 pResult->kblks = pEnc->sStat.kblks;  
                 pResult->mblks = pEnc->sStat.mblks;  
                 pResult->ublks = pEnc->sStat.ublks;  
765          }          }
766    
767          EMMS();                  data.type = coding2type(frame->coding_type);
768                    data.quant = frame->quant;
769    
770          if (pFrame->quant == 0)                  if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
771          {                          data.dquant = pEnc->temp_dquants;
772                  RateControlUpdate(pEnc->current->quant, pFrame->length, pFrame->intra);                          data.dquant_stride = pEnc->mbParam.mb_width;
         }  
773    
774  #ifdef _DEBUG                          for (j=0; j<pEnc->mbParam.mb_height; j++)
775          psnr = image_psnr(&pEnc->sOriginal, &pEnc->current->image, pEnc->mbParam.edged_width,                          for (i=0; i<pEnc->mbParam.mb_width; i++) {
776                                  pEnc->mbParam.width, pEnc->mbParam.height);                                  data.dquant[j*data.dquant_stride + i] = frame->mbs[j*pEnc->mbParam.mb_width + i].dquant;
777                            }
778                    }
779    
780          sprintf(temp, "PSNR: %f\n", psnr);                  data.vol_flags = frame->vol_flags;
781          DEBUG(temp);                  data.vop_flags = frame->vop_flags;
782  #endif                  data.motion_flags = frame->motion_flags;
783    
784          pEnc->iFrameNum++;                  data.length = frame->length;
785                    data.kblks = frame->sStat.kblks;
786                    data.mblks = frame->sStat.mblks;
787                    data.ublks = frame->sStat.ublks;
788    
789          stop_global_timer();                  /* New code */
790          write_timer();                  data.stats.type      = coding2type(frame->coding_type);
791                    data.stats.quant     = frame->quant;
792                    data.stats.vol_flags = frame->vol_flags;
793                    data.stats.vop_flags = frame->vop_flags;
794                    data.stats.length    = frame->length;
795                    data.stats.hlength   = frame->length - (frame->sStat.iTextBits / 8);
796                    data.stats.kblks     = frame->sStat.kblks;
797                    data.stats.mblks     = frame->sStat.mblks;
798                    data.stats.ublks     = frame->sStat.ublks;
799                    data.stats.sse_y     = data.sse_y;
800                    data.stats.sse_u     = data.sse_u;
801                    data.stats.sse_v     = data.sse_v;
802    
803          return XVID_ERR_OK;                  if (stats)
804                            *stats = data.stats;
805  }  }
 #endif  
806    
807            /* call plugins */
808            for (i=0; i<(unsigned int)pEnc->num_plugins;i++) {
809                    emms();
810                    if (pEnc->plugins[i].func) {
811                            if (pEnc->plugins[i].func(pEnc->plugins[i].param, opt, &data, NULL) < 0) {
812                                    continue;
813                            }
814                    }
815            }
816            emms();
817    
818  static __inline void CodeIntraMB(Encoder *pEnc, MACROBLOCK *pMB) {          /* copy modified values back into frame*/
819            if (opt == XVID_PLG_BEFORE) {
820          pMB->mode = MODE_INTRA;                  *type = data.type;
821                    *quant = data.quant > 0 ? data.quant : 2;   /* default */
822    
823          /* zero mv statistics */                  frame->vol_flags = data.vol_flags;
824          pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = 0;                  frame->vop_flags = data.vop_flags;
825          pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = 0;                  frame->motion_flags = data.motion_flags;
         pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = 0;  
         pMB->sad16 = 0;  
826    
827          if ((pEnc->current->global_flags & XVID_LUMIMASKING)) {          } else if (opt == XVID_PLG_FRAME) {
                 if(pMB->dquant != NO_CHANGE)  
                 {  
                         pMB->mode = MODE_INTRA_Q;  
                         pEnc->current->quant += DQtab[pMB->dquant];  
828    
829                          if (pEnc->current->quant > 31) pEnc->current->quant = 31;                  if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
830                          if (pEnc->current->quant < 1) pEnc->current->quant = 1;                          for (j=0; j<pEnc->mbParam.mb_height; j++)
831                            for (i=0; i<pEnc->mbParam.mb_width; i++) {
832                                    frame->mbs[j*pEnc->mbParam.mb_width + i].dquant = data.dquant[j*data.mb_width + i];
833                            }
834                    } else {
835                            for (j=0; j<pEnc->mbParam.mb_height; j++)
836                            for (i=0; i<pEnc->mbParam.mb_width; i++) {
837                                    frame->mbs[j*pEnc->mbParam.mb_width + i].dquant = 0;
838                  }                  }
839          }          }
840    
841          pMB->quant = pEnc->current->quant;                  if (pEnc->mbParam.plugin_flags & XVID_REQLAMBDA) {
842                            for (j = 0; j < pEnc->mbParam.mb_height; j++)
843                                    for (i = 0; i < pEnc->mbParam.mb_width; i++)
844                                            for (k = 0; k < 6; k++) {
845                                                    frame->mbs[j*pEnc->mbParam.mb_width + i].lambda[k] =
846                                                            (int) ((float)(1<<LAMBDA_EXP) * data.lambda[6 * (j * data.mb_width + i) + k]);
847                            }
848                    } else {
849                            for (j = 0; j<pEnc->mbParam.mb_height; j++)
850                                    for (i = 0; i<pEnc->mbParam.mb_width; i++)
851                                            for (k = 0; k < 6; k++) {
852                                                    frame->mbs[j*pEnc->mbParam.mb_width + i].lambda[k] = 1<<LAMBDA_EXP;
853                            }
854  }  }
855    
856    
857  #define FCODEBITS       3                  frame->mbs[0].quant = data.quant; /* FRAME will not affect the quant in stats */
858  #define MODEBITS        5          }
859    
 void HintedMESet(Encoder * pEnc, int * intra)  
 {  
         HINTINFO * hint;  
         Bitstream bs;  
         int length, high;  
         uint32_t x, y;  
860    
861          hint = pEnc->mbParam.hint;  }
862    
863    
864          if (hint->rawhints)  static __inline void inc_frame_num(Encoder * pEnc)
865          {          {
866                  *intra = hint->mvhint.intra;          pEnc->current->frame_num = pEnc->m_framenum;
867            pEnc->current->stamp = pEnc->mbParam.m_stamp;   /* first frame is zero */
868    
869            pEnc->mbParam.m_stamp += pEnc->current->fincr;
870            pEnc->m_framenum++;     /* debug ticker */
871          }          }
872          else  
873    static __inline void dec_frame_num(Encoder * pEnc)
874          {          {
875                  BitstreamInit(&bs, hint->hintstream, hint->hintlength);          pEnc->mbParam.m_stamp -= pEnc->mbParam.fincr;
876                  *intra = BitstreamGetBit(&bs);          pEnc->m_framenum--;     /* debug ticker */
877          }          }
878    
879          if (*intra)  static __inline void
880    MBSetDquant(MACROBLOCK * pMB, int x, int y, MBParam * mbParam)
881          {          {
882            if (pMB->cbp == 0) {
883                    /* we want to code dquant but the quantizer value will not be used yet
884                            let's find out if we can postpone dquant to next MB
885                    */
886                    if (x == mbParam->mb_width-1 && y == mbParam->mb_height-1) {
887                            pMB->dquant = 0; /* it's the last MB of all, the easiest case */
888                            return;
889                    } else {
890                            MACROBLOCK * next = pMB + 1;
891                            const MACROBLOCK * prev = pMB - 1;
892                            if (next->mode != MODE_INTER4V && next->mode != MODE_NOT_CODED)
893                                    /* mode allows dquant change in the future */
894                                    if (abs(next->quant - prev->quant) <= 2) {
895                                            /* quant change is not out of range */
896                                            pMB->quant = prev->quant;
897                                            pMB->dquant = 0;
898                                            next->dquant = next->quant - prev->quant;
899                  return;                  return;
900          }          }
901                    }
902            }
903            /* couldn't skip this dquant */
904            pMB->mode = MODE_INTER_Q;
905    }
906    
         pEnc->current->fcode = (hint->rawhints) ? hint->mvhint.fcode : BitstreamGetBits(&bs, FCODEBITS);  
907    
         length  = pEnc->current->fcode + 5;  
         high    = 1 << (length - 1);  
908    
909          for (y=0 ; y<pEnc->mbParam.mb_height ; ++y)  static __inline void
910    set_timecodes(FRAMEINFO* pCur,FRAMEINFO *pRef, int32_t time_base)
911          {          {
912                  for (x=0 ; x<pEnc->mbParam.mb_width ; ++x)  
913            pCur->ticks = (int32_t)pCur->stamp % time_base;
914            pCur->seconds =  ((int32_t)pCur->stamp / time_base)     - ((int32_t)pRef->stamp / time_base) ;
915    
916    #if 0   /* HEAVY DEBUG OUTPUT */
917            fprintf(stderr,"WriteVop:   %d - %d \n",
918                            ((int32_t)pCur->stamp / time_base), ((int32_t)pRef->stamp / time_base));
919            fprintf(stderr,"set_timecodes: VOP %1d   stamp=%lld ref_stamp=%lld  base=%d\n",
920                            pCur->coding_type, pCur->stamp, pRef->stamp, time_base);
921            fprintf(stderr,"set_timecodes: VOP %1d   seconds=%d   ticks=%d   (ref-sec=%d  ref-tick=%d)\n",
922                            pCur->coding_type, pCur->seconds, pCur->ticks, pRef->seconds, pRef->ticks);
923    #endif
924    }
925    
926    static void
927    simplify_par(int *par_width, int *par_height)
928                  {                  {
                         MACROBLOCK * pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
                         MVBLOCKHINT * bhint = &hint->mvhint.block[x + y * pEnc->mbParam.mb_width];  
                         VECTOR pred[4];  
                         VECTOR tmp;  
                         int32_t dummy[4];  
                         int vec;  
929    
930                          pMB->mode = (hint->rawhints) ? bhint->mode : BitstreamGetBits(&bs, MODEBITS);          int _par_width  = (!*par_width)  ? 1 : (*par_width<0)  ? -*par_width:  *par_width;
931            int _par_height = (!*par_height) ? 1 : (*par_height<0) ? -*par_height: *par_height;
932            int divisor = gcd(_par_width, _par_height);
933    
934            _par_width  /= divisor;
935            _par_height /= divisor;
936    
937            /* 2^8 precision maximum */
938            if (_par_width>255 || _par_height>255) {
939                    float div;
940                    emms();
941                    if (_par_width>_par_height)
942                            div = (float)_par_width/255;
943                    else
944                            div = (float)_par_height/255;
945    
946                    _par_width  = (int)((float)_par_width/div);
947                    _par_height = (int)((float)_par_height/div);
948            }
949    
950                          pMB->mode = (pMB->mode == MODE_INTER_Q) ? MODE_INTER : pMB->mode;          *par_width = _par_width;
951                          pMB->mode = (pMB->mode == MODE_INTRA_Q) ? MODE_INTRA : pMB->mode;          *par_height = _par_height;
952    
953                          if (pMB->mode == MODE_INTER)          return;
954    }
955    
956    
957    /*****************************************************************************
958     * IPB frame encoder entry point
959     *
960     * Returned values :
961     *      - >0                       - output bytes
962     *      - 0                             - no output
963     *      - XVID_ERR_VERSION - wrong version passed to core
964     *      - XVID_ERR_END   - End of stream reached before end of coding
965     *      - XVID_ERR_FORMAT  - the image subsystem reported the image had a wrong
966     *                                               format
967     ****************************************************************************/
968    
969    
970    int
971    enc_encode(Encoder * pEnc,
972                               xvid_enc_frame_t * xFrame,
973                               xvid_enc_stats_t * stats)
974                          {                          {
975                                  tmp.x  = (hint->rawhints) ? bhint->mvs[0].x : BitstreamGetBits(&bs, length);          xvid_enc_frame_t * frame;
976                                  tmp.y  = (hint->rawhints) ? bhint->mvs[0].y : BitstreamGetBits(&bs, length);          int type;
977                                  tmp.x -= (tmp.x >= high) ? high*2 : 0;          Bitstream bs;
978                                  tmp.y -= (tmp.y >= high) ? high*2 : 0;  
979            if (XVID_VERSION_MAJOR(xFrame->version) != 1 || (stats && XVID_VERSION_MAJOR(stats->version) != 1))     /* v1.x.x */
980                    return XVID_ERR_VERSION;
981    
982            xFrame->out_flags = 0;
983    
984            start_global_timer();
985            BitstreamInit(&bs, xFrame->bitstream, 0);
986    
                                 get_pmvdata(pEnc->current->mbs, x, y, pEnc->mbParam.mb_width, 0, pred, dummy);  
987    
988                                  for (vec=0 ; vec<4 ; ++vec)          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
989             * enqueue image to the encoding-queue
990             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
991    
992            if (xFrame->input.csp != XVID_CSP_NULL)
993            {
994                    QUEUEINFO * q = &pEnc->queue[pEnc->queue_tail];
995    
996                    start_timer();
997                    if (image_input
998                            (&q->image, pEnc->mbParam.width, pEnc->mbParam.height,
999                            pEnc->mbParam.edged_width, (uint8_t**)xFrame->input.plane, xFrame->input.stride,
1000                            xFrame->input.csp, xFrame->vol_flags & XVID_VOL_INTERLACING))
1001                                  {                                  {
1002                                          pMB->mvs[vec].x  = tmp.x;                          emms();
1003                                          pMB->mvs[vec].y  = tmp.y;                          return XVID_ERR_FORMAT;
                                         pMB->pmvs[vec].x = pMB->mvs[0].x - pred[0].x;  
                                         pMB->pmvs[vec].y = pMB->mvs[0].y - pred[0].y;  
1004                                  }                                  }
1005                    stop_conv_timer();
1006    
1007                    if ((xFrame->vop_flags & XVID_VOP_CHROMAOPT)) {
1008                            image_chroma_optimize(&q->image,
1009                                    pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width);
1010                          }                          }
1011                          else if (pMB->mode == MODE_INTER4V)  
1012                    q->frame = *xFrame;
1013    
1014                    if (xFrame->quant_intra_matrix)
1015                          {                          {
1016                                  for (vec=0 ; vec<4 ; ++vec)                          memcpy(q->quant_intra_matrix, xFrame->quant_intra_matrix, 64*sizeof(unsigned char));
1017                            q->frame.quant_intra_matrix = q->quant_intra_matrix;
1018                    }
1019    
1020                    if (xFrame->quant_inter_matrix)
1021                    {
1022                            memcpy(q->quant_inter_matrix, xFrame->quant_inter_matrix, 64*sizeof(unsigned char));
1023                            q->frame.quant_inter_matrix = q->quant_inter_matrix;
1024                    }
1025    
1026                    pEnc->queue_tail = (pEnc->queue_tail + 1) % (pEnc->mbParam.max_bframes+1);
1027                    pEnc->queue_size++;
1028            }
1029    
1030    
1031            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1032             * bframe flush code
1033             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1034    
1035    repeat:
1036    
1037            if (pEnc->flush_bframes)
1038                                  {                                  {
1039                                          tmp.x  = (hint->rawhints) ? bhint->mvs[vec].x : BitstreamGetBits(&bs, length);                  if (pEnc->bframenum_head < pEnc->bframenum_tail) {
                                         tmp.y  = (hint->rawhints) ? bhint->mvs[vec].y : BitstreamGetBits(&bs, length);  
                                         tmp.x -= (tmp.x >= high) ? high*2 : 0;  
                                         tmp.y -= (tmp.y >= high) ? high*2 : 0;  
1040    
1041                                          get_pmvdata(pEnc->current->mbs, x, y, pEnc->mbParam.mb_width, vec, pred, dummy);                          DPRINTF(XVID_DEBUG_DEBUG,"*** BFRAME (flush) bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1042                                            pEnc->bframenum_head, pEnc->bframenum_tail,
1043                                            pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1044    
1045                                          pMB->mvs[vec].x  = tmp.x;                          if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1046                                          pMB->mvs[vec].y  = tmp.y;                                  image_copy(&pEnc->sOriginal2, &pEnc->bframes[pEnc->bframenum_head]->image,
1047                                          pMB->pmvs[vec].x = pMB->mvs[vec].x - pred[0].x;                                                     pEnc->mbParam.edged_width, pEnc->mbParam.height);
                                         pMB->pmvs[vec].y = pMB->mvs[vec].y - pred[0].y;  
1048                                  }                                  }
1049    
1050                            FrameCodeB(pEnc, pEnc->bframes[pEnc->bframenum_head], &bs);
1051                            call_plugins(pEnc, pEnc->bframes[pEnc->bframenum_head], &pEnc->sOriginal2, XVID_PLG_AFTER, NULL, NULL, stats);
1052                            pEnc->bframenum_head++;
1053    
1054                            goto done;
1055                          }                          }
1056                          else    // intra / stuffing / not_coded  
1057                    /* write an empty marker to the bitstream.
1058    
1059                       for divx5 decoder compatibility, this marker must consist
1060                       of a not-coded p-vop, with a time_base of zero, and time_increment
1061                       indentical to the future-referece frame.
1062                    */
1063    
1064                    if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED && pEnc->bframenum_tail > 0)) {
1065                            int tmp;
1066                            int bits;
1067    
1068                            DPRINTF(XVID_DEBUG_DEBUG,"*** EMPTY bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1069                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1070                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1071    
1072                            bits = BitstreamPos(&bs);
1073    
1074                            tmp = pEnc->current->seconds;
1075                            pEnc->current->seconds = 0; /* force time_base = 0 */
1076    
1077                            BitstreamWriteVopHeader(&bs, &pEnc->mbParam, pEnc->current, 0, pEnc->current->quant);
1078                            BitstreamPad(&bs);
1079                            pEnc->current->seconds = tmp;
1080    
1081                            /* add the not-coded length to the reference frame size */
1082                            pEnc->current->length += (BitstreamPos(&bs) - bits) / 8;
1083                            call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1084    
1085                            /* flush complete: reset counters */
1086                            pEnc->flush_bframes = 0;
1087                            pEnc->bframenum_head = pEnc->bframenum_tail = 0;
1088                            goto done;
1089    
1090                    }
1091    
1092                    /* flush complete: reset counters */
1093                    pEnc->flush_bframes = 0;
1094                    pEnc->bframenum_head = pEnc->bframenum_tail = 0;
1095            }
1096    
1097            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1098             * dequeue frame from the encoding queue
1099             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1100    
1101            if (pEnc->queue_size == 0)              /* empty */
1102                          {                          {
1103                                  for (vec=0 ; vec<4 ; ++vec)                  if (xFrame->input.csp == XVID_CSP_NULL) /* no futher input */
1104                                  {                                  {
1105                                          pMB->mvs[vec].x  = pMB->mvs[vec].y  = 0;  
1106                            DPRINTF(XVID_DEBUG_DEBUG,"*** FINISH bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1107                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1108                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1109    
1110                            if (!(pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->mbParam.max_bframes > 0) {
1111                                    call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1112                                  }                                  }
1113    
1114                            /* if the very last frame is to be b-vop, we must change it to a p-vop */
1115                            if (pEnc->bframenum_tail > 0) {
1116    
1117                                    SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1118                                    pEnc->bframenum_tail--;
1119                                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1120    
1121                                    /* convert B-VOP to P-VOP */
1122                                    pEnc->current->quant  = 100*pEnc->current->quant - pEnc->mbParam.bquant_offset;
1123                                    pEnc->current->quant += pEnc->mbParam.bquant_ratio - 1; /* to avoid rouding issues */
1124                                    pEnc->current->quant /= pEnc->mbParam.bquant_ratio;
1125    
1126                                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1127                                            image_copy(&pEnc->sOriginal, &pEnc->current->image,
1128                                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1129                          }                          }
1130    
1131                          if (pMB->mode == MODE_INTER4V &&                                  DPRINTF(XVID_DEBUG_DEBUG,"*** PFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1132                                  (pEnc->current->global_flags & XVID_LUMIMASKING) && pMB->dquant != NO_CHANGE)                                  pEnc->bframenum_head, pEnc->bframenum_tail,
1133                          {                                  pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1134                                  pMB->mode = MODE_INTRA;                                  pEnc->mbParam.frame_drop_ratio = -1; /* it must be a coded vop */
1135    
1136                                  for (vec=0 ; vec<4 ; ++vec)                                  FrameCodeP(pEnc, &bs);
1137                                  {  
1138                                          pMB->mvs[vec].x = pMB->mvs[vec].y = 0;  
1139                                    if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail==0) {
1140                                            call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1141                                    }else{
1142                                            pEnc->flush_bframes = 1;
1143                                            goto done;
1144                                  }                                  }
1145                          }                          }
1146                            DPRINTF(XVID_DEBUG_DEBUG, "*** END\n");
1147    
1148                            emms();
1149                            return XVID_ERR_END;    /* end of stream reached */
1150                  }                  }
1151                    goto done;      /* nothing to encode yet; encoder lag */
1152          }          }
1153    
1154            /* the current FRAME becomes the reference */
1155            SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1156    
1157            /* remove frame from encoding-queue (head), and move it into the current */
1158            image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_head].image);
1159            frame = &pEnc->queue[pEnc->queue_head].frame;
1160            pEnc->queue_head = (pEnc->queue_head + 1) % (pEnc->mbParam.max_bframes+1);
1161            pEnc->queue_size--;
1162    
1163    
1164            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1165             * init pEnc->current fields
1166             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1167    
1168            pEnc->current->fincr = pEnc->mbParam.fincr>0 ? pEnc->mbParam.fincr : frame->fincr;
1169            inc_frame_num(pEnc);
1170            pEnc->current->vol_flags = frame->vol_flags;
1171            pEnc->current->vop_flags = frame->vop_flags;
1172            pEnc->current->motion_flags = frame->motion;
1173            pEnc->current->fcode = pEnc->mbParam.m_fcode;
1174            pEnc->current->bcode = pEnc->mbParam.m_fcode;
1175    
1176    
1177            if ((xFrame->vop_flags & XVID_VOP_CHROMAOPT)) {
1178                    image_chroma_optimize(&pEnc->current->image,
1179                            pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width);
1180  }  }
1181    
1182            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1183             * frame type & quant selection
1184             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1185    
1186  void HintedMEGet(Encoder * pEnc, int intra)          type = frame->type;
1187  {          pEnc->current->quant = frame->quant;
         HINTINFO * hint;  
         Bitstream bs;  
         uint32_t x, y;  
         int length, high;  
1188    
1189          hint = pEnc->mbParam.hint;          call_plugins(pEnc, pEnc->current, NULL, XVID_PLG_BEFORE, &type, (int*)&pEnc->current->quant, stats);
1190    
1191          if (hint->rawhints)          if (type > 0){  /* XVID_TYPE_?VOP */
1192          {                  type = type2coding(type);       /* convert XVID_TYPE_?VOP to bitstream coding type */
1193                  hint->mvhint.intra = intra;          } else{         /* XVID_TYPE_AUTO */
1194                    if (pEnc->iFrameNum == 0 || (pEnc->mbParam.iMaxKeyInterval > 0 && pEnc->iFrameNum >= pEnc->mbParam.iMaxKeyInterval)){
1195                            pEnc->iFrameNum = 0;
1196                            type = I_VOP;
1197                    }else{
1198                            type = MEanalysis(&pEnc->reference->image, pEnc->current,
1199                                                              &pEnc->mbParam, pEnc->mbParam.iMaxKeyInterval,
1200                                                              pEnc->iFrameNum, pEnc->bframenum_tail, xFrame->bframe_threshold,
1201                                                              (pEnc->bframes) ? pEnc->bframes[pEnc->bframenum_head]->mbs: NULL);
1202          }          }
         else  
         {  
                 BitstreamInit(&bs, hint->hintstream, 0);  
                 BitstreamPutBit(&bs, intra);  
1203          }          }
1204    
1205          if (intra)          if (type != I_VOP)
1206          {                  pEnc->current->vol_flags = pEnc->mbParam.vol_flags; /* don't allow VOL changes here */
1207                  if (!hint->rawhints)  
1208                  {          /* bframes buffer overflow check */
1209                          BitstreamPad(&bs);          if (type == B_VOP && pEnc->bframenum_tail >= pEnc->mbParam.max_bframes) {
1210                          hint->hintlength = BitstreamLength(&bs);                  type = P_VOP;
1211                  }                  }
1212                  return;  
1213            pEnc->iFrameNum++;
1214    
1215            if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1216                    image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 5,
1217                            "%d  st:%lld  if:%d", pEnc->current->frame_num, pEnc->current->stamp, pEnc->iFrameNum);
1218          }          }
1219    
1220          length  = pEnc->current->fcode + 5;          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1221          high    = 1 << (length - 1);           * encode this frame as a b-vop
1222             * (we dont encode here, rather we store the frame in the bframes queue, to be encoded later)
1223             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1224            if (type == B_VOP) {
1225                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1226                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "BVOP");
1227                    }
1228    
1229          if (hint->rawhints)                  if (frame->quant < 1) {
1230          {                          pEnc->current->quant = ((((pEnc->reference->quant + pEnc->current->quant) *
1231                  hint->mvhint.fcode = pEnc->current->fcode;                                  pEnc->mbParam.bquant_ratio) / 2) + pEnc->mbParam.bquant_offset)/100;
1232    
1233                    } else {
1234                            pEnc->current->quant = frame->quant;
1235          }          }
1236          else  
1237          {                  if (pEnc->current->quant < 1)
1238                  BitstreamPutBits(&bs, pEnc->current->fcode, FCODEBITS);                          pEnc->current->quant = 1;
1239                    else if (pEnc->current->quant > 31)
1240                            pEnc->current->quant = 31;
1241    
1242                    DPRINTF(XVID_DEBUG_DEBUG,"*** BFRAME (store) bf: head=%i tail=%i   queue: head=%i tail=%i size=%i  quant=%i\n",
1243                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1244                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size,pEnc->current->quant);
1245    
1246                    /* store frame into bframe buffer & swap ref back to current */
1247                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1248                    SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1249    
1250                    pEnc->bframenum_tail++;
1251    
1252                    goto repeat;
1253          }          }
1254    
         for (y=0 ; y<pEnc->mbParam.mb_height ; ++y)  
         {  
                 for (x=0 ; x<pEnc->mbParam.mb_width ; ++x)  
                 {  
                         MACROBLOCK * pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
                         MVBLOCKHINT * bhint = &hint->mvhint.block[x + y * pEnc->mbParam.mb_width];  
                         VECTOR tmp;  
1255    
1256                          if (hint->rawhints)                  DPRINTF(XVID_DEBUG_DEBUG,"*** XXXXXX bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1257                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1258                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1259    
1260            /* for unpacked bframes, output the stats for the last encoded frame */
1261            if (!(pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->mbParam.max_bframes > 0)
1262                          {                          {
1263                                  bhint->mode = pMB->mode;                  if (pEnc->current->stamp > 0) {
1264                            call_plugins(pEnc, pEnc->reference, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1265                          }                          }
1266                          else                          else
1267                          {                          stats->type = XVID_TYPE_NOTHING;
                                 BitstreamPutBits(&bs, pMB->mode, MODEBITS);  
1268                          }                          }
1269    
1270                          if (pMB->mode == MODE_INTER || pMB->mode == MODE_INTER_Q)          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1271                          {           * closed-gop
1272                                  tmp.x  = pMB->mvs[0].x;           * if the frame prior to an iframe is scheduled as a bframe, we must change it to a pframe
1273                                  tmp.y  = pMB->mvs[0].y;           * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
                                 tmp.x += (tmp.x < 0) ? high*2 : 0;  
                                 tmp.y += (tmp.y < 0) ? high*2 : 0;  
1274    
1275                                  if (hint->rawhints)          if (type == I_VOP && (pEnc->mbParam.global_flags & XVID_GLOBAL_CLOSED_GOP) && pEnc->bframenum_tail > 0) {
1276                                  {  
1277                                          bhint->mvs[0].x = tmp.x;                  /* place this frame back on the encoding-queue (head) */
1278                                          bhint->mvs[0].y = tmp.y;                  /* we will deal with it next time */
1279                    dec_frame_num(pEnc);
1280                    pEnc->iFrameNum--;
1281    
1282                    pEnc->queue_head = (pEnc->queue_head + (pEnc->mbParam.max_bframes+1) - 1) % (pEnc->mbParam.max_bframes+1);
1283                    pEnc->queue_size++;
1284                    image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_head].image);
1285    
1286                    /* grab the last frame from the bframe-queue */
1287    
1288                    pEnc->bframenum_tail--;
1289                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1290    
1291                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1292                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 100, "CLOSED GOP BVOP->PVOP");
1293                                  }                                  }
1294                                  else  
1295                                  {                  /* convert B-VOP quant to P-VOP */
1296                                          BitstreamPutBits(&bs, tmp.x, length);                  pEnc->current->quant  = 100*pEnc->current->quant - pEnc->mbParam.bquant_offset;
1297                                          BitstreamPutBits(&bs, tmp.y, length);                  pEnc->current->quant += pEnc->mbParam.bquant_ratio - 1; /* to avoid rouding issues */
1298                    pEnc->current->quant /= pEnc->mbParam.bquant_ratio;
1299                    type = P_VOP;
1300                                  }                                  }
1301    
1302    
1303            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1304             * encode this frame as an i-vop
1305             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1306    
1307            if (type == I_VOP) {
1308    
1309                    DPRINTF(XVID_DEBUG_DEBUG,"*** IFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1310                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1311                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1312    
1313                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1314                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "IVOP");
1315                          }                          }
                         else if (pMB->mode == MODE_INTER4V)  
                         {  
                                 int vec;  
1316    
1317                                  for (vec=0 ; vec<4 ; ++vec)                  pEnc->iFrameNum = 1;
                                 {  
                                         tmp.x  = pMB->mvs[vec].x;  
                                         tmp.y  = pMB->mvs[vec].y;  
                                         tmp.x += (tmp.x < 0) ? high*2 : 0;  
                                         tmp.y += (tmp.y < 0) ? high*2 : 0;  
1318    
1319                                          if (hint->rawhints)                  /* ---- update vol flags at IVOP ----------- */
1320                                          {                  pEnc->mbParam.vol_flags = pEnc->current->vol_flags;
1321                                                  bhint->mvs[vec].x = tmp.x;  
1322                                                  bhint->mvs[vec].y = tmp.y;                  /* Aspect ratio */
1323                    switch(frame->par) {
1324                    case XVID_PAR_11_VGA:
1325                    case XVID_PAR_43_PAL:
1326                    case XVID_PAR_43_NTSC:
1327                    case XVID_PAR_169_PAL:
1328                    case XVID_PAR_169_NTSC:
1329                    case XVID_PAR_EXT:
1330                            pEnc->mbParam.par = frame->par;
1331                            break;
1332                    default:
1333                            pEnc->mbParam.par = XVID_PAR_11_VGA;
1334                            break;
1335                                          }                                          }
1336                                          else  
1337                                          {                  /* For extended PAR only, we try to sanityse/simplify par values */
1338                                                  BitstreamPutBits(&bs, tmp.x, length);                  if (pEnc->mbParam.par == XVID_PAR_EXT) {
1339                                                  BitstreamPutBits(&bs, tmp.y, length);                          pEnc->mbParam.par_width  = frame->par_width;
1340                            pEnc->mbParam.par_height = frame->par_height;
1341                            simplify_par(&pEnc->mbParam.par_width, &pEnc->mbParam.par_height);
1342                                          }                                          }
1343    
1344                    if ((pEnc->mbParam.vol_flags & XVID_VOL_MPEGQUANT)) {
1345                            if (frame->quant_intra_matrix != NULL)
1346                                    set_intra_matrix(pEnc->mbParam.mpeg_quant_matrices, frame->quant_intra_matrix);
1347                            if (frame->quant_inter_matrix != NULL)
1348                                    set_inter_matrix(pEnc->mbParam.mpeg_quant_matrices, frame->quant_inter_matrix);
1349                    }
1350    
1351                    /* prevent vol/vop misuse */
1352    
1353                    if (!(pEnc->current->vol_flags & XVID_VOL_INTERLACING))
1354                            pEnc->current->vop_flags &= ~(XVID_VOP_TOPFIELDFIRST|XVID_VOP_ALTERNATESCAN);
1355    
1356                    /* ^^^------------------------ */
1357    
1358                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1359                            image_copy(&pEnc->sOriginal, &pEnc->current->image,
1360                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1361                    }
1362    
1363                    FrameCodeI(pEnc, &bs);
1364                    xFrame->out_flags |= XVID_KEYFRAME;
1365    
1366            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1367             * encode this frame as an p-vop
1368             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1369    
1370            } else { /* (type == P_VOP || type == S_VOP) */
1371    
1372                    DPRINTF(XVID_DEBUG_DEBUG,"*** PFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1373                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1374                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1375    
1376                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1377                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "PVOP");
1378                    }
1379    
1380                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1381                            image_copy(&pEnc->sOriginal, &pEnc->current->image,
1382                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1383                    }
1384    
1385                    if ( FrameCodeP(pEnc, &bs) == 0 ) {
1386                            /* N-VOP, we mustn't code b-frames yet */
1387                            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) ||
1388                                     pEnc->mbParam.max_bframes == 0)
1389                                    call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1390                            goto done;
1391                                  }                                  }
1392                          }                          }
1393    
1394    
1395            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1396             * on next enc_encode call we must flush bframes
1397             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1398    
1399    /*done_flush:*/
1400    
1401            pEnc->flush_bframes = 1;
1402    
1403            /* packed & queued_bframes: dont bother outputting stats here, we do so after the flush */
1404            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail > 0) {
1405                    goto repeat;
1406                  }                  }
1407    
1408            /* packed or no-bframes or no-bframes-queued: output stats */
1409            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) || pEnc->mbParam.max_bframes == 0 ) {
1410                    call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1411          }          }
1412    
1413          if (!hint->rawhints)          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1414             * done; return number of bytes consumed
1415             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1416    
1417    done:
1418    
1419            stop_global_timer();
1420            write_timer();
1421    
1422            emms();
1423            return BitstreamLength(&bs);
1424    }
1425    
1426    
1427    static void SetMacroblockQuants(MBParam * const pParam, FRAMEINFO * frame)
1428          {          {
1429                  BitstreamPad(&bs);          unsigned int i;
1430                  hint->hintlength = BitstreamLength(&bs);          MACROBLOCK * pMB = frame->mbs;
1431            int quant = frame->mbs[0].quant; /* set by XVID_PLG_FRAME */
1432            if (quant > 31)
1433                    frame->quant = quant = 31;
1434            else if (quant < 1)
1435                    frame->quant = quant = 1;
1436    
1437            for (i = 0; i < pParam->mb_height * pParam->mb_width; i++) {
1438                    quant += pMB->dquant;
1439                    if (quant > 31)
1440                            quant = 31;
1441                    else if (quant < 1)
1442                            quant = 1;
1443                    pMB->quant = quant;
1444                    pMB++;
1445          }          }
1446  }  }
1447    
1448    
1449  static int FrameCodeI(Encoder * pEnc, Bitstream * bs, uint32_t *pBits)  static __inline void
1450    CodeIntraMB(Encoder * pEnc,
1451                            MACROBLOCK * pMB)
1452  {  {
1453    
1454            pMB->mode = MODE_INTRA;
1455    
1456            /* zero mv statistics */
1457            pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = 0;
1458            pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = 0;
1459            pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = 0;
1460            pMB->sad16 = 0;
1461    
1462            if (pMB->dquant != 0) {
1463                    pMB->mode = MODE_INTRA_Q;
1464            }
1465    }
1466    
1467    
1468    
1469    static int
1470    FrameCodeI(Encoder * pEnc,
1471                       Bitstream * bs)
1472    {
1473            int bits = BitstreamPos(bs);
1474            int mb_width = pEnc->mbParam.mb_width;
1475            int mb_height = pEnc->mbParam.mb_height;
1476    
1477          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1478          DECLARE_ALIGNED_MATRIX(qcoeff,    6, 64, int16_t, CACHE_LINE);          DECLARE_ALIGNED_MATRIX(qcoeff,    6, 64, int16_t, CACHE_LINE);
1479    
1480          uint16_t x, y;          uint16_t x, y;
1481    
         pEnc->iFrameNum = 0;  
1482          pEnc->mbParam.m_rounding_type = 1;          pEnc->mbParam.m_rounding_type = 1;
1483          pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;          pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;
1484          pEnc->current->coding_type = I_VOP;          pEnc->current->coding_type = I_VOP;
1485    
1486            call_plugins(pEnc, pEnc->current, NULL, XVID_PLG_FRAME, NULL, NULL, NULL);
1487    
1488            SetMacroblockQuants(&pEnc->mbParam, pEnc->current);
1489    
1490          BitstreamWriteVolHeader(bs, &pEnc->mbParam, pEnc->current);          BitstreamWriteVolHeader(bs, &pEnc->mbParam, pEnc->current);
         BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current);  
1491    
1492          *pBits = BitstreamPos(bs);          set_timecodes(pEnc->current,pEnc->reference,pEnc->mbParam.fbase);
1493    
1494          pEnc->sStat.iTextBits = 0;          BitstreamPad(bs);
         pEnc->sStat.kblks = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height;  
         pEnc->sStat.mblks = pEnc->sStat.ublks = 0;  
1495    
1496          for (y = 0; y < pEnc->mbParam.mb_height; y++)          BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current, 1, pEnc->current->mbs[0].quant);
1497                  for (x = 0; x < pEnc->mbParam.mb_width; x++)  
1498                  {          pEnc->current->sStat.iTextBits = 0;
1499                          MACROBLOCK *pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];          pEnc->current->sStat.iMVBits = 0;
1500            pEnc->current->sStat.kblks = mb_width * mb_height;
1501            pEnc->current->sStat.mblks = pEnc->current->sStat.ublks = 0;
1502    
1503            for (y = 0; y < mb_height; y++)
1504                    for (x = 0; x < mb_width; x++) {
1505                            MACROBLOCK *pMB =
1506                                    &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];
1507    
1508                          CodeIntraMB(pEnc, pMB);                          CodeIntraMB(pEnc, pMB);
1509    
1510                          MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y, dct_codes, qcoeff);                          MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y,
1511                                                              dct_codes, qcoeff);
1512    
1513                          start_timer();                          start_timer();
1514                          MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);                          MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);
1515                          stop_prediction_timer();                          stop_prediction_timer();
1516    
1517                          start_timer();                          start_timer();
1518                          MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->sStat);                          MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1519                          stop_coding_timer();                          stop_coding_timer();
1520                  }                  }
1521    
1522          emms();          emms();
1523    
1524          *pBits = BitstreamPos(bs) - *pBits;          BitstreamPadAlways(bs); /* next_start_code() at the end of VideoObjectPlane() */
1525          pEnc->sStat.fMvPrevSigma = -1;  
1526          pEnc->sStat.iMvSum = 0;          pEnc->current->length = (BitstreamPos(bs) - bits) / 8;
1527          pEnc->sStat.iMvCount = 0;  
1528            pEnc->fMvPrevSigma = -1;
1529          pEnc->mbParam.m_fcode = 2;          pEnc->mbParam.m_fcode = 2;
1530    
1531          if (pEnc->current->global_flags & XVID_HINTEDME_GET)          pEnc->current->is_edged = 0; /* not edged */
1532          {          pEnc->current->is_interpolated = -1; /* not interpolated (fake rounding -1) */
                 HintedMEGet(pEnc, 1);  
         }  
1533    
1534          return 1;                                        // intra          return 1;                                       /* intra */
1535  }  }
1536    
1537    static __inline void
1538    updateFcode(Statistics * sStat, Encoder * pEnc)
1539    {
1540            float fSigma;
1541            int iSearchRange;
1542    
1543            if (sStat->iMvCount == 0)
1544                    sStat->iMvCount = 1;
1545    
1546            fSigma = (float) sqrt((float) sStat->iMvSum / sStat->iMvCount);
1547    
1548            iSearchRange = 16 << pEnc->mbParam.m_fcode;
1549    
1550  #define INTRA_THRESHOLD 0.5          if ((3.0 * fSigma > iSearchRange) && (pEnc->mbParam.m_fcode <= 5) )
1551                    pEnc->mbParam.m_fcode++;
1552    
1553            else if ((5.0 * fSigma < iSearchRange)
1554                               && (4.0 * pEnc->fMvPrevSigma < iSearchRange)
1555                               && (pEnc->mbParam.m_fcode >= 2) )
1556                    pEnc->mbParam.m_fcode--;
1557    
1558            pEnc->fMvPrevSigma = fSigma;
1559    }
1560    
1561    #define BFRAME_SKIP_THRESHHOLD 30
1562    
1563  static int FrameCodeP(Encoder * pEnc, Bitstream * bs, uint32_t *pBits, bool force_inter, bool vol_header)  /* FrameCodeP also handles S(GMC)-VOPs */
1564    static int
1565    FrameCodeP(Encoder * pEnc,
1566                       Bitstream * bs)
1567  {  {
1568          float fSigma;          int bits = BitstreamPos(bs);
1569    
1570          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1571          DECLARE_ALIGNED_MATRIX(qcoeff,    6, 64, int16_t, CACHE_LINE);          DECLARE_ALIGNED_MATRIX(qcoeff,    6, 64, int16_t, CACHE_LINE);
1572    
1573          int iLimit;          int x, y, k;
1574          uint32_t x, y;          FRAMEINFO *const current = pEnc->current;
1575          int iSearchRange;          FRAMEINFO *const reference = pEnc->reference;
1576          int bIntra;          MBParam * const pParam = &pEnc->mbParam;
1577            int mb_width = pParam->mb_width;
1578            int mb_height = pParam->mb_height;
1579            int coded = 1;
1580    
1581          /* IMAGE *pCurrent = &pEnc->current->image; */          IMAGE *pRef = &reference->image;
         IMAGE *pRef = &pEnc->reference->image;  
1582    
1583            if (!reference->is_edged) {
1584          start_timer();          start_timer();
1585          image_setedges(pRef,                  image_setedges(pRef, pParam->edged_width, pParam->edged_height,
1586                         pEnc->mbParam.edged_width,                                             pParam->width, pParam->height, 0);
                        pEnc->mbParam.edged_height,  
                        pEnc->mbParam.width,  
                        pEnc->mbParam.height,  
                        pEnc->current->global_flags & XVID_INTERLACING);  
1587          stop_edges_timer();          stop_edges_timer();
1588                    reference->is_edged = 1;
1589            }
1590    
1591          pEnc->mbParam.m_rounding_type = 1 - pEnc->mbParam.m_rounding_type;          pParam->m_rounding_type = 1 - pParam->m_rounding_type;
1592          pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;          current->rounding_type = pParam->m_rounding_type;
1593          pEnc->current->fcode = pEnc->mbParam.m_fcode;          current->fcode = pParam->m_fcode;
   
         if (!force_inter)  
                 iLimit = (int)(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * INTRA_THRESHOLD);  
         else  
                 iLimit = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height + 1;  
1594    
1595          if ((pEnc->current->global_flags & XVID_HALFPEL)) {          if ((current->vop_flags & XVID_VOP_HALFPEL)) {
1596                    if (reference->is_interpolated != current->rounding_type) {
1597                  start_timer();                  start_timer();
1598                  image_interpolate(pRef, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,                          image_interpolate(pRef->y, pEnc->vInterH.y, pEnc->vInterV.y,
1599                                    pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,                                                            pEnc->vInterHV.y, pParam->edged_width,
1600                                    pEnc->current->rounding_type);                                                            pParam->edged_height,
1601                                                              (pParam->vol_flags & XVID_VOL_QUARTERPEL),
1602                                                              current->rounding_type);
1603                  stop_inter_timer();                  stop_inter_timer();
1604                            reference->is_interpolated = current->rounding_type;
1605                    }
1606          }          }
1607    
1608            current->sStat.iTextBits = current->sStat.iMvSum = current->sStat.iMvCount =
1609                    current->sStat.kblks = current->sStat.mblks = current->sStat.ublks =
1610                    current->sStat.iMVBits = 0;
1611    
1612            current->coding_type = P_VOP;
1613    
1614            call_plugins(pEnc, pEnc->current, NULL, XVID_PLG_FRAME, NULL, NULL, NULL);
1615    
1616            SetMacroblockQuants(&pEnc->mbParam, current);
1617    
1618          start_timer();          start_timer();
1619          if (pEnc->current->global_flags & XVID_HINTEDME_SET)          if (current->vol_flags & XVID_VOL_GMC ) /* GMC only for S(GMC)-VOPs */
1620          {          {       int gmcval;
1621                  HintedMESet(pEnc, &bIntra);                  current->warp = GlobalMotionEst( current->mbs, pParam, current, reference,
1622          }                                                                   &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV);
1623          else  
1624          {                  if (current->motion_flags & XVID_ME_GME_REFINE) {
1625                  bIntra = MotionEstimation(                          gmcval = GlobalMotionEstRefine(&current->warp,
1626                          &pEnc->mbParam,                                                                                     current->mbs, pParam,
1627                          pEnc->current,                                                                                     current, reference,
1628                          pEnc->reference,                                                                                     &current->image,
1629                                                                                       &reference->image,
1630                          &pEnc->vInterH,                          &pEnc->vInterH,
1631                          &pEnc->vInterV,                          &pEnc->vInterV,
1632                          &pEnc->vInterHV,                                                                                     &pEnc->vInterHV);
1633                          iLimit);                  } else {
1634                            gmcval = globalSAD(&current->warp, pParam, current->mbs,
1635                                                               current,
1636                                                               &reference->image,
1637                                                               &current->image,
1638                                                               pEnc->vGMC.y);
1639          }          }
         stop_motion_timer();  
1640    
1641          if (bIntra == 1)                  gmcval += /*current->quant*/ 2 * (int)(pParam->mb_width*pParam->mb_height);
1642    
1643                    /* 1st '3': 3 warpoints, 2nd '3': 16th pel res (2<<3) */
1644                    generate_GMCparameters( 3, 3, &current->warp,
1645                                    pParam->width, pParam->height,
1646                                    &current->new_gmc_data);
1647    
1648                    if ( (gmcval<0) && ( (current->warp.duv[1].x != 0) || (current->warp.duv[1].y != 0) ||
1649                             (current->warp.duv[2].x != 0) || (current->warp.duv[2].y != 0) ) )
1650          {          {
1651                  return FrameCodeI(pEnc, bs, pBits);                          current->coding_type = S_VOP;
1652    
1653                            generate_GMCimage(&current->new_gmc_data, &reference->image,
1654                                    pParam->mb_width, pParam->mb_height,
1655                                    pParam->edged_width, pParam->edged_width/2,
1656                                    pParam->m_fcode, ((pParam->vol_flags & XVID_VOL_QUARTERPEL)?1:0), 0,
1657                                    current->rounding_type, current->mbs, &pEnc->vGMC);
1658    
1659                    } else {
1660    
1661                            generate_GMCimage(&current->new_gmc_data, &reference->image,
1662                                    pParam->mb_width, pParam->mb_height,
1663                                    pParam->edged_width, pParam->edged_width/2,
1664                                    pParam->m_fcode, ((pParam->vol_flags & XVID_VOL_QUARTERPEL)?1:0), 0,
1665                                    current->rounding_type, current->mbs, NULL);    /* no warping, just AMV */
1666                    }
1667          }          }
1668    
1669          pEnc->current->coding_type = P_VOP;          MotionEstimation(&pEnc->mbParam, current, reference,
1670                                             &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,
1671                                             &pEnc->vGMC, 256*4096);
1672    
         if(vol_header)  
                 BitstreamWriteVolHeader(bs, &pEnc->mbParam, pEnc->current);  
1673    
1674          BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current);          stop_motion_timer();
1675    
1676          *pBits = BitstreamPos(bs);          set_timecodes(current,reference,pParam->fbase);
1677    
1678          pEnc->sStat.iTextBits = 0;          BitstreamWriteVopHeader(bs, &pEnc->mbParam, current, 1, current->mbs[0].quant);
         pEnc->sStat.iMvSum = 0;  
         pEnc->sStat.iMvCount = 0;  
         pEnc->sStat.kblks = pEnc->sStat.mblks = pEnc->sStat.ublks = 0;  
1679    
1680          for(y = 0; y < pEnc->mbParam.mb_height; y++)          for (y = 0; y < mb_height; y++) {
1681          {                  for (x = 0; x < mb_width; x++) {
1682                  for(x = 0; x < pEnc->mbParam.mb_width; x++)                          MACROBLOCK *pMB = &current->mbs[x + y * pParam->mb_width];
1683                  {                          int skip_possible;
                         MACROBLOCK * pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
1684    
1685                          bIntra = (pMB->mode == MODE_INTRA) || (pMB->mode == MODE_INTRA_Q);                          if (pMB->mode == MODE_INTRA || pMB->mode == MODE_INTRA_Q) {
1686                                    CodeIntraMB(pEnc, pMB);
1687                                    MBTransQuantIntra(&pEnc->mbParam, current, pMB, x, y,
1688                                                                      dct_codes, qcoeff);
1689    
                         if (!bIntra)  
                         {  
1690                                  start_timer();                                  start_timer();
1691                                  MBMotionCompensation(pMB,                                  MBPrediction(current, x, y, pParam->mb_width, qcoeff);
1692                                                       x, y,                                  stop_prediction_timer();
                                                      &pEnc->reference->image,  
                                                      &pEnc->vInterH,  
                                                      &pEnc->vInterV,  
                                                      &pEnc->vInterHV,  
                                                      &pEnc->current->image,  
                                                      dct_codes,  
                                                      pEnc->mbParam.width,  
                                                      pEnc->mbParam.height,  
                                                      pEnc->mbParam.edged_width,  
                                                      pEnc->current->rounding_type);  
                                 stop_comp_timer();  
1693    
1694                                  if ((pEnc->current->global_flags & XVID_LUMIMASKING)) {                                  current->sStat.kblks++;
1695                                          if(pMB->dquant != NO_CHANGE) {  
1696                                                  pMB->mode = MODE_INTER_Q;                                  MBCoding(current, pMB, qcoeff, bs, &current->sStat);
1697                                                  pEnc->current->quant += DQtab[pMB->dquant];                                  stop_coding_timer();
1698                                                  if (pEnc->current->quant > 31) pEnc->current->quant = 31;                                  continue;
                                                 else if(pEnc->current->quant < 1) pEnc->current->quant = 1;  
                                         }  
1699                                  }                                  }
1700                                  pMB->quant = pEnc->current->quant;  
1701                            start_timer();
1702                            MBMotionCompensation(pMB, x, y, &reference->image,
1703                                                                     &pEnc->vInterH, &pEnc->vInterV,
1704                                                                     &pEnc->vInterHV, &pEnc->vGMC,
1705                                                                     &current->image,
1706                                                                     dct_codes, pParam->width,
1707                                                                     pParam->height,
1708                                                                     pParam->edged_width,
1709                                                                     (current->vol_flags & XVID_VOL_QUARTERPEL),
1710                                                                     current->rounding_type);
1711    
1712                            stop_comp_timer();
1713    
1714                                  pMB->field_pred = 0;                                  pMB->field_pred = 0;
1715    
1716                                  pMB->cbp = MBTransQuantInter(&pEnc->mbParam, pEnc->current, pMB, x, y, dct_codes, qcoeff);                          if (pMB->cbp != 0) {
1717                                    pMB->cbp = MBTransQuantInter(&pEnc->mbParam, current, pMB, x, y,
1718                                                                              dct_codes, qcoeff);
1719                          }                          }
1720                          else  
1721                          {                          if (pMB->dquant != 0)
1722                                  CodeIntraMB(pEnc, pMB);                                  MBSetDquant(pMB, x, y, &pEnc->mbParam);
1723                                  MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y, dct_codes, qcoeff);  
1724    
1725                            if (pMB->cbp || pMB->mvs[0].x || pMB->mvs[0].y ||
1726                                       pMB->mvs[1].x || pMB->mvs[1].y || pMB->mvs[2].x ||
1727                                       pMB->mvs[2].y || pMB->mvs[3].x || pMB->mvs[3].y) {
1728                                    current->sStat.mblks++;
1729                            }  else {
1730                                    current->sStat.ublks++;
1731                          }                          }
1732    
1733                          start_timer();                          start_timer();
                         MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);  
                         stop_prediction_timer();  
1734    
1735                          if (pMB->mode == MODE_INTRA || pMB->mode == MODE_INTRA_Q)                          /* Finished processing the MB, now check if to CODE or SKIP */
1736                          {  
1737                                  pEnc->sStat.kblks++;                          skip_possible = (pMB->cbp == 0) && (pMB->mode == MODE_INTER);
1738    
1739                            if (current->coding_type == S_VOP)
1740                                    skip_possible &= (pMB->mcsel == 1);
1741                            else { /* PVOP */
1742                                    const VECTOR * const mv = (pParam->vol_flags & XVID_VOL_QUARTERPEL) ?
1743                                                                                    pMB->qmvs : pMB->mvs;
1744                                    skip_possible &= ((mv->x|mv->y) == 0);
1745                            }
1746    
1747                            if ((pMB->mode == MODE_NOT_CODED) || (skip_possible)) {
1748                                    /* This is a candidate for SKIPping, but for P-VOPs check intermediate B-frames first */
1749                                    int bSkip = 1;
1750    
1751                                    if (current->coding_type == P_VOP) {    /* special rule for P-VOP's SKIP */
1752    
1753                                            for (k = pEnc->bframenum_head; k < pEnc->bframenum_tail; k++) {
1754                                                    int iSAD;
1755                                                    iSAD = sad16(reference->image.y + 16*y*pParam->edged_width + 16*x,
1756                                                                                    pEnc->bframes[k]->image.y + 16*y*pParam->edged_width + 16*x,
1757                                                                                    pParam->edged_width, BFRAME_SKIP_THRESHHOLD * pMB->quant);
1758                                                    if (iSAD >= BFRAME_SKIP_THRESHHOLD * pMB->quant) {
1759                                                            bSkip = 0; /* could not SKIP */
1760                                                            if (pParam->vol_flags & XVID_VOL_QUARTERPEL) {
1761                                                                    VECTOR predMV = get_qpmv2(current->mbs, pParam->mb_width, 0, x, y, 0);
1762                                                                    pMB->pmvs[0].x = - predMV.x;
1763                                                                    pMB->pmvs[0].y = - predMV.y;
1764                                                            } else {
1765                                                                    VECTOR predMV = get_pmv2(current->mbs, pParam->mb_width, 0, x, y, 0);
1766                                                                    pMB->pmvs[0].x = - predMV.x;
1767                                                                    pMB->pmvs[0].y = - predMV.y;
1768                                                            }
1769                                                            pMB->mode = MODE_INTER;
1770                                                            pMB->cbp = 0;
1771                                                            break;
1772                          }                          }
                         else if (pMB->cbp ||  
                                  pMB->mvs[0].x || pMB->mvs[0].y ||  
                                  pMB->mvs[1].x || pMB->mvs[1].y ||  
                                  pMB->mvs[2].x || pMB->mvs[2].y ||  
                                  pMB->mvs[3].x || pMB->mvs[3].y)  
                         {  
                                 pEnc->sStat.mblks++;  
1773                          }                          }
                         else  
                         {  
                                 pEnc->sStat.ublks++;  
1774                          }                          }
1775    
1776                          start_timer();                                  if (bSkip) {
1777                          MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->sStat);                                          /* do SKIP */
1778                                            pMB->mode = MODE_NOT_CODED;
1779                                            MBSkip(bs);
1780                                            stop_coding_timer();
1781                                            continue;       /* next MB */
1782                                    }
1783                            }
1784    
1785                            /* ordinary case: normal coded INTER/INTER4V block */
1786                            MBCoding(current, pMB, qcoeff, bs, &pEnc->current->sStat);
1787                          stop_coding_timer();                          stop_coding_timer();
1788                  }                  }
1789          }          }
1790    
1791          emms();          emms();
1792            updateFcode(&current->sStat, pEnc);
1793    
1794          if (pEnc->current->global_flags & XVID_HINTEDME_GET)          /* frame drop code */
1795    #if 0
1796            DPRINTF(XVID_DEBUG_DEBUG, "kmu %i %i %i\n", current->sStat.kblks, current->sStat.mblks, current->sStat.ublks);
1797    #endif
1798            if (current->sStat.kblks + current->sStat.mblks <=
1799                    (pParam->frame_drop_ratio * mb_width * mb_height) / 100 &&
1800                    ( (pEnc->bframenum_head >= pEnc->bframenum_tail) || !(pEnc->mbParam.global_flags & XVID_GLOBAL_CLOSED_GOP)) )
1801          {          {
1802                  HintedMEGet(pEnc, 0);                  current->sStat.kblks = current->sStat.mblks = current->sStat.iTextBits = 0;
1803          }                  current->sStat.ublks = mb_width * mb_height;
1804    
1805          if (pEnc->sStat.iMvCount == 0)                  BitstreamReset(bs);
                 pEnc->sStat.iMvCount = 1;  
1806    
1807          fSigma = (float)sqrt((float) pEnc->sStat.iMvSum / pEnc->sStat.iMvCount);                  set_timecodes(current,reference,pParam->fbase);
1808                    BitstreamWriteVopHeader(bs, &pEnc->mbParam, current, 0, current->mbs[0].quant);
1809    
1810          iSearchRange = 1 << (3 + pEnc->mbParam.m_fcode);                  /* copy reference frame details into the current frame */
1811                    current->quant = reference->quant;
1812                    current->motion_flags = reference->motion_flags;
1813                    current->rounding_type = reference->rounding_type;
1814                    current->fcode = reference->fcode;
1815                    current->bcode = reference->bcode;
1816                    current->stamp = reference->stamp;
1817                    image_copy(&current->image, &reference->image, pParam->edged_width, pParam->height);
1818                    memcpy(current->mbs, reference->mbs, sizeof(MACROBLOCK) * mb_width * mb_height);
1819                    coded = 0;
1820    
1821          if ((fSigma > iSearchRange / 3)          } else {
1822              && (pEnc->mbParam.m_fcode <= 3))    // maximum search range 128  
1823          {                  pEnc->current->is_edged = 0; /* not edged */
1824                  pEnc->mbParam.m_fcode++;                  pEnc->current->is_interpolated = -1; /* not interpolated (fake rounding -1) */
1825                  iSearchRange *= 2;  
1826                    /* what was this frame's interpolated reference will become
1827                            forward (past) reference in b-frame coding */
1828    
1829                    image_swap(&pEnc->vInterH, &pEnc->f_refh);
1830                    image_swap(&pEnc->vInterV, &pEnc->f_refv);
1831                    image_swap(&pEnc->vInterHV, &pEnc->f_refhv);
1832          }          }
1833          else if ((fSigma < iSearchRange / 6)  
1834                   && (pEnc->sStat.fMvPrevSigma >= 0)          /* XXX: debug
                  && (pEnc->sStat.fMvPrevSigma < iSearchRange / 6)  
                  && (pEnc->mbParam.m_fcode >= 2))       // minimum search range 16  
1835          {          {
1836                  pEnc->mbParam.m_fcode--;                  char s[100];
1837                  iSearchRange /= 2;                  sprintf(s, "\\%05i_cur.pgm", pEnc->m_framenum);
1838                    image_dump_yuvpgm(&current->image,
1839                            pParam->edged_width,
1840                            pParam->width, pParam->height, s);
1841    
1842                    sprintf(s, "\\%05i_ref.pgm", pEnc->m_framenum);
1843                    image_dump_yuvpgm(&reference->image,
1844                            pParam->edged_width,
1845                            pParam->width, pParam->height, s);
1846          }          }
1847            */
1848    
1849          pEnc->sStat.fMvPrevSigma = fSigma;          BitstreamPadAlways(bs); /* next_start_code() at the end of VideoObjectPlane() */
1850    
1851          *pBits = BitstreamPos(bs) - *pBits;          current->length = (BitstreamPos(bs) - bits) / 8;
1852    
1853          return 0;                                        // inter          return coded;
1854  }  }
1855    
1856    
1857  #ifdef BFRAMES  static void
1858  static void FrameCodeB(Encoder * pEnc, FRAMEINFO * frame, Bitstream * bs, uint32_t *pBits)  FrameCodeB(Encoder * pEnc,
1859                       FRAMEINFO * frame,
1860                       Bitstream * bs)
1861  {  {
1862      int16_t dct_codes[6*64];          int bits = BitstreamPos(bs);
1863      int16_t qcoeff[6*64];          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1864            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
1865      uint32_t x, y;      uint32_t x, y;
         VECTOR forward;  
         VECTOR backward;  
1866    
1867      IMAGE *f_ref = &pEnc->reference->image;      IMAGE *f_ref = &pEnc->reference->image;
1868          IMAGE *b_ref = &pEnc->current->image;          IMAGE *b_ref = &pEnc->current->image;
1869    
1870          // forward          #ifdef BFRAMES_DEC_DEBUG
1871          image_setedges(f_ref, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, pEnc->mbParam.width, pEnc->mbParam.height, frame->global_flags & XVID_INTERLACING);          FILE *fp;
1872            static char first=0;
1873    #define BFRAME_DEBUG    if (!first && fp){ \
1874                    fprintf(fp,"Y=%3d   X=%3d   MB=%2d   CBP=%02X\n",y,x,mb->mode,mb->cbp); \
1875            }
1876    
1877            if (!first){
1878                    fp=fopen("C:\\XVIDDBGE.TXT","w");
1879            }
1880    #endif
1881    
1882            /* forward  */
1883            if (!pEnc->reference->is_edged) {
1884                    image_setedges(f_ref, pEnc->mbParam.edged_width,
1885                                               pEnc->mbParam.edged_height, pEnc->mbParam.width,
1886                                               pEnc->mbParam.height, 0);
1887                    pEnc->current->is_edged = 1;
1888            }
1889    
1890            if (pEnc->reference->is_interpolated != 0) {
1891          start_timer();          start_timer();
1892          image_interpolate(f_ref, &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,                  image_interpolate(f_ref->y, pEnc->f_refh.y, pEnc->f_refv.y, pEnc->f_refhv.y,
1893                  pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, 0);                                                    pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
1894                                                      (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL), 0);
1895          stop_inter_timer();          stop_inter_timer();
1896                    pEnc->reference->is_interpolated = 0;
1897            }
1898    
1899          // backward          /* backward */
1900          image_setedges(b_ref, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, pEnc->mbParam.width, pEnc->mbParam.height, frame->global_flags & XVID_INTERLACING);          if (!pEnc->current->is_edged) {
1901                    image_setedges(b_ref, pEnc->mbParam.edged_width,
1902                                               pEnc->mbParam.edged_height, pEnc->mbParam.width,
1903                                               pEnc->mbParam.height, 0);
1904                    pEnc->current->is_edged = 1;
1905            }
1906    
1907            if (pEnc->current->is_interpolated != 0) {
1908      start_timer();      start_timer();
1909          image_interpolate(b_ref, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,                  image_interpolate(b_ref->y, pEnc->vInterH.y, pEnc->vInterV.y, pEnc->vInterHV.y,
1910                  pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, 0);                                                  pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
1911                                                    (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL), 0);
1912          stop_inter_timer();          stop_inter_timer();
1913                    pEnc->current->is_interpolated = 0;
1914            }
1915    
1916            frame->coding_type = B_VOP;
1917            call_plugins(pEnc, frame, NULL, XVID_PLG_FRAME, NULL, NULL, NULL);
1918    
1919          start_timer();          start_timer();
1920          MotionEstimationBVOP(&pEnc->mbParam, frame,          MotionEstimationBVOP(&pEnc->mbParam, frame,
1921                  pEnc->reference->mbs, f_ref, &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,                                                   ((int32_t)(pEnc->current->stamp - frame->stamp)),                              /* time_bp */
1922                  pEnc->current->mbs, b_ref, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV);                                                   ((int32_t)(pEnc->current->stamp - pEnc->reference->stamp)),    /* time_pp */
1923                                                     pEnc->reference->mbs, f_ref,
1924                                                     &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,
1925                                                     pEnc->current, b_ref, &pEnc->vInterH,
1926                                                     &pEnc->vInterV, &pEnc->vInterHV);
1927          stop_motion_timer();          stop_motion_timer();
1928    
1929          /*if (test_quant_type(&pEnc->mbParam, pEnc->current))          set_timecodes(frame, pEnc->reference,pEnc->mbParam.fbase);
1930          {          BitstreamWriteVopHeader(bs, &pEnc->mbParam, frame, 1, frame->quant);
                 BitstreamWriteVolHeader(bs, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.quant_type);  
         }*/  
   
     frame->coding_type = B_VOP;  
     BitstreamWriteVopHeader(bs, &pEnc->mbParam, frame);  
   
     *pBits = BitstreamPos(bs);  
   
     pEnc->sStat.iTextBits = 0;  
     pEnc->sStat.iMvSum = 0;  
     pEnc->sStat.iMvCount = 0;  
         pEnc->sStat.kblks = pEnc->sStat.mblks = pEnc->sStat.ublks = 0;  
1931    
1932            frame->sStat.iTextBits = 0;
1933      for (y = 0; y < pEnc->mbParam.mb_height; y++)          frame->sStat.iMVBits = 0;
1934          {          frame->sStat.iMvSum = 0;
1935                  // reset prediction          frame->sStat.iMvCount = 0;
1936            frame->sStat.kblks = frame->sStat.mblks = frame->sStat.ublks = 0;
1937                  forward.x = 0;          frame->sStat.mblks = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height;
1938                  forward.y = 0;          frame->sStat.kblks = frame->sStat.ublks = 0;
1939                  backward.x = 0;  
1940                  backward.y = 0;          for (y = 0; y < pEnc->mbParam.mb_height; y++) {
1941                    for (x = 0; x < pEnc->mbParam.mb_width; x++) {
1942                  for (x = 0; x < pEnc->mbParam.mb_width; x++)                          MACROBLOCK * const mb = &frame->mbs[x + y * pEnc->mbParam.mb_width];
1943                  {  
1944                          MACROBLOCK * f_mb = &pEnc->reference->mbs[x + y * pEnc->mbParam.mb_width];                          /* decoder ignores mb when refence block is INTER(0,0), CBP=0 */
1945                          MACROBLOCK * b_mb = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];                          if (mb->mode == MODE_NOT_CODED) {
1946                          MACROBLOCK * mb = &frame->mbs[x + y * pEnc->mbParam.mb_width];                                  if (pEnc->mbParam.plugin_flags & XVID_REQORIGINAL) {
1947                                            MBMotionCompensation(mb, x, y, f_ref, NULL, f_ref, NULL, NULL, &frame->image,
1948                          // decoder ignores mb when refence block is INTER(0,0), CBP=0                                                                                          NULL, 0, 0, pEnc->mbParam.edged_width, 0, 0);
1949                          if (mb->mode == MODE_NOT_CODED)                                  }
                         {  
                                 mb->mvs[0].x = 0;  
                                 mb->mvs[0].y = 0;  
1950                                  continue;                                  continue;
1951                          }                          }
1952    
                         MBMotionCompensationBVOP(&pEnc->mbParam, mb, x, y, &frame->image,  
                                         f_ref, &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,  
                                         b_ref, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,  
                                         dct_codes);  
   
1953                          mb->quant = frame->quant;                          mb->quant = frame->quant;
                         mb->cbp = MBTransQuantInter(&pEnc->mbParam, frame, mb, x, y, dct_codes, qcoeff);  
                         //mb->cbp = MBTransQuantBVOP(&pEnc->mbParam, x, y, dct_codes, qcoeff, &frame->image, frame->quant);  
1954    
1955                            if (mb->cbp != 0 || pEnc->mbParam.plugin_flags & XVID_REQORIGINAL) {
1956                                    /* we have to motion-compensate, transfer etc,
1957                                            because there might be blocks to code */
1958    
1959                          if ((mb->mode == MODE_INTERPOLATE || mb->mode == MODE_DIRECT) &&                                  MBMotionCompensationBVOP(&pEnc->mbParam, mb, x, y, &frame->image,
1960                                  mb->cbp == 0 &&                                                                                   f_ref, &pEnc->f_refh, &pEnc->f_refv,
1961                                  mb->mvs[0].x == 0 &&                                                                                   &pEnc->f_refhv, b_ref, &pEnc->vInterH,
1962                                  mb->mvs[0].y == 0)                                                                                   &pEnc->vInterV, &pEnc->vInterHV,
1963                          {                                                                                   dct_codes);
                                 mb->mode = 5;  // skipped  
                         }  
1964    
1965                          if (mb->mode == MODE_INTERPOLATE || mb->mode == MODE_FORWARD)                                  mb->cbp = MBTransQuantInterBVOP(&pEnc->mbParam, frame, mb, x, y,  dct_codes, qcoeff);
                         {  
                                 mb->pmvs[0].x = mb->mvs[0].x - forward.x;  
                                 mb->pmvs[0].y = mb->mvs[0].y - forward.y;  
                                 forward.x = mb->mvs[0].x;  
                                 forward.y = mb->mvs[0].y;  
1966                          }                          }
1967    
1968                          if (mb->mode == MODE_INTERPOLATE || mb->mode == MODE_BACKWARD)                          if (mb->mode == MODE_DIRECT_NO4V)
1969                          {                                  mb->mode = MODE_DIRECT;
                                 mb->b_pmvs[0].x = mb->b_mvs[0].x - backward.x;  
                                 mb->b_pmvs[0].y = mb->b_mvs[0].y - backward.y;  
                                 backward.x = mb->b_mvs[0].x;  
                                 backward.y = mb->b_mvs[0].y;  
                         }  
1970    
1971  //                      printf("[%i %i] M=%i CBP=%i MVX=%i MVY=%i %i,%i  %i,%i\n", x, y, pMB->mode, pMB->cbp, pMB->mvs[0].x, bmb->pmvs[0].x, bmb->pmvs[0].y, forward.x, forward.y);                          if (mb->mode == MODE_DIRECT && (mb->cbp | mb->pmvs[3].x | mb->pmvs[3].y) == 0)
1972                                    mb->mode = MODE_DIRECT_NONE_MV; /* skipped */
1973                            else
1974                                    if (frame->vop_flags & XVID_VOP_GREYSCALE)
1975                                            /* keep only bits 5-2 -- Chroma blocks will just be skipped by MBCodingBVOP */
1976                                            mb->cbp &= 0x3C;
1977    
1978                          start_timer();                          start_timer();
1979                          MBCodingBVOP(mb, qcoeff, frame->fcode, frame->bcode, bs, &pEnc->sStat);                          MBCodingBVOP(frame, mb, qcoeff, frame->fcode, frame->bcode, bs,
1980                                                     &frame->sStat);
1981                          stop_coding_timer();                          stop_coding_timer();
1982                  }                  }
1983          }          }
1984    
1985          emms();          emms();
1986    
1987          // TODO: dynamic fcode/bcode ???          BitstreamPadAlways(bs); /* next_start_code() at the end of VideoObjectPlane() */
1988            frame->length = (BitstreamPos(bs) - bits) / 8;
1989    
1990          *pBits = BitstreamPos(bs) - *pBits;  #ifdef BFRAMES_DEC_DEBUG
1991            if (!first){
1992                    first=1;
1993                    if (fp)
1994                            fclose(fp);
1995  }  }
1996  #endif  #endif
1997    }

Legend:
Removed from v.152  
changed lines
  Added in v.1679

No admin address has been configured
ViewVC Help
Powered by ViewVC 1.0.4