[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.12, Thu Mar 28 12:24:41 2002 UTC revision 1.91, Sat Feb 15 15:22:17 2003 UTC
# Line 1  Line 1 
1    /*****************************************************************************
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     ****************************************************************************/
30    
31    /*****************************************************************************
32     *
33     *  History
34     *
35     *  10.07.2002  added BFRAMES_DEC_DEBUG support
36     *              MinChen <chenm001@163.com>
37     *  20.06.2002 bframe patch
38     *  08.05.2002 fix some problem in DEBUG mode;
39     *             MinChen <chenm001@163.com>
40     *  14.04.2002 added FrameCodeB()
41     *
42     *  $Id$
43     *
44     ****************************************************************************/
45    
46  #include <stdlib.h>  #include <stdlib.h>
47  #include <stdio.h>  #include <stdio.h>
48  #include <math.h>  #include <math.h>
49    #include <string.h>
50    
51  #include "encoder.h"  #include "encoder.h"
52  #include "prediction/mbprediction.h"  #include "prediction/mbprediction.h"
53  #include "global.h"  #include "global.h"
54  #include "utils/timer.h"  #include "utils/timer.h"
55  #include "image/image.h"  #include "image/image.h"
56    #include "image/font.h"
57    #include "motion/sad.h"
58    #include "motion/motion.h"
59  #include "bitstream/cbp.h"  #include "bitstream/cbp.h"
60  #include "utils/mbfunctions.h"  #include "utils/mbfunctions.h"
61  #include "bitstream/bitstream.h"  #include "bitstream/bitstream.h"
# Line 18  Line 67 
67  #include "quant/quant_matrix.h"  #include "quant/quant_matrix.h"
68  #include "utils/mem_align.h"  #include "utils/mem_align.h"
69    
70  #define ENC_CHECK(X) if(!(X)) return XVID_ERR_FORMAT  /*****************************************************************************
71     * Local macros
72     ****************************************************************************/
73    
74    #define ENC_CHECK(X) if(!(X)) return XVID_ERR_FORMAT
75    #define SWAP(_T_,A,B)    { _T_ tmp = A; A = B; B = tmp; }
76    
77  static int FrameCodeI(Encoder * pEnc, Bitstream * bs, uint32_t *pBits);  /*****************************************************************************
78  static int FrameCodeP(Encoder * pEnc, Bitstream * bs, uint32_t *pBits, bool force_inter, bool vol_header);   * Local function prototypes
79     ****************************************************************************/
80    
81    static int FrameCodeI(Encoder * pEnc,
82                                              Bitstream * bs,
83                                              uint32_t * pBits);
84    
85    static int FrameCodeP(Encoder * pEnc,
86                                              Bitstream * bs,
87                                              uint32_t * pBits,
88                                              bool force_inter,
89                                              bool vol_header);
90    
91    static void FrameCodeB(Encoder * pEnc,
92                                               FRAMEINFO * frame,
93                                               Bitstream * bs,
94                                               uint32_t * pBits);
95    
96    /*****************************************************************************
97     * Local data
98     ****************************************************************************/
99    
100  static int DQtab[4] =  static int DQtab[4] = {
 {  
101          -1, -2, 1, 2          -1, -2, 1, 2
102  };  };
103    
104  static int iDQtab[5] =  static int iDQtab[5] = {
 {  
105          1, 0, NO_CHANGE, 2, 3          1, 0, NO_CHANGE, 2, 3
106  };  };
107    
108    
109  int encoder_create(XVID_ENC_PARAM * pParam)  /*****************************************************************************
110     * Encoder creation
111     *
112     * This function creates an Encoder instance, it allocates all necessary
113     * image buffers (reference, current and bframes) and initialize the internal
114     * xvid encoder paremeters according to the XVID_ENC_PARAM input parameter.
115     *
116     * The code seems to be very long but is very basic, mainly memory allocation
117     * and cleaning code.
118     *
119     * Returned values :
120     *    - XVID_ERR_OK     - no errors
121     *    - XVID_ERR_MEMORY - the libc could not allocate memory, the function
122     *                        cleans the structure before exiting.
123     *                        pParam->handle is also set to NULL.
124     *
125     ****************************************************************************/
126    
127    int
128    encoder_create(XVID_ENC_PARAM * pParam)
129  {  {
130          Encoder *pEnc;          Encoder *pEnc;
131          uint32_t i;          int i;
132    
133          pParam->handle = NULL;          pParam->handle = NULL;
134    
# Line 49  Line 139 
139          ENC_CHECK(!(pParam->width % 2));          ENC_CHECK(!(pParam->width % 2));
140          ENC_CHECK(!(pParam->height % 2));          ENC_CHECK(!(pParam->height % 2));
141    
142          if (pParam->fincr <= 0 || pParam->fbase <= 0)          /* Fps */
143          {  
144            if (pParam->fincr <= 0 || pParam->fbase <= 0) {
145                  pParam->fincr = 1;                  pParam->fincr = 1;
146                  pParam->fbase = 25;                  pParam->fbase = 25;
147          }          }
148    
149          // simplify the "fincr/fbase" fraction          /*
150          // (neccessary, since windows supplies us with huge numbers)           * Simplify the "fincr/fbase" fraction
151             * (neccessary, since windows supplies us with huge numbers)
152             */
153    
154          i = pParam->fincr;          i = pParam->fincr;
155          while (i > 1)          while (i > 1) {
156          {                  if (pParam->fincr % i == 0 && pParam->fbase % i == 0) {
                 if (pParam->fincr % i == 0 && pParam->fbase % i == 0)  
                 {  
157                          pParam->fincr /= i;                          pParam->fincr /= i;
158                          pParam->fbase /= i;                          pParam->fbase /= i;
159                          i = pParam->fincr;                          i = pParam->fincr;
# Line 71  Line 162 
162                  i--;                  i--;
163          }          }
164    
165          if (pParam->fbase > 65535)          if (pParam->fbase > 65535) {
         {  
166                  float div = (float)pParam->fbase / 65535;                  float div = (float)pParam->fbase / 65535;
167    
168                  pParam->fbase = (int)(pParam->fbase / div);                  pParam->fbase = (int)(pParam->fbase / div);
169                  pParam->fincr = (int)(pParam->fincr / div);                  pParam->fincr = (int)(pParam->fincr / div);
170          }          }
171    
172          if (pParam->bitrate <= 0)          /* Bitrate allocator defaults */
173                  pParam->bitrate = 900000;  
174            if (pParam->rc_bitrate <= 0)
175                    pParam->rc_bitrate = 900000;
176    
177            if (pParam->rc_reaction_delay_factor <= 0)
178                    pParam->rc_reaction_delay_factor = 16;
179    
180            if (pParam->rc_averaging_period <= 0)
181                    pParam->rc_averaging_period = 100;
182    
183            if (pParam->rc_buffer <= 0)
184                    pParam->rc_buffer = 100;
185    
186          if (pParam->rc_buffersize <= 0)          /* Max and min quantizers */
                 pParam->rc_buffersize = 16;  
187    
188          if ((pParam->min_quantizer <= 0) || (pParam->min_quantizer > 31))          if ((pParam->min_quantizer <= 0) || (pParam->min_quantizer > 31))
189                  pParam->min_quantizer = 1;                  pParam->min_quantizer = 1;
# Line 90  Line 191 
191          if ((pParam->max_quantizer <= 0) || (pParam->max_quantizer > 31))          if ((pParam->max_quantizer <= 0) || (pParam->max_quantizer > 31))
192                  pParam->max_quantizer = 31;                  pParam->max_quantizer = 31;
193    
         if (pParam->max_key_interval == 0)              /* 1 keyframe each 10 seconds */  
                 pParam->max_key_interval = 10 * pParam->fincr / pParam->fbase;  
   
194          if (pParam->max_quantizer < pParam->min_quantizer)          if (pParam->max_quantizer < pParam->min_quantizer)
195                  pParam->max_quantizer = pParam->min_quantizer;                  pParam->max_quantizer = pParam->min_quantizer;
196    
197          if ((pEnc = (Encoder *) xvid_malloc(sizeof(Encoder), CACHE_LINE)) == NULL)          /* 1 keyframe each 10 seconds */
198    
199            if (pParam->max_key_interval <= 0)
200                    pParam->max_key_interval = 10 * pParam->fincr / pParam->fbase;
201    
202            pEnc = (Encoder *) xvid_malloc(sizeof(Encoder), CACHE_LINE);
203            if (pEnc == NULL)
204                  return XVID_ERR_MEMORY;                  return XVID_ERR_MEMORY;
205    
206            /* Zero the Encoder Structure */
207    
208            memset(pEnc, 0, sizeof(Encoder));
209    
210          /* Fill members of Encoder structure */          /* Fill members of Encoder structure */
211    
212          pEnc->mbParam.width = pParam->width;          pEnc->mbParam.width = pParam->width;
# Line 110  Line 218 
218          pEnc->mbParam.edged_width = 16 * pEnc->mbParam.mb_width + 2 * EDGE_SIZE;          pEnc->mbParam.edged_width = 16 * pEnc->mbParam.mb_width + 2 * EDGE_SIZE;
219          pEnc->mbParam.edged_height = 16 * pEnc->mbParam.mb_height + 2 * EDGE_SIZE;          pEnc->mbParam.edged_height = 16 * pEnc->mbParam.mb_height + 2 * EDGE_SIZE;
220    
221          pEnc->sStat.fMvPrevSigma = -1;          pEnc->mbParam.fbase = pParam->fbase;
222            pEnc->mbParam.fincr = pParam->fincr;
223    
224            pEnc->mbParam.m_quant_type = H263_QUANT;
225    
226            pEnc->fMvPrevSigma = -1;
227    
228          /* Fill rate control parameters */          /* Fill rate control parameters */
229    
230          pEnc->mbParam.quant = 4;          pEnc->bitrate = pParam->rc_bitrate;
231    
232          pEnc->bitrate = pParam->bitrate;          pEnc->iFrameNum = -1;
233            pEnc->mbParam.iMaxKeyInterval = pParam->max_key_interval;
234    
235          pEnc->iFrameNum = 0;          /* try to allocate frame memory */
         pEnc->iMaxKeyInterval = pParam->max_key_interval;  
236    
237          if (image_create(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          pEnc->current = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
238          {          pEnc->reference = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
239    
240          if (image_create(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          if (pEnc->current == NULL || pEnc->reference == NULL)
241          {                  goto xvid_err_memory1;
                 image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
242    
243          if (image_create(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          /* try to allocate mb memory */
         {  
                 image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 image_destroy(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
244    
245          if (image_create(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          pEnc->current->mbs =
246          {                  xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
247                  image_destroy(&pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                                          pEnc->mbParam.mb_height, CACHE_LINE);
248                  image_destroy(&pEnc->sReference, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);          pEnc->reference->mbs =
249                  image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                  xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
250                  xvid_free(pEnc);                                          pEnc->mbParam.mb_height, CACHE_LINE);
                 return XVID_ERR_MEMORY;  
         }  
251    
252          if (image_create(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)          if (pEnc->current->mbs == NULL || pEnc->reference->mbs == NULL)
253          {                  goto xvid_err_memory2;
                 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);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
254    
255          pEnc->pMBs = xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width * pEnc->mbParam.mb_height, CACHE_LINE);          /* try to allocate image memory */
         if (pEnc->pMBs == 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->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
256    
257          // init macroblock array          if (pParam->global & XVID_GLOBAL_EXTRASTATS)
258          for (i = 0; i < pEnc->mbParam.mb_width * pEnc->mbParam.mb_height; i++)                  image_null(&pEnc->sOriginal);
         {  
                 pEnc->pMBs[i].dquant = NO_CHANGE;  
         }  
259    
260          pParam->handle = (void *)pEnc;          image_null(&pEnc->f_refh);
261            image_null(&pEnc->f_refv);
262            image_null(&pEnc->f_refhv);
263    
264          if (pParam->bitrate)          image_null(&pEnc->current->image);
265          {          image_null(&pEnc->reference->image);
266                  RateControlInit(pParam->bitrate, pParam->rc_buffersize, pParam->fbase * 100 / pParam->fincr,          image_null(&pEnc->vInterH);
267                                  pParam->max_quantizer, pParam->min_quantizer);          image_null(&pEnc->vInterV);
268            image_null(&pEnc->vInterVf);
269            image_null(&pEnc->vInterHV);
270            image_null(&pEnc->vInterHVf);
271    
272            if (pParam->global & XVID_GLOBAL_EXTRASTATS)
273            {       if (image_create
274                            (&pEnc->sOriginal, pEnc->mbParam.edged_width,
275                             pEnc->mbParam.edged_height) < 0)
276                            goto xvid_err_memory3;
277          }          }
278    
279          create_vlc_tables();          if (image_create
280          init_timer();                  (&pEnc->f_refh, pEnc->mbParam.edged_width,
281                     pEnc->mbParam.edged_height) < 0)
282                    goto xvid_err_memory3;
283            if (image_create
284                    (&pEnc->f_refv, pEnc->mbParam.edged_width,
285                     pEnc->mbParam.edged_height) < 0)
286                    goto xvid_err_memory3;
287            if (image_create
288                    (&pEnc->f_refhv, pEnc->mbParam.edged_width,
289                     pEnc->mbParam.edged_height) < 0)
290                    goto xvid_err_memory3;
291    
292          return XVID_ERR_OK;          if (image_create
293  }                  (&pEnc->current->image, pEnc->mbParam.edged_width,
294                     pEnc->mbParam.edged_height) < 0)
295                    goto xvid_err_memory3;
296            if (image_create
297                    (&pEnc->reference->image, pEnc->mbParam.edged_width,
298                     pEnc->mbParam.edged_height) < 0)
299                    goto xvid_err_memory3;
300            if (image_create
301                    (&pEnc->vInterH, pEnc->mbParam.edged_width,
302                     pEnc->mbParam.edged_height) < 0)
303                    goto xvid_err_memory3;
304            if (image_create
305                    (&pEnc->vInterV, pEnc->mbParam.edged_width,
306                     pEnc->mbParam.edged_height) < 0)
307                    goto xvid_err_memory3;
308            if (image_create
309                    (&pEnc->vInterVf, pEnc->mbParam.edged_width,
310                     pEnc->mbParam.edged_height) < 0)
311                    goto xvid_err_memory3;
312            if (image_create
313                    (&pEnc->vInterHV, pEnc->mbParam.edged_width,
314                     pEnc->mbParam.edged_height) < 0)
315                    goto xvid_err_memory3;
316            if (image_create
317                    (&pEnc->vInterHVf, pEnc->mbParam.edged_width,
318                     pEnc->mbParam.edged_height) < 0)
319                    goto xvid_err_memory3;
320    
321    /* Create full bitplane for GMC, this might be wasteful */
322            if (image_create
323                    (&pEnc->vGMC, pEnc->mbParam.edged_width,
324                     pEnc->mbParam.edged_height) < 0)
325                    goto xvid_err_memory3;
326    
 int encoder_destroy(Encoder * pEnc)  
 {  
         ENC_CHECK(pEnc);  
         ENC_CHECK(pEnc->sCurrent.y);  
         ENC_CHECK(pEnc->sReference.y);  
327    
         xvid_free(pEnc->pMBs);  
         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->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         xvid_free(pEnc);  
328    
329          destroy_vlc_tables();          pEnc->mbParam.global = pParam->global;
330    
331          return XVID_ERR_OK;          /* B Frames specific init */
332  }          pEnc->mbParam.max_bframes = pParam->max_bframes;
333            pEnc->mbParam.bquant_ratio = pParam->bquant_ratio;
334            pEnc->mbParam.bquant_offset = pParam->bquant_offset;
335            pEnc->mbParam.frame_drop_ratio = pParam->frame_drop_ratio;
336            pEnc->bframes = NULL;
337    
338  int encoder_encode(Encoder * pEnc, XVID_ENC_FRAME * pFrame, XVID_ENC_STATS * pResult)          if (pEnc->mbParam.max_bframes > 0) {
339  {                  int n;
         uint16_t x, y;  
         Bitstream bs;  
         uint32_t bits;  
         uint16_t write_vol_header = 0;  
340    
341          start_global_timer();                  pEnc->bframes =
342                            xvid_malloc(pEnc->mbParam.max_bframes * sizeof(FRAMEINFO *),
343                                                    CACHE_LINE);
344    
345          ENC_CHECK(pEnc);                  if (pEnc->bframes == NULL)
346          ENC_CHECK(pFrame);                          goto xvid_err_memory3;
         ENC_CHECK(pFrame->bitstream);  
         ENC_CHECK(pFrame->image);  
347    
348          pEnc->mbParam.global_flags = pFrame->general;                  for (n = 0; n < pEnc->mbParam.max_bframes; n++)
349          pEnc->mbParam.motion_flags = pFrame->motion;                          pEnc->bframes[n] = NULL;
350    
         start_timer();  
         if (image_input(&pEnc->sCurrent, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width,  
                         pFrame->image, pFrame->colorspace))  
         {  
                 return XVID_ERR_FORMAT;  
         }  
         stop_conv_timer();  
351    
352          EMMS();                  for (n = 0; n < pEnc->mbParam.max_bframes; n++) {
353                            pEnc->bframes[n] = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
354    
355          BitstreamInit(&bs, pFrame->bitstream, 0);                          if (pEnc->bframes[n] == NULL)
356                                    goto xvid_err_memory4;
357    
358          if (pFrame->quant == 0)                          pEnc->bframes[n]->mbs =
359          {                                  xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
360                  pEnc->mbParam.quant = RateControlGetQ(0);                                                          pEnc->mbParam.mb_height, CACHE_LINE);
         }  
         else  
         {  
                 pEnc->mbParam.quant = pFrame->quant;  
         }  
361    
362          if ((pEnc->mbParam.global_flags & XVID_LUMIMASKING) > 0)                          if (pEnc->bframes[n]->mbs == NULL)
363          {                                  goto xvid_err_memory4;
                 int * temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * sizeof(int), CACHE_LINE);  
364    
365                  pEnc->mbParam.quant = adaptive_quantization(pEnc->sCurrent.y, pEnc->mbParam.width,                          image_null(&pEnc->bframes[n]->image);
366                                                              temp_dquants, pFrame->quant, pFrame->quant,  
367                                                              2*pFrame->quant, pEnc->mbParam.mb_width, pEnc->mbParam.mb_height);                          if (image_create
368                                    (&pEnc->bframes[n]->image, pEnc->mbParam.edged_width,
369                                     pEnc->mbParam.edged_height) < 0)
370                                    goto xvid_err_memory4;
371    
                 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)];  
372                          }                          }
                 xvid_free(temp_dquants);  
373          }          }
374    
375          if(pEnc->mbParam.global_flags & XVID_H263QUANT) {          pEnc->bframenum_head = 0;
376                  if(pEnc->mbParam.quant_type != H263_QUANT)          pEnc->bframenum_tail = 0;
377                          write_vol_header = 1;          pEnc->flush_bframes = 0;
378                  pEnc->mbParam.quant_type = H263_QUANT;          pEnc->bframenum_dx50bvop = -1;
         }  
         else if(pEnc->mbParam.global_flags & XVID_MPEGQUANT) {  
                 int ret1, ret2;  
379    
380                  if(pEnc->mbParam.quant_type != MPEG4_QUANT)          pEnc->queue = NULL;
                         write_vol_header = 1;  
381    
                 pEnc->mbParam.quant_type = MPEG4_QUANT;  
382    
383                  if ((pEnc->mbParam.global_flags & XVID_CUSTOM_QMATRIX) > 0) {          if (pEnc->mbParam.max_bframes > 0) {
384                          if(pFrame->quant_intra_matrix != NULL)                  int n;
                                 ret1 = set_intra_matrix(pFrame->quant_intra_matrix);  
                         if(pFrame->quant_inter_matrix != NULL)  
                                 ret2 = set_inter_matrix(pFrame->quant_inter_matrix);  
                 }  
                 else {  
                         ret1 = set_intra_matrix(get_default_intra_matrix());  
                         ret2 = set_inter_matrix(get_default_inter_matrix());  
                 }  
                 if(write_vol_header == 0)  
                         write_vol_header = ret1 | ret2;  
         }  
385    
386          if (pFrame->intra < 0)                  pEnc->queue =
387          {                          xvid_malloc(pEnc->mbParam.max_bframes * sizeof(IMAGE),
388                  if ((pEnc->iFrameNum == 0) || ((pEnc->iMaxKeyInterval > 0)                                                  CACHE_LINE);
389                                                 && (pEnc->iFrameNum >= pEnc->iMaxKeyInterval)))  
390                    if (pEnc->queue == NULL)
391                            goto xvid_err_memory4;
392    
393                    for (n = 0; n < pEnc->mbParam.max_bframes; n++)
394                            image_null(&pEnc->queue[n]);
395    
396                    for (n = 0; n < pEnc->mbParam.max_bframes; n++) {
397                            if (image_create
398                                    (&pEnc->queue[n], pEnc->mbParam.edged_width,
399                                     pEnc->mbParam.edged_height) < 0)
400                                    goto xvid_err_memory5;
401    
                         pFrame->intra = FrameCodeI(pEnc, &bs, &bits);  
                 else  
                         pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 0, write_vol_header);  
402          }          }
         else  
         {  
                 if (pFrame->intra == 1)  
                         pFrame->intra = FrameCodeI(pEnc, &bs, &bits);  
                 else  
                         pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 1, write_vol_header);  
403          }          }
404    
405          BitstreamPutBits(&bs, 0xFFFF, 16);          pEnc->queue_head = 0;
406          BitstreamPutBits(&bs, 0xFFFF, 16);          pEnc->queue_tail = 0;
407          BitstreamPad(&bs);          pEnc->queue_size = 0;
         pFrame->length = BitstreamLength(&bs);  
408    
409          if (pResult)          pEnc->mbParam.m_stamp = 0;
         {  
                 pResult->quant = pEnc->mbParam.quant;  
                 pResult->hlength = pFrame->length - (pEnc->sStat.iTextBits / 8);  
                 pResult->kblks = pEnc->sStat.kblks;  
                 pResult->mblks = pEnc->sStat.mblks;  
                 pResult->ublks = pEnc->sStat.ublks;  
         }  
410    
411          EMMS();          pEnc->m_framenum = 0;
412            pEnc->current->stamp = 0;
413            pEnc->reference->stamp = 0;
414    
415          if (pFrame->quant == 0)          pParam->handle = (void *) pEnc;
         {  
                 RateControlUpdate(pEnc->mbParam.quant, pFrame->length, pFrame->intra);  
         }  
416    
417          pEnc->iFrameNum++;          if (pParam->rc_bitrate) {
418          image_swap(&pEnc->sCurrent, &pEnc->sReference);                  RateControlInit(&pEnc->rate_control, pParam->rc_bitrate,
419                                                    pParam->rc_reaction_delay_factor,
420                                                    pParam->rc_averaging_period, pParam->rc_buffer,
421                                                    pParam->fbase * 1000 / pParam->fincr,
422                                                    pParam->max_quantizer, pParam->min_quantizer);
423            }
424    
425          stop_global_timer();          init_timer();
         write_timer();  
426    
427          return XVID_ERR_OK;          return XVID_ERR_OK;
 }  
428    
429            /*
430             * We handle all XVID_ERR_MEMORY here, this makes the code lighter
431             */
432    
433  static __inline void CodeIntraMB(Encoder *pEnc, MACROBLOCK *pMB) {    xvid_err_memory5:
434    
         pMB->mode = MODE_INTRA;  
435    
436          if ((pEnc->mbParam.global_flags & XVID_LUMIMASKING) > 0) {          if (pEnc->mbParam.max_bframes > 0) {
                 if(pMB->dquant != NO_CHANGE)  
                 {  
                         pMB->mode = MODE_INTRA_Q;  
                         pEnc->mbParam.quant += DQtab[pMB->dquant];  
437    
438                          if (pEnc->mbParam.quant > 31) pEnc->mbParam.quant = 31;                  for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
439                          if (pEnc->mbParam.quant < 1) pEnc->mbParam.quant = 1;                          image_destroy(&pEnc->queue[i], pEnc->mbParam.edged_width,
440                                                      pEnc->mbParam.edged_height);
441                  }                  }
442                    xvid_free(pEnc->queue);
443          }          }
444    
445          pMB->quant = pEnc->mbParam.quant;    xvid_err_memory4:
446    
447            if (pEnc->mbParam.max_bframes > 0) {
448    
449                    for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
450    
451                            if (pEnc->bframes[i] == NULL)
452                                    continue;
453    
454                            image_destroy(&pEnc->bframes[i]->image, pEnc->mbParam.edged_width,
455                                                      pEnc->mbParam.edged_height);
456    
457                            xvid_free(pEnc->bframes[i]->mbs);
458    
459                            xvid_free(pEnc->bframes[i]);
460    
461  }  }
462    
463                    xvid_free(pEnc->bframes);
464            }
465    
466  static int FrameCodeI(Encoder * pEnc, Bitstream * bs, uint32_t *pBits)    xvid_err_memory3:
 {  
 #ifdef LINUX  
         DECLARE_ALIGNED_MATRIX(dct_codes,6,64,int16_t,16);  
         DECLARE_ALIGNED_MATRIX(qcoeff,6,64,int16_t,16);  
 #else  
         CACHE_ALIGN int16_t dct_codes[6][64];  
         CACHE_ALIGN int16_t qcoeff[6][64];  
 #endif  
         uint16_t x, y;  
467    
468          pEnc->iFrameNum = 0;          if (pEnc->mbParam.global & XVID_GLOBAL_EXTRASTATS)
469          pEnc->mbParam.rounding_type = 1;          {       image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width,
470          pEnc->mbParam.coding_type = I_VOP;                                            pEnc->mbParam.edged_height);
471            }
472    
473          BitstreamWriteVolHeader(bs, &pEnc->mbParam);          image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width,
474          BitstreamWriteVopHeader(bs, &pEnc->mbParam);                                    pEnc->mbParam.edged_height);
475            image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width,
476                                      pEnc->mbParam.edged_height);
477            image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width,
478                                      pEnc->mbParam.edged_height);
479    
480          *pBits = BitstreamPos(bs);          image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width,
481                                      pEnc->mbParam.edged_height);
482            image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width,
483                                      pEnc->mbParam.edged_height);
484            image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width,
485                                      pEnc->mbParam.edged_height);
486            image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width,
487                                      pEnc->mbParam.edged_height);
488            image_destroy(&pEnc->vInterVf, pEnc->mbParam.edged_width,
489                                      pEnc->mbParam.edged_height);
490            image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width,
491                                      pEnc->mbParam.edged_height);
492            image_destroy(&pEnc->vInterHVf, pEnc->mbParam.edged_width,
493                                      pEnc->mbParam.edged_height);
494    
495          pEnc->sStat.iTextBits = 0;  /* destroy GMC image */
496          pEnc->sStat.kblks = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height;          image_destroy(&pEnc->vGMC, pEnc->mbParam.edged_width,
497          pEnc->sStat.mblks = pEnc->sStat.ublks = 0;                                    pEnc->mbParam.edged_height);
498    
         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];  
