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

Diff of /xvidcore/src/encoder.c

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

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

Legend:
Removed from v.1.95.2.66  
changed lines
  Added in v.1.98

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