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

Legend:
Removed from v.1.24  
changed lines
  Added in v.1.95.2.2

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