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

Legend:
Removed from v.1.42  
changed lines
  Added in v.1.95.2.28

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