[svn] / branches / dev-api-3 / xvidcore / src / encoder.c Repository:
ViewVC logotype

Diff of /branches/dev-api-3/xvidcore/src/encoder.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.136  
changed lines
  Added in v.709

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