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

Legend:
Removed from v.1.35  
changed lines
  Added in v.1.95.2.6

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