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

Legend:
Removed from v.1.40  
changed lines
  Added in v.1.95.2.4

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