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

Legend:
Removed from v.1.95.2.56  
changed lines
  Added in v.1.99.2.1

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