499    
500                          CodeIntraMB(pEnc, pMB);    xvid_err_memory2:
501            xvid_free(pEnc->current->mbs);
502            xvid_free(pEnc->reference->mbs);
503    
504                          MBTransQuantIntra(&pEnc->mbParam, pMB, x, y, dct_codes, qcoeff, &pEnc->sCurrent);    xvid_err_memory1:
505            xvid_free(pEnc->current);
506            xvid_free(pEnc->reference);
507            xvid_free(pEnc);
508    
509                          start_timer();          pParam->handle = NULL;
                         MBPrediction(&pEnc->mbParam, x, y, pEnc->mbParam.mb_width, qcoeff, pEnc->pMBs);  
                         stop_prediction_timer();  
510    
511                          start_timer();          return XVID_ERR_MEMORY;
                         MBCoding(&pEnc->mbParam, pMB, qcoeff, bs, &pEnc->sStat);  
                         stop_coding_timer();  
512                  }                  }
513    
514          emms();  /*****************************************************************************
515     * Encoder destruction
516     *
517     * This function destroy the entire encoder structure created by a previous
518     * successful encoder_create call.
519     *
520     * Returned values (for now only one returned value) :
521     *    - XVID_ERR_OK     - no errors
522     *
523     ****************************************************************************/
524    
525          *pBits = BitstreamPos(bs) - *pBits;  int
526          pEnc->sStat.fMvPrevSigma = -1;  encoder_destroy(Encoder * pEnc)
527          pEnc->sStat.iMvSum = 0;  {
528          pEnc->sStat.iMvCount = 0;          int i;
         pEnc->mbParam.fixed_code = 2;  
529    
530          return 1;                                        // intra          ENC_CHECK(pEnc);
 }  
