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

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

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