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

Legend:
Removed from v.1.36  
changed lines
  Added in v.1.95.2.5

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