531    
532            /* B Frames specific */
533            if (pEnc->mbParam.max_bframes > 0) {
534    
535  #define INTRA_THRESHOLD 0.5                  for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
536    
537  static int FrameCodeP(Encoder * pEnc, Bitstream * bs, uint32_t *pBits, bool force_inter, bool vol_header)                          image_destroy(&pEnc->queue[i], pEnc->mbParam.edged_width,
538  {                                            pEnc->mbParam.edged_height);
539          float fSigma;                  }
540  #ifdef LINUX                  xvid_free(pEnc->queue);
541          DECLARE_ALIGNED_MATRIX(dct_codes,6,64,int16_t,16);          }
         DECLARE_ALIGNED_MATRIX(qcoeff,6,64,int16_t,16);  
 #else  
         CACHE_ALIGN int16_t dct_codes[6][64];  
         CACHE_ALIGN int16_t qcoeff[6][64];  
 #endif  
542    
         int iLimit;  
         uint32_t x, y;  
         int iSearchRange;  
         bool bIntra;  
543    
544          IMAGE *pCurrent = &pEnc->sCurrent;          if (pEnc->mbParam.max_bframes > 0) {
         IMAGE *pRef = &pEnc->sReference;  
545    
546          start_timer();                  for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
         image_setedges(pRef,pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.global_flags & XVID_INTERLACING);  
         stop_edges_timer();  
547    
548          pEnc->mbParam.rounding_type = 1 - pEnc->mbParam.rounding_type;                          if (pEnc->bframes[i] == NULL)
549                                    continue;
550    
551          if (!force_inter)                          image_destroy(&pEnc->bframes[i]->image, pEnc->mbParam.edged_width,
552                  iLimit = (int)(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * INTRA_THRESHOLD);                                            pEnc->mbParam.edged_height);
         else  
                 iLimit = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height + 1;  
553    
554          if ((pEnc->mbParam.global_flags & XVID_HALFPEL) > 0) {                          xvid_free(pEnc->bframes[i]->mbs);
555                  start_timer();  
556                  image_interpolate(pRef, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,                          xvid_free(pEnc->bframes[i]);
                                   pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,  
                                   pEnc->mbParam.rounding_type);  
                 stop_inter_timer();  
557          }          }
558    
559          start_timer();                  xvid_free(pEnc->bframes);
         bIntra = MotionEstimation(pEnc->pMBs, &pEnc->mbParam, &pEnc->sReference,  
                                   &pEnc->vInterH, &pEnc->vInterV,  
                                   &pEnc->vInterHV, &pEnc->sCurrent, iLimit);  
         stop_motion_timer();  
560    
561          if (bIntra == 1)          }
                 return FrameCodeI(pEnc, bs, pBits);  
562    
563          pEnc->mbParam.coding_type = P_VOP;          /* All images, reference, current etc ... */
564    
565          if(vol_header)          image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width,
566                  BitstreamWriteVolHeader(bs, &pEnc->mbParam);                                    pEnc->mbParam.edged_height);
567            image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width,
568                                      pEnc->mbParam.edged_height);
569            image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width,
570                                      pEnc->mbParam.edged_height);
571            image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width,
572                                      pEnc->mbParam.edged_height);
573            image_destroy(&pEnc->vInterVf, pEnc->mbParam.edged_width,
574                                      pEnc->mbParam.edged_height);
575            image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width,
576                                      pEnc->mbParam.edged_height);
577            image_destroy(&pEnc->vInterHVf, pEnc->mbParam.edged_width,
578                                      pEnc->mbParam.edged_height);
579    
580          BitstreamWriteVopHeader(bs, &pEnc->mbParam);          image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width,
581                                      pEnc->mbParam.edged_height);
582            image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width,
583                                      pEnc->mbParam.edged_height);
584            image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width,
585                                      pEnc->mbParam.edged_height);
586    
587          *pBits = BitstreamPos(bs);          if (pEnc->mbParam.global & XVID_GLOBAL_EXTRASTATS)
588            {       image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width,
589                                              pEnc->mbParam.edged_height);
590            }
591    
592          pEnc->sStat.iTextBits = 0;          /* Encoder structure */
         pEnc->sStat.iMvSum = 0;  
         pEnc->sStat.iMvCount = 0;  
         pEnc->sStat.kblks = pEnc->sStat.mblks = pEnc->sStat.ublks = 0;  
593    
594          for(y = 0; y < pEnc->mbParam.mb_height; y++)          xvid_free(pEnc->current->mbs);
595          {          xvid_free(pEnc->current);
                 for(x = 0; x < pEnc->mbParam.mb_width; x++)  
                 {  
                         MACROBLOCK * pMB = &pEnc->pMBs[x + y * pEnc->mbParam.mb_width];  
596    
597                          bIntra = (pMB->mode == MODE_INTRA) || (pMB->mode == MODE_INTRA_Q);          xvid_free(pEnc->reference->mbs);
598            xvid_free(pEnc->reference);
599    
600                          if (!bIntra)          xvid_free(pEnc);
                         {  
                                 start_timer();  
                                 MBMotionCompensation(pMB, x, y, &pEnc->sReference,  
                                                      &pEnc->vInterH, &pEnc->vInterV,  
                                                      &pEnc->vInterHV, &pEnc->sCurrent, dct_codes,  
                                                      pEnc->mbParam.width,  
                                                      pEnc->mbParam.height,  
                                                      pEnc->mbParam.edged_width,  
                                                      pEnc->mbParam.rounding_type);  
                                 stop_comp_timer();  
601    
602                                  if ((pEnc->mbParam.global_flags & XVID_LUMIMASKING) > 0) {          return XVID_ERR_OK;
                                         if(pMB->dquant != NO_CHANGE) {  
                                                 pMB->mode = MODE_INTER_Q;  
                                                 pEnc->mbParam.quant += DQtab[pMB->dquant];  
                                                 if (pEnc->mbParam.quant > 31) pEnc->mbParam.quant = 31;  
                                                 else if(pEnc->mbParam.quant < 1) pEnc->mbParam.quant = 1;  
                                         }  
603                                  }                                  }
                                 pMB->quant = pEnc->mbParam.quant;  
604    
                                 pMB->field_pred = 0;  
605    
606                                  pMB->cbp = MBTransQuantInter(&pEnc->mbParam, pMB, x, y, dct_codes, qcoeff, pCurrent);  static __inline void inc_frame_num(Encoder * pEnc)
                         }  
                         else  
607                          {                          {
608                                  CodeIntraMB(pEnc, pMB);          pEnc->current->stamp = pEnc->mbParam.m_stamp;   // first frame is zero
609                                  MBTransQuantIntra(&pEnc->mbParam, pMB, x, y, dct_codes, qcoeff, pCurrent);          pEnc->mbParam.m_stamp += pEnc->mbParam.fincr;
610                          }                          }
611    
                         start_timer();  
                         MBPrediction(&pEnc->mbParam, x, y, pEnc->mbParam.mb_width, qcoeff, pEnc->pMBs);  
                         stop_prediction_timer();  
612    
613                          if (pMB->mode == MODE_INTRA || pMB->mode == MODE_INTRA_Q)  static __inline void
614                          {  queue_image(Encoder * pEnc, XVID_ENC_FRAME * pFrame)
                                 pEnc->sStat.kblks++;  
                         }  
                         else if (pMB->cbp ||  
                                  pMB->mvs[0].x || pMB->mvs[0].y ||  
                                  pMB->mvs[1].x || pMB->mvs[1].y ||  
                                  pMB->mvs[2].x || pMB->mvs[2].y ||  
                                  pMB->mvs[3].x || pMB->mvs[3].y)  
615                          {                          {
616                                  pEnc->sStat.mblks++;          if (pEnc->queue_size >= pEnc->mbParam.max_bframes)
                         }  
                         else  
617                          {                          {
618                                  pEnc->sStat.ublks++;                  DPRINTF(DPRINTF_DEBUG,"FATAL: QUEUE FULL");
619                    return;
620                          }                          }
621    
622            DPRINTF(DPRINTF_DEBUG,"*** QUEUE bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
623                                    pEnc->bframenum_head, pEnc->bframenum_tail,
624                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
625    
626    
627                          start_timer();                          start_timer();
628                          MBCoding(&pEnc->mbParam, pMB, qcoeff, bs, &pEnc->sStat);          if (image_input
629                          stop_coding_timer();                  (&pEnc->queue[pEnc->queue_tail], pEnc->mbParam.width, pEnc->mbParam.height,
630                  }                   pEnc->mbParam.edged_width, pFrame->image, pFrame->stride, pFrame->colorspace, pFrame->general & XVID_INTERLACING))
631                    return;
632            stop_conv_timer();
633    
634            pEnc->queue_size++;
635            pEnc->queue_tail =  (pEnc->queue_tail + 1) % pEnc->mbParam.max_bframes;
636          }          }
637    
638          emms();  static __inline void
639    set_timecodes(FRAMEINFO* pCur,FRAMEINFO *pRef, int32_t time_base)
640    {
641    
642          if (pEnc->sStat.iMvCount == 0)                  pCur->ticks = (int32_t)pCur->stamp % time_base;
643                  pEnc->sStat.iMvCount = 1;                  pCur->seconds =  ((int32_t)pCur->stamp / time_base)     - ((int32_t)pRef->stamp / time_base) ;
644    
645          fSigma = (float)sqrt((float) pEnc->sStat.iMvSum / pEnc->sStat.iMvCount);                  //HEAVY DEBUG OUTPUT    remove when timecodes prove to be stable
646    
647          iSearchRange = 1 << (3 + pEnc->mbParam.fixed_code);  /*              fprintf(stderr,"WriteVop:   %d - %d \n",
648                            ((int32_t)pCur->stamp / time_base), ((int32_t)pRef->stamp / time_base));
649                    fprintf(stderr,"set_timecodes: VOP %1d   stamp=%lld ref_stamp=%lld  base=%d\n",
650                            pCur->coding_type, pCur->stamp, pRef->stamp, time_base);
651                    fprintf(stderr,"set_timecodes: VOP %1d   seconds=%d   ticks=%d   (ref-sec=%d  ref-tick=%d)\n",
652                            pCur->coding_type, pCur->seconds, pCur->ticks, pRef->seconds, pRef->ticks);
653    
654          if ((fSigma > iSearchRange / 3)  */
             && (pEnc->mbParam.fixed_code <= 3)) // maximum search range 128  
         {  
                 pEnc->mbParam.fixed_code++;  
                 iSearchRange *= 2;  
655          }          }
656          else if ((fSigma < iSearchRange / 6)  
657                   && (pEnc->sStat.fMvPrevSigma >= 0)  
658                   && (pEnc->sStat.fMvPrevSigma < iSearchRange / 6)  
659                   && (pEnc->mbParam.fixed_code >= 2))    // minimum search range 16  /* convert pFrame->intra to coding_type */
660    static int intra2coding_type(int intra)
661          {          {
662                  pEnc->mbParam.fixed_code--;          if (intra < 0)  return -1;
663                  iSearchRange /= 2;          if (intra == 1) return I_VOP;
664            if (intra == 2) return B_VOP;
665    
666            return P_VOP;
667          }          }
668    
         pEnc->sStat.fMvPrevSigma = fSigma;  
