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

Legend:
Removed from v.1.39  
changed lines
  Added in v.1.95.2.8

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