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

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.76.2.38

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