669    
         *pBits = BitstreamPos(bs) - *pBits;  
670    
671          return 0;                                        // inter  /*****************************************************************************
672     * IPB frame encoder entry point
673     *
674     * Returned values :
675     *    - XVID_ERR_OK     - no errors
676     *    - XVID_ERR_FORMAT - the image subsystem reported the image had a wrong
677     *                        format
678     ****************************************************************************/
679    
680    int
681    encoder_encode_bframes(Encoder * pEnc,
682                               XVID_ENC_FRAME * pFrame,
683                               XVID_ENC_STATS * pResult)
684    {
685            uint16_t x, y;
686            Bitstream bs;
687            uint32_t bits;
688            int mode;
689    
690            int input_valid = 1;
691            int bframes_count = 0;
692    
693            ENC_CHECK(pEnc);
694            ENC_CHECK(pFrame);
695            ENC_CHECK(pFrame->image);
696    
697            start_global_timer();
698    
699            BitstreamInit(&bs, pFrame->bitstream, 0);
700    
701    ipvop_loop:
702    
703            /*
704             * bframe "flush" code
705             */
706    
707            if ((pFrame->image == NULL || pEnc->flush_bframes)
708                    && (pEnc->bframenum_head < pEnc->bframenum_tail)) {
709    
710                    if (pEnc->flush_bframes == 0) {
711                            /*
712                             * we have reached the end of stream without getting
713                             * a future reference frame... so encode last final
714                             * frame as a pframe
715                             */
716    
717                            DPRINTF(DPRINTF_DEBUG,"*** BFRAME (final frame) bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
718                                    pEnc->bframenum_head, pEnc->bframenum_tail,
719                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
720    
721                            pEnc->bframenum_tail--;
722                            SWAP(FRAMEINFO *, pEnc->current, pEnc->reference);
723    
724                            SWAP(FRAMEINFO *, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
725    
726                            FrameCodeP(pEnc, &bs, &bits, 1, 0);
727                            bframes_count = 0;
728    
729                            BitstreamPadAlways(&bs);
730                            pFrame->length = BitstreamLength(&bs);
731                            pFrame->intra = 0;
732    
733    
734                            emms();
735    
736                            if (pResult) {
737                                    pResult->quant = pEnc->current->quant;
738                                    pResult->hlength = pFrame->length - (pEnc->current->sStat.iTextBits / 8);
739                                    pResult->kblks = pEnc->current->sStat.kblks;
740                                    pResult->mblks = pEnc->current->sStat.mblks;
741                                    pResult->ublks = pEnc->current->sStat.ublks;
742                            }
743    
744                            return XVID_ERR_OK;
745                    }
746    
747    
748                    DPRINTF(DPRINTF_DEBUG,"*** BFRAME (flush) 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                    FrameCodeB(pEnc, pEnc->bframes[pEnc->bframenum_head], &bs, &bits);
753                    pEnc->bframenum_head++;
754    
755                    BitstreamPadAlways(&bs);
756                    pFrame->length = BitstreamLength(&bs);
757                    pFrame->intra = 2;
758    
759                    if (pResult) {
760                            pResult->quant = pEnc->current->quant;
761                            pResult->hlength = pFrame->length - (pEnc->current->sStat.iTextBits / 8);
762                            pResult->kblks = pEnc->current->sStat.kblks;
763                            pResult->mblks = pEnc->current->sStat.mblks;
764                            pResult->ublks = pEnc->current->sStat.ublks;
765                    }
766    
767                    if (input_valid)
768                            queue_image(pEnc, pFrame);
769    
770                    emms();
771    
772                    return XVID_ERR_OK;
773            }
774    
775            if (pEnc->bframenum_head > 0) {
776                    pEnc->bframenum_head = pEnc->bframenum_tail = 0;
777    
778                    /* write an empty marker to the bitstream.
779    
780                       for divx5 decoder compatibility, this marker must consist
781                       of a not-coded p-vop, with a time_base of zero, and time_increment
782                       indentical to the future-referece frame.
783                    */
784    
785                    if ((pEnc->mbParam.global & XVID_GLOBAL_PACKED)) {
786                            int tmp;
787    
788                            DPRINTF(DPRINTF_DEBUG,"*** EMPTY bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
789                                    pEnc->bframenum_head, pEnc->bframenum_tail,
790                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
791    
792    
793                            tmp = pEnc->current->seconds;
794                            pEnc->current->seconds = 0; /* force time_base = 0 */
795    
796                            BitstreamWriteVopHeader(&bs, &pEnc->mbParam, pEnc->current, 0);
797                            pEnc->current->seconds = tmp;
798    
799                            BitstreamPadAlways(&bs);
800                            pFrame->length = BitstreamLength(&bs);
801                            pFrame->intra = 4;
802    
803                            if (pResult) {
804                                    pResult->quant = pEnc->current->quant;
805                                    pResult->hlength = pFrame->length - (pEnc->current->sStat.iTextBits / 8);
806                                    pResult->kblks = pEnc->current->sStat.kblks;
807                                    pResult->mblks = pEnc->current->sStat.mblks;
808                                    pResult->ublks = pEnc->current->sStat.ublks;
809                            }
810    
811                            if (input_valid)
812                                    queue_image(pEnc, pFrame);
813    
814                            emms();
815    
816                            return XVID_ERR_OK;
817                    }
818            }
819    
820    
821    bvop_loop:
822    
823            if (pEnc->bframenum_dx50bvop != -1)
824            {
825    
826                    SWAP(FRAMEINFO *, pEnc->current, pEnc->reference);
827                    SWAP(FRAMEINFO *, pEnc->current, pEnc->bframes[pEnc->bframenum_dx50bvop]);
828    
829                    if ((pEnc->mbParam.global & XVID_GLOBAL_DEBUG)) {
830                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 100, "DX50 IVOP");
831                    }
832    
833                    if (input_valid)
834                    {
835                            queue_image(pEnc, pFrame);
836                            input_valid = 0;
837                    }
838    
839            } else if (input_valid) {
840    
841                    SWAP(FRAMEINFO *, pEnc->current, pEnc->reference);
842    
843                    start_timer();
844                    if (image_input
845                            (&pEnc->current->image, pEnc->mbParam.width, pEnc->mbParam.height,
846                            pEnc->mbParam.edged_width, pFrame->image, pFrame->stride, pFrame->colorspace, pFrame->general & XVID_INTERLACING))
847                    {
848                            emms();
849                            return XVID_ERR_FORMAT;
850                    }
851                    stop_conv_timer();
852    
853                    // queue input frame, and dequue next image
854                    if (pEnc->queue_size > 0)
855                    {
856                            image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_tail]);
857                            if (pEnc->queue_head != pEnc->queue_tail)
858                            {
859                                    image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_head]);
860                            }
861                            pEnc->queue_head =  (pEnc->queue_head + 1) % pEnc->mbParam.max_bframes;
862                            pEnc->queue_tail =  (pEnc->queue_tail + 1) % pEnc->mbParam.max_bframes;
863                    }
864    
865            } else if (pEnc->queue_size > 0) {
866    
867                    SWAP(FRAMEINFO *, pEnc->current, pEnc->reference);
868    
869                    image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_head]);
870                    pEnc->queue_head =  (pEnc->queue_head + 1) % pEnc->mbParam.max_bframes;
871                    pEnc->queue_size--;
872    
873            } else {
874    
875                    /* if nothing was encoded, write an 'ignore this frame' flag
876                       to the bitstream */
877    
878                    if (BitstreamPos(&bs) == 0) {
879    
880                            DPRINTF(DPRINTF_DEBUG,"*** SKIP bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
881                                    pEnc->bframenum_head, pEnc->bframenum_tail,
882                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
883    
884                    //      BitstreamPutBits(&bs, 0x7f, 8);
885                            pFrame->intra = 5;
886    
887                            if (pResult) {
888                                    /*
889                                     * We must decide what to put there because i know some apps
890                                     * are storing statistics about quantizers and just do
891                                     * stats[quant]++ or stats[quant-1]++
892                                     * transcode is one of these app with its 2pass module
893                                     */
894    
895                                    /*
896                                     * For now i prefer 31 than 0 that could lead to a segfault
897                                     * in transcode
898                                     */
899                                    pResult->quant = 31;
900    
901                                    pResult->hlength = 0;
902                                    pResult->kblks = 0;
903                                    pResult->mblks = 0;
904                                    pResult->ublks = 0;
905                            }
906    
907                    } else {
908    
909                            if (pResult) {
910                                    pResult->quant = pEnc->current->quant;
911                                    pResult->hlength = pFrame->length - (pEnc->current->sStat.iTextBits / 8);
912                                    pResult->kblks = pEnc->current->sStat.kblks;
913                                    pResult->mblks = pEnc->current->sStat.mblks;
914                                    pResult->ublks = pEnc->current->sStat.ublks;
915                            }
916    
917                    }
918    
919                    pFrame->length = BitstreamLength(&bs);
920    
921                    emms();
922    
923                    return XVID_ERR_OK;
924            }
925    
926            pEnc->flush_bframes = 0;
927    
928            emms();
929    
930            // only inc frame num, adapt quant, etc. if we havent seen it before
931            if (pEnc->bframenum_dx50bvop < 0 )
932            {
933                    mode = intra2coding_type(pFrame->intra);
934                    if (pFrame->quant == 0)
935                            pEnc->current->quant = RateControlGetQ(&pEnc->rate_control, 0);
936                    else
937                            pEnc->current->quant = pFrame->quant;
938    
939    /*              if (pEnc->current->quant < 1)
940                            pEnc->current->quant = 1;
941    
942                    if (pEnc->current->quant > 31)
943                            pEnc->current->quant = 31;
944    */
945                    pEnc->current->global_flags = pFrame->general;
946                    pEnc->current->motion_flags = pFrame->motion;
947    
948                    /* ToDo : dynamic fcode (in both directions) */
949                    pEnc->current->fcode = pEnc->mbParam.m_fcode;
950                    pEnc->current->bcode = pEnc->mbParam.m_fcode;
951    
952                    inc_frame_num(pEnc);
953    
954                    if (pFrame->general & XVID_EXTRASTATS)
955                    {       image_copy(&pEnc->sOriginal, &pEnc->current->image,
956                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
957                    }
958    
959                    emms();
960    
961                    if ((pEnc->mbParam.global & XVID_GLOBAL_DEBUG)) {
962                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 5,
963                                    "%i  if:%i  st:%i", pEnc->m_framenum++, pEnc->iFrameNum, pEnc->current->stamp);
964                    }
965    
966            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
967             * Luminance masking
968             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
969    
970                    if ((pEnc->current->global_flags & XVID_LUMIMASKING)) {
971                            int *temp_dquants =
972                                    (int *) xvid_malloc(pEnc->mbParam.mb_width *
973                                                                    pEnc->mbParam.mb_height * sizeof(int),
974                                                                    CACHE_LINE);
975    
976                            pEnc->current->quant =
977                                    adaptive_quantization(pEnc->current->image.y,
978                                                                      pEnc->mbParam.edged_width, temp_dquants,
979                                                                      pEnc->current->quant, pEnc->current->quant,
980                                                                      2 * pEnc->current->quant,
981                                                                      pEnc->mbParam.mb_width,
982                                                                      pEnc->mbParam.mb_height);
983    
984                            for (y = 0; y < pEnc->mbParam.mb_height; y++) {
985    
986    #define OFFSET(x,y) ((x) + (y)*pEnc->mbParam.mb_width)
987    
988                                    for (x = 0; x < pEnc->mbParam.mb_width; x++) {
989                                            MACROBLOCK *pMB = &pEnc->current->mbs[OFFSET(x, y)];
990    
991                                            pMB->dquant = iDQtab[temp_dquants[OFFSET(x, y)] + 2];
992                                    }
993    
994    #undef OFFSET
995                            }
996    
997                            xvid_free(temp_dquants);
998                    }
999    
1000            }
1001    
1002            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1003             * ivop/pvop/bvop selection
1004             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1005            pEnc->iFrameNum++;
1006    
1007            if (pEnc->iFrameNum == 0 || pEnc->bframenum_dx50bvop >= 0 ||
1008                    (mode < 0 && pEnc->mbParam.iMaxKeyInterval > 0 &&
1009                            pEnc->iFrameNum >= pEnc->mbParam.iMaxKeyInterval))
1010            {
1011                    mode = I_VOP;
1012            }else{
1013                    mode = MEanalysis(&pEnc->reference->image, pEnc->current,
1014                                            &pEnc->mbParam, pEnc->mbParam.iMaxKeyInterval,
1015                                            (mode < 0) ? pEnc->iFrameNum : 0,
1016                                            bframes_count++);
1017            }
1018    
1019            if (mode == I_VOP) {
1020                    /*
1021                     * This will be coded as an Intra Frame
1022                     */
1023                    if ((pEnc->current->global_flags & XVID_QUARTERPEL))
1024                            pEnc->mbParam.m_quarterpel = 1;
1025                    else
1026                            pEnc->mbParam.m_quarterpel = 0;
1027    
1028                    if (pEnc->current->global_flags & XVID_MPEGQUANT) pEnc->mbParam.m_quant_type = MPEG4_QUANT;
1029    
1030                    if ((pEnc->current->global_flags & XVID_CUSTOM_QMATRIX) > 0) {
1031                            if (pFrame->quant_intra_matrix != NULL)
1032                                    set_intra_matrix(pFrame->quant_intra_matrix);
1033                            if (pFrame->quant_inter_matrix != NULL)
1034                                    set_inter_matrix(pFrame->quant_inter_matrix);
1035                    }
1036    
1037    
1038                    DPRINTF(DPRINTF_DEBUG,"*** IFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
1039                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1040                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1041    
1042                    if ((pEnc->mbParam.global & XVID_GLOBAL_DEBUG)) {
1043                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "IVOP");
1044                    }
1045    
1046                    // when we reach an iframe in DX50BVOP mode, encode the last bframe as a pframe
1047    
1048                    if ((pEnc->mbParam.global & XVID_GLOBAL_DX50BVOP) && pEnc->bframenum_tail > 0) {
1049    
1050                            pEnc->bframenum_tail--;
1051                            pEnc->bframenum_dx50bvop = pEnc->bframenum_tail;
1052    
1053                            SWAP(FRAMEINFO *, pEnc->current, pEnc->bframes[pEnc->bframenum_dx50bvop]);
1054                            if ((pEnc->mbParam.global & XVID_GLOBAL_DEBUG)) {
1055                                    image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 100, "DX50 BVOP->PVOP");
1056                            }
1057                            FrameCodeP(pEnc, &bs, &bits, 1, 0);
1058                            bframes_count = 0;
1059                            pFrame->intra = 0;
1060    
1061                    } else {
1062    
1063                            FrameCodeI(pEnc, &bs, &bits);
1064                            bframes_count = 0;
1065                            pFrame->intra = 1;
1066    
1067                            pEnc->bframenum_dx50bvop = -1;
1068                    }
1069    
1070                    pEnc->flush_bframes = 1;
1071    
1072                    if ((pEnc->mbParam.global & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail > 0) {
1073                            BitstreamPadAlways(&bs);
1074                            input_valid = 0;
1075                            goto ipvop_loop;
1076                    }
1077    
1078                    /*
1079                     * NB : sequences like "IIBB" decode fine with msfdam but,
1080                     *      go screwy with divx 5.00
1081                     */
1082            } else if (mode == P_VOP || mode == S_VOP || pEnc->bframenum_tail >= pEnc->mbParam.max_bframes) {
1083                    /*
1084                     * This will be coded as a Predicted Frame
1085                     */
1086    
1087                    DPRINTF(DPRINTF_DEBUG,"*** PFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i",
1088                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1089                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1090    
1091                    if ((pEnc->mbParam.global & XVID_GLOBAL_DEBUG)) {
1092                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "PVOP");
1093                    }
1094    
1095                    FrameCodeP(pEnc, &bs, &bits, 1, 0);
1096                    bframes_count = 0;
1097                    pFrame->intra = 0;
1098                    pEnc->flush_bframes = 1;
1099    
1100                    if ((pEnc->mbParam.global & XVID_GLOBAL_PACKED) && (pEnc->bframenum_tail > 0)) {
1101                            BitstreamPadAlways(&bs);
1102                            input_valid = 0;
1103                            goto ipvop_loop;
1104                    }
1105    
1106            } else {        /* mode == B_VOP */
1107                    /*
1108                     * This will be coded as a Bidirectional Frame
1109                     */
1110    
1111                    if ((pEnc->mbParam.global & XVID_GLOBAL_DEBUG)) {
1112                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "BVOP");
1113                    }
1114    
1115                    if (pFrame->bquant < 1) {
1116                            pEnc->current->quant = ((((pEnc->reference->quant + pEnc->current->quant) *
1117                                    pEnc->mbParam.bquant_ratio) / 2) + pEnc->mbParam.bquant_offset)/100;
1118    
1119                    } else {
1120                            pEnc->current->quant = pFrame->bquant;
1121                    }
1122    
1123                    if (pEnc->current->quant < 1)
1124                            pEnc->current->quant = 1;
1125                    else if (pEnc->current->quant > 31)
1126                pEnc->current->quant = 31;
1127    
1128                    DPRINTF(DPRINTF_DEBUG,"*** BFRAME (store) bf: head=%i tail=%i   queue: head=%i tail=%i size=%i  quant=%i\n",
1129                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1130                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size,pEnc->current->quant);
1131    
1132                    /* store frame into bframe buffer & swap ref back to current */
1133                    SWAP(FRAMEINFO *, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1134                    SWAP(FRAMEINFO *, pEnc->current, pEnc->reference);
1135    
1136                    pEnc->bframenum_tail++;
1137    
1138    // bframe report by koepi
1139                    pFrame->intra = 2;
1140                    pFrame->length = 0;
1141    
1142                    input_valid = 0;
1143                    goto bvop_loop;
1144            }
1145    
1146            BitstreamPadAlways(&bs);
1147            pFrame->length = BitstreamLength(&bs);
1148    
1149            if (pResult) {
1150                    pResult->quant = pEnc->current->quant;
1151                    pResult->hlength = pFrame->length - (pEnc->current->sStat.iTextBits / 8);
1152                    pResult->kblks = pEnc->current->sStat.kblks;
1153                    pResult->mblks = pEnc->current->sStat.mblks;
1154                    pResult->ublks = pEnc->current->sStat.ublks;
1155    
1156                    if (pFrame->general & XVID_EXTRASTATS)
1157                    {       pResult->sse_y =
1158                                    plane_sse( pEnc->sOriginal.y, pEnc->current->image.y,
1159                                                       pEnc->mbParam.edged_width, pEnc->mbParam.width,
1160                                                       pEnc->mbParam.height);
1161    
1162                            pResult->sse_u =
1163                                    plane_sse( pEnc->sOriginal.u, pEnc->current->image.u,
1164                                                       pEnc->mbParam.edged_width/2, pEnc->mbParam.width/2,
1165                                                       pEnc->mbParam.height/2);
1166    
1167                            pResult->sse_v =
1168                                    plane_sse( pEnc->sOriginal.v, pEnc->current->image.v,
1169                                                       pEnc->mbParam.edged_width/2, pEnc->mbParam.width/2,
1170                                                       pEnc->mbParam.height/2);
1171                    }
1172            }
1173    
1174            emms();
1175    
1176            if (pFrame->quant == 0) {
1177                    RateControlUpdate(&pEnc->rate_control, pEnc->current->quant,
1178                                                      pFrame->length, pFrame->intra);
1179            }
1180    
1181            stop_global_timer();
1182            write_timer();
1183    
1184            emms();
1185            return XVID_ERR_OK;
1186    }
1187    
1188    
1189    
1190    /*****************************************************************************
1191     * "original" IP frame encoder entry point
1192     *
1193     * Returned values :
1194     *    - XVID_ERR_OK     - no errors
1195     *    - XVID_ERR_FORMAT - the image subsystem reported the image had a wrong
1196     *                        format
1197     ****************************************************************************/
1198    
1199    int
1200    encoder_encode(Encoder * pEnc,
1201                               XVID_ENC_FRAME * pFrame,
1202                               XVID_ENC_STATS * pResult)
1203    {
1204            uint16_t x, y;
1205            Bitstream bs;
1206            uint32_t bits;
1207            uint16_t write_vol_header = 0;
1208    
1209            float psnr;
1210            uint8_t temp[128];
1211    
1212            start_global_timer();
1213    
1214            ENC_CHECK(pEnc);
1215            ENC_CHECK(pFrame);
1216            ENC_CHECK(pFrame->bitstream);
1217            ENC_CHECK(pFrame->image);
1218    
1219            SWAP(FRAMEINFO *, pEnc->current, pEnc->reference);
1220    
1221            pEnc->current->global_flags = pFrame->general;
1222            pEnc->current->motion_flags = pFrame->motion;
1223            pEnc->mbParam.hint = &pFrame->hint;
1224    
1225            inc_frame_num(pEnc);
1226    
1227            /* disable alternate scan flag if interlacing is not enabled */
1228            if ((pEnc->current->global_flags & XVID_ALTERNATESCAN) &&
1229                    !(pEnc->current->global_flags & XVID_INTERLACING))
1230            {
1231                    pEnc->current->global_flags -= XVID_ALTERNATESCAN;
1232            }
1233    
1234            start_timer();
1235            if (image_input
1236                    (&pEnc->current->image, pEnc->mbParam.width, pEnc->mbParam.height,
1237                     pEnc->mbParam.edged_width, pFrame->image, pFrame->stride, pFrame->colorspace, pFrame->general & XVID_INTERLACING) < 0)
1238                    return XVID_ERR_FORMAT;
1239            stop_conv_timer();
1240    
1241            if (pFrame->general & XVID_EXTRASTATS)
1242            {       image_copy(&pEnc->sOriginal, &pEnc->current->image,
1243                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1244            }
1245    
1246            emms();
1247    
1248            BitstreamInit(&bs, pFrame->bitstream, 0);
1249    
1250            if (pFrame->quant == 0) {
1251                    pEnc->current->quant = RateControlGetQ(&pEnc->rate_control, 0);
1252            } else {
1253                    pEnc->current->quant = pFrame->quant;
1254            }
1255    
1256            if ((pEnc->current->global_flags & XVID_QUARTERPEL))
1257                    pEnc->mbParam.m_quarterpel = 1;
1258            else
1259                    pEnc->mbParam.m_quarterpel = 0;
1260    
1261            if ((pEnc->current->global_flags & XVID_LUMIMASKING)) {
1262                    int *temp_dquants =
1263                            (int *) xvid_malloc(pEnc->mbParam.mb_width *
1264                                                                    pEnc->mbParam.mb_height * sizeof(int),
1265                                                                    CACHE_LINE);
1266    
1267                    pEnc->current->quant =
1268                            adaptive_quantization(pEnc->current->image.y,
1269                                                                      pEnc->mbParam.edged_width, temp_dquants,
1270                                                                      pEnc->current->quant, pEnc->current->quant,
1271                                                                      2 * pEnc->current->quant,
1272                                                                      pEnc->mbParam.mb_width,
1273                                                                      pEnc->mbParam.mb_height);
1274    
1275                    for (y = 0; y < pEnc->mbParam.mb_height; y++) {
1276    
1277    #define OFFSET(x,y) ((x) + (y)*pEnc->mbParam.mb_width)
1278    
1279                            for (x = 0; x < pEnc->mbParam.mb_width; x++) {
1280    
1281    
1282                                    MACROBLOCK *pMB = &pEnc->current->mbs[OFFSET(x, y)];
1283    
1284                                    pMB->dquant = iDQtab[temp_dquants[OFFSET(x, y)] + 2];
1285                            }
1286    
1287    #undef OFFSET
1288                    }
1289    
1290                    xvid_free(temp_dquants);
1291            }
1292    
1293            if (pEnc->current->global_flags & XVID_H263QUANT) {
1294                    if (pEnc->mbParam.m_quant_type != H263_QUANT)
1295                            write_vol_header = 1;
1296                    pEnc->mbParam.m_quant_type = H263_QUANT;
1297            } else if (pEnc->current->global_flags & XVID_MPEGQUANT) {
1298                    int matrix1_changed, matrix2_changed;
1299    
1300                    matrix1_changed = matrix2_changed = 0;
1301    
1302                    if (pEnc->mbParam.m_quant_type != MPEG4_QUANT)
1303                            write_vol_header = 1;
1304    
1305                    pEnc->mbParam.m_quant_type = MPEG4_QUANT;
1306    
1307                    if ((pEnc->current->global_flags & XVID_CUSTOM_QMATRIX) > 0) {
1308                            if (pFrame->quant_intra_matrix != NULL)
1309                                    matrix1_changed = set_intra_matrix(pFrame->quant_intra_matrix);
1310                            if (pFrame->quant_inter_matrix != NULL)
1311                                    matrix2_changed = set_inter_matrix(pFrame->quant_inter_matrix);
1312                    } else {
1313                            matrix1_changed = set_intra_matrix(get_default_intra_matrix());
1314                            matrix2_changed = set_inter_matrix(get_default_inter_matrix());
1315                    }
1316                    if (write_vol_header == 0)
1317                            write_vol_header = matrix1_changed | matrix2_changed;
1318            }
1319    
1320            if (pFrame->intra < 0) {
1321                    if ((pEnc->iFrameNum == -1)
1322                            || ((pEnc->mbParam.iMaxKeyInterval > 0)
1323                                    && (pEnc->iFrameNum >= pEnc->mbParam.iMaxKeyInterval))) {
1324                            pFrame->intra = FrameCodeI(pEnc, &bs, &bits);
1325                    } else {
1326                            pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 0, write_vol_header);
1327                    }
1328            } else {
1329                    if (pFrame->intra == 1) {
1330                            pFrame->intra = FrameCodeI(pEnc, &bs, &bits);
1331                    } else {
1332                            pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 1, write_vol_header);
1333                    }
1334    
1335            }
1336    
1337    //      BitstreamPutBits(&bs, 0xFFFF, 16);
1338    //      BitstreamPutBits(&bs, 0xFFFF, 16);
1339            BitstreamPadAlways(&bs);
1340            pFrame->length = BitstreamLength(&bs);
1341    
1342            if (pResult) {
1343                    pResult->quant = pEnc->current->quant;
1344                    pResult->hlength = pFrame->length - (pEnc->current->sStat.iTextBits / 8);
1345                    pResult->kblks = pEnc->current->sStat.kblks;
1346                    pResult->mblks = pEnc->current->sStat.mblks;
1347                    pResult->ublks = pEnc->current->sStat.ublks;
1348            }
1349    
1350            emms();
1351    
1352            if (pFrame->quant == 0) {
1353                    RateControlUpdate(&pEnc->rate_control, pEnc->current->quant,
1354                                                      pFrame->length, pFrame->intra);
1355            }
1356            if (pFrame->general & XVID_EXTRASTATS)
1357            {
1358                    psnr =
1359                            image_psnr(&pEnc->sOriginal, &pEnc->current->image,
1360                                               pEnc->mbParam.edged_width, pEnc->mbParam.width,
1361                                               pEnc->mbParam.height);
1362    
1363                    snprintf(temp, 127, "PSNR: %f\n", psnr);
1364            }
1365    
1366            pEnc->iFrameNum++;
1367    
1368            stop_global_timer();
1369            write_timer();
1370    
1371            return XVID_ERR_OK;
1372    }
1373    
1374    
1375    static __inline void
1376    CodeIntraMB(Encoder * pEnc,
1377                            MACROBLOCK * pMB)
1378    {
1379    
1380            pMB->mode = MODE_INTRA;
1381    
1382            /* zero mv statistics */
1383            pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = 0;
1384            pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = 0;
1385            pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = 0;
1386            pMB->sad16 = 0;
1387    
1388            if ((pEnc->current->global_flags & XVID_LUMIMASKING)) {
1389                    if (pMB->dquant != NO_CHANGE) {
1390                            pMB->mode = MODE_INTRA_Q;
1391                            pEnc->current->quant += DQtab[pMB->dquant];
1392    
1393                            if (pEnc->current->quant > 31)
1394                                    pEnc->current->quant = 31;
1395                            if (pEnc->current->quant < 1)
1396                                    pEnc->current->quant = 1;
1397                    }
1398            }
1399    
1400            pMB->quant = pEnc->current->quant;
1401    }
1402    
1403    
1404    #define FCODEBITS       3
1405    #define MODEBITS        5
1406    
1407    void
1408    HintedMESet(Encoder * pEnc,
1409                            int *intra)
1410    {
1411            HINTINFO *hint;
1412            Bitstream bs;
1413            int length, high;
1414            uint32_t x, y;
1415    
1416            hint = pEnc->mbParam.hint;
1417    
1418            if (hint->rawhints) {
1419                    *intra = hint->mvhint.intra;
1420            } else {
1421                    BitstreamInit(&bs, hint->hintstream, hint->hintlength);
1422                    *intra = BitstreamGetBit(&bs);
1423            }
1424    
1425            if (*intra) {
1426                    return;
1427            }
1428    
1429            pEnc->current->fcode =
1430                    (hint->rawhints) ? hint->mvhint.fcode : BitstreamGetBits(&bs,
1431                                                                                                                                     FCODEBITS);
1432    
1433            length = pEnc->current->fcode + 5;
1434            high = 1 << (length - 1);
1435    
1436            for (y = 0; y < pEnc->mbParam.mb_height; ++y) {
1437                    for (x = 0; x < pEnc->mbParam.mb_width; ++x) {
1438                            MACROBLOCK *pMB =
1439                                    &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];
1440                            MVBLOCKHINT *bhint =
1441                                    &hint->mvhint.block[x + y * pEnc->mbParam.mb_width];
1442                            VECTOR pred;
1443                            VECTOR tmp;
1444                            int vec;
1445    
1446                            pMB->mode =
1447                                    (hint->rawhints) ? bhint->mode : BitstreamGetBits(&bs,
1448                                                                                                                                      MODEBITS);
1449    
1450                            pMB->mode = (pMB->mode == MODE_INTER_Q) ? MODE_INTER : pMB->mode;
1451                            pMB->mode = (pMB->mode == MODE_INTRA_Q) ? MODE_INTRA : pMB->mode;
1452    
1453                            if (pMB->mode == MODE_INTER) {
1454                                    tmp.x =
1455                                            (hint->rawhints) ? bhint->mvs[0].x : BitstreamGetBits(&bs,
1456                                                                                                                                                      length);
1457                                    tmp.y =
1458                                            (hint->rawhints) ? bhint->mvs[0].y : BitstreamGetBits(&bs,
1459                                                                                                                                                      length);
1460                                    tmp.x -= (tmp.x >= high) ? high * 2 : 0;
1461                                    tmp.y -= (tmp.y >= high) ? high * 2 : 0;
1462    
1463                                    pred = get_pmv2(pEnc->current->mbs,pEnc->mbParam.mb_width,0,x,y,0);
1464    
1465                                    for (vec = 0; vec < 4; ++vec) {
1466                                            pMB->mvs[vec].x = tmp.x;
1467                                            pMB->mvs[vec].y = tmp.y;
1468                                            pMB->pmvs[vec].x = pMB->mvs[0].x - pred.x;
1469                                            pMB->pmvs[vec].y = pMB->mvs[0].y - pred.y;
1470                                    }
1471                            } else if (pMB->mode == MODE_INTER4V) {
1472                                    for (vec = 0; vec < 4; ++vec) {
1473                                            tmp.x =
1474                                                    (hint->rawhints) ? bhint->mvs[vec].
1475                                                    x : BitstreamGetBits(&bs, length);
1476                                            tmp.y =
1477                                                    (hint->rawhints) ? bhint->mvs[vec].
1478                                                    y : BitstreamGetBits(&bs, length);
1479                                            tmp.x -= (tmp.x >= high) ? high * 2 : 0;
1480                                            tmp.y -= (tmp.y >= high) ? high * 2 : 0;
1481    
1482                                            pred = get_pmv2(pEnc->current->mbs,pEnc->mbParam.mb_width,0,x,y,vec);
1483    
1484                                            pMB->mvs[vec].x = tmp.x;
1485                                            pMB->mvs[vec].y = tmp.y;
1486                                            pMB->pmvs[vec].x = pMB->mvs[vec].x - pred.x;
1487                                            pMB->pmvs[vec].y = pMB->mvs[vec].y - pred.y;
1488                                    }
1489                            } else                          // intra / stuffing / not_coded
1490                            {
1491                                    for (vec = 0; vec < 4; ++vec) {
1492                                            pMB->mvs[vec].x = pMB->mvs[vec].y = 0;
1493                                    }
1494                            }
1495    
1496                            if (pMB->mode == MODE_INTER4V &&
1497                                    (pEnc->current->global_flags & XVID_LUMIMASKING)
1498                                    && pMB->dquant != NO_CHANGE) {
1499                                    pMB->mode = MODE_INTRA;
1500    
1501                                    for (vec = 0; vec < 4; ++vec) {
1502                                            pMB->mvs[vec].x = pMB->mvs[vec].y = 0;
1503                                    }
1504                            }
1505                    }
1506            }
1507    }
1508    
1509    
1510    void
1511    HintedMEGet(Encoder * pEnc,
1512                            int intra)
1513    {
1514            HINTINFO *hint;
1515            Bitstream bs;
1516            uint32_t x, y;
1517            int length, high;
1518    
1519            hint = pEnc->mbParam.hint;
1520    
1521            if (hint->rawhints) {
1522                    hint->mvhint.intra = intra;
1523            } else {
1524                    BitstreamInit(&bs, hint->hintstream, 0);
1525                    BitstreamPutBit(&bs, intra);
1526            }
1527    
1528            if (intra) {
1529                    if (!hint->rawhints) {
1530                            BitstreamPadAlways(&bs);
1531                            hint->hintlength = BitstreamLength(&bs);
1532                    }
1533                    return;
1534            }
1535    
1536            length = pEnc->current->fcode + 5;
1537            high = 1 << (length - 1);
1538    
1539            if (hint->rawhints) {
1540                    hint->mvhint.fcode = pEnc->current->fcode;
1541            } else {
1542                    BitstreamPutBits(&bs, pEnc->current->fcode, FCODEBITS);
1543            }
1544    
1545            for (y = 0; y < pEnc->mbParam.mb_height; ++y) {
1546                    for (x = 0; x < pEnc->mbParam.mb_width; ++x) {
1547                            MACROBLOCK *pMB =
1548                                    &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];
1549                            MVBLOCKHINT *bhint =
1550                                    &hint->mvhint.block[x + y * pEnc->mbParam.mb_width];
1551                            VECTOR tmp;
1552    
1553                            if (hint->rawhints) {
1554                                    bhint->mode = pMB->mode;
1555                            } else {
1556                                    BitstreamPutBits(&bs, pMB->mode, MODEBITS);
1557                            }
1558    
1559                            if (pMB->mode == MODE_INTER || pMB->mode == MODE_INTER_Q) {
1560                                    tmp.x = pMB->mvs[0].x;
1561                                    tmp.y = pMB->mvs[0].y;
1562                                    tmp.x += (tmp.x < 0) ? high * 2 : 0;
1563                                    tmp.y += (tmp.y < 0) ? high * 2 : 0;
1564    
1565                                    if (hint->rawhints) {
1566                                            bhint->mvs[0].x = tmp.x;
1567                                            bhint->mvs[0].y = tmp.y;
1568                                    } else {
1569                                            BitstreamPutBits(&bs, tmp.x, length);
1570                                            BitstreamPutBits(&bs, tmp.y, length);
1571                                    }
1572                            } else if (pMB->mode == MODE_INTER4V) {
1573                                    int vec;
1574    
1575                                    for (vec = 0; vec < 4; ++vec) {
1576                                            tmp.x = pMB->mvs[vec].x;
1577                                            tmp.y = pMB->mvs[vec].y;
1578                                            tmp.x += (tmp.x < 0) ? high * 2 : 0;
1579                                            tmp.y += (tmp.y < 0) ? high * 2 : 0;
1580    
1581                                            if (hint->rawhints) {
1582                                                    bhint->mvs[vec].x = tmp.x;
1583                                                    bhint->mvs[vec].y = tmp.y;
1584                                            } else {
1585                                                    BitstreamPutBits(&bs, tmp.x, length);
1586                                                    BitstreamPutBits(&bs, tmp.y, length);
1587                                            }
1588                                    }
1589                            }
1590                    }
1591            }
1592    
1593            if (!hint->rawhints) {
1594                    BitstreamPad(&bs);
1595                    hint->hintlength = BitstreamLength(&bs);
1596            }
1597    }
1598    
1599    
1600    static int
1601    FrameCodeI(Encoder * pEnc,
1602                       Bitstream * bs,
1603                       uint32_t * pBits)
1604    {
1605            int mb_width = pEnc->mbParam.mb_width;
1606            int mb_height = pEnc->mbParam.mb_height;
1607    
1608            DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1609            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
1610    
1611            uint16_t x, y;
1612    
1613            if ((pEnc->current->global_flags & XVID_REDUCED))
1614            {
1615                    mb_width = (pEnc->mbParam.width + 31) / 32;
1616                    mb_height = (pEnc->mbParam.height + 31) / 32;
1617    
1618                    /* 16x16->8x8 downsample requires 1 additional edge pixel*/
1619                    /* XXX: setedges is overkill */
1620                    start_timer();
1621                    image_setedges(&pEnc->current->image,
1622                            pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
1623                            pEnc->mbParam.width, pEnc->mbParam.height);
1624                    stop_edges_timer();
1625            }
1626    
1627            pEnc->iFrameNum = 0;
1628            pEnc->mbParam.m_rounding_type = 1;
1629            pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;
1630            pEnc->current->quarterpel =  pEnc->mbParam.m_quarterpel;
1631            pEnc->current->coding_type = I_VOP;
1632    
1633            BitstreamWriteVolHeader(bs, &pEnc->mbParam, pEnc->current);
1634    
1635            set_timecodes(pEnc->current,pEnc->reference,pEnc->mbParam.fbase);
1636    
1637            BitstreamPadAlways(bs);
1638            BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current, 1);
1639    
1640            *pBits = BitstreamPos(bs);
1641    
1642            pEnc->current->sStat.iTextBits = 0;
1643            pEnc->current->sStat.kblks = mb_width * mb_height;
1644            pEnc->current->sStat.mblks = pEnc->current->sStat.ublks = 0;
1645    
1646            for (y = 0; y < mb_height; y++)
1647                    for (x = 0; x < mb_width; x++) {
1648                            MACROBLOCK *pMB =
1649                                    &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];
1650    
1651                            CodeIntraMB(pEnc, pMB);
1652    
1653                            MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y,
1654                                                              dct_codes, qcoeff);
1655    
1656                            start_timer();
1657                            MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);
1658                            stop_prediction_timer();
1659    
1660                            start_timer();
1661                            if (pEnc->current->global_flags & XVID_GREYSCALE)
1662                            {       pMB->cbp &= 0x3C;               /* keep only bits 5-2 */
1663                                    qcoeff[4*64+0]=0;               /* zero, because for INTRA MBs DC value is saved */
1664                                    qcoeff[5*64+0]=0;
1665                            }
1666                            MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1667                            stop_coding_timer();
1668                    }
1669    
1670            if ((pEnc->current->global_flags & XVID_REDUCED))
1671            {
1672                    image_deblock_rrv(&pEnc->current->image, pEnc->mbParam.edged_width,
1673                            pEnc->current->mbs, mb_width, mb_height, pEnc->mbParam.mb_width,
1674                            16, XVID_DEC_DEBLOCKY|XVID_DEC_DEBLOCKUV);
1675            }
1676            emms();
1677    
1678            *pBits = BitstreamPos(bs) - *pBits;
1679            pEnc->fMvPrevSigma = -1;
1680            pEnc->mbParam.m_fcode = 2;
1681    
1682            if (pEnc->current->global_flags & XVID_HINTEDME_GET) {
1683                    HintedMEGet(pEnc, 1);
1684            }
1685    
1686            return 1;                                       // intra
1687    }
1688    
1689    
1690    #define INTRA_THRESHOLD 0.5
1691    #define BFRAME_SKIP_THRESHHOLD 30
1692    
1693    
1694    /* FrameCodeP also handles S(GMC)-VOPs */
1695    static int
1696    FrameCodeP(Encoder * pEnc,
1697                       Bitstream * bs,
1698                       uint32_t * pBits,
1699                       bool force_inter,
1700                       bool vol_header)
1701    {
1702            float fSigma;
1703    
1704            DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1705            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
1706    
1707            int mb_width = pEnc->mbParam.mb_width;
1708            int mb_height = pEnc->mbParam.mb_height;
1709    
1710            int iLimit;
1711            int x, y, k;
1712            int iSearchRange;
1713            int bIntra, skip_possible;
1714    
1715            /* IMAGE *pCurrent = &pEnc->current->image; */
1716            IMAGE *pRef = &pEnc->reference->image;
1717    
1718            if ((pEnc->current->global_flags & XVID_REDUCED))
1719            {
1720                    mb_width = (pEnc->mbParam.width + 31) / 32;
1721                    mb_height = (pEnc->mbParam.height + 31) / 32;
1722            }
1723    
1724    
1725            start_timer();
1726            image_setedges(pRef, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
1727                                       pEnc->mbParam.width, pEnc->mbParam.height);
1728            stop_edges_timer();
1729    
1730            pEnc->mbParam.m_rounding_type = 1 - pEnc->mbParam.m_rounding_type;
1731            pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;
1732            pEnc->current->quarterpel =  pEnc->mbParam.m_quarterpel;
1733            pEnc->current->fcode = pEnc->mbParam.m_fcode;
1734    
1735            if (!force_inter)
1736                    iLimit = (int)(mb_width * mb_height *  INTRA_THRESHOLD);
1737            else
1738                    iLimit = mb_width * mb_height + 1;
1739    
1740            if ((pEnc->current->global_flags & XVID_HALFPEL)) {
1741                    start_timer();
1742                    image_interpolate(pRef, &pEnc->vInterH, &pEnc->vInterV,
1743                                                      &pEnc->vInterHV, pEnc->mbParam.edged_width,
1744                                                      pEnc->mbParam.edged_height,
1745                                                      pEnc->mbParam.m_quarterpel,
1746                                                      pEnc->current->rounding_type);
1747                    stop_inter_timer();
1748            }
1749    
1750            pEnc->current->coding_type = P_VOP;
1751    
1752            start_timer();
1753            if (pEnc->current->global_flags & XVID_HINTEDME_SET)
1754                    HintedMESet(pEnc, &bIntra);
1755            else
1756                    bIntra =
1757                            MotionEstimation(&pEnc->mbParam, pEnc->current, pEnc->reference,
1758                             &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,
1759                             iLimit);
1760    
1761            stop_motion_timer();
1762    
1763            if (bIntra == 1) return FrameCodeI(pEnc, bs, pBits);
1764    
1765            if ( ( pEnc->current->global_flags & XVID_GMC )
1766                    && ( (pEnc->current->warp.duv[1].x != 0) || (pEnc->current->warp.duv[1].y != 0) ) )
1767            {
1768                    pEnc->current->coding_type = S_VOP;
1769    
1770                    generate_GMCparameters( 2, 16, &pEnc->current->warp,
1771                                            pEnc->mbParam.width, pEnc->mbParam.height,
1772                                            &pEnc->current->gmc_data);
1773    
1774                    generate_GMCimage(&pEnc->current->gmc_data, &pEnc->reference->image,
1775                                    pEnc->mbParam.mb_width, pEnc->mbParam.mb_height,
1776                                    pEnc->mbParam.edged_width, pEnc->mbParam.edged_width/2,
1777                                    pEnc->mbParam.m_fcode, pEnc->mbParam.m_quarterpel, 0,
1778                                    pEnc->current->rounding_type, pEnc->current->mbs, &pEnc->vGMC);
1779    
1780            }
1781    
1782            set_timecodes(pEnc->current,pEnc->reference,pEnc->mbParam.fbase);
1783            if (vol_header)
1784            {       BitstreamWriteVolHeader(bs, &pEnc->mbParam, pEnc->current);
1785                    BitstreamPadAlways(bs);
1786            }
1787    
1788            BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current, 1);
1789    
1790            *pBits = BitstreamPos(bs);
1791    
1792            pEnc->current->sStat.iTextBits = pEnc->current->sStat.iMvSum = pEnc->current->sStat.iMvCount =
1793                    pEnc->current->sStat.kblks = pEnc->current->sStat.mblks = pEnc->current->sStat.ublks = 0;
1794    
1795    
1796            for (y = 0; y < mb_height; y++) {
1797                    for (x = 0; x < mb_width; x++) {
1798                            MACROBLOCK *pMB =
1799                                    &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];
1800    
1801    /* Mode decision: Check, if the block should be INTRA / INTER or GMC-coded */
1802    /* For a start, leave INTRA decision as is, only choose only between INTER/GMC  - gruel, 9.1.2002 */
1803    
1804                            bIntra = (pMB->mode == MODE_INTRA) || (pMB->mode == MODE_INTRA_Q);
1805    
1806                            if (bIntra) {
1807                                    CodeIntraMB(pEnc, pMB);
1808                                    MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y,
1809                                                                      dct_codes, qcoeff);
1810    
1811                                    start_timer();
1812                                    MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);
1813                                    stop_prediction_timer();
1814    
1815                                    pEnc->current->sStat.kblks++;
1816    
1817                                    MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1818                                    stop_coding_timer();
1819                                    continue;
1820                            }
1821    
1822                            if (pEnc->current->coding_type == S_VOP) {
1823    
1824                                    int32_t iSAD = sad16(pEnc->current->image.y + 16*y*pEnc->mbParam.edged_width + 16*x,
1825                                            pEnc->vGMC.y + 16*y*pEnc->mbParam.edged_width + 16*x,
1826                                            pEnc->mbParam.edged_width, 65536);
1827    
1828                                    if (pEnc->current->motion_flags & PMV_CHROMA16) {
1829                                            iSAD += sad8(pEnc->current->image.u + 8*y*(pEnc->mbParam.edged_width/2) + 8*x,
1830                                            pEnc->vGMC.u + 8*y*(pEnc->mbParam.edged_width/2) + 8*x, pEnc->mbParam.edged_width/2);
1831    
1832                                            iSAD += sad8(pEnc->current->image.v + 8*y*(pEnc->mbParam.edged_width/2) + 8*x,
1833                                            pEnc->vGMC.v + 8*y*(pEnc->mbParam.edged_width/2) + 8*x, pEnc->mbParam.edged_width/2);
1834                                    }
1835    
1836                                    if (iSAD <= pMB->sad16) {               /* mode decision GMC */
1837    
1838                                            if (pEnc->mbParam.m_quarterpel)
1839                                                    pMB->qmvs[0] = pMB->qmvs[1] = pMB->qmvs[2] = pMB->qmvs[3] = pMB->amv;
1840                                            else
1841                                                    pMB->mvs[0] = pMB->mvs[1] = pMB->mvs[2] = pMB->mvs[3] = pMB->amv;
1842    
1843                                            pMB->mode = MODE_INTER;
1844                                            pMB->mcsel = 1;
1845                                            pMB->sad16 = iSAD;
1846                                    } else {
1847                                            pMB->mcsel = 0;
1848                                    }
1849                            } else {
1850                                    pMB->mcsel = 0; /* just a precaution */
1851                            }
1852    
1853                            start_timer();
1854                            MBMotionCompensation(pMB, x, y, &pEnc->reference->image,
1855                                                                     &pEnc->vInterH, &pEnc->vInterV,
1856                                                                     &pEnc->vInterHV, &pEnc->vGMC,
1857                                                                     &pEnc->current->image,
1858                                                                     dct_codes, pEnc->mbParam.width,
1859                                                                     pEnc->mbParam.height,
1860                                                                     pEnc->mbParam.edged_width,
1861                                                                     pEnc->mbParam.m_quarterpel,
1862                                                                     (pEnc->current->global_flags & XVID_REDUCED),
1863                                                                     pEnc->current->rounding_type);
1864    
1865                            stop_comp_timer();
1866    
1867                            if ((pEnc->current->global_flags & XVID_LUMIMASKING)) {
1868                                    if (pMB->dquant != NO_CHANGE) {
1869                                            pMB->mode = MODE_INTER_Q;
1870                                            pEnc->current->quant += DQtab[pMB->dquant];
1871                                            if (pEnc->current->quant > 31)
1872                                                    pEnc->current->quant = 31;
1873                                            else if (pEnc->current->quant < 1)
1874                                                    pEnc->current->quant = 1;
1875                                    }
1876                            }
1877                            pMB->quant = pEnc->current->quant;
1878    
1879                            pMB->field_pred = 0;
1880    
1881                            if (pMB->mode != MODE_NOT_CODED)
1882                            {       pMB->cbp =
1883                                            MBTransQuantInter(&pEnc->mbParam, pEnc->current, pMB, x, y,
1884                                                                              dct_codes, qcoeff);
1885                            }
1886    
1887                            if (pMB->cbp || pMB->mvs[0].x || pMB->mvs[0].y ||
1888                                       pMB->mvs[1].x || pMB->mvs[1].y || pMB->mvs[2].x ||
1889                                       pMB->mvs[2].y || pMB->mvs[3].x || pMB->mvs[3].y) {
1890                                    pEnc->current->sStat.mblks++;
1891                            }  else {
1892                                    pEnc->current->sStat.ublks++;
1893                            }
1894    
1895                            start_timer();
1896    
1897                            /* Finished processing the MB, now check if to CODE or SKIP */
1898    
1899                            skip_possible = (pMB->cbp == 0) && (pMB->mode == MODE_INTER) &&
1900                                                            (pMB->dquant == NO_CHANGE);
1901    
1902                            if (pEnc->current->coding_type == S_VOP)
1903                                    skip_possible &= (pMB->mcsel == 1);
1904                            else if (pEnc->current->coding_type == P_VOP) {
1905                                    if (pEnc->mbParam.m_quarterpel)
1906                                            skip_possible &= ( (pMB->qmvs[0].x == 0) && (pMB->qmvs[0].y == 0) );
1907                                    else
1908                                            skip_possible &= ( (pMB->mvs[0].x == 0) && (pMB->mvs[0].y == 0) );
1909                            }
1910    
1911                            if ( (pMB->mode == MODE_NOT_CODED) || (skip_possible)) {
1912    
1913    /* This is a candidate for SKIPping, but for P-VOPs check intermediate B-frames first */
1914    
1915                                    if (pEnc->current->coding_type == P_VOP)        /* special rule for P-VOP's SKIP */
1916                                    {
1917                                            int bSkip = 1;
1918    
1919                                            for (k=pEnc->bframenum_head; k< pEnc->bframenum_tail; k++)
1920                                            {
1921                                                    int iSAD;
1922                                                    iSAD = sad16(pEnc->reference->image.y + 16*y*pEnc->mbParam.edged_width + 16*x,
1923                                                                            pEnc->bframes[k]->image.y + 16*y*pEnc->mbParam.edged_width + 16*x,
1924                                                                    pEnc->mbParam.edged_width,BFRAME_SKIP_THRESHHOLD);
1925                                                    if (iSAD >= BFRAME_SKIP_THRESHHOLD * pMB->quant)
1926                                                    {       bSkip = 0;
1927                                                            break;
1928                                                    }
1929                                            }
1930    
1931                                            if (!bSkip) {   /* no SKIP, but trivial block */
1932                                                    if(pEnc->mbParam.m_quarterpel) {
1933                                                            VECTOR predMV = get_qpmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, 0);
1934                                                            pMB->pmvs[0].x = - predMV.x;
1935                                                            pMB->pmvs[0].y = - predMV.y;
1936                                                    }
1937                                                    else {
1938                                                            VECTOR predMV = get_pmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, 0);
1939                                                            pMB->pmvs[0].x = - predMV.x;
1940                                                            pMB->pmvs[0].y = - predMV.y;
1941                                                    }
1942                                                    pMB->mode = MODE_INTER;
1943                                                    pMB->cbp = 0;
1944                                                    MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1945                                                    stop_coding_timer();
1946    
1947                                                    continue;       /* next MB */
1948                                            }
1949                                    }
1950                                    /* do SKIP */
1951    
1952                                    pMB->mode = MODE_NOT_CODED;
1953                                    MBSkip(bs);
1954                                    stop_coding_timer();
1955                                    continue;       /* next MB */
1956                            }
1957                            /* ordinary case: normal coded INTER/INTER4V block */
1958    
1959                            if (pEnc->current->global_flags & XVID_GREYSCALE)
1960                            {       pMB->cbp &= 0x3C;               /* keep only bits 5-2 */
1961                                    qcoeff[4*64+0]=0;               /* zero, because DC for INTRA MBs DC value is saved */
1962                                    qcoeff[5*64+0]=0;
1963                            }
1964    
1965                            if(pEnc->mbParam.m_quarterpel) {
1966                                    VECTOR predMV = get_qpmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, 0);
1967                                    pMB->pmvs[0].x = pMB->qmvs[0].x - predMV.x;
1968                                    pMB->pmvs[0].y = pMB->qmvs[0].y - predMV.y;
1969                                    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);
1970                            } else {
1971                                    VECTOR predMV = get_pmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, 0);
1972                                    pMB->pmvs[0].x = pMB->mvs[0].x - predMV.x;
1973                                    pMB->pmvs[0].y = pMB->mvs[0].y - predMV.y;
1974                                    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);
1975                            }
1976    
1977    
1978                            if (pMB->mode == MODE_INTER4V)
1979                            {       int k;
1980                                    for (k=1;k<4;k++)
1981                                    {
1982                                            if(pEnc->mbParam.m_quarterpel) {
1983                                                    VECTOR predMV = get_qpmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, k);
1984                                                    pMB->pmvs[k].x = pMB->qmvs[k].x - predMV.x;
1985                                                    pMB->pmvs[k].y = pMB->qmvs[k].y - predMV.y;
1986                                    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);
1987                                            } else {
1988                                                    VECTOR predMV = get_pmv2(pEnc->current->mbs, pEnc->mbParam.mb_width, 0, x, y, k);
1989                                                    pMB->pmvs[k].x = pMB->mvs[k].x - predMV.x;
1990                                                    pMB->pmvs[k].y = pMB->mvs[k].y - predMV.y;
1991                                    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);
1992                                            }
1993    
1994                                    }
1995                            }
1996    
1997                            MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->current->sStat);
1998                            stop_coding_timer();
1999    
2000                    }
2001            }
2002    
2003            if ((pEnc->current->global_flags & XVID_REDUCED))
2004            {
2005                    image_deblock_rrv(&pEnc->current->image, pEnc->mbParam.edged_width,
2006                            pEnc->current->mbs, mb_width, mb_height, pEnc->mbParam.mb_width,
2007                            16, XVID_DEC_DEBLOCKY|XVID_DEC_DEBLOCKUV);
2008            }
2009    
2010            emms();
2011    
2012            if (pEnc->current->global_flags & XVID_HINTEDME_GET) {
2013                    HintedMEGet(pEnc, 0);
2014            }
2015    
2016            if (pEnc->current->sStat.iMvCount == 0)
2017                    pEnc->current->sStat.iMvCount = 1;
2018    
2019            fSigma = (float) sqrt((float) pEnc->current->sStat.iMvSum / pEnc->current->sStat.iMvCount);
2020    
2021            iSearchRange = 1 << (3 + pEnc->mbParam.m_fcode);
2022    
2023            if ((fSigma > iSearchRange / 3)
2024                    && (pEnc->mbParam.m_fcode <= (3 + pEnc->mbParam.m_quarterpel))) // maximum search range 128
2025            {
2026                    pEnc->mbParam.m_fcode++;
2027                    iSearchRange *= 2;
2028            } else if ((fSigma < iSearchRange / 6)
2029                               && (pEnc->fMvPrevSigma >= 0)
2030                               && (pEnc->fMvPrevSigma < iSearchRange / 6)
2031                            && (pEnc->mbParam.m_fcode >= (2 + pEnc->mbParam.m_quarterpel))) // minimum search range 16
2032            {
2033                    pEnc->mbParam.m_fcode--;
2034                    iSearchRange /= 2;
2035            }
2036    
2037            pEnc->fMvPrevSigma = fSigma;
2038    
2039            /* frame drop code */
2040            DPRINTF(DPRINTF_DEBUG, "kmu %i %i %i", pEnc->current->sStat.kblks, pEnc->current->sStat.mblks, pEnc->current->sStat.ublks);
2041            if (pEnc->current->sStat.kblks + pEnc->current->sStat.mblks <
2042                    (pEnc->mbParam.frame_drop_ratio * mb_width * mb_height) / 100)
2043            {
2044                    pEnc->current->sStat.kblks = pEnc->current->sStat.mblks = 0;
2045                    pEnc->current->sStat.ublks = mb_width * mb_height;
2046    
2047                    BitstreamReset(bs);
2048    
2049                    set_timecodes(pEnc->current,pEnc->reference,pEnc->mbParam.fbase);
2050                    BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current, 0);
2051    
2052                    // copy reference frame details into the current frame
2053                    pEnc->current->quant = pEnc->reference->quant;
2054                    pEnc->current->motion_flags = pEnc->reference->motion_flags;
2055                    pEnc->current->rounding_type = pEnc->reference->rounding_type;
2056                    pEnc->current->quarterpel =  pEnc->reference->quarterpel;
2057                    pEnc->current->fcode = pEnc->reference->fcode;
2058                    pEnc->current->bcode = pEnc->reference->bcode;
2059                    image_copy(&pEnc->current->image, &pEnc->reference->image, pEnc->mbParam.edged_width, pEnc->mbParam.height);
2060                    memcpy(pEnc->current->mbs, pEnc->reference->mbs, sizeof(MACROBLOCK) * mb_width * mb_height);
2061            }
2062    
2063            /* XXX: debug
2064            {
2065                    char s[100];
2066                    sprintf(s, "\\%05i_cur.pgm", pEnc->m_framenum);
2067                    image_dump_yuvpgm(&pEnc->current->image,
2068                            pEnc->mbParam.edged_width,
2069                            pEnc->mbParam.width, pEnc->mbParam.height, s);
2070    
2071                    sprintf(s, "\\%05i_ref.pgm", pEnc->m_framenum);
2072                    image_dump_yuvpgm(&pEnc->reference->image,
2073                            pEnc->mbParam.edged_width,
2074                            pEnc->mbParam.width, pEnc->mbParam.height, s);
2075            }
2076            */
2077    
2078    
2079            *pBits = BitstreamPos(bs) - *pBits;
2080    
2081            return 0;                                       // inter
2082    }
2083    
2084    
2085    static void
2086    FrameCodeB(Encoder * pEnc,
2087                       FRAMEINFO * frame,
2088                       Bitstream * bs,
2089                       uint32_t * pBits)
2090    {
2091            DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
2092            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
2093            uint32_t x, y;
2094    
2095            IMAGE *f_ref = &pEnc->reference->image;
2096            IMAGE *b_ref = &pEnc->current->image;
2097    
2098    #ifdef BFRAMES_DEC_DEBUG
2099            FILE *fp;
2100            static char first=0;
2101    #define BFRAME_DEBUG    if (!first && fp){ \
2102                    fprintf(fp,"Y=%3d   X=%3d   MB=%2d   CBP=%02X\n",y,x,mb->mode,mb->cbp); \
2103            }
2104    
2105            pEnc->current->global_flags &= ~XVID_REDUCED;   /* reduced resoltion not yet supported */
2106    
2107            if (!first){
2108                    fp=fopen("C:\\XVIDDBGE.TXT","w");
2109            }
2110    #endif
2111    
2112            frame->quarterpel =  pEnc->mbParam.m_quarterpel;
2113    
2114            // forward
2115            image_setedges(f_ref, pEnc->mbParam.edged_width,
2116                                       pEnc->mbParam.edged_height, pEnc->mbParam.width,
2117                                       pEnc->mbParam.height);
2118            start_timer();
2119            image_interpolate(f_ref, &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,
2120                                              pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
2121                                              pEnc->mbParam.m_quarterpel, 0);
2122            stop_inter_timer();
2123    
2124            // backward
2125            image_setedges(b_ref, pEnc->mbParam.edged_width,
2126                                       pEnc->mbParam.edged_height, pEnc->mbParam.width,
2127                                       pEnc->mbParam.height);
2128            start_timer();
2129            image_interpolate(b_ref, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,
2130                                              pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
2131                                              pEnc->mbParam.m_quarterpel, 0);
2132            stop_inter_timer();
2133    
2134            start_timer();
2135    
2136            MotionEstimationBVOP(&pEnc->mbParam, frame,
2137                    ((int32_t)(pEnc->current->stamp - frame->stamp)),                               // time_bp
2138                    ((int32_t)(pEnc->current->stamp - pEnc->reference->stamp)),     // time_pp
2139                            pEnc->reference->mbs, f_ref,
2140                                                     &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,
2141                                                     pEnc->current, b_ref, &pEnc->vInterH,
2142                                                     &pEnc->vInterV, &pEnc->vInterHV);
2143    
2144    
2145            stop_motion_timer();
2146    
2147            /*if (test_quant_type(&pEnc->mbParam, pEnc->current))
2148               {
2149               BitstreamWriteVolHeader(bs, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.quant_type);
2150               } */
2151    
2152            frame->coding_type = B_VOP;
2153    
2154            set_timecodes(frame, pEnc->reference,pEnc->mbParam.fbase);
2155            BitstreamWriteVopHeader(bs, &pEnc->mbParam, frame, 1);
2156    
2157            *pBits = BitstreamPos(bs);
2158    
2159            frame->sStat.iTextBits = 0;
2160            frame->sStat.iMvSum = 0;
2161            frame->sStat.iMvCount = 0;
2162            frame->sStat.kblks = frame->sStat.mblks = frame->sStat.ublks = 0;
2163    
2164    
2165            for (y = 0; y < pEnc->mbParam.mb_height; y++) {
2166                    for (x = 0; x < pEnc->mbParam.mb_width; x++) {
2167                            MACROBLOCK * const mb = &frame->mbs[x + y * pEnc->mbParam.mb_width];
2168                            int direction = pEnc->mbParam.global & XVID_ALTERNATESCAN ? 2 : 0;
2169    
2170                            // decoder ignores mb when refence block is INTER(0,0), CBP=0
2171                            if (mb->mode == MODE_NOT_CODED) {
2172                                    //mb->mvs[0].x = mb->mvs[0].y = mb->cbp = 0;
2173                                    continue;
2174                            }
2175    
2176                            if (mb->mode != MODE_DIRECT_NONE_MV) {
2177                                    MBMotionCompensationBVOP(&pEnc->mbParam, mb, x, y, &frame->image,
2178                                                                             f_ref, &pEnc->f_refh, &pEnc->f_refv,
2179                                                                             &pEnc->f_refhv, b_ref, &pEnc->vInterH,
2180                                                                             &pEnc->vInterV, &pEnc->vInterHV,
2181                                                                             dct_codes);
2182    
2183                                    if (mb->mode == MODE_DIRECT_NO4V) mb->mode = MODE_DIRECT;
2184                                    mb->quant = frame->quant;
2185    
2186                                    mb->cbp =
2187                                            MBTransQuantInterBVOP(&pEnc->mbParam, frame, mb, dct_codes, qcoeff);
2188    
2189                                    if ( (mb->mode == MODE_DIRECT) && (mb->cbp == 0)
2190                                            && (mb->pmvs[3].x == 0) && (mb->pmvs[3].y == 0) ) {
2191                                            mb->mode = MODE_DIRECT_NONE_MV; // skipped
2192                                    }
2193                            }
2194    
2195    #ifdef BFRAMES_DEC_DEBUG
2196            BFRAME_DEBUG
2197    #endif
2198                            start_timer();
2199                            MBCodingBVOP(mb, qcoeff, frame->fcode, frame->bcode, bs,
2200                                                     &frame->sStat, direction);
2201                            stop_coding_timer();
2202                    }
2203            }
2204    
2205            emms();
2206    
2207            // TODO: dynamic fcode/bcode ???
2208    
2209            *pBits = BitstreamPos(bs) - *pBits;
2210    
2211    #ifdef BFRAMES_DEC_DEBUG
2212            if (!first){
2213                    first=1;
2214                    if (fp)
2215                            fclose(fp);
2216            }
2217    #endif
2218  }  }

Legend:
Removed from v.1.12  
changed lines
  Added in v.1.91

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