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

Legend:
Removed from v.1.23  
changed lines
  Added in v.1.76.2.37

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