[cvs] / xvidcore / src / encoder.c Repository:
ViewVC logotype

Diff of /xvidcore/src/encoder.c

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

revision 1.32, Wed May 1 13:00:01 2002 UTC revision 1.137, Wed Dec 29 22:39:35 2010 UTC
# Line 1  Line 1 
1  /**************************************************************************  /*****************************************************************************
2   *   *
3   *  XVID MPEG-4 VIDEO CODEC   *  XVID MPEG-4 VIDEO CODEC
4   *  -  Encoder main module  -   *  -  Encoder main module  -
5   *   *
6   *  This program is an implementation of a part of one or more MPEG-4   *  Copyright(C) 2002-2010 Michael Militzer <isibaar@xvid.org>
7   *  Video tools as specified in ISO/IEC 14496-2 standard.  Those intending   *               2002-2003 Peter Ross <pross@xvid.org>
8   *  to use this software module in hardware or software products are   *               2002      Daniel Smith <danielsmith@astroboymail.com>
  *  advised that its use may infringe existing patents or copyrights, and  
  *  any such use would be at such party's own risk.  The original  
  *  developer of this software module and his/her company, and subsequent  
  *  editors and their companies, will have no liability for use of this  
  *  software or modifications or derivatives thereof.  
9   *   *
10   *  This program is free software; you can redistribute it and/or modify   *  This program is free software; you can redistribute it and/or modify
11   *  it under the terms of the GNU General Public License as published by   *  it under the terms of the GNU General Public License as published by
# Line 26  Line 21 
21   *  along with this program; if not, write to the Free Software   *  along with this program; if not, write to the Free Software
22   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
23   *   *
  ***************************************************************************/  
   
 /****************************************************************************  
  *  
  *  History  
  *  
  *  14.04.2002 added FrameCodeB()  
  *  
24   *  $Id$   *  $Id$
25   *   *
26   ***************************************************************************/   ****************************************************************************/
27    
28  #include <stdlib.h>  #include <stdlib.h>
29  #include <stdio.h>  #include <stdio.h>
30  #include <math.h>  #include <math.h>
31    #include <string.h>
32    
33  #include "encoder.h"  #include "encoder.h"
34  #include "prediction/mbprediction.h"  #include "prediction/mbprediction.h"
35  #include "global.h"  #include "global.h"
36  #include "utils/timer.h"  #include "utils/timer.h"
37  #include "image/image.h"  #include "image/image.h"
38    #include "image/font.h"
39    #include "motion/sad.h"
40  #include "motion/motion.h"  #include "motion/motion.h"
41    #include "motion/gmc.h"
42    
43  #include "bitstream/cbp.h"  #include "bitstream/cbp.h"
44  #include "utils/mbfunctions.h"  #include "utils/mbfunctions.h"
45  #include "bitstream/bitstream.h"  #include "bitstream/bitstream.h"
46  #include "bitstream/mbcoding.h"  #include "bitstream/mbcoding.h"
 #include "utils/ratecontrol.h"  
47  #include "utils/emms.h"  #include "utils/emms.h"
48  #include "bitstream/mbcoding.h"  #include "bitstream/mbcoding.h"
 #include "quant/adapt_quant.h"  
49  #include "quant/quant_matrix.h"  #include "quant/quant_matrix.h"
50  #include "utils/mem_align.h"  #include "utils/mem_align.h"
51    
52  #define ENC_CHECK(X) if(!(X)) return XVID_ERR_FORMAT  # include "motion/motion_smp.h"
 #define SWAP(A,B)    { void * tmp = A; A = B; B = tmp; }  
53    
54    
55  static int FrameCodeI(Encoder * pEnc, Bitstream * bs, uint32_t *pBits);  /*****************************************************************************
56  static int FrameCodeP(Encoder * pEnc, Bitstream * bs, uint32_t *pBits, bool force_inter, bool vol_header);   * Local function prototypes
57  static void FrameCodeB(Encoder * pEnc, FRAMEINFO * frame, Bitstream * bs, uint32_t *pBits);   ****************************************************************************/
58    
59  static int DQtab[4] =  static int FrameCodeI(Encoder * pEnc,
60  {                                            Bitstream * bs);
         -1, -2, 1, 2  
 };  
61    
62  static int iDQtab[5] =  static int FrameCodeP(Encoder * pEnc,
63  {                                            Bitstream * bs);
         1, 0, NO_CHANGE, 2, 3  
 };  
64    
65    static void FrameCodeB(Encoder * pEnc,
66                                               FRAMEINFO * frame,
67                                               Bitstream * bs);
68    
 void static image_null(IMAGE * image)  
 {  
         image->y = image->u = image->v = NULL;  
 }  
69    
70    /*****************************************************************************
71     * Encoder creation
72     *
73     * This function creates an Encoder instance, it allocates all necessary
74     * image buffers (reference, current and bframes) and initialize the internal
75     * xvid encoder paremeters according to the XVID_ENC_PARAM input parameter.
76     *
77     * The code seems to be very long but is very basic, mainly memory allocation
78     * and cleaning code.
79     *
80     * Returned values :
81     *      - 0                             - no errors
82     *      - XVID_ERR_MEMORY - the libc could not allocate memory, the function
83     *                                              cleans the structure before exiting.
84     *                                              pParam->handle is also set to NULL.
85     *
86     ****************************************************************************/
87    
88  int encoder_create(XVID_ENC_PARAM * pParam)  /*
89     * Simplify the "fincr/fbase" fraction
90    */
91    static int
92    gcd(int a, int b)
93  {  {
94          Encoder *pEnc;          int r ;
         uint32_t i;  
   
         pParam->handle = NULL;  
   
         ENC_CHECK(pParam);  
95    
96          ENC_CHECK(pParam->width > 0 && pParam->width <= 1920);          if (b > a) {
97          ENC_CHECK(pParam->height > 0 && pParam->height <= 1280);                  r = a;
98          ENC_CHECK(!(pParam->width % 2));                  a = b;
99          ENC_CHECK(!(pParam->height % 2));                  b = r;
   
         if (pParam->fincr <= 0 || pParam->fbase <= 0)  
         {  
                 pParam->fincr = 1;  
                 pParam->fbase = 25;  
100          }          }
101    
102          // simplify the "fincr/fbase" fraction          while ((r = a % b)) {
103          // (neccessary, since windows supplies us with huge numbers)                  a = b;
104                    b = r;
         i = pParam->fincr;  
         while (i > 1)  
         {  
                 if (pParam->fincr % i == 0 && pParam->fbase % i == 0)  
                 {  
                         pParam->fincr /= i;  
                         pParam->fbase /= i;  
                         i = pParam->fincr;  
                         continue;  
105                  }                  }
106                  i--;          return b;
107          }          }
108    
109          if (pParam->fbase > 65535)  static void
110    simplify_time(int *inc, int *base)
111          {          {
112                  float div = (float)pParam->fbase / 65535;          /* common factor */
113                  pParam->fbase = (int)(pParam->fbase / div);          const int s = gcd(*inc, *base);
114                  pParam->fincr = (int)(pParam->fincr / div);    *inc  /= s;
115          }    *base /= s;
116    
117            if (*base > 65535 || *inc > 65535) {
118                    int *biggest;
119                    int *other;
120                    float div;
121    
122          if (pParam->rc_bitrate <= 0)                  if (*base > *inc) {
123                  pParam->rc_bitrate = 900000;                          biggest = base;
124                            other = inc;
125                    } else {
126                            biggest = inc;
127                            other = base;
128                    }
129    
130          if (pParam->rc_reaction_delay_factor <= 0)                  div = ((float)*biggest)/((float)65535);
131                  pParam->rc_reaction_delay_factor = 16;                  *biggest = (unsigned int)(((float)*biggest)/div);
132                    *other = (unsigned int)(((float)*other)/div);
133            }
134    }
135    
         if (pParam->rc_averaging_period <= 0)  
                 pParam->rc_averaging_period = 100;  
136    
137          if (pParam->rc_buffer <= 0)  int
138                  pParam->rc_buffer = 100;  enc_create(xvid_enc_create_t * create)
139    {
140            Encoder *pEnc;
141            int n;
142    
143          if ((pParam->min_quantizer <= 0) || (pParam->min_quantizer > 31))          if (XVID_VERSION_MAJOR(create->version) != 1) /* v1.x.x */
144                  pParam->min_quantizer = 1;                  return XVID_ERR_VERSION;
145    
146          if ((pParam->max_quantizer <= 0) || (pParam->max_quantizer > 31))          if (create->width%2 || create->height%2)
147                  pParam->max_quantizer = 31;                  return XVID_ERR_FAIL;
148    
149          if (pParam->max_key_interval == 0)              /* 1 keyframe each 10 seconds */          if (create->width<=0 || create->height<=0)
150                  pParam->max_key_interval = 10 * pParam->fincr / pParam->fbase;                  return XVID_ERR_FAIL;
151    
152          if (pParam->max_quantizer < pParam->min_quantizer)          /* allocate encoder struct */
                 pParam->max_quantizer = pParam->min_quantizer;  
153    
154          if ((pEnc = (Encoder *) xvid_malloc(sizeof(Encoder), CACHE_LINE)) == NULL)          pEnc = (Encoder *) xvid_malloc(sizeof(Encoder), CACHE_LINE);
155            if (pEnc == NULL)
156                  return XVID_ERR_MEMORY;                  return XVID_ERR_MEMORY;
157            memset(pEnc, 0, sizeof(Encoder));
158    
159          /* Fill members of Encoder structure */          pEnc->mbParam.profile = create->profile;
   
         pEnc->mbParam.width = pParam->width;  
         pEnc->mbParam.height = pParam->height;  
160    
161            /* global flags */
162            pEnc->mbParam.global_flags = create->global;
163      if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED))
164        pEnc->mbParam.global_flags |= XVID_GLOBAL_DIVX5_USERDATA;
165    
166            /* width, height */
167            pEnc->mbParam.width = create->width;
168            pEnc->mbParam.height = create->height;
169          pEnc->mbParam.mb_width = (pEnc->mbParam.width + 15) / 16;          pEnc->mbParam.mb_width = (pEnc->mbParam.width + 15) / 16;
170          pEnc->mbParam.mb_height = (pEnc->mbParam.height + 15) / 16;          pEnc->mbParam.mb_height = (pEnc->mbParam.height + 15) / 16;
   
171          pEnc->mbParam.edged_width = 16 * pEnc->mbParam.mb_width + 2 * EDGE_SIZE;          pEnc->mbParam.edged_width = 16 * pEnc->mbParam.mb_width + 2 * EDGE_SIZE;
172          pEnc->mbParam.edged_height = 16 * pEnc->mbParam.mb_height + 2 * EDGE_SIZE;          pEnc->mbParam.edged_height = 16 * pEnc->mbParam.mb_height + 2 * EDGE_SIZE;
173    
174          pEnc->mbParam.fbase = pParam->fbase;          /* framerate */
175          pEnc->mbParam.fincr = pParam->fincr;          pEnc->mbParam.fincr = MAX(create->fincr, 0);
176            pEnc->mbParam.fbase = create->fincr <= 0 ? 25 : create->fbase;
177            if (pEnc->mbParam.fincr>0)
178                    simplify_time((int*)&pEnc->mbParam.fincr, (int*)&pEnc->mbParam.fbase);
179    
180          pEnc->sStat.fMvPrevSigma = -1;          /* zones */
181            if(create->num_zones > 0) {
182                    pEnc->num_zones = create->num_zones;
183                    pEnc->zones = xvid_malloc(sizeof(xvid_enc_zone_t) * pEnc->num_zones, CACHE_LINE);
184                    if (pEnc->zones == NULL)
185                            goto xvid_err_memory0;
186                    memcpy(pEnc->zones, create->zones, sizeof(xvid_enc_zone_t) * pEnc->num_zones);
187            } else {
188                    pEnc->num_zones = 0;
189                    pEnc->zones = NULL;
190            }
191    
192          /* Fill rate control parameters */          /* plugins */
193            if(create->num_plugins > 0) {
194                    pEnc->num_plugins = create->num_plugins;
195                    pEnc->plugins = xvid_malloc(sizeof(xvid_enc_plugin_t) * pEnc->num_plugins, CACHE_LINE);
196                    if (pEnc->plugins == NULL)
197                            goto xvid_err_memory0;
198            } else {
199                    pEnc->num_plugins = 0;
200                    pEnc->plugins = NULL;
201            }
202    
203          pEnc->bitrate = pParam->rc_bitrate;          for (n=0; n<pEnc->num_plugins;n++) {
204                    xvid_plg_create_t pcreate;
205                    xvid_plg_info_t pinfo;
206    
207          pEnc->iFrameNum = 0;                  memset(&pinfo, 0, sizeof(xvid_plg_info_t));
208          pEnc->iMaxKeyInterval = pParam->max_key_interval;                  pinfo.version = XVID_VERSION;
209                    if (create->plugins[n].func(NULL, XVID_PLG_INFO, &pinfo, NULL) >= 0) {
210                            pEnc->mbParam.plugin_flags |= pinfo.flags;
211                    }
212    
213          /* try to allocate frame memory */                  memset(&pcreate, 0, sizeof(xvid_plg_create_t));
214                    pcreate.version = XVID_VERSION;
215                    pcreate.num_zones = pEnc->num_zones;
216                    pcreate.zones = pEnc->zones;
217                    pcreate.width = pEnc->mbParam.width;
218                    pcreate.height = pEnc->mbParam.height;
219                    pcreate.mb_width = pEnc->mbParam.mb_width;
220                    pcreate.mb_height = pEnc->mbParam.mb_height;
221                    pcreate.fincr = pEnc->mbParam.fincr;
222                    pcreate.fbase = pEnc->mbParam.fbase;
223                    pcreate.param = create->plugins[n].param;
224    
225          pEnc->current = NULL;                  pEnc->plugins[n].func = NULL;   /* disable plugins that fail */
226          pEnc->reference = NULL;                  if (create->plugins[n].func(NULL, XVID_PLG_CREATE, &pcreate, &pEnc->plugins[n].param) >= 0) {
227          if ( (pEnc->current = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE)) == NULL ||                          pEnc->plugins[n].func = create->plugins[n].func;
228                   (pEnc->reference = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE)) == NULL)                  }
         {  
                 if (pEnc->current) xvid_free(pEnc->current);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
229          }          }
230    
231          /* try to allocate mb memory */          if ((pEnc->mbParam.global_flags & XVID_GLOBAL_EXTRASTATS_ENABLE) ||
232                    (pEnc->mbParam.plugin_flags & XVID_REQPSNR)) {
233                    pEnc->mbParam.plugin_flags |= XVID_REQORIGINAL; /* psnr calculation requires the original */
234            }
235    
236          pEnc->current->mbs = NULL;          /* temp dquants */
237          pEnc->reference->mbs = NULL;          if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
238                    pEnc->temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width *
239                                                    pEnc->mbParam.mb_height * sizeof(int), CACHE_LINE);
240                    if (pEnc->temp_dquants==NULL)
241                            goto xvid_err_memory1a;
242            }
243    
244          if ((pEnc->current->mbs = xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width * pEnc->mbParam.mb_height, CACHE_LINE)) == NULL ||          /* temp lambdas */
245                  (pEnc->reference->mbs = xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width * pEnc->mbParam.mb_height, CACHE_LINE)) == NULL)          if (pEnc->mbParam.plugin_flags & XVID_REQLAMBDA) {
246          {                  pEnc->temp_lambda = (float *) xvid_malloc(pEnc->mbParam.mb_width *
247                  if (pEnc->current->mbs) xvid_free(pEnc->current->mbs);                                                  pEnc->mbParam.mb_height * 6 * sizeof(float), CACHE_LINE);
248                  xvid_free(pEnc->current);                  if (pEnc->temp_lambda == NULL)
249                  xvid_free(pEnc->reference);                          goto xvid_err_memory1a;
250                  xvid_free(pEnc);          }
251    
252            /* bframes */
253            pEnc->mbParam.max_bframes = MAX(create->max_bframes, 0);
254            pEnc->mbParam.bquant_ratio = MAX(create->bquant_ratio, 0);
255            pEnc->mbParam.bquant_offset = create->bquant_offset;
256    
257            /* min/max quant */
258            for (n=0; n<3; n++) {
259                    pEnc->mbParam.min_quant[n] = create->min_quant[n] > 0 ? create->min_quant[n] : 2;
260                    pEnc->mbParam.max_quant[n] = create->max_quant[n] > 0 ? create->max_quant[n] : 31;
261          }          }
262    
263          /* try to allocate image memory */          /* frame drop ratio */
264            pEnc->mbParam.frame_drop_ratio = MAX(create->frame_drop_ratio, 0);
265    
266            /* max keyframe interval */
267            pEnc->mbParam.iMaxKeyInterval = create->max_key_interval <= 0 ? (10 * (int)pEnc->mbParam.fbase) / (int)pEnc->mbParam.fincr : create->max_key_interval;
268    
269            /* allocate working frame-image memory */
270    
271            pEnc->current = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
272            pEnc->reference = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
273    
274            if (pEnc->current == NULL || pEnc->reference == NULL)
275                    goto xvid_err_memory1;
276    
277            /* allocate macroblock memory */
278    
279            pEnc->current->mbs =
280                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
281                                            pEnc->mbParam.mb_height, CACHE_LINE);
282            pEnc->reference->mbs =
283                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
284                                            pEnc->mbParam.mb_height, CACHE_LINE);
285    
286            if (pEnc->current->mbs == NULL || pEnc->reference->mbs == NULL)
287                    goto xvid_err_memory2;
288    
289  #ifdef _DEBUG          /* allocate quant matrix memory */
290    
291            pEnc->mbParam.mpeg_quant_matrices =
292                    xvid_malloc(sizeof(uint16_t) * 64 * 8, CACHE_LINE);
293    
294            if (pEnc->mbParam.mpeg_quant_matrices == NULL)
295                    goto xvid_err_memory2a;
296    
297            /* allocate interpolation image memory */
298    
299            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
300          image_null(&pEnc->sOriginal);          image_null(&pEnc->sOriginal);
301  #endif                  image_null(&pEnc->sOriginal2);
302  #ifdef BFRAMES          }
303    
304          image_null(&pEnc->f_refh);          image_null(&pEnc->f_refh);
305          image_null(&pEnc->f_refv);          image_null(&pEnc->f_refv);
306          image_null(&pEnc->f_refhv);          image_null(&pEnc->f_refhv);
307  #endif  
308          image_null(&pEnc->current->image);          image_null(&pEnc->current->image);
309          image_null(&pEnc->reference->image);          image_null(&pEnc->reference->image);
310          image_null(&pEnc->vInterH);          image_null(&pEnc->vInterH);
311          image_null(&pEnc->vInterV);          image_null(&pEnc->vInterV);
         image_null(&pEnc->vInterVf);  
312          image_null(&pEnc->vInterHV);          image_null(&pEnc->vInterHV);
         image_null(&pEnc->vInterHVf);  
313    
314          if (          if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
315  #ifdef _DEBUG                  if (image_create
316                  image_create(&pEnc->sOriginal, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||                          (&pEnc->sOriginal, pEnc->mbParam.edged_width,
317  #endif                           pEnc->mbParam.edged_height) < 0)
318  #ifdef BFRAMES                          goto xvid_err_memory3;
319                  image_create(&pEnc->f_refh, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
320                  image_create(&pEnc->f_refv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||                  if (image_create
321                  image_create(&pEnc->f_refhv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||                          (&pEnc->sOriginal2, pEnc->mbParam.edged_width,
322  #endif                           pEnc->mbParam.edged_height) < 0)
323                  image_create(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||                          goto xvid_err_memory3;
324                  image_create(&pEnc->reference->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||          }
325                  image_create(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||  
326                  image_create(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||          if (image_create
327                  image_create(&pEnc->vInterVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||                  (&pEnc->f_refh, pEnc->mbParam.edged_width,
328                  image_create(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0 ||                   pEnc->mbParam.edged_height) < 0)
329                  image_create(&pEnc->vInterHVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)                  goto xvid_err_memory3;
330          {          if (image_create
331  #ifdef _DEBUG                  (&pEnc->f_refv, pEnc->mbParam.edged_width,
332                  image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                   pEnc->mbParam.edged_height) < 0)
333  #endif                  goto xvid_err_memory3;
334  #ifdef BFRAMES          if (image_create
335                  image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                  (&pEnc->f_refhv, pEnc->mbParam.edged_width,
336                  image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                   pEnc->mbParam.edged_height) < 0)
337                  image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                  goto xvid_err_memory3;
338  #endif  
339                  image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);          if (image_create
340                  image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                  (&pEnc->current->image, pEnc->mbParam.edged_width,
341                  image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                   pEnc->mbParam.edged_height) < 0)
342                  image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                  goto xvid_err_memory3;
343                  image_destroy(&pEnc->vInterVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);          if (image_create
344                  image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                  (&pEnc->reference->image, pEnc->mbParam.edged_width,
345                  image_destroy(&pEnc->vInterHVf, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);                   pEnc->mbParam.edged_height) < 0)
346                    goto xvid_err_memory3;
347            if (image_create
348                    (&pEnc->vInterH, pEnc->mbParam.edged_width,
349                     pEnc->mbParam.edged_height) < 0)
350                    goto xvid_err_memory3;
351            if (image_create
352                    (&pEnc->vInterV, pEnc->mbParam.edged_width,
353                     pEnc->mbParam.edged_height) < 0)
354                    goto xvid_err_memory3;
355            if (image_create
356                    (&pEnc->vInterHV, pEnc->mbParam.edged_width,
357                     pEnc->mbParam.edged_height) < 0)
358                    goto xvid_err_memory3;
359    
360    /* Create full bitplane for GMC, this might be wasteful */
361            if (image_create
362                    (&pEnc->vGMC, pEnc->mbParam.edged_width,
363                     pEnc->mbParam.edged_height) < 0)
364                    goto xvid_err_memory3;
365    
366                  xvid_free(pEnc->current);          /* init bframe image buffers */
                 xvid_free(pEnc->reference);  
                 xvid_free(pEnc);  
                 return XVID_ERR_MEMORY;  
         }  
367    
368  // ==============================================================================          pEnc->bframenum_head = 0;
369  #ifdef BFRAMES          pEnc->bframenum_tail = 0;
370            pEnc->flush_bframes = 0;
371            pEnc->closed_bframenum = -1;
372    
373          // TODO: handle malloc() == NULL          /* B Frames specific init */
374          pEnc->max_bframes = pParam->max_bframes;          pEnc->bframes = NULL;
         pEnc->bquant_ratio = pParam->bquant_ratio;  
         if (pEnc->max_bframes > 0)  
         {  
                 int n;  
375    
376                  pEnc->bframes = malloc(pEnc->max_bframes * sizeof(FRAMEINFO *));          if (pEnc->mbParam.max_bframes > 0) {
377    
378                  for (n = 0; n < pEnc->max_bframes; n++)                  pEnc->bframes =
379                  {                          xvid_malloc(pEnc->mbParam.max_bframes * sizeof(FRAMEINFO *),
380                          pEnc->bframes[n] = malloc(sizeof(FRAMEINFO));                                                  CACHE_LINE);
                         pEnc->bframes[n]->mbs = malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width * pEnc->mbParam.mb_height);  
381    
382                          if (image_create(&pEnc->bframes[n]->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height) < 0)                  if (pEnc->bframes == NULL)
383                          {                          goto xvid_err_memory3;
                                 return XVID_ERR_MEMORY;  
                         }  
                 }  
         }  
         pEnc->bframenum_head = 0;  
         pEnc->bframenum_tail = 0;  
         pEnc->flush_bframes = 0;  
384    
385          pEnc->mbParam.m_seconds = 0;                  for (n = 0; n < pEnc->mbParam.max_bframes; n++)
386          pEnc->mbParam.m_ticks = 0;                          pEnc->bframes[n] = NULL;
 #endif  
387    
388    
389  // ==============================================================================                  for (n = 0; n < pEnc->mbParam.max_bframes; n++) {
390                            pEnc->bframes[n] = xvid_malloc(sizeof(FRAMEINFO), CACHE_LINE);
391    
392                            if (pEnc->bframes[n] == NULL)
393                                    goto xvid_err_memory4;
394    
395          pParam->handle = (void *)pEnc;                          pEnc->bframes[n]->mbs =
396                                    xvid_malloc(sizeof(MACROBLOCK) * pEnc->mbParam.mb_width *
397                                                            pEnc->mbParam.mb_height, CACHE_LINE);
398    
399          if (pParam->rc_bitrate)                          if (pEnc->bframes[n]->mbs == NULL)
400          {                                  goto xvid_err_memory4;
                 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);  
         }  
401    
402          init_timer();                          image_null(&pEnc->bframes[n]->image);
403    
404                            if (image_create
405                                    (&pEnc->bframes[n]->image, pEnc->mbParam.edged_width,
406                                     pEnc->mbParam.edged_height) < 0)
407                                    goto xvid_err_memory4;
408    
409          return XVID_ERR_OK;                  }
410  }  }
411    
412            /* init incoming frame queue */
413            pEnc->queue_head = 0;
414            pEnc->queue_tail = 0;
415            pEnc->queue_size = 0;
416    
417  int encoder_destroy(Encoder * pEnc)          pEnc->queue =
418  {                  xvid_malloc((pEnc->mbParam.max_bframes+1) * sizeof(QUEUEINFO),
419          ENC_CHECK(pEnc);                                          CACHE_LINE);
420    
421  // =================================================================          if (pEnc->queue == NULL)
422  #ifdef BFRAMES                  goto xvid_err_memory4;
         if (pEnc->max_bframes > 0)  
         {  
                 int n;  
                 for (n = 0; n < pEnc->max_bframes; n++)  
                 {  
                         image_destroy(&pEnc->bframes[n]->image, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
                         free(pEnc->bframes[n]->mbs);  
                         free(pEnc->bframes[n]);  
                 }  
                 free(pEnc->bframes);  
         }  
 #endif BFRAMES  
 //====================================================================  
   
         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);  
 #ifdef BFRAMES  
         image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
         image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
 #endif  
 #ifdef _DEBUG  
                 image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height);  
 #endif  
         xvid_free(pEnc->current->mbs);  
         xvid_free(pEnc->current);  
423    
424          xvid_free(pEnc->reference->mbs);          for (n = 0; n < pEnc->mbParam.max_bframes+1; n++)
425          xvid_free(pEnc->reference);                  image_null(&pEnc->queue[n].image);
426    
         xvid_free(pEnc);  
         return XVID_ERR_OK;  
 }  
427    
428            for (n = 0; n < pEnc->mbParam.max_bframes+1; n++) {
429                    if (image_create
430                            (&pEnc->queue[n].image, pEnc->mbParam.edged_width,
431                             pEnc->mbParam.edged_height) < 0)
432                            goto xvid_err_memory5;
433            }
434    
435            /* timestamp stuff */
436    
437  // ==================================================================          pEnc->mbParam.m_stamp = 0;
438  #ifdef BFRAMES          pEnc->m_framenum = create->start_frame_num;
439  int encoder_encode(Encoder * pEnc, XVID_ENC_FRAME * pFrame, XVID_ENC_STATS * pResult)          pEnc->current->stamp = 0;
440  {          pEnc->reference->stamp = 0;
         uint16_t x, y;  
         Bitstream bs;  
         uint32_t bits;  
441    
442          ENC_CHECK(pEnc);          /* other stuff */
         ENC_CHECK(pFrame);  
443    
444          start_global_timer();          pEnc->iFrameNum = 0;
445            pEnc->fMvPrevSigma = -1;
446    
447          BitstreamInit(&bs, pFrame->bitstream, 0);          /* slices */
448            pEnc->num_slices = MIN(MAX(1, create->num_slices), (int) pEnc->mbParam.mb_height);
449    
450  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          /* multithreaded stuff */
451  // bframe "flush" code          if (create->num_threads > 0) {
452  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                  int t = MIN(create->num_threads, (int) (pEnc->mbParam.mb_height>>1)); /* at least two rows per thread */
453                    int threads_per_slice = MAX(1, (t / pEnc->num_slices));
454                    int rows_per_thread = (pEnc->mbParam.mb_height + threads_per_slice - 1) / threads_per_slice;
455    
456          if ((pFrame->image == NULL || pEnc->flush_bframes) &&                  pEnc->num_threads = t;
457                  pEnc->bframenum_head < pEnc->bframenum_tail)                  pEnc->smpData = xvid_malloc(t*sizeof(SMPData), CACHE_LINE);
458          {                  if (!pEnc->smpData)
459                            goto xvid_err_nosmp;
460    
461                  if (pEnc->flush_bframes == 0)                  /* tmp bitstream buffer for slice coding */
462                  {                  pEnc->smpData[0].tmp_buffer = xvid_malloc(16*pEnc->mbParam.edged_width*pEnc->mbParam.mb_height*sizeof(uint8_t), CACHE_LINE);
463                          // we have reached end of stream without getting a future reference                  if (! pEnc->smpData[0].tmp_buffer) goto xvid_err_nosmp;
                         // .. so encode last final frame a pframe  
                         dprintf("--- PFRAME (final frame correction) --- ");  
                         pEnc->bframenum_tail--;  
                         SWAP(pEnc->current, pEnc->reference);  
464    
465                          SWAP(pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);                  for (n = 0; n < t; n++) {
466                            int s = MIN(pEnc->num_threads, pEnc->num_slices);
467    
468                          FrameCodeP(pEnc, &bs, &bits, 1, 0);                          pEnc->smpData[n].complete_count_self =
469                                    xvid_malloc(rows_per_thread * sizeof(int), CACHE_LINE);
470    
471                          BitstreamPad(&bs);                          if (!pEnc->smpData[n].complete_count_self)
472                          pFrame->length = BitstreamLength(&bs);                                  goto xvid_err_nosmp;
                         pFrame->input_consumed = 0;  
                         pFrame->intra = 0;  
                         return XVID_ERR_OK;  
                 }  
473    
474                  dprintf("--- BFRAME (flush) --- ");                          if (n > 0 && n < s) {
475                  FrameCodeB(pEnc,                                  pEnc->smpData[n].bs = (Bitstream *) xvid_malloc(sizeof(Bitstream), CACHE_LINE);
476                          pEnc->bframes[pEnc->bframenum_head],                                  if (!pEnc->smpData[n].bs)
477                           &bs, &bits);                                          goto xvid_err_nosmp;
                 pEnc->bframenum_head++;  
478    
479                                    pEnc->smpData[n].sStat = (Statistics *) xvid_malloc(sizeof(Statistics), CACHE_LINE);
480                                    if (!pEnc->smpData[n].sStat)
481                                            goto xvid_err_nosmp;
482    
483                  BitstreamPad(&bs);                                  pEnc->smpData[n].tmp_buffer = pEnc->smpData[0].tmp_buffer + 16*(((n-1)*pEnc->mbParam.edged_width*pEnc->mbParam.mb_height)/s);
484                  pFrame->length = BitstreamLength(&bs);                                  BitstreamInit(pEnc->smpData[n].bs, pEnc->smpData[n].tmp_buffer, 0);
                 pFrame->input_consumed = 0;  
                 pFrame->intra = 0;  
                 return XVID_ERR_OK;  
485          }          }
486    
487          if (pFrame->image == NULL)                          if (n != 0)
488          {                                  pEnc->smpData[n].complete_count_above =
489                  pFrame->length = 0;                                          pEnc->smpData[n-1].complete_count_self;
                 pFrame->input_consumed = 1;  
                 pFrame->intra = 0;  
                 return XVID_ERR_OK;  
490          }          }
491                    pEnc->smpData[0].complete_count_above =
492                            pEnc->smpData[t-1].complete_count_self - 1;
493    
494          if (pEnc->bframenum_head > 0)          } else {
495          {    xvid_err_nosmp:
496                  pEnc->bframenum_head = pEnc->bframenum_tail = 0;                  /* no SMP */
497                    if (pEnc->smpData) {
498                            if (pEnc->smpData[0].tmp_buffer)
499                                    xvid_free(pEnc->smpData[0].tmp_buffer);
500                    }
501                    else {
502                            pEnc->smpData = xvid_malloc(1*sizeof(SMPData), CACHE_LINE);
503                            if (pEnc->smpData == NULL)
504                                    goto xvid_err_memory5;
505          }          }
506    
507          pEnc->flush_bframes = 0;                  create->num_threads = 0;
508            }
509    
510  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          create->handle = (void *) pEnc;
511    
512          SWAP(pEnc->current, pEnc->reference);          init_timer();
513            init_mpeg_matrix(pEnc->mbParam.mpeg_quant_matrices);
514    
515          pEnc->current->quant = (pFrame->quant == 0) ? RateControlGetQ(0) : pFrame->quant;          return 0;   /* ok */
         pEnc->current->global_flags = pFrame->general;  
         pEnc->current->motion_flags = pFrame->motion;  
         pEnc->current->seconds = pEnc->mbParam.m_seconds;  
         pEnc->current->ticks = pEnc->mbParam.m_ticks;  
         //@@@ TODO: dyanmic fcode (in both directions)  
         pEnc->current->fcode = pEnc->mbParam.m_fcode;  
         pEnc->current->bcode = pEnc->mbParam.m_fcode;  
516    
517          start_timer();          /*
518          if (image_input(&pEnc->current->image, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width,           * We handle all XVID_ERR_MEMORY here, this makes the code lighter
519                          pFrame->image, pFrame->colorspace))           */
         {  
                 return XVID_ERR_FORMAT;  
         }  
         stop_conv_timer();  
520    
521  #ifdef _DEBUG    xvid_err_memory5:
         image_copy(&pEnc->sOriginal, &pEnc->sCurrent, pEnc->mbParam.edged_width, pEnc->mbParam.height);  
 #endif  
522    
523            for (n = 0; n < pEnc->mbParam.max_bframes+1; n++) {
524                            image_destroy(&pEnc->queue[n].image, pEnc->mbParam.edged_width,
525                                                      pEnc->mbParam.edged_height);
526                    }
527    
528  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%          xvid_free(pEnc->queue);
 // lumi masking  
 // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%  
529    
530          if ((pEnc->current->global_flags & XVID_LUMIMASKING))    xvid_err_memory4:
         {  
                 int * temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * sizeof(int), CACHE_LINE);  
531    
532                  pEnc->current->quant = adaptive_quantization(pEnc->current->image.y,          if (pEnc->mbParam.max_bframes > 0) {
533                                                              pEnc->mbParam.edged_width,  // stride                  int i;
                                                             temp_dquants,  
                                                             pEnc->current->quant,  
                                                             pEnc->current->quant,       // min_quant  
                                                             2*pEnc->current->quant,     // max_quant  
                                                             pEnc->mbParam.mb_width,  
                                                             pEnc->mbParam.mb_height);  
534    
535                  for (y = 0; y < pEnc->mbParam.mb_height; y++)                  for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
                         for (x = 0; x < pEnc->mbParam.mb_width; x++)  
                         {  
                                 MACROBLOCK *pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
                                 pMB->dquant = iDQtab[(temp_dquants[y * pEnc->mbParam.mb_width + x] + 2)];  
                         }  
                 xvid_free(temp_dquants);  
         }  
536    
537                            if (pEnc->bframes[i] == NULL)
538                                    continue;
539    
540  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                          image_destroy(&pEnc->bframes[i]->image, pEnc->mbParam.edged_width,
541  // ivop/pvop/bvop selection                                                    pEnc->mbParam.edged_height);
542  // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                          xvid_free(pEnc->bframes[i]->mbs);
543                            xvid_free(pEnc->bframes[i]);
544                    }
545    
546                    xvid_free(pEnc->bframes);
547            }
548    
549      xvid_err_memory3:
550    
551            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
552                    image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width,
553                                              pEnc->mbParam.edged_height);
554                    image_destroy(&pEnc->sOriginal2, pEnc->mbParam.edged_width,
555                                              pEnc->mbParam.edged_height);
556            }
557    
558            image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width,
559                                      pEnc->mbParam.edged_height);
560            image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width,
561                                      pEnc->mbParam.edged_height);
562            image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width,
563                                      pEnc->mbParam.edged_height);
564    
565            image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width,
566                                      pEnc->mbParam.edged_height);
567            image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width,
568                                      pEnc->mbParam.edged_height);
569            image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width,
570                                      pEnc->mbParam.edged_height);
571            image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width,
572                                      pEnc->mbParam.edged_height);
573            image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width,
574                                      pEnc->mbParam.edged_height);
575    
576    /* destroy GMC image */
577            image_destroy(&pEnc->vGMC, pEnc->mbParam.edged_width,
578                                      pEnc->mbParam.edged_height);
579    
580          if (pEnc->iFrameNum == 0 ||    xvid_err_memory2a:
581                  pFrame->intra == 1 ||          xvid_free(pEnc->mbParam.mpeg_quant_matrices);
                 (pFrame->intra < 0 && (pEnc->iMaxKeyInterval > 0 && pEnc->iFrameNum >= pEnc->iMaxKeyInterval)) ||  
                 image_mad(&pEnc->reference->image, &pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.width, pEnc->mbParam.height) > 30)  
         {  
                 dprintf("--- IFRAME ---");  
582    
583                  FrameCodeI(pEnc, &bs, &bits);    xvid_err_memory2:
584            xvid_free(pEnc->current->mbs);
585            xvid_free(pEnc->reference->mbs);
586    
587                  pFrame->intra = 1;    xvid_err_memory1:
588                  pEnc->flush_bframes = 1;          xvid_free(pEnc->current);
589            xvid_free(pEnc->reference);
590    
591                  /* note: sequences like "IIBB" decode fine with msfdam but,    xvid_err_memory1a:
592                     go screwy with divx5.00 */          if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
593                    xvid_free(pEnc->temp_dquants);
594          }          }
         else if (pEnc->bframenum_tail >= pEnc->max_bframes)  
         {  
                 dprintf("--- PFRAME ---");  
595    
596                  FrameCodeP(pEnc, &bs, &bits, 1, 0);          if(pEnc->mbParam.plugin_flags & XVID_REQLAMBDA) {
597                  pFrame->intra = 0;                  xvid_free(pEnc->temp_lambda);
                 pEnc->flush_bframes = 1;  
598          }          }
         else  
         {  
                 dprintf("--- BFRAME (store) ---  head=%i tail=%i", pEnc->bframenum_head, pEnc->bframenum_tail);  
599    
600                  if (pFrame->bquant < 1)    xvid_err_memory0:
601                  {          for (n=0; n<pEnc->num_plugins;n++) {
602                          pEnc->current->quant = ((pEnc->reference->quant + pEnc->current->quant) * pEnc->bquant_ratio) / 200;                  if (pEnc->plugins[n].func) {
603                            pEnc->plugins[n].func(pEnc->plugins[n].param, XVID_PLG_DESTROY, NULL, NULL);
604                  }                  }
                 else  
                 {  
                         pEnc->current->quant = pFrame->bquant;  
605                  }                  }
606            xvid_free(pEnc->plugins);
607    
608                  // store frame into bframe buffer & swap ref back to current          xvid_free(pEnc->zones);
                 SWAP(pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);  
                 SWAP(pEnc->current, pEnc->reference);  
609    
610                  pEnc->bframenum_tail++;          xvid_free(pEnc);
611    
612                  pFrame->intra = 0;          create->handle = NULL;
                 pFrame->length = 0;  
                 pFrame->input_consumed = 1;  
613    
614                  pEnc->mbParam.m_ticks += pEnc->mbParam.fincr;          return XVID_ERR_MEMORY;
                 if (pEnc->mbParam.m_ticks > pEnc->mbParam.fbase)  
                 {  
                         pEnc->mbParam.m_seconds++;  
                         pEnc->mbParam.m_ticks = 0;  
                 }  
                 return XVID_ERR_OK;  
615          }          }
616    
617          BitstreamPad(&bs);  /*****************************************************************************
618          pFrame->length = BitstreamLength(&bs);   * Encoder destruction
619     *
620     * This function destroy the entire encoder structure created by a previous
621     * successful enc_create call.
622     *
623     * Returned values (for now only one returned value) :
624     *      - 0      - no errors
625     *
626     ****************************************************************************/
627    
628          if (pResult)  int
629    enc_destroy(Encoder * pEnc)
630          {          {
631                  pResult->quant = pEnc->current->quant;          int i;
632                  pResult->hlength = pFrame->length - (pEnc->sStat.iTextBits / 8);  
633                  pResult->kblks = pEnc->sStat.kblks;          /* B Frames specific */
634                  pResult->mblks = pEnc->sStat.mblks;          for (i = 0; i < pEnc->mbParam.max_bframes+1; i++) {
635                  pResult->ublks = pEnc->sStat.ublks;                  image_destroy(&pEnc->queue[i].image, pEnc->mbParam.edged_width,
636                                              pEnc->mbParam.edged_height);
637          }          }
638    
639  #ifdef _DEBUG          xvid_free(pEnc->queue);
         psnr = image_psnr(&pEnc->sOriginal, &pEnc->current->image, pEnc->mbParam.edged_width,  
                                 pEnc->mbParam.width, pEnc->mbParam.height);  
640    
641          sprintf(temp, "PSNR: %f\n", psnr);          if (pEnc->mbParam.max_bframes > 0) {
         DEBUG(temp);  
 #endif  
642    
643          if (pFrame->quant == 0)                  for (i = 0; i < pEnc->mbParam.max_bframes; i++) {
         {  
                 RateControlUpdate(pEnc->current->quant, pFrame->length, pFrame->intra);  
         }  
644    
645          pEnc->iFrameNum++;                          if (pEnc->bframes[i] == NULL)
646          pEnc->mbParam.m_ticks += pEnc->mbParam.fincr;                                  continue;
         if (pEnc->mbParam.m_ticks > pEnc->mbParam.fbase)  
         {  
                 pEnc->mbParam.m_seconds++;  
                 pEnc->mbParam.m_ticks = 0;  
         }  
         pFrame->input_consumed = 1;  
647    
648          stop_global_timer();                          image_destroy(&pEnc->bframes[i]->image, pEnc->mbParam.edged_width,
649          write_timer();                                            pEnc->mbParam.edged_height);
650                            xvid_free(pEnc->bframes[i]->mbs);
651                            xvid_free(pEnc->bframes[i]);
652                    }
653    
654                    xvid_free(pEnc->bframes);
655    
         return XVID_ERR_OK;  
656  }  }
 // ==================================================================  
 #else  
 int encoder_encode(Encoder * pEnc, XVID_ENC_FRAME * pFrame, XVID_ENC_STATS * pResult)  
 {  
         uint16_t x, y;  
         Bitstream bs;  
         uint32_t bits;  
         uint16_t write_vol_header = 0;  
 #ifdef _DEBUG  
         float psnr;  
         uint8_t temp[100];  
 #endif  
   
         start_global_timer();  
657    
658          ENC_CHECK(pEnc);          /* All images, reference, current etc ... */
659          ENC_CHECK(pFrame);  
660          ENC_CHECK(pFrame->bitstream);          image_destroy(&pEnc->current->image, pEnc->mbParam.edged_width,
661          ENC_CHECK(pFrame->image);                                    pEnc->mbParam.edged_height);
662            image_destroy(&pEnc->reference->image, pEnc->mbParam.edged_width,
663          SWAP(pEnc->current, pEnc->reference);                                    pEnc->mbParam.edged_height);
664            image_destroy(&pEnc->vInterH, pEnc->mbParam.edged_width,
665          pEnc->current->global_flags = pFrame->general;                                    pEnc->mbParam.edged_height);
666          pEnc->current->motion_flags = pFrame->motion;          image_destroy(&pEnc->vInterV, pEnc->mbParam.edged_width,
667          pEnc->mbParam.hint = &pFrame->hint;                                    pEnc->mbParam.edged_height);
668            image_destroy(&pEnc->vInterHV, pEnc->mbParam.edged_width,
669          start_timer();                                    pEnc->mbParam.edged_height);
670          if (image_input(&pEnc->current->image, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width,          image_destroy(&pEnc->f_refh, pEnc->mbParam.edged_width,
671                          pFrame->image, pFrame->colorspace))                                    pEnc->mbParam.edged_height);
672          {          image_destroy(&pEnc->f_refv, pEnc->mbParam.edged_width,
673                  return XVID_ERR_FORMAT;                                    pEnc->mbParam.edged_height);
674            image_destroy(&pEnc->f_refhv, pEnc->mbParam.edged_width,
675                                      pEnc->mbParam.edged_height);
676            image_destroy(&pEnc->vGMC, pEnc->mbParam.edged_width,
677                                      pEnc->mbParam.edged_height);
678    
679            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
680                    image_destroy(&pEnc->sOriginal, pEnc->mbParam.edged_width,
681                                              pEnc->mbParam.edged_height);
682                    image_destroy(&pEnc->sOriginal2, pEnc->mbParam.edged_width,
683                                              pEnc->mbParam.edged_height);
684          }          }
         stop_conv_timer();  
685    
686  #ifdef _DEBUG          /* Encoder structure */
         image_copy(&pEnc->sOriginal, &pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height);  
 #endif  
687    
688          EMMS();          xvid_free(pEnc->current->mbs);
689            xvid_free(pEnc->current);
690    
691          BitstreamInit(&bs, pFrame->bitstream, 0);          xvid_free(pEnc->reference->mbs);
692            xvid_free(pEnc->reference);
693    
694          if (pFrame->quant == 0)          if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
695          {                  xvid_free(pEnc->temp_dquants);
                 pEnc->current->quant = RateControlGetQ(0);  
696          }          }
697          else  
698          {          if ((pEnc->mbParam.plugin_flags & XVID_REQLAMBDA)) {
699                  pEnc->current->quant = pFrame->quant;                  xvid_free(pEnc->temp_lambda);
700          }          }
701    
702          if ((pEnc->current->global_flags & XVID_LUMIMASKING))          if (pEnc->num_plugins>0) {
703          {                  xvid_plg_destroy_t pdestroy;
704                  int * temp_dquants = (int *) xvid_malloc(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * sizeof(int), CACHE_LINE);                  memset(&pdestroy, 0, sizeof(xvid_plg_destroy_t));
705    
706                  pEnc->current->quant = adaptive_quantization(pEnc->current->image.y,                  pdestroy.version = XVID_VERSION;
707                                                              pEnc->mbParam.edged_width,  // stride                  pdestroy.num_frames = pEnc->m_framenum;
                                                             temp_dquants,  
                                                             pEnc->current->quant,  
                                                             pEnc->current->quant,       // min_quant  
                                                             2*pEnc->current->quant,     // max_quant  
                                                             pEnc->mbParam.mb_width,  
                                                             pEnc->mbParam.mb_height);  
708    
709                  for (y = 0; y < pEnc->mbParam.mb_height; y++)                  for (i=0; i<pEnc->num_plugins;i++) {
710                          for (x = 0; x < pEnc->mbParam.mb_width; x++)                          if (pEnc->plugins[i].func) {
711                          {                                  pEnc->plugins[i].func(pEnc->plugins[i].param, XVID_PLG_DESTROY, &pdestroy, NULL);
                                 MACROBLOCK *pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
                                 pMB->dquant = iDQtab[(temp_dquants[y * pEnc->mbParam.mb_width + x] + 2)];  
712                          }                          }
                 xvid_free(temp_dquants);  
713          }          }
714                    xvid_free(pEnc->plugins);
         if (pEnc->current->global_flags & XVID_H263QUANT) {  
                 if(pEnc->mbParam.m_quant_type != H263_QUANT)  
                         write_vol_header = 1;  
                 pEnc->mbParam.m_quant_type = H263_QUANT;  
715          }          }
         else if(pEnc->current->global_flags & XVID_MPEGQUANT) {  
                 int ret1, ret2;  
   
                 ret1 = ret2 = 0;  
716    
717                  if(pEnc->mbParam.m_quant_type != MPEG4_QUANT)          xvid_free(pEnc->mbParam.mpeg_quant_matrices);
                         write_vol_header = 1;  
718    
719                  pEnc->mbParam.m_quant_type = MPEG4_QUANT;          if (pEnc->num_zones > 0)
720                    xvid_free(pEnc->zones);
721    
722                  if ((pEnc->current->global_flags & XVID_CUSTOM_QMATRIX) > 0) {          if (pEnc->num_threads > 0) {
723                          if(pFrame->quant_intra_matrix != NULL)                  for (i = 1; i < MAX(1, MIN(pEnc->num_threads, pEnc->num_slices)); i++) {
724                                  ret1 = set_intra_matrix(pFrame->quant_intra_matrix);                          xvid_free(pEnc->smpData[i].bs);
725                          if(pFrame->quant_inter_matrix != NULL)                          xvid_free(pEnc->smpData[i].sStat);
                                 ret2 = set_inter_matrix(pFrame->quant_inter_matrix);  
                 }  
                 else {  
                         ret1 = set_intra_matrix(get_default_intra_matrix());  
                         ret2 = set_inter_matrix(get_default_inter_matrix());  
726                  }                  }
727                  if(write_vol_header == 0)                  if (pEnc->smpData[0].tmp_buffer) xvid_free(pEnc->smpData[0].tmp_buffer);
728                          write_vol_header = ret1 | ret2;  
729                    for (i = 0; i < pEnc->num_threads; i++)
730                            xvid_free(pEnc->smpData[i].complete_count_self);
731          }          }
732            xvid_free(pEnc->smpData);
733    
734          if (pFrame->intra < 0)          xvid_free(pEnc);
         {  
                 if ((pEnc->iFrameNum == 0) || ((pEnc->iMaxKeyInterval > 0)  
                                                && (pEnc->iFrameNum >= pEnc->iMaxKeyInterval)))  
735    
736                          pFrame->intra = FrameCodeI(pEnc, &bs, &bits);          return 0;  /* ok */
                 else  
                         pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 0, write_vol_header);  
         }  
         else  
         {  
                 if (pFrame->intra == 1)  
                         pFrame->intra = FrameCodeI(pEnc, &bs, &bits);  
                 else  
                         pFrame->intra = FrameCodeP(pEnc, &bs, &bits, 1, write_vol_header);  
737          }          }
738    
         BitstreamPutBits(&bs, 0xFFFF, 16);  
         BitstreamPutBits(&bs, 0xFFFF, 16);  
         BitstreamPad(&bs);  
         pFrame->length = BitstreamLength(&bs);  
739    
740          if (pResult)  /*
741      call the plugins
742      */
743    
744    static void call_plugins(Encoder * pEnc, FRAMEINFO * frame, IMAGE * original,
745                                                     int opt, int * type, int * quant, xvid_enc_stats_t * stats)
746          {          {
747                  pResult->quant = pEnc->current->quant;          unsigned int i, j, k;
748                  pResult->hlength = pFrame->length - (pEnc->sStat.iTextBits / 8);          xvid_plg_data_t data;
                 pResult->kblks = pEnc->sStat.kblks;  
                 pResult->mblks = pEnc->sStat.mblks;  
                 pResult->ublks = pEnc->sStat.ublks;  
         }  
749    
750          EMMS();          /* set data struct */
751    
752          if (pFrame->quant == 0)          memset(&data, 0, sizeof(xvid_plg_data_t));
753          {          data.version = XVID_VERSION;
754                  RateControlUpdate(pEnc->current->quant, pFrame->length, pFrame->intra);  
755            /* find zone */
756            for(i=0; i<pEnc->num_zones && pEnc->zones[i].frame<=frame->frame_num; i++) ;
757            data.zone = i>0 ? &pEnc->zones[i-1] : NULL;
758    
759            data.width = pEnc->mbParam.width;
760            data.height = pEnc->mbParam.height;
761            data.mb_width = pEnc->mbParam.mb_width;
762            data.mb_height = pEnc->mbParam.mb_height;
763            data.fincr = frame->fincr;
764            data.fbase = pEnc->mbParam.fbase;
765            data.bquant_ratio = pEnc->mbParam.bquant_ratio;
766            data.bquant_offset = pEnc->mbParam.bquant_offset;
767    
768            for (i=0; i<3; i++) {
769                    data.min_quant[i] = pEnc->mbParam.min_quant[i];
770                    data.max_quant[i] = pEnc->mbParam.max_quant[i];
771          }          }
772    
773  #ifdef _DEBUG          data.reference.csp = XVID_CSP_PLANAR;
774          psnr = image_psnr(&pEnc->sOriginal, &pEnc->current->image, pEnc->mbParam.edged_width,          data.reference.plane[0] = pEnc->reference->image.y;
775                                  pEnc->mbParam.width, pEnc->mbParam.height);          data.reference.plane[1] = pEnc->reference->image.u;
776            data.reference.plane[2] = pEnc->reference->image.v;
777            data.reference.stride[0] = pEnc->mbParam.edged_width;
778            data.reference.stride[1] = pEnc->mbParam.edged_width/2;
779            data.reference.stride[2] = pEnc->mbParam.edged_width/2;
780    
781          sprintf(temp, "PSNR: %f\n", psnr);          data.current.csp = XVID_CSP_PLANAR;
782          DEBUG(temp);          data.current.plane[0] = frame->image.y;
783  #endif          data.current.plane[1] = frame->image.u;
784            data.current.plane[2] = frame->image.v;
785            data.current.stride[0] = pEnc->mbParam.edged_width;
786            data.current.stride[1] = pEnc->mbParam.edged_width/2;
787            data.current.stride[2] = pEnc->mbParam.edged_width/2;
788    
789          pEnc->iFrameNum++;          data.frame_num = frame->frame_num;
790    
791          stop_global_timer();          if (opt == XVID_PLG_BEFORE) {
792          write_timer();                  data.type = *type;
793                    data.quant = *quant;
794    
795                    data.vol_flags = frame->vol_flags;
796                    data.vop_flags = frame->vop_flags;
797                    data.motion_flags = frame->motion_flags;
798    
799          return XVID_ERR_OK;          } else if (opt == XVID_PLG_FRAME) {
800                    data.type = coding2type(frame->coding_type);
801                    data.quant = frame->quant;
802    
803                    if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
804                            data.dquant = pEnc->temp_dquants;
805                            data.dquant_stride = pEnc->mbParam.mb_width;
806                            memset(data.dquant, 0, data.mb_width*data.mb_height*sizeof(int));
807  }  }
 #endif  
808    
809                    if(pEnc->mbParam.plugin_flags & XVID_REQLAMBDA) {
810                            int block = 0;
811                            emms();
812                            data.lambda = pEnc->temp_lambda;
813                            for(i = 0;i < pEnc->mbParam.mb_height; i++)
814                                    for(j = 0;j < pEnc->mbParam.mb_width; j++)
815                                            for (k = 0; k < 6; k++)
816                                                    data.lambda[block++] = 1.0f;
817                    }
818    
819            } else { /* XVID_PLG_AFTER */
820                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
821                            data.original.csp = XVID_CSP_PLANAR;
822                            data.original.plane[0] = original->y;
823                            data.original.plane[1] = original->u;
824                            data.original.plane[2] = original->v;
825                            data.original.stride[0] = pEnc->mbParam.edged_width;
826                            data.original.stride[1] = pEnc->mbParam.edged_width/2;
827                            data.original.stride[2] = pEnc->mbParam.edged_width/2;
828                    }
829    
830                    if ((frame->vol_flags & XVID_VOL_EXTRASTATS) ||
831                            (pEnc->mbParam.plugin_flags & XVID_REQPSNR)) {
832    
833                            data.sse_y =
834                                    plane_sse( original->y, frame->image.y,
835                                                       pEnc->mbParam.edged_width, pEnc->mbParam.width,
836                                                       pEnc->mbParam.height);
837    
838                            data.sse_u =
839                                    plane_sse( original->u, frame->image.u,
840                                                       pEnc->mbParam.edged_width/2, pEnc->mbParam.width/2,
841                                                       pEnc->mbParam.height/2);
842    
843                            data.sse_v =
844                                    plane_sse( original->v, frame->image.v,
845                                                       pEnc->mbParam.edged_width/2, pEnc->mbParam.width/2,
846                                                       pEnc->mbParam.height/2);
847                    }
848    
849                    data.type = coding2type(frame->coding_type);
850                    data.quant = frame->quant;
851    
852                    if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
853                            data.dquant = pEnc->temp_dquants;
854                            data.dquant_stride = pEnc->mbParam.mb_width;
855    
856                            for (j=0; j<pEnc->mbParam.mb_height; j++)
857                            for (i=0; i<pEnc->mbParam.mb_width; i++) {
858                                    data.dquant[j*data.dquant_stride + i] = frame->mbs[j*pEnc->mbParam.mb_width + i].dquant;
859                            }
860                    }
861    
862                    data.vol_flags = frame->vol_flags;
863                    data.vop_flags = frame->vop_flags;
864                    data.motion_flags = frame->motion_flags;
865    
866                    data.length = frame->length;
867                    data.kblks = frame->sStat.kblks;
868                    data.mblks = frame->sStat.mblks;
869                    data.ublks = frame->sStat.ublks;
870    
871                    /* New code */
872                    data.stats.type      = coding2type(frame->coding_type);
873                    data.stats.quant     = frame->quant;
874                    data.stats.vol_flags = frame->vol_flags;
875                    data.stats.vop_flags = frame->vop_flags;
876                    data.stats.length    = frame->length;
877                    data.stats.hlength   = frame->length - (frame->sStat.iTextBits / 8);
878                    data.stats.kblks     = frame->sStat.kblks;
879                    data.stats.mblks     = frame->sStat.mblks;
880                    data.stats.ublks     = frame->sStat.ublks;
881                    data.stats.sse_y     = data.sse_y;
882                    data.stats.sse_u     = data.sse_u;
883                    data.stats.sse_v     = data.sse_v;
884    
885                    if (stats)
886                            *stats = data.stats;
887            }
888    
889  static __inline void CodeIntraMB(Encoder *pEnc, MACROBLOCK *pMB) {          /* call plugins */
890            for (i=0; i<(unsigned int)pEnc->num_plugins;i++) {
891                    emms();
892                    if (pEnc->plugins[i].func) {
893                            if (pEnc->plugins[i].func(pEnc->plugins[i].param, opt, &data, NULL) < 0) {
894                                    continue;
895                            }
896                    }
897            }
898            emms();
899    
900          pMB->mode = MODE_INTRA;          /* copy modified values back into frame*/
901            if (opt == XVID_PLG_BEFORE) {
902                    *type = data.type;
903                    *quant = data.quant > 0 ? data.quant : 2;   /* default */
904    
905          /* zero mv statistics */                  frame->vol_flags = data.vol_flags;
906          pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = 0;                  frame->vop_flags = data.vop_flags;
907          pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = 0;                  frame->motion_flags = data.motion_flags;
         pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = 0;  
         pMB->sad16 = 0;  
908    
909          if ((pEnc->current->global_flags & XVID_LUMIMASKING)) {          } else if (opt == XVID_PLG_FRAME) {
                 if(pMB->dquant != NO_CHANGE)  
                 {  
                         pMB->mode = MODE_INTRA_Q;  
                         pEnc->current->quant += DQtab[pMB->dquant];  
910    
911                          if (pEnc->current->quant > 31) pEnc->current->quant = 31;                  if ((pEnc->mbParam.plugin_flags & XVID_REQDQUANTS)) {
912                          if (pEnc->current->quant < 1) pEnc->current->quant = 1;                          for (j=0; j<pEnc->mbParam.mb_height; j++)
913                            for (i=0; i<pEnc->mbParam.mb_width; i++) {
914                                    frame->mbs[j*pEnc->mbParam.mb_width + i].dquant = data.dquant[j*data.mb_width + i];
915                            }
916                    } else {
917                            for (j=0; j<pEnc->mbParam.mb_height; j++)
918                            for (i=0; i<pEnc->mbParam.mb_width; i++) {
919                                    frame->mbs[j*pEnc->mbParam.mb_width + i].dquant = 0;
920                  }                  }
921          }          }
922    
923          pMB->quant = pEnc->current->quant;                  if (pEnc->mbParam.plugin_flags & XVID_REQLAMBDA) {
924                            for (j = 0; j < pEnc->mbParam.mb_height; j++)
925                                    for (i = 0; i < pEnc->mbParam.mb_width; i++)
926                                            for (k = 0; k < 6; k++) {
927                                                    frame->mbs[j*pEnc->mbParam.mb_width + i].lambda[k] =
928                                                            (int) ((float)(1<<LAMBDA_EXP) * data.lambda[6 * (j * data.mb_width + i) + k]);
929                                            }
930                    } else {
931                            for (j = 0; j<pEnc->mbParam.mb_height; j++)
932                                    for (i = 0; i<pEnc->mbParam.mb_width; i++)
933                                            for (k = 0; k < 6; k++) {
934                                                    frame->mbs[j*pEnc->mbParam.mb_width + i].lambda[k] = 1<<LAMBDA_EXP;
935                                            }
936  }  }
937    
938    
939  #define FCODEBITS       3                  frame->mbs[0].quant = data.quant; /* FRAME will not affect the quant in stats */
940  #define MODEBITS        5          }
941    
 void HintedMESet(Encoder * pEnc, int * intra)  
 {  
         HINTINFO * hint;  
         Bitstream bs;  
         int length, high;  
         uint32_t x, y;  
942    
943          hint = pEnc->mbParam.hint;  }
944    
945    
946          if (hint->rawhints)  static __inline void inc_frame_num(Encoder * pEnc)
947          {          {
948                  *intra = hint->mvhint.intra;          pEnc->current->frame_num = pEnc->m_framenum;
949            pEnc->current->stamp = pEnc->mbParam.m_stamp;   /* first frame is zero */
950    
951            pEnc->mbParam.m_stamp += pEnc->current->fincr;
952            pEnc->m_framenum++;     /* debug ticker */
953          }          }
954          else  
955    static __inline void dec_frame_num(Encoder * pEnc)
956          {          {
957                  BitstreamInit(&bs, hint->hintstream, hint->hintlength);          pEnc->mbParam.m_stamp -= pEnc->mbParam.fincr;
958                  *intra = BitstreamGetBit(&bs);          pEnc->m_framenum--;     /* debug ticker */
959          }          }
960    
961          if (*intra)  static __inline void
962    MBSetDquant(MACROBLOCK * pMB, int x, int y, MBParam * mbParam)
963          {          {
964            if (pMB->cbp == 0) {
965                    /* we want to code dquant but the quantizer value will not be used yet
966                            let's find out if we can postpone dquant to next MB
967                    */
968                    if (x == mbParam->mb_width-1 && y == mbParam->mb_height-1) {
969                            pMB->dquant = 0; /* it's the last MB of all, the easiest case */
970                  return;                  return;
971                    } else {
972                            MACROBLOCK * next = pMB + 1;
973                            const MACROBLOCK * prev = pMB - 1;
974                            if (next->mode != MODE_INTER4V && next->mode != MODE_NOT_CODED)
975                                    /* mode allows dquant change in the future */
976                                    if (abs(next->quant - prev->quant) <= 2) {
977                                            /* quant change is not out of range */
978                                            pMB->quant = prev->quant;
979                                            pMB->dquant = 0;
980                                            next->dquant = next->quant - prev->quant;
981                                            return;
982                                    }
983                    }
984            }
985            /* couldn't skip this dquant */
986            pMB->mode = MODE_INTER_Q;
987          }          }
988    
         pEnc->current->fcode = (hint->rawhints) ? hint->mvhint.fcode : BitstreamGetBits(&bs, FCODEBITS);  
989    
         length  = pEnc->current->fcode + 5;  
         high    = 1 << (length - 1);  
990    
991          for (y=0 ; y<pEnc->mbParam.mb_height ; ++y)  static __inline void
992          {  set_timecodes(FRAMEINFO* pCur,FRAMEINFO *pRef, int32_t time_base)
                 for (x=0 ; x<pEnc->mbParam.mb_width ; ++x)  
993                  {                  {
                         MACROBLOCK * pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
                         MVBLOCKHINT * bhint = &hint->mvhint.block[x + y * pEnc->mbParam.mb_width];  
                         VECTOR pred[4];  
                         VECTOR tmp;  
                         int32_t dummy[4];  
                         int vec;  
994    
995                          pMB->mode = (hint->rawhints) ? bhint->mode : BitstreamGetBits(&bs, MODEBITS);          pCur->ticks = (int32_t)pCur->stamp % time_base;
996            pCur->seconds =  ((int32_t)pCur->stamp / time_base)     - ((int32_t)pRef->stamp / time_base) ;
997    
998                          pMB->mode = (pMB->mode == MODE_INTER_Q) ? MODE_INTER : pMB->mode;  #if 0   /* HEAVY DEBUG OUTPUT */
999                          pMB->mode = (pMB->mode == MODE_INTRA_Q) ? MODE_INTRA : pMB->mode;          fprintf(stderr,"WriteVop:   %d - %d \n",
1000                            ((int32_t)pCur->stamp / time_base), ((int32_t)pRef->stamp / time_base));
1001            fprintf(stderr,"set_timecodes: VOP %1d   stamp=%lld ref_stamp=%lld  base=%d\n",
1002                            pCur->coding_type, pCur->stamp, pRef->stamp, time_base);
1003            fprintf(stderr,"set_timecodes: VOP %1d   seconds=%d   ticks=%d   (ref-sec=%d  ref-tick=%d)\n",
1004                            pCur->coding_type, pCur->seconds, pCur->ticks, pRef->seconds, pRef->ticks);
1005    #endif
1006    }
1007    
1008                          if (pMB->mode == MODE_INTER)  static void
1009    simplify_par(int *par_width, int *par_height)
1010                          {                          {
                                 tmp.x  = (hint->rawhints) ? bhint->mvs[0].x : BitstreamGetBits(&bs, length);  
                                 tmp.y  = (hint->rawhints) ? bhint->mvs[0].y : BitstreamGetBits(&bs, length);  
                                 tmp.x -= (tmp.x >= high) ? high*2 : 0;  
                                 tmp.y -= (tmp.y >= high) ? high*2 : 0;  
1011    
1012                                  get_pmvdata(pEnc->current->mbs, x, y, pEnc->mbParam.mb_width, 0, pred, dummy);          int _par_width  = (!*par_width)  ? 1 : (*par_width<0)  ? -*par_width:  *par_width;
1013            int _par_height = (!*par_height) ? 1 : (*par_height<0) ? -*par_height: *par_height;
1014            int divisor = gcd(_par_width, _par_height);
1015    
1016                                  for (vec=0 ; vec<4 ; ++vec)          _par_width  /= divisor;
1017                                  {          _par_height /= divisor;
1018                                          pMB->mvs[vec].x  = tmp.x;  
1019                                          pMB->mvs[vec].y  = tmp.y;          /* 2^8 precision maximum */
1020                                          pMB->pmvs[vec].x = pMB->mvs[0].x - pred[0].x;          if (_par_width>255 || _par_height>255) {
1021                                          pMB->pmvs[vec].y = pMB->mvs[0].y - pred[0].y;                  float div;
1022                    emms();
1023                    if (_par_width>_par_height)
1024                            div = (float)_par_width/255;
1025                    else
1026                            div = (float)_par_height/255;
1027    
1028                    _par_width  = (int)((float)_par_width/div);
1029                    _par_height = (int)((float)_par_height/div);
1030                                  }                                  }
1031    
1032            *par_width = _par_width;
1033            *par_height = _par_height;
1034    
1035            return;
1036                          }                          }
1037                          else if (pMB->mode == MODE_INTER4V)  
1038                          {  /*****************************************************************************
1039                                  for (vec=0 ; vec<4 ; ++vec)   * IPB frame encoder entry point
1040     *
1041     * Returned values :
1042     *      - >0                       - output bytes
1043     *      - 0                             - no output
1044     *      - XVID_ERR_VERSION - wrong version passed to core
1045     *      - XVID_ERR_END   - End of stream reached before end of coding
1046     *      - XVID_ERR_FORMAT  - the image subsystem reported the image had a wrong
1047     *                                               format
1048     ****************************************************************************/
1049    
1050    
1051    int
1052    enc_encode(Encoder * pEnc,
1053                               xvid_enc_frame_t * xFrame,
1054                               xvid_enc_stats_t * stats)
1055                                  {                                  {
1056                                          tmp.x  = (hint->rawhints) ? bhint->mvs[vec].x : BitstreamGetBits(&bs, length);          xvid_enc_frame_t * frame;
1057                                          tmp.y  = (hint->rawhints) ? bhint->mvs[vec].y : BitstreamGetBits(&bs, length);          int type;
1058                                          tmp.x -= (tmp.x >= high) ? high*2 : 0;          Bitstream bs;
1059                                          tmp.y -= (tmp.y >= high) ? high*2 : 0;  
1060            if (XVID_VERSION_MAJOR(xFrame->version) != 1 || (stats && XVID_VERSION_MAJOR(stats->version) != 1))     /* v1.x.x */
1061                    return XVID_ERR_VERSION;
1062    
1063                                          get_pmvdata(pEnc->current->mbs, x, y, pEnc->mbParam.mb_width, vec, pred, dummy);          xFrame->out_flags = 0;
1064    
1065                                          pMB->mvs[vec].x  = tmp.x;          start_global_timer();
1066                                          pMB->mvs[vec].y  = tmp.y;          BitstreamInit(&bs, xFrame->bitstream, 0);
1067                                          pMB->pmvs[vec].x = pMB->mvs[vec].x - pred[0].x;  
1068                                          pMB->pmvs[vec].y = pMB->mvs[vec].y - pred[0].y;  
1069            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1070             * enqueue image to the encoding-queue
1071             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1072    
1073            if (xFrame->input.csp != XVID_CSP_NULL)
1074            {
1075                    QUEUEINFO * q = &pEnc->queue[pEnc->queue_tail];
1076    
1077                    start_timer();
1078                    if (image_input
1079                            (&q->image, pEnc->mbParam.width, pEnc->mbParam.height,
1080                            pEnc->mbParam.edged_width, (uint8_t**)xFrame->input.plane, xFrame->input.stride,
1081                            xFrame->input.csp, xFrame->vol_flags & XVID_VOL_INTERLACING))
1082                    {
1083                            emms();
1084                            return XVID_ERR_FORMAT;
1085                                  }                                  }
1086                    stop_conv_timer();
1087    
1088                    if ((xFrame->vop_flags & XVID_VOP_CHROMAOPT)) {
1089                            image_chroma_optimize(&q->image,
1090                                    pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width);
1091                          }                          }
1092                          else    // intra / stuffing / not_coded  
1093                    q->frame = *xFrame;
1094    
1095                    if (xFrame->quant_intra_matrix)
1096                          {                          {
1097                                  for (vec=0 ; vec<4 ; ++vec)                          memcpy(q->quant_intra_matrix, xFrame->quant_intra_matrix, 64*sizeof(unsigned char));
1098                            q->frame.quant_intra_matrix = q->quant_intra_matrix;
1099                    }
1100    
1101                    if (xFrame->quant_inter_matrix)
1102                                  {                                  {
1103                                          pMB->mvs[vec].x  = pMB->mvs[vec].y  = 0;                          memcpy(q->quant_inter_matrix, xFrame->quant_inter_matrix, 64*sizeof(unsigned char));
1104                            q->frame.quant_inter_matrix = q->quant_inter_matrix;
1105                                  }                                  }
1106    
1107                    pEnc->queue_tail = (pEnc->queue_tail + 1) % (pEnc->mbParam.max_bframes+1);
1108                    pEnc->queue_size++;
1109                          }                          }
1110    
1111                          if (pMB->mode == MODE_INTER4V &&  
1112                                  (pEnc->current->global_flags & XVID_LUMIMASKING) && pMB->dquant != NO_CHANGE)          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1113             * bframe flush code
1114             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1115    
1116    repeat:
1117    
1118            if (pEnc->flush_bframes)
1119                          {                          {
1120                                  pMB->mode = MODE_INTRA;                  if (pEnc->bframenum_head < pEnc->bframenum_tail) {
1121    
1122                            DPRINTF(XVID_DEBUG_DEBUG,"*** BFRAME (flush) bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1123                                            pEnc->bframenum_head, pEnc->bframenum_tail,
1124                                            pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1125    
1126                            if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1127                                    image_copy(&pEnc->sOriginal2, &pEnc->bframes[pEnc->bframenum_head]->image,
1128                                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1129                            }
1130    
1131                            FrameCodeB(pEnc, pEnc->bframes[pEnc->bframenum_head], &bs);
1132                            call_plugins(pEnc, pEnc->bframes[pEnc->bframenum_head], &pEnc->sOriginal2, XVID_PLG_AFTER, NULL, NULL, stats);
1133                            pEnc->bframenum_head++;
1134    
1135                            goto done;
1136                    }
1137    
1138                    /* write an empty marker to the bitstream.
1139    
1140                       for divx5 decoder compatibility, this marker must consist
1141                       of a not-coded p-vop, with a time_base of zero, and time_increment
1142                       indentical to the future-referece frame.
1143                    */
1144    
1145                    if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED && pEnc->bframenum_tail > 0)) {
1146                            int tmp;
1147                            int bits;
1148    
1149                            DPRINTF(XVID_DEBUG_DEBUG,"*** EMPTY bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1150                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1151                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1152    
1153                            bits = BitstreamPos(&bs);
1154    
1155                            tmp = pEnc->current->seconds;
1156                            pEnc->current->seconds = 0; /* force time_base = 0 */
1157    
1158                            BitstreamWriteVopHeader(&bs, &pEnc->mbParam, pEnc->current, 0, pEnc->current->quant);
1159                            BitstreamPad(&bs);
1160                            pEnc->current->seconds = tmp;
1161    
1162                            /* add the not-coded length to the reference frame size */
1163                            pEnc->current->length += (BitstreamPos(&bs) - bits) / 8;
1164                            call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1165    
1166                            /* flush complete: reset counters */
1167                            pEnc->flush_bframes = 0;
1168                            pEnc->bframenum_head = pEnc->bframenum_tail = 0;
1169                            goto done;
1170    
1171                    }
1172    
1173                    /* flush complete: reset counters */
1174                    pEnc->flush_bframes = 0;
1175                    pEnc->bframenum_head = pEnc->bframenum_tail = 0;
1176            }
1177    
1178            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1179             * dequeue frame from the encoding queue
1180             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1181    
1182                                  for (vec=0 ; vec<4 ; ++vec)          if (pEnc->queue_size == 0)              /* empty */
1183                                  {                                  {
1184                                          pMB->mvs[vec].x = pMB->mvs[vec].y = 0;                  if (xFrame->input.csp == XVID_CSP_NULL) /* no futher input */
1185                    {
1186    
1187                            DPRINTF(XVID_DEBUG_DEBUG,"*** FINISH bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1188                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1189                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1190    
1191                            if (!(pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->mbParam.max_bframes > 0) {
1192                                    call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1193                                  }                                  }
1194    
1195                            /* if the very last frame is to be b-vop, we must change it to a p-vop */
1196                            if (pEnc->bframenum_tail > 0) {
1197    
1198                                    SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1199                                    pEnc->bframenum_tail--;
1200                                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1201    
1202                                    /* convert B-VOP to P-VOP */
1203                                    pEnc->current->quant  = 100*pEnc->current->quant - pEnc->mbParam.bquant_offset;
1204                                    pEnc->current->quant += pEnc->mbParam.bquant_ratio - 1; /* to avoid rouding issues */
1205                                    pEnc->current->quant /= pEnc->mbParam.bquant_ratio;
1206    
1207                                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1208                                            image_copy(&pEnc->sOriginal, &pEnc->current->image,
1209                                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1210                          }                          }
1211    
1212                                    DPRINTF(XVID_DEBUG_DEBUG,"*** PFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1213                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1214                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1215                                    pEnc->mbParam.frame_drop_ratio = -1; /* it must be a coded vop */
1216    
1217                                    FrameCodeP(pEnc, &bs);
1218    
1219    
1220                                    if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail==0) {
1221                                            call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1222                                    }else{
1223                                            pEnc->flush_bframes = 1;
1224                                            goto done;
1225                  }                  }
1226          }          }
1227                            DPRINTF(XVID_DEBUG_DEBUG, "*** END\n");
1228    
1229                            emms();
1230                            return XVID_ERR_END;    /* end of stream reached */
1231                    }
1232                    goto done;      /* nothing to encode yet; encoder lag */
1233  }  }
1234    
1235            /* the current FRAME becomes the reference */
1236            SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1237    
1238  void HintedMEGet(Encoder * pEnc, int intra)          /* remove frame from encoding-queue (head), and move it into the current */
1239  {          image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_head].image);
1240          HINTINFO * hint;          frame = &pEnc->queue[pEnc->queue_head].frame;
1241          Bitstream bs;          pEnc->queue_head = (pEnc->queue_head + 1) % (pEnc->mbParam.max_bframes+1);
1242          uint32_t x, y;          pEnc->queue_size--;
         int length, high;  
1243    
         hint = pEnc->mbParam.hint;  
1244    
1245          if (hint->rawhints)          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1246          {           * init pEnc->current fields
1247                  hint->mvhint.intra = intra;           * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1248    
1249            pEnc->current->fincr = pEnc->mbParam.fincr>0 ? pEnc->mbParam.fincr : frame->fincr;
1250            inc_frame_num(pEnc);
1251            pEnc->current->vol_flags = frame->vol_flags;
1252            pEnc->current->vop_flags = frame->vop_flags;
1253            pEnc->current->motion_flags = frame->motion;
1254            pEnc->current->fcode = pEnc->mbParam.m_fcode;
1255            pEnc->current->bcode = pEnc->mbParam.m_fcode;
1256    
1257    
1258            if ((xFrame->vop_flags & XVID_VOP_CHROMAOPT)) {
1259                    image_chroma_optimize(&pEnc->current->image,
1260                            pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.edged_width);
1261            }
1262    
1263            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1264             * frame type & quant selection
1265             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1266    
1267            type = frame->type;
1268            pEnc->current->quant = frame->quant;
1269    
1270            call_plugins(pEnc, pEnc->current, NULL, XVID_PLG_BEFORE, &type, (int*)&pEnc->current->quant, stats);
1271    
1272            if (type > 0){  /* XVID_TYPE_?VOP */
1273                    type = type2coding(type);       /* convert XVID_TYPE_?VOP to bitstream coding type */
1274            } else{         /* XVID_TYPE_AUTO */
1275                    if (pEnc->iFrameNum == 0 || (pEnc->mbParam.iMaxKeyInterval > 0 && pEnc->iFrameNum >= pEnc->mbParam.iMaxKeyInterval)){
1276                            pEnc->iFrameNum = 0;
1277                            type = I_VOP;
1278                    }else{
1279                            type = MEanalysis(&pEnc->reference->image, pEnc->current,
1280                                                              &pEnc->mbParam, pEnc->mbParam.iMaxKeyInterval,
1281                                                              pEnc->iFrameNum, pEnc->bframenum_tail, xFrame->bframe_threshold,
1282                                                              (pEnc->bframes) ? pEnc->bframes[pEnc->bframenum_head]->mbs: NULL);
1283          }          }
         else  
         {  
                 BitstreamInit(&bs, hint->hintstream, 0);  
                 BitstreamPutBit(&bs, intra);  
1284          }          }
1285    
1286          if (intra)          if (type != I_VOP)
1287          {                  pEnc->current->vol_flags = pEnc->mbParam.vol_flags; /* don't allow VOL changes here */
1288                  if (!hint->rawhints)  
1289                  {          /* bframes buffer overflow check */
1290                          BitstreamPad(&bs);          if (type == B_VOP && pEnc->bframenum_tail >= pEnc->mbParam.max_bframes) {
1291                          hint->hintlength = BitstreamLength(&bs);                  type = P_VOP;
1292                  }                  }
1293                  return;  
1294            pEnc->iFrameNum++;
1295    
1296            if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1297                    image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 5,
1298                            "%d  st:%lld  if:%d", pEnc->current->frame_num, pEnc->current->stamp, pEnc->iFrameNum);
1299          }          }
1300    
1301          length  = pEnc->current->fcode + 5;          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1302          high    = 1 << (length - 1);           * encode this frame as a b-vop
1303             * (we dont encode here, rather we store the frame in the bframes queue, to be encoded later)
1304             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1305            if (type == B_VOP) {
1306                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1307                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "BVOP");
1308                    }
1309    
1310          if (hint->rawhints)                  if (frame->quant < 1) {
1311          {                          pEnc->current->quant = ((((pEnc->reference->quant + pEnc->current->quant) *
1312                  hint->mvhint.fcode = pEnc->current->fcode;                                  pEnc->mbParam.bquant_ratio) / 2) + pEnc->mbParam.bquant_offset)/100;
1313    
1314                    } else {
1315                            pEnc->current->quant = frame->quant;
1316          }          }
1317          else  
1318          {                  if (pEnc->current->quant < 1)
1319                  BitstreamPutBits(&bs, pEnc->current->fcode, FCODEBITS);                          pEnc->current->quant = 1;
1320                    else if (pEnc->current->quant > 31)
1321                            pEnc->current->quant = 31;
1322    
1323                    DPRINTF(XVID_DEBUG_DEBUG,"*** BFRAME (store) bf: head=%i tail=%i   queue: head=%i tail=%i size=%i  quant=%i\n",
1324                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1325                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size,pEnc->current->quant);
1326    
1327                    /* store frame into bframe buffer & swap ref back to current */
1328                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1329                    SWAP(FRAMEINFO*, pEnc->current, pEnc->reference);
1330    
1331                    pEnc->bframenum_tail++;
1332    
1333                    goto repeat;
1334          }          }
1335    
         for (y=0 ; y<pEnc->mbParam.mb_height ; ++y)  
         {  
                 for (x=0 ; x<pEnc->mbParam.mb_width ; ++x)  
                 {  
                         MACROBLOCK * pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
                         MVBLOCKHINT * bhint = &hint->mvhint.block[x + y * pEnc->mbParam.mb_width];  
                         VECTOR tmp;  
1336    
1337                          if (hint->rawhints)                  DPRINTF(XVID_DEBUG_DEBUG,"*** XXXXXX bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1338                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1339                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1340    
1341            /* for unpacked bframes, output the stats for the last encoded frame */
1342            if (!(pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->mbParam.max_bframes > 0)
1343                          {                          {
1344                                  bhint->mode = pMB->mode;                  if (pEnc->current->stamp > 0) {
1345                            call_plugins(pEnc, pEnc->reference, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1346                    }
1347            else if (stats) {
1348                stats->type = XVID_TYPE_NOTHING;
1349                          }                          }
                         else  
                         {  
                                 BitstreamPutBits(&bs, pMB->mode, MODEBITS);  
1350                          }                          }
1351    
1352                          if (pMB->mode == MODE_INTER || pMB->mode == MODE_INTER_Q)          /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1353                          {           * closed-gop
1354                                  tmp.x  = pMB->mvs[0].x;           * if the frame prior to an iframe is scheduled as a bframe, we must change it to a pframe
1355                                  tmp.y  = pMB->mvs[0].y;           * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
                                 tmp.x += (tmp.x < 0) ? high*2 : 0;  
                                 tmp.y += (tmp.y < 0) ? high*2 : 0;  
1356    
1357                                  if (hint->rawhints)          if (type == I_VOP && (pEnc->mbParam.global_flags & XVID_GLOBAL_CLOSED_GOP) && pEnc->bframenum_tail > 0) {
1358                                  {  
1359                                          bhint->mvs[0].x = tmp.x;                  /* place this frame back on the encoding-queue (head) */
1360                                          bhint->mvs[0].y = tmp.y;                  /* we will deal with it next time */
1361                    dec_frame_num(pEnc);
1362                    pEnc->iFrameNum--;
1363    
1364                    pEnc->queue_head = (pEnc->queue_head + (pEnc->mbParam.max_bframes+1) - 1) % (pEnc->mbParam.max_bframes+1);
1365                    pEnc->queue_size++;
1366                    image_swap(&pEnc->current->image, &pEnc->queue[pEnc->queue_head].image);
1367    
1368                    /* grab the last frame from the bframe-queue */
1369    
1370                    pEnc->bframenum_tail--;
1371                    SWAP(FRAMEINFO*, pEnc->current, pEnc->bframes[pEnc->bframenum_tail]);
1372    
1373                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1374                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 100, "CLOSED GOP BVOP->PVOP");
1375                                  }                                  }
1376                                  else  
1377                                  {                  /* convert B-VOP quant to P-VOP */
1378                                          BitstreamPutBits(&bs, tmp.x, length);                  pEnc->current->quant  = 100*pEnc->current->quant - pEnc->mbParam.bquant_offset;
1379                                          BitstreamPutBits(&bs, tmp.y, length);                  pEnc->current->quant += pEnc->mbParam.bquant_ratio - 1; /* to avoid rouding issues */
1380                    pEnc->current->quant /= pEnc->mbParam.bquant_ratio;
1381                    type = P_VOP;
1382                                  }                                  }
1383    
1384    
1385            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1386             * encode this frame as an i-vop
1387             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1388    
1389            if (type == I_VOP) {
1390    
1391                    DPRINTF(XVID_DEBUG_DEBUG,"*** IFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1392                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1393                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1394    
1395                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1396                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "IVOP");
1397                          }                          }
                         else if (pMB->mode == MODE_INTER4V)  
                         {  
                                 int vec;  
1398    
1399                                  for (vec=0 ; vec<4 ; ++vec)                  pEnc->iFrameNum = 1;
                                 {  
                                         tmp.x  = pMB->mvs[vec].x;  
                                         tmp.y  = pMB->mvs[vec].y;  
                                         tmp.x += (tmp.x < 0) ? high*2 : 0;  
                                         tmp.y += (tmp.y < 0) ? high*2 : 0;  
1400    
1401                                          if (hint->rawhints)                  /* ---- update vol flags at IVOP ----------- */
1402                                          {                  pEnc->mbParam.vol_flags = pEnc->current->vol_flags;
1403                                                  bhint->mvs[vec].x = tmp.x;  
1404                                                  bhint->mvs[vec].y = tmp.y;                  /* Aspect ratio */
1405                    switch(frame->par) {
1406                    case XVID_PAR_11_VGA:
1407                    case XVID_PAR_43_PAL:
1408                    case XVID_PAR_43_NTSC:
1409                    case XVID_PAR_169_PAL:
1410                    case XVID_PAR_169_NTSC:
1411                    case XVID_PAR_EXT:
1412                            pEnc->mbParam.par = frame->par;
1413                            break;
1414                    default:
1415                            pEnc->mbParam.par = XVID_PAR_11_VGA;
1416                            break;
1417                                          }                                          }
1418                                          else  
1419                                          {                  /* For extended PAR only, we try to sanityse/simplify par values */
1420                                                  BitstreamPutBits(&bs, tmp.x, length);                  if (pEnc->mbParam.par == XVID_PAR_EXT) {
1421                                                  BitstreamPutBits(&bs, tmp.y, length);                          pEnc->mbParam.par_width  = frame->par_width;
1422                            pEnc->mbParam.par_height = frame->par_height;
1423                            simplify_par(&pEnc->mbParam.par_width, &pEnc->mbParam.par_height);
1424                    }
1425    
1426                    if ((pEnc->mbParam.vol_flags & XVID_VOL_MPEGQUANT)) {
1427                            if (frame->quant_intra_matrix != NULL)
1428                                    set_intra_matrix(pEnc->mbParam.mpeg_quant_matrices, frame->quant_intra_matrix);
1429                            if (frame->quant_inter_matrix != NULL)
1430                                    set_inter_matrix(pEnc->mbParam.mpeg_quant_matrices, frame->quant_inter_matrix);
1431                    }
1432    
1433                    /* prevent vol/vop misuse */
1434    
1435                    if (!(pEnc->current->vol_flags & XVID_VOL_INTERLACING))
1436                            pEnc->current->vop_flags &= ~(XVID_VOP_TOPFIELDFIRST|XVID_VOP_ALTERNATESCAN);
1437    
1438                    /* ^^^------------------------ */
1439    
1440                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1441                            image_copy(&pEnc->sOriginal, &pEnc->current->image,
1442                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1443                                          }                                          }
1444    
1445                    FrameCodeI(pEnc, &bs);
1446                    xFrame->out_flags |= XVID_KEYFRAME;
1447    
1448            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1449             * encode this frame as an p-vop
1450             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1451    
1452            } else { /* (type == P_VOP || type == S_VOP) */
1453    
1454                    DPRINTF(XVID_DEBUG_DEBUG,"*** PFRAME bf: head=%i tail=%i   queue: head=%i tail=%i size=%i\n",
1455                                    pEnc->bframenum_head, pEnc->bframenum_tail,
1456                                    pEnc->queue_head, pEnc->queue_tail, pEnc->queue_size);
1457    
1458                    if ((pEnc->current->vop_flags & XVID_VOP_DEBUG)) {
1459                            image_printf(&pEnc->current->image, pEnc->mbParam.edged_width, pEnc->mbParam.height, 5, 200, "PVOP");
1460                                  }                                  }
1461    
1462                    if ((pEnc->mbParam.plugin_flags & XVID_REQORIGINAL)) {
1463                            image_copy(&pEnc->sOriginal, &pEnc->current->image,
1464                                       pEnc->mbParam.edged_width, pEnc->mbParam.height);
1465                          }                          }
1466    
1467                    if ( FrameCodeP(pEnc, &bs) == 0 ) {
1468                            /* N-VOP, we mustn't code b-frames yet */
1469                            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) ||
1470                                     pEnc->mbParam.max_bframes == 0)
1471                                    call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1472                            goto done;
1473                  }                  }
1474          }          }
1475    
1476          if (!hint->rawhints)  
1477            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1478             * on next enc_encode call we must flush bframes
1479             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1480    
1481    /*done_flush:*/
1482    
1483            pEnc->flush_bframes = 1;
1484    
1485            /* packed & queued_bframes: dont bother outputting stats here, we do so after the flush */
1486            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) && pEnc->bframenum_tail > 0) {
1487                    goto repeat;
1488            }
1489    
1490            /* packed or no-bframes or no-bframes-queued: output stats */
1491            if ((pEnc->mbParam.global_flags & XVID_GLOBAL_PACKED) || pEnc->mbParam.max_bframes == 0 ) {
1492                    call_plugins(pEnc, pEnc->current, &pEnc->sOriginal, XVID_PLG_AFTER, NULL, NULL, stats);
1493            }
1494    
1495            /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1496             * done; return number of bytes consumed
1497             * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */
1498    
1499    done:
1500    
1501            stop_global_timer();
1502            write_timer();
1503    
1504            emms();
1505            return BitstreamLength(&bs);
1506    }
1507    
1508    
1509    static void SetMacroblockQuants(MBParam * const pParam, FRAMEINFO * frame)
1510          {          {
1511                  BitstreamPad(&bs);          unsigned int i;
1512                  hint->hintlength = BitstreamLength(&bs);          MACROBLOCK * pMB = frame->mbs;
1513            int quant = frame->mbs[0].quant; /* set by XVID_PLG_FRAME */
1514            if (quant > 31)
1515                    frame->quant = quant = 31;
1516            else if (quant < 1)
1517                    frame->quant = quant = 1;
1518    
1519            for (i = 0; i < pParam->mb_height * pParam->mb_width; i++) {
1520                    quant += pMB->dquant;
1521                    if (quant > 31)
1522                            quant = 31;
1523                    else if (quant < 1)
1524                            quant = 1;
1525                    pMB->quant = quant;
1526                    pMB++;
1527          }          }
1528  }  }
1529    
1530    
1531  static int FrameCodeI(Encoder * pEnc, Bitstream * bs, uint32_t *pBits)  static __inline void
1532    CodeIntraMB(MACROBLOCK * pMB)
1533  {  {
1534            pMB->mode = MODE_INTRA;
1535    
1536          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);          /* zero mv statistics */
1537          DECLARE_ALIGNED_MATRIX(qcoeff,    6, 64, int16_t, CACHE_LINE);          pMB->mvs[0].x = pMB->mvs[1].x = pMB->mvs[2].x = pMB->mvs[3].x = 0;
1538            pMB->mvs[0].y = pMB->mvs[1].y = pMB->mvs[2].y = pMB->mvs[3].y = 0;
1539            pMB->sad8[0] = pMB->sad8[1] = pMB->sad8[2] = pMB->sad8[3] = 0;
1540            pMB->sad16 = 0;
1541    
1542            if (pMB->dquant != 0) {
1543                    pMB->mode = MODE_INTRA_Q;
1544            }
1545    }
1546    
1547    static void
1548    SliceCodeI(SMPData *data)
1549    {
1550            Encoder *pEnc = (Encoder *) data->pEnc;
1551            Bitstream *bs = (Bitstream *) data->bs;
1552    
1553          uint16_t x, y;          uint16_t x, y;
1554            int mb_width = pEnc->mbParam.mb_width;
1555            int mb_height = pEnc->mbParam.mb_height;
1556    
1557          pEnc->iFrameNum = 0;          int bound = 0, num_slices = pEnc->num_slices;
1558          pEnc->mbParam.m_rounding_type = 1;          FRAMEINFO *const current = pEnc->current;
1559          pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;  
1560          pEnc->current->coding_type = I_VOP;          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1561            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
1562    
1563          BitstreamWriteVolHeader(bs, &pEnc->mbParam, pEnc->current);          if (data->start_y > 0) { /* write resync marker */
1564          BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current);                  bound = data->start_y*mb_width;
1565                    write_video_packet_header(bs, &pEnc->mbParam, current, bound);
1566            }
1567    
1568          *pBits = BitstreamPos(bs);          for (y = data->start_y; y < data->stop_y; y++) {
1569                    int new_bound = mb_width * ((((y*num_slices) / mb_height) * mb_height + (num_slices-1)) / num_slices);
1570    
1571          pEnc->sStat.iTextBits = 0;                  if (new_bound > bound) {
1572          pEnc->sStat.kblks = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height;                          bound = new_bound;
1573          pEnc->sStat.mblks = pEnc->sStat.ublks = 0;                          BitstreamPadAlways(bs);
1574                            write_video_packet_header(bs, &pEnc->mbParam, current, bound);
1575                    }
1576    
1577          for (y = 0; y < pEnc->mbParam.mb_height; y++)                  for (x = 0; x < mb_width; x++) {
1578                  for (x = 0; x < pEnc->mbParam.mb_width; x++)                          MACROBLOCK *pMB = &current->mbs[x + y * mb_width];
                 {  
                         MACROBLOCK *pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
1579    
1580                          CodeIntraMB(pEnc, pMB);                          CodeIntraMB(pMB);
1581    
1582                          MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y, dct_codes, qcoeff);                          MBTransQuantIntra(&pEnc->mbParam, current, pMB, x, y,
1583                                                              dct_codes, qcoeff);
1584    
1585                          start_timer();                          start_timer();
1586                          MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);                          MBPrediction(current, x, y, mb_width, qcoeff, bound);
1587                          stop_prediction_timer();                          stop_prediction_timer();
1588    
1589                          start_timer();                          start_timer();
1590                          MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->sStat);                          MBCoding(current, pMB, qcoeff, bs, data->sStat);
1591                          stop_coding_timer();                          stop_coding_timer();
1592    
1593                    }
1594                  }                  }
1595    
1596          emms();          emms();
1597            BitstreamPadAlways(bs);
1598    }
1599    
1600          *pBits = BitstreamPos(bs) - *pBits;  static __inline void
1601          pEnc->sStat.fMvPrevSigma = -1;  SerializeBitstreams(Encoder *pEnc, FRAMEINFO *current, Bitstream *bs, int num_threads)
1602          pEnc->sStat.iMvSum = 0;  {
1603          pEnc->sStat.iMvCount = 0;          int k;
1604          pEnc->mbParam.m_fcode = 2;          uint32_t pos = BitstreamLength(bs);
1605    
1606            for (k = 1; k < num_threads; k++) {
1607                    uint32_t len = BitstreamLength(pEnc->smpData[k].bs);
1608    
1609                    memcpy((void *)((ptr_t)bs->start + pos),
1610                               (void *)((ptr_t)pEnc->smpData[k].bs->start), len);
1611    
1612                    current->length = pos += len;
1613    
1614                    /* collect stats */
1615                    current->sStat.iTextBits += pEnc->smpData[k].sStat->iTextBits;
1616                    current->sStat.kblks += pEnc->smpData[k].sStat->kblks;
1617                    current->sStat.mblks += pEnc->smpData[k].sStat->mblks;
1618                    current->sStat.ublks += pEnc->smpData[k].sStat->ublks;
1619                    current->sStat.iMVBits += pEnc->smpData[k].sStat->iMVBits;
1620            }
1621    
1622            if (num_threads > 1) {
1623                    uint32_t pos32 = pos>>2;
1624                    bs->tail = bs->start + pos32;
1625                    bs->pos = 8*(pos - (pos32<<2));
1626                    bs->buf = 0;
1627    
1628          if (pEnc->current->global_flags & XVID_HINTEDME_GET)                  if (bs->pos > 0) {
1629                            uint32_t pos8 = bs->pos/8;
1630                            memset((void *)((ptr_t)bs->tail+pos8), 0, (4-pos8));
1631                            pos = *bs->tail;
1632    #ifndef ARCH_IS_BIG_ENDIAN
1633                            BSWAP(pos);
1634    #endif
1635                            bs->buf = pos;
1636                    }
1637            }
1638    }
1639    
1640    static int
1641    FrameCodeI(Encoder * pEnc,
1642                       Bitstream * bs)
1643          {          {
1644                  HintedMEGet(pEnc, 1);          int bits = BitstreamPos(bs);
1645            int bound = 0, num_slices = pEnc->num_slices;
1646            int num_threads = MAX(1, MIN(pEnc->num_threads, num_slices));
1647            int slices_per_thread = (num_slices*1024 / num_threads);
1648            int mb_height = pEnc->mbParam.mb_height;
1649            void * status = NULL;
1650            uint16_t k;
1651    
1652            pEnc->mbParam.m_rounding_type = 1;
1653            pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;
1654            pEnc->current->coding_type = I_VOP;
1655    
1656            call_plugins(pEnc, pEnc->current, NULL, XVID_PLG_FRAME, NULL, NULL, NULL);
1657    
1658            SetMacroblockQuants(&pEnc->mbParam, pEnc->current);
1659    
1660            BitstreamWriteVolHeader(bs, &pEnc->mbParam, pEnc->current, num_slices);
1661    
1662            set_timecodes(pEnc->current,pEnc->reference,pEnc->mbParam.fbase);
1663    
1664            BitstreamPad(bs);
1665    
1666            BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current, 1, pEnc->current->mbs[0].quant);
1667    
1668            pEnc->current->sStat.iTextBits = 0;
1669    
1670            /* multithreaded intra coding - dispatch threads */
1671            for (k = 0; k < num_threads; k++) {
1672                    int add = ((slices_per_thread + 512) >> 10);
1673    
1674                    slices_per_thread += ((num_slices*1024 / num_threads) - add*1024);
1675    
1676                    pEnc->smpData[k].pEnc = (void *) pEnc;
1677                    pEnc->smpData[k].stop_y = (((bound+add) * mb_height + (num_slices-1)) / num_slices);
1678                    pEnc->smpData[k].start_y = ((bound * mb_height + (num_slices-1)) / num_slices);
1679    
1680                    bound += add;
1681    
1682                    if (k > 0) {
1683                            BitstreamReset(pEnc->smpData[k].bs);
1684                            pEnc->smpData[k].sStat->iTextBits = 0;
1685          }          }
1686            }
1687            pEnc->smpData[0].bs = bs;
1688            pEnc->smpData[0].sStat = &pEnc->current->sStat;
1689    
1690            /* create threads */
1691            for (k = 1; k < num_threads; k++) {
1692                    pthread_create(&pEnc->smpData[k].handle, NULL,
1693                                   (void*)SliceCodeI, (void*)&pEnc->smpData[k]);
1694            }
1695    
1696            SliceCodeI(&pEnc->smpData[0]);
1697    
1698          return 1;                                        // intra          /* wait until all threads are finished */
1699            for (k = 1; k < num_threads; k++) {
1700                    pthread_join(pEnc->smpData[k].handle, &status);
1701  }  }
1702    
1703            pEnc->current->length = BitstreamLength(bs) - (bits/8);
1704    
1705            /* reassemble the pieces together */
1706            SerializeBitstreams(pEnc, pEnc->current, bs, num_threads);
1707    
1708            pEnc->current->sStat.iMVBits = 0;
1709            pEnc->current->sStat.mblks = pEnc->current->sStat.ublks = 0;
1710            pEnc->current->sStat.kblks = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height;
1711    
1712            pEnc->fMvPrevSigma = -1;
1713            pEnc->mbParam.m_fcode = 2;
1714    
1715  #define INTRA_THRESHOLD 0.5          pEnc->current->is_edged = 0; /* not edged */
1716            pEnc->current->is_interpolated = -1; /* not interpolated (fake rounding -1) */
1717    
1718  static int FrameCodeP(Encoder * pEnc, Bitstream * bs, uint32_t *pBits, bool force_inter, bool vol_header)          return 1;                                       /* intra */
1719    }
1720    
1721    static __inline void
1722    updateFcode(Statistics * sStat, Encoder * pEnc)
1723  {  {
1724          float fSigma;          float fSigma;
1725            int iSearchRange;
1726    
1727            if (sStat->iMvCount == 0)
1728                    sStat->iMvCount = 1;
1729    
1730            fSigma = (float) sqrt((float) sStat->iMvSum / sStat->iMvCount);
1731    
1732            iSearchRange = 16 << pEnc->mbParam.m_fcode;
1733    
1734            if ((3.0 * fSigma > iSearchRange) && (pEnc->mbParam.m_fcode <= 5) )
1735                    pEnc->mbParam.m_fcode++;
1736    
1737            else if ((5.0 * fSigma < iSearchRange)
1738                               && (4.0 * pEnc->fMvPrevSigma < iSearchRange)
1739                               && (pEnc->mbParam.m_fcode >= 2) )
1740                    pEnc->mbParam.m_fcode--;
1741    
1742            pEnc->fMvPrevSigma = fSigma;
1743    }
1744    
1745    #define BFRAME_SKIP_THRESHHOLD 30
1746    
1747    static void
1748    SliceCodeP(SMPData *data)
1749    {
1750            Encoder *pEnc = (Encoder *) data->pEnc;
1751            Bitstream *bs = (Bitstream *) data->bs;
1752    
1753            int x, y, k;
1754            FRAMEINFO *const current = pEnc->current;
1755            FRAMEINFO *const reference = pEnc->reference;
1756            MBParam * const pParam = &pEnc->mbParam;
1757            int mb_width = pParam->mb_width;
1758            int mb_height = pParam->mb_height;
1759    
1760          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
1761          DECLARE_ALIGNED_MATRIX(qcoeff,    6, 64, int16_t, CACHE_LINE);          DECLARE_ALIGNED_MATRIX(qcoeff,    6, 64, int16_t, CACHE_LINE);
1762    
1763          int iLimit;          int bound = 0, num_slices = pEnc->num_slices;
1764          uint32_t x, y;  
1765          int iSearchRange;          if (data->start_y > 0) { /* write resync marker */
1766          int bIntra;                  bound = data->start_y*mb_width;
1767                    write_video_packet_header(bs, pParam, current, bound);
1768            }
1769    
1770            for (y = data->start_y; y < data->stop_y; y++) {
1771                    int new_bound = mb_width * ((((y*num_slices) / mb_height) * mb_height + (num_slices-1)) / num_slices);
1772    
1773                    if (new_bound > bound) {
1774                            bound = new_bound;
1775                            BitstreamPadAlways(bs);
1776                            write_video_packet_header(bs, pParam, current, bound);
1777                    }
1778    
1779                    for (x = 0; x < mb_width; x++) {
1780                            MACROBLOCK *pMB = &current->mbs[x + y * pParam->mb_width];
1781                            int skip_possible;
1782    
1783          /* IMAGE *pCurrent = &pEnc->current->image; */                          if (pMB->mode == MODE_INTRA || pMB->mode == MODE_INTRA_Q) {
1784          IMAGE *pRef = &pEnc->reference->image;                                  CodeIntraMB(pMB);
1785                                    MBTransQuantIntra(pParam, current, pMB, x, y,
1786                                                                      dct_codes, qcoeff);
1787    
1788          start_timer();          start_timer();
1789          image_setedges(pRef,                                  MBPrediction(current, x, y, pParam->mb_width, qcoeff, bound);
1790                         pEnc->mbParam.edged_width,                                  stop_prediction_timer();
                        pEnc->mbParam.edged_height,  
                        pEnc->mbParam.width,  
                        pEnc->mbParam.height,  
                        pEnc->current->global_flags & XVID_INTERLACING);  
         stop_edges_timer();  
1791    
1792          pEnc->mbParam.m_rounding_type = 1 - pEnc->mbParam.m_rounding_type;                                  data->sStat->kblks++;
         pEnc->current->rounding_type = pEnc->mbParam.m_rounding_type;  
         pEnc->current->fcode = pEnc->mbParam.m_fcode;  
1793    
1794          if (!force_inter)                                  MBCoding(current, pMB, qcoeff, bs, data->sStat);
1795                  iLimit = (int)(pEnc->mbParam.mb_width * pEnc->mbParam.mb_height * INTRA_THRESHOLD);                                  stop_coding_timer();
1796          else                                  continue;
1797                  iLimit = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height + 1;                          }
1798    
         if ((pEnc->current->global_flags & XVID_HALFPEL)) {  
1799                  start_timer();                  start_timer();
1800                  image_interpolate(pRef, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,                          MBMotionCompensation(pMB, x, y, &reference->image,
1801                                    pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,                                                                   &pEnc->vInterH, &pEnc->vInterV,
1802                                    pEnc->current->rounding_type);                                                                   &pEnc->vInterHV, &pEnc->vGMC,
1803                  stop_inter_timer();                                                                   &current->image,
1804                                                                     dct_codes, pParam->width,
1805                                                                     pParam->height,
1806                                                                     pParam->edged_width,
1807                                                                     (current->vol_flags & XVID_VOL_QUARTERPEL),
1808                                                                     current->rounding_type,
1809                                                                     data->RefQ);
1810    
1811                            stop_comp_timer();
1812    
1813                            pMB->field_pred = 0;
1814    
1815                            if (pMB->cbp != 0) {
1816                                    pMB->cbp = MBTransQuantInter(pParam, current, pMB, x, y,
1817                                                                 dct_codes, qcoeff);
1818                            }
1819    
1820                            if (pMB->dquant != 0)
1821                                    MBSetDquant(pMB, x, y, pParam);
1822    
1823    
1824                            if (pMB->cbp || pMB->mvs[0].x || pMB->mvs[0].y ||
1825                                       pMB->mvs[1].x || pMB->mvs[1].y || pMB->mvs[2].x ||
1826                                       pMB->mvs[2].y || pMB->mvs[3].x || pMB->mvs[3].y) {
1827                                    data->sStat->mblks++;
1828                            }  else {
1829                                    data->sStat->ublks++;
1830          }          }
1831    
1832          start_timer();          start_timer();
1833          if (pEnc->current->global_flags & XVID_HINTEDME_SET)  
1834          {                          /* Finished processing the MB, now check if to CODE or SKIP */
1835                  HintedMESet(pEnc, &bIntra);  
1836                            skip_possible = (pMB->cbp == 0) && (pMB->mode == MODE_INTER);
1837    
1838                            if (current->coding_type == S_VOP)
1839                                    skip_possible &= (pMB->mcsel == 1);
1840                            else { /* PVOP */
1841                                    const VECTOR * const mv = (pParam->vol_flags & XVID_VOL_QUARTERPEL) ?
1842                                                                                    pMB->qmvs : pMB->mvs;
1843                                    skip_possible &= ((mv->x|mv->y) == 0);
1844                            }
1845    
1846                            if ((pMB->mode == MODE_NOT_CODED) || (skip_possible)) {
1847                                    /* This is a candidate for SKIPping, but for P-VOPs check intermediate B-frames first */
1848                                    int bSkip = 1;
1849    
1850                                    if (current->coding_type == P_VOP) {    /* special rule for P-VOP's SKIP */
1851                                            for (k = pEnc->bframenum_head; k < pEnc->bframenum_tail; k++) {
1852                                                    int iSAD;
1853                                                    iSAD = sad16(reference->image.y + 16*y*pParam->edged_width + 16*x,
1854                                                                                    pEnc->bframes[k]->image.y + 16*y*pParam->edged_width + 16*x,
1855                                                                                    pParam->edged_width, BFRAME_SKIP_THRESHHOLD * pMB->quant);
1856                                                    if (iSAD >= BFRAME_SKIP_THRESHHOLD * pMB->quant || ((bound > 1) &&
1857                                                            ((y*mb_width+x == bound) || (y*mb_width+x == bound+1)))) { /* Some third-party decoders have problems with coloc skip MB before or after
1858                                                                                                                                                                               resync marker in BVOP. We avoid any ambiguity and force no skip at slice boundary */
1859                                                            bSkip = 0; /* could not SKIP */
1860                                                            if (pParam->vol_flags & XVID_VOL_QUARTERPEL) {
1861                                                                    VECTOR predMV = get_qpmv2(current->mbs, pParam->mb_width, bound, x, y, 0);
1862                                                                    pMB->pmvs[0].x = - predMV.x;
1863                                                                    pMB->pmvs[0].y = - predMV.y;
1864                                                            } else {
1865                                                                    VECTOR predMV = get_pmv2(current->mbs, pParam->mb_width, bound, x, y, 0);
1866                                                                    pMB->pmvs[0].x = - predMV.x;
1867                                                                    pMB->pmvs[0].y = - predMV.y;
1868                                                            }
1869                                                            pMB->mode = MODE_INTER;
1870                                                            pMB->cbp = 0;
1871                                                            break;
1872                                                    }
1873          }          }
         else  
         {  
                 bIntra = MotionEstimation(  
                         &pEnc->mbParam,  
                         pEnc->current,  
                         pEnc->reference,  
                         &pEnc->vInterH,  
                         &pEnc->vInterV,  
                         &pEnc->vInterHV,  
                         iLimit);  
1874          }          }
         stop_motion_timer();  
1875    
1876          if (bIntra == 1)                                  if (bSkip) {
1877          {                                          /* do SKIP */
1878                  return FrameCodeI(pEnc, bs, pBits);                                          pMB->mode = MODE_NOT_CODED;
1879                                            MBSkip(bs);
1880                                            stop_coding_timer();
1881                                            continue;       /* next MB */
1882                                    }
1883          }          }
1884    
1885          pEnc->current->coding_type = P_VOP;                          /* ordinary case: normal coded INTER/INTER4V block */
1886                            MBCoding(current, pMB, qcoeff, bs, data->sStat);
1887                            stop_coding_timer();
1888                    }
1889            }
1890    
1891          if(vol_header)          BitstreamPadAlways(bs); /* next_start_code() at the end of VideoObjectPlane() */
1892                  BitstreamWriteVolHeader(bs, &pEnc->mbParam, pEnc->current);          emms();
1893    }
1894    
1895          BitstreamWriteVopHeader(bs, &pEnc->mbParam, pEnc->current);  /* FrameCodeP also handles S(GMC)-VOPs */
1896    static int
1897    FrameCodeP(Encoder * pEnc, Bitstream * bs)
1898    {
1899            int bits = BitstreamPos(bs);
1900    
1901            FRAMEINFO *const current = pEnc->current;
1902            FRAMEINFO *const reference = pEnc->reference;
1903            MBParam * const pParam = &pEnc->mbParam;
1904            int mb_width = pParam->mb_width;
1905            int mb_height = pParam->mb_height;
1906            int coded = 1;
1907    
1908            int k = 0, bound = 0, num_slices = pEnc->num_slices;
1909            int num_threads = MAX(1, MIN(pEnc->num_threads, num_slices));
1910            void * status = NULL;
1911            int slices_per_thread = (num_slices*1024 / num_threads);
1912            int threads_per_slice = (pEnc->num_threads*1024 / num_threads);
1913    
1914          *pBits = BitstreamPos(bs);          IMAGE *pRef = &reference->image;
1915    
1916          pEnc->sStat.iTextBits = 0;          if (!reference->is_edged) {
1917          pEnc->sStat.iMvSum = 0;                  start_timer();
1918          pEnc->sStat.iMvCount = 0;                  image_setedges(pRef, pParam->edged_width, pParam->edged_height,
1919          pEnc->sStat.kblks = pEnc->sStat.mblks = pEnc->sStat.ublks = 0;                                             pParam->width, pParam->height, 0);
1920                    stop_edges_timer();
1921                    reference->is_edged = 1;
1922            }
1923    
1924          for(y = 0; y < pEnc->mbParam.mb_height; y++)          pParam->m_rounding_type = 1 - pParam->m_rounding_type;
1925          {          current->rounding_type = pParam->m_rounding_type;
1926                  for(x = 0; x < pEnc->mbParam.mb_width; x++)          current->fcode = pParam->m_fcode;
                 {  
                         MACROBLOCK * pMB = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
1927    
1928                          bIntra = (pMB->mode == MODE_INTRA) || (pMB->mode == MODE_INTRA_Q);          if ((current->vop_flags & XVID_VOP_HALFPEL)) {
1929                    if (reference->is_interpolated != current->rounding_type) {
1930                            start_timer();
1931                            image_interpolate(pRef->y, pEnc->vInterH.y, pEnc->vInterV.y,
1932                                                              pEnc->vInterHV.y, pParam->edged_width,
1933                                                              pParam->edged_height,
1934                                                              (pParam->vol_flags & XVID_VOL_QUARTERPEL),
1935                                                              current->rounding_type);
1936                            stop_inter_timer();
1937                            reference->is_interpolated = current->rounding_type;
1938                    }
1939            }
1940    
1941            current->sStat.iTextBits = current->sStat.iMvSum = current->sStat.iMvCount =
1942                    current->sStat.kblks = current->sStat.mblks = current->sStat.ublks =
1943                    current->sStat.iMVBits = 0;
1944    
1945            current->coding_type = P_VOP;
1946    
1947            if (current->vop_flags & XVID_VOP_RD_PSNRHVSM) {
1948                    image_block_variance(&current->image, pParam->edged_width, current->mbs,
1949                                         pParam->mb_width, pParam->mb_height);
1950            }
1951    
1952            call_plugins(pEnc, pEnc->current, NULL, XVID_PLG_FRAME, NULL, NULL, NULL);
1953    
1954            SetMacroblockQuants(&pEnc->mbParam, current);
1955    
                         if (!bIntra)  
                         {  
1956                                  start_timer();                                  start_timer();
1957                                  MBMotionCompensation(pMB,          if (current->vol_flags & XVID_VOL_GMC)  /* GMC only for S(GMC)-VOPs */
1958                                                       x, y,          {       int gmcval;
1959                                                       &pEnc->reference->image,                  current->warp = GlobalMotionEst( current->mbs, pParam, current, reference,
1960                                                                     &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV, num_slices);
1961    
1962                    if (current->motion_flags & XVID_ME_GME_REFINE) {
1963                            gmcval = GlobalMotionEstRefine(&current->warp,
1964                                                                                       current->mbs, pParam,
1965                                                                                       current, reference,
1966                                                                                       &current->image,
1967                                                                                       &reference->image,
1968                                                       &pEnc->vInterH,                                                       &pEnc->vInterH,
1969                                                       &pEnc->vInterV,                                                       &pEnc->vInterV,
1970                                                       &pEnc->vInterHV,                                                                                     &pEnc->vInterHV);
1971                                                       &pEnc->current->image,                  } else {
1972                                                       dct_codes,                          gmcval = globalSAD(&current->warp, pParam, current->mbs,
1973                                                       pEnc->mbParam.width,                                                             current,
1974                                                       pEnc->mbParam.height,                                                             &reference->image,
1975                                                       pEnc->mbParam.edged_width,                                                             &current->image,
1976                                                       pEnc->current->rounding_type);                                                             pEnc->vGMC.y);
1977                                  stop_comp_timer();                  }
1978    
1979                                  if ((pEnc->current->global_flags & XVID_LUMIMASKING)) {                  gmcval += /*current->quant*/ 2 * (int)(pParam->mb_width*pParam->mb_height);
1980                                          if(pMB->dquant != NO_CHANGE) {  
1981                                                  pMB->mode = MODE_INTER_Q;                  /* 1st '3': 3 warpoints, 2nd '3': 16th pel res (2<<3) */
1982                                                  pEnc->current->quant += DQtab[pMB->dquant];                  generate_GMCparameters( 3, 3, &current->warp,
1983                                                  if (pEnc->current->quant > 31) pEnc->current->quant = 31;                                  pParam->width, pParam->height,
1984                                                  else if(pEnc->current->quant < 1) pEnc->current->quant = 1;                                  &current->new_gmc_data);
1985    
1986                    if ( (gmcval<0) && ( (current->warp.duv[1].x != 0) || (current->warp.duv[1].y != 0) ||
1987                             (current->warp.duv[2].x != 0) || (current->warp.duv[2].y != 0) ) )
1988                    {
1989                            current->coding_type = S_VOP;
1990    
1991                            generate_GMCimage(&current->new_gmc_data, &reference->image,
1992                                    pParam->mb_width, pParam->mb_height,
1993                                    pParam->edged_width, pParam->edged_width/2,
1994                                    pParam->m_fcode, ((pParam->vol_flags & XVID_VOL_QUARTERPEL)?1:0), 0,
1995                                    current->rounding_type, current->mbs, &pEnc->vGMC);
1996    
1997                    } else {
1998    
1999                            generate_GMCimage(&current->new_gmc_data, &reference->image,
2000                                    pParam->mb_width, pParam->mb_height,
2001                                    pParam->edged_width, pParam->edged_width/2,
2002                                    pParam->m_fcode, ((pParam->vol_flags & XVID_VOL_QUARTERPEL)?1:0), 0,
2003                                    current->rounding_type, current->mbs, NULL);    /* no warping, just AMV */
2004                                          }                                          }
2005                                  }                                  }
                                 pMB->quant = pEnc->current->quant;  
2006    
2007                                  pMB->field_pred = 0;          if (pEnc->num_threads > 0) {
2008    
2009                    /* multithreaded motion estimation - dispatch threads */
2010                    while (k < pEnc->num_threads) {
2011                            int i, add_s = (slices_per_thread + 512) >> 10;
2012                            int add_t = (threads_per_slice + 512) >> 10;
2013    
2014                                  pMB->cbp = MBTransQuantInter(&pEnc->mbParam, pEnc->current, pMB, x, y, dct_codes, qcoeff);                          int start_y = (bound * mb_height + (num_slices-1)) / num_slices;
2015                            int stop_y = ((bound+add_s) * mb_height + (num_slices-1)) / num_slices;
2016                            int rows_per_thread = (stop_y - start_y + add_t - 1) / add_t;
2017    
2018                            slices_per_thread += ((num_slices*1024 / num_threads) - add_s*1024);
2019                            threads_per_slice += ((pEnc->num_threads*1024 / num_threads) - add_t*1024);
2020    
2021                            for (i = 0; i < add_t; i++) {
2022                                    memset(pEnc->smpData[k+i].complete_count_self, 0, rows_per_thread * sizeof(int));
2023    
2024                                    pEnc->smpData[k+i].pEnc = (void *) pEnc;
2025                                    pEnc->smpData[k+i].y_row = i;
2026                                    pEnc->smpData[k+i].y_step = add_t;
2027                                    pEnc->smpData[k+i].stop_y = stop_y;
2028                                    pEnc->smpData[k+i].start_y = start_y;
2029    
2030                                    /* todo: sort out temp space once and for all */
2031                                    pEnc->smpData[k+i].RefQ = (((k+i)&1) ? pEnc->vInterV.u : pEnc->vInterV.v) +
2032                                                                                            16*((k+i)>>1)*pParam->edged_width;
2033                          }                          }
2034                          else  
2035                          {                          pEnc->smpData[k].complete_count_above =
2036                                  CodeIntraMB(pEnc, pMB);                                  pEnc->smpData[k+add_t-1].complete_count_self - 1;
2037                                  MBTransQuantIntra(&pEnc->mbParam, pEnc->current, pMB, x, y, dct_codes, qcoeff);  
2038                            bound += add_s;
2039                            k += add_t;
2040                          }                          }
2041    
2042                          start_timer();                  for (k = 1; k < pEnc->num_threads; k++) {
2043                          MBPrediction(pEnc->current, x, y, pEnc->mbParam.mb_width, qcoeff);                          pthread_create(&pEnc->smpData[k].handle, NULL,
2044                          stop_prediction_timer();                                  (void*)MotionEstimateSMP, (void*)&pEnc->smpData[k]);
2045                    }
2046    
2047                          if (pMB->mode == MODE_INTRA || pMB->mode == MODE_INTRA_Q)                  MotionEstimateSMP(&pEnc->smpData[0]);
2048                          {  
2049                                  pEnc->sStat.kblks++;                  for (k = 1; k < pEnc->num_threads; k++) {
2050                            pthread_join(pEnc->smpData[k].handle, &status);
2051                          }                          }
2052                          else if (pMB->cbp ||  
2053                                   pMB->mvs[0].x || pMB->mvs[0].y ||                  current->fcode = 0;
2054                                   pMB->mvs[1].x || pMB->mvs[1].y ||                  for (k = 0; k < pEnc->num_threads; k++) {
2055                                   pMB->mvs[2].x || pMB->mvs[2].y ||                          current->sStat.iMvSum += pEnc->smpData[k].mvSum;
2056                                   pMB->mvs[3].x || pMB->mvs[3].y)                          current->sStat.iMvCount += pEnc->smpData[k].mvCount;
2057                          {                          if (pEnc->smpData[k].minfcode > current->fcode)
2058                                  pEnc->sStat.mblks++;                                  current->fcode = pEnc->smpData[k].minfcode;
2059                          }                          }
2060                          else  
2061                          {          } else {
2062                                  pEnc->sStat.ublks++;  
2063                    /* regular ME */
2064    
2065                    MotionEstimation(&pEnc->mbParam, current, reference,
2066                                                     &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,
2067                                                     &pEnc->vGMC, 256*4096, num_slices);
2068    
2069                          }                          }
2070    
2071                          start_timer();          stop_motion_timer();
2072                          MBCoding(pEnc->current, pMB, qcoeff, bs, &pEnc->sStat);  
2073                          stop_coding_timer();          set_timecodes(current,reference,pParam->fbase);
2074    
2075            BitstreamWriteVopHeader(bs, &pEnc->mbParam, current, 1, current->mbs[0].quant);
2076    
2077            /* multithreaded inter coding - dispatch threads */
2078    
2079            bound = 0;
2080            slices_per_thread = (num_slices*1024 / num_threads);
2081    
2082            for (k = 0; k < num_threads; k++) {
2083                    int add = ((slices_per_thread + 512) >> 10);
2084    
2085                    slices_per_thread += ((num_slices*1024 / num_threads) - add*1024);
2086    
2087                    pEnc->smpData[k].pEnc = (void *) pEnc;
2088                    pEnc->smpData[k].stop_y = (((bound+add) * mb_height + (num_slices-1)) / num_slices);
2089                    pEnc->smpData[k].start_y = ((bound * mb_height + (num_slices-1)) / num_slices);
2090                    pEnc->smpData[k].RefQ = ((k&1) ? pEnc->vInterV.u : pEnc->vInterV.v) + 16*(k>>1)*pParam->edged_width;
2091    
2092                    bound += add;
2093    
2094                    if (k > 0) {
2095                            pEnc->smpData[k].sStat->iTextBits = pEnc->smpData[k].sStat->kblks =
2096                            pEnc->smpData[k].sStat->mblks = pEnc->smpData[k].sStat->ublks =
2097                            pEnc->smpData[k].sStat->iMVBits = 0;
2098    
2099                            BitstreamReset(pEnc->smpData[k].bs);
2100                  }                  }
2101          }          }
2102            pEnc->smpData[0].bs = bs;
2103            pEnc->smpData[0].sStat = &current->sStat;
2104    
2105          emms();          /* create threads */
2106            for (k = 1; k < num_threads; k++) {
2107                    pthread_create(&pEnc->smpData[k].handle, NULL,
2108                            (void*)SliceCodeP, (void*)&pEnc->smpData[k]);
2109            }
2110    
2111          if (pEnc->current->global_flags & XVID_HINTEDME_GET)          SliceCodeP(&pEnc->smpData[0]);
2112          {  
2113                  HintedMEGet(pEnc, 0);          /* wait until all threads are finished */
2114            for (k = 1; k < num_threads; k++) {
2115                    pthread_join(pEnc->smpData[k].handle, &status);
2116          }          }
2117    
2118          if (pEnc->sStat.iMvCount == 0)          current->length = BitstreamLength(bs) - (bits/8);
                 pEnc->sStat.iMvCount = 1;  
2119    
2120          fSigma = (float)sqrt((float) pEnc->sStat.iMvSum / pEnc->sStat.iMvCount);          /* reassemble the pieces together */
2121            SerializeBitstreams(pEnc, pEnc->current, bs, num_threads);
2122    
2123          iSearchRange = 1 << (3 + pEnc->mbParam.m_fcode);          updateFcode(&current->sStat, pEnc);
2124    
2125            /* frame drop code */
2126    #if 0
2127            DPRINTF(XVID_DEBUG_DEBUG, "kmu %i %i %i\n", current->sStat.kblks, current->sStat.mblks, current->sStat.ublks);
2128    #endif
2129    
2130          if ((fSigma > iSearchRange / 3)          if (current->sStat.kblks + current->sStat.mblks <
2131              && (pEnc->mbParam.m_fcode <= 3))    // maximum search range 128                  (pParam->frame_drop_ratio * mb_width * mb_height) / 100 &&
2132                    ( (pEnc->bframenum_head >= pEnc->bframenum_tail) || !(pEnc->mbParam.global_flags & XVID_GLOBAL_CLOSED_GOP)) )
2133          {          {
2134                  pEnc->mbParam.m_fcode++;                  current->sStat.kblks = current->sStat.mblks = current->sStat.iTextBits = 0;
2135                  iSearchRange *= 2;                  current->sStat.ublks = mb_width * mb_height;
2136    
2137                    BitstreamReset(bs);
2138    
2139                    set_timecodes(current,reference,pParam->fbase);
2140                    BitstreamWriteVopHeader(bs, &pEnc->mbParam, current, 0, current->mbs[0].quant);
2141    
2142                    /* copy reference frame details into the current frame */
2143                    current->quant = reference->quant;
2144                    current->motion_flags = reference->motion_flags;
2145                    current->rounding_type = reference->rounding_type;
2146                    current->fcode = reference->fcode;
2147                    current->bcode = reference->bcode;
2148                    current->stamp = reference->stamp;
2149                    image_copy(&current->image, &reference->image, pParam->edged_width, pParam->height);
2150                    memcpy(current->mbs, reference->mbs, sizeof(MACROBLOCK) * mb_width * mb_height);
2151                    coded = 0;
2152    
2153                    BitstreamPadAlways(bs); /* next_start_code() at the end of VideoObjectPlane() */
2154    
2155                    current->length = (BitstreamPos(bs) - bits) / 8;
2156    
2157            } else {
2158    
2159                    pEnc->current->is_edged = 0; /* not edged */
2160                    pEnc->current->is_interpolated = -1; /* not interpolated (fake rounding -1) */
2161    
2162                    /* what was this frame's interpolated reference will become
2163                            forward (past) reference in b-frame coding */
2164    
2165                    image_swap(&pEnc->vInterH, &pEnc->f_refh);
2166                    image_swap(&pEnc->vInterV, &pEnc->f_refv);
2167                    image_swap(&pEnc->vInterHV, &pEnc->f_refhv);
2168          }          }
2169          else if ((fSigma < iSearchRange / 6)  
2170                   && (pEnc->sStat.fMvPrevSigma >= 0)          /* XXX: debug
                  && (pEnc->sStat.fMvPrevSigma < iSearchRange / 6)  
                  && (pEnc->mbParam.m_fcode >= 2))       // minimum search range 16  
2171          {          {
2172                  pEnc->mbParam.m_fcode--;                  char s[100];
2173                  iSearchRange /= 2;                  sprintf(s, "\\%05i_cur.pgm", pEnc->m_framenum);
2174                    image_dump_yuvpgm(&current->image,
2175                            pParam->edged_width,
2176                            pParam->width, pParam->height, s);
2177    
2178                    sprintf(s, "\\%05i_ref.pgm", pEnc->m_framenum);
2179                    image_dump_yuvpgm(&reference->image,
2180                            pParam->edged_width,
2181                            pParam->width, pParam->height, s);
2182            }
2183            */
2184    
2185            return coded;
2186          }          }
2187    
2188          pEnc->sStat.fMvPrevSigma = fSigma;  static void
2189    SliceCodeB(SMPData *data)
2190    {
2191            Encoder *pEnc = (Encoder *) data->pEnc;
2192            Bitstream *bs = (Bitstream *) data->bs;
2193    
2194          *pBits = BitstreamPos(bs) - *pBits;          DECLARE_ALIGNED_MATRIX(dct_codes, 6, 64, int16_t, CACHE_LINE);
2195            DECLARE_ALIGNED_MATRIX(qcoeff, 6, 64, int16_t, CACHE_LINE);
2196    
2197          return 0;                                        // inter          int x, y;
2198            FRAMEINFO * const frame = (FRAMEINFO * const) data->current;
2199            MBParam * const pParam = &pEnc->mbParam;
2200            int mb_width = pParam->mb_width;
2201            int mb_height = pParam->mb_height;
2202            IMAGE *f_ref = &pEnc->reference->image;
2203            IMAGE *b_ref = &pEnc->current->image;
2204    
2205            int bound = data->start_y*mb_width;
2206            int num_slices = pEnc->num_slices;
2207    
2208            if (data->start_y > 0) { /* write resync marker */
2209                    write_video_packet_header(bs, pParam, frame, bound+1);
2210  }  }
2211    
2212            for (y = data->start_y; y < MIN(data->stop_y+1, mb_height); y++) {
2213                    int new_bound = mb_width * ((((y*num_slices) / mb_height) * mb_height + (num_slices-1)) / num_slices);
2214                    int stop_x = (y == data->stop_y) ? 1 : mb_width;
2215                    int start_x = (y == data->start_y && y > 0) ? 1 : 0;
2216    
2217                    for (x = start_x; x < stop_x; x++) {
2218                            MACROBLOCK * const mb = &frame->mbs[x + y * pEnc->mbParam.mb_width];
2219    
2220                            /* decoder ignores mb when refence block is INTER(0,0), CBP=0 */
2221                            if (mb->mode == MODE_NOT_CODED) {
2222                                    if (pParam->plugin_flags & XVID_REQORIGINAL) {
2223                                            MBMotionCompensation(mb, x, y, f_ref, NULL, f_ref, NULL, NULL, &frame->image,
2224                                                                                     NULL, 0, 0, pParam->edged_width, 0, 0, data->RefQ);
2225                                    }
2226                                    continue;
2227                            }
2228    
2229  #ifdef BFRAMES                          if (new_bound > bound && x > 0) {
2230  static void FrameCodeB(Encoder * pEnc, FRAMEINFO * frame, Bitstream * bs, uint32_t *pBits)                                  bound = new_bound;
2231  {                                  BitstreamPadAlways(bs);
2232      int16_t dct_codes[6*64];                                  write_video_packet_header(bs, pParam, frame, y*mb_width+x);
2233      int16_t qcoeff[6*64];                          }
2234      uint32_t x, y;  
2235          VECTOR forward;                          mb->quant = frame->quant;
2236          VECTOR backward;  
2237                            if (mb->cbp != 0 || pParam->plugin_flags & XVID_REQORIGINAL) {
2238                                    /* we have to motion-compensate, transfer etc,
2239                                            because there might be blocks to code */
2240    
2241                                    MBMotionCompensationBVOP(pParam, mb, x, y, &frame->image,
2242                                                                                     f_ref, &pEnc->f_refh, &pEnc->f_refv,
2243                                                                                     &pEnc->f_refhv, b_ref, &pEnc->vInterH,
2244                                                                                     &pEnc->vInterV, &pEnc->vInterHV, dct_codes,
2245                                                                                     data->RefQ);
2246    
2247                                    mb->cbp = MBTransQuantInterBVOP(pParam, frame, mb, x, y,  dct_codes, qcoeff);
2248                            }
2249    
2250                            if (mb->mode == MODE_DIRECT_NO4V)
2251                                    mb->mode = MODE_DIRECT;
2252    
2253                            if (mb->mode == MODE_DIRECT && (mb->cbp | mb->pmvs[3].x | mb->pmvs[3].y) == 0)
2254                                    mb->mode = MODE_DIRECT_NONE_MV; /* skipped */
2255                            else
2256                                    if (frame->vop_flags & XVID_VOP_GREYSCALE)
2257                                            /* keep only bits 5-2 -- Chroma blocks will just be skipped by MBCodingBVOP */
2258                                            mb->cbp &= 0x3C;
2259    
2260                            start_timer();
2261                            MBCodingBVOP(frame, mb, qcoeff, frame->fcode, frame->bcode, bs, data->sStat);
2262                            stop_coding_timer();
2263                    }
2264            }
2265    
2266            BitstreamPadAlways(bs); /* next_start_code() at the end of VideoObjectPlane() */
2267            emms();
2268    }
2269    
2270    static void
2271    FrameCodeB(Encoder * pEnc,
2272                       FRAMEINFO * frame,
2273                       Bitstream * bs)
2274    {
2275            int bits = BitstreamPos(bs);
2276            int k = 0, bound = 0, num_slices = pEnc->num_slices;
2277            int num_threads = MAX(1, MIN(pEnc->num_threads, num_slices));
2278            void * status = NULL;
2279            int slices_per_thread = (num_slices*1024 / num_threads);
2280            int threads_per_slice = (pEnc->num_threads*1024 / num_threads);
2281    
2282      IMAGE *f_ref = &pEnc->reference->image;      IMAGE *f_ref = &pEnc->reference->image;
2283          IMAGE *b_ref = &pEnc->current->image;          IMAGE *b_ref = &pEnc->current->image;
2284    
2285          // forward          MBParam * const pParam = &pEnc->mbParam;
2286          image_setedges(f_ref, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, pEnc->mbParam.width, pEnc->mbParam.height, frame->global_flags & XVID_INTERLACING);          int mb_height = pParam->mb_height;
2287    
2288            #ifdef BFRAMES_DEC_DEBUG
2289            FILE *fp;
2290            static char first=0;
2291    #define BFRAME_DEBUG    if (!first && fp){ \
2292                    fprintf(fp,"Y=%3d   X=%3d   MB=%2d   CBP=%02X\n",y,x,mb->mode,mb->cbp); \
2293            }
2294    
2295            if (!first){
2296                    fp=fopen("C:\\XVIDDBGE.TXT","w");
2297            }
2298    #endif
2299    
2300            /* forward  */
2301            if (!pEnc->reference->is_edged) {
2302                    image_setedges(f_ref, pEnc->mbParam.edged_width,
2303                                               pEnc->mbParam.edged_height, pEnc->mbParam.width,
2304                                               pEnc->mbParam.height, 0);
2305                    pEnc->reference->is_edged = 1;
2306            }
2307    
2308            if (pEnc->reference->is_interpolated != 0) {
2309          start_timer();          start_timer();
2310          image_interpolate(f_ref, &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,                  image_interpolate(f_ref->y, pEnc->f_refh.y, pEnc->f_refv.y, pEnc->f_refhv.y,
2311                  pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, 0);                                                    pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
2312                                                      (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL), 0);
2313          stop_inter_timer();          stop_inter_timer();
2314                    pEnc->reference->is_interpolated = 0;
2315            }
2316    
2317            /* backward */
2318            if (!pEnc->current->is_edged) {
2319                    image_setedges(b_ref, pEnc->mbParam.edged_width,
2320                                               pEnc->mbParam.edged_height, pEnc->mbParam.width,
2321                                               pEnc->mbParam.height, 0);
2322                    pEnc->current->is_edged = 1;
2323            }
2324    
2325          // backward          if (pEnc->current->is_interpolated != 0) {
         image_setedges(b_ref, pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, pEnc->mbParam.width, pEnc->mbParam.height, frame->global_flags & XVID_INTERLACING);  
2326      start_timer();      start_timer();
2327          image_interpolate(b_ref, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,                  image_interpolate(b_ref->y, pEnc->vInterH.y, pEnc->vInterV.y, pEnc->vInterHV.y,
2328                  pEnc->mbParam.edged_width, pEnc->mbParam.edged_height, 0);                                                  pEnc->mbParam.edged_width, pEnc->mbParam.edged_height,
2329                                                    (pEnc->mbParam.vol_flags & XVID_VOL_QUARTERPEL), 0);
2330          stop_inter_timer();          stop_inter_timer();
2331                    pEnc->current->is_interpolated = 0;
2332            }
2333    
2334          start_timer();          frame->coding_type = B_VOP;
         MotionEstimationBVOP(&pEnc->mbParam, frame,  
                 pEnc->reference->mbs, f_ref, &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,  
                 pEnc->current->mbs, b_ref, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV);  
2335    
2336            if ((frame->vop_flags & XVID_VOP_RD_PSNRHVSM) && (frame->vop_flags & XVID_VOP_RD_BVOP)) {
2337                    image_block_variance(&frame->image, pEnc->mbParam.edged_width, frame->mbs,
2338                                         pEnc->mbParam.mb_width, pEnc->mbParam.mb_height);
2339            }
2340    
2341          stop_motion_timer();          call_plugins(pEnc, frame, NULL, XVID_PLG_FRAME, NULL, NULL, NULL);
2342    
2343          /*if (test_quant_type(&pEnc->mbParam, pEnc->current))          frame->fcode = frame->bcode = pEnc->current->fcode;
         {  
                 BitstreamWriteVolHeader(bs, pEnc->mbParam.width, pEnc->mbParam.height, pEnc->mbParam.quant_type);  
         }*/  
2344    
2345      frame->coding_type = B_VOP;          start_timer();
     BitstreamWriteVopHeader(bs, &pEnc->mbParam, frame);  
2346    
2347      *pBits = BitstreamPos(bs);          if (pEnc->num_threads > 0) {
2348    
2349      pEnc->sStat.iTextBits = 0;                  /* multithreaded motion estimation - dispatch threads */
2350      pEnc->sStat.iMvSum = 0;                  while (k < pEnc->num_threads) {
2351      pEnc->sStat.iMvCount = 0;                          int i, add_s = (slices_per_thread + 512) >> 10;
2352          pEnc->sStat.kblks = pEnc->sStat.mblks = pEnc->sStat.ublks = 0;                          int add_t = (threads_per_slice + 512) >> 10;
2353    
2354                            int start_y = (bound * mb_height + (num_slices-1)) / num_slices;
2355                            int stop_y = ((bound+add_s) * mb_height + (num_slices-1)) / num_slices;
2356                            int rows_per_thread = (stop_y - start_y + add_t - 1) / add_t;
2357    
2358      for (y = 0; y < pEnc->mbParam.mb_height; y++)                          slices_per_thread += ((num_slices*1024 / num_threads) - add_s*1024);
2359          {                          threads_per_slice += ((pEnc->num_threads*1024 / num_threads) - add_t*1024);
                 // reset prediction  
2360    
2361                  forward.x = 0;                          for (i = 0; i < add_t; i++) {
2362                  forward.y = 0;                                  memset(pEnc->smpData[k+i].complete_count_self, 0, rows_per_thread * sizeof(int));
                 backward.x = 0;  
                 backward.y = 0;  
2363    
2364                  for (x = 0; x < pEnc->mbParam.mb_width; x++)                                  pEnc->smpData[k+i].pEnc = (void *) pEnc;
2365                  {                                  pEnc->smpData[k+i].current = frame;
                         MACROBLOCK * f_mb = &pEnc->reference->mbs[x + y * pEnc->mbParam.mb_width];  
                         MACROBLOCK * b_mb = &pEnc->current->mbs[x + y * pEnc->mbParam.mb_width];  
                         MACROBLOCK * mb = &frame->mbs[x + y * pEnc->mbParam.mb_width];  
2366    
2367                          // decoder ignores mb when refence block is INTER(0,0), CBP=0                                  pEnc->smpData[k+i].y_row = i;
2368                          if (mb->mode == MODE_NOT_CODED)                                  pEnc->smpData[k+i].y_step = add_t;
2369                          {                                  pEnc->smpData[k+i].stop_y = stop_y;
2370                                  mb->mvs[0].x = 0;                                  pEnc->smpData[k+i].start_y = start_y;
2371                                  mb->mvs[0].y = 0;  
2372                                  continue;                                  /* todo: sort out temp space once and for all */
2373                                    pEnc->smpData[k+i].RefQ = (((k+i)&1) ? pEnc->vInterV.u : pEnc->vInterV.v) +
2374                                                                                            16*((k+i)>>1)*pParam->edged_width;
2375                          }                          }
2376    
2377                          MBMotionCompensationBVOP(&pEnc->mbParam, mb, x, y, &frame->image,                          pEnc->smpData[k].complete_count_above =
2378                                          f_ref, &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,                                  pEnc->smpData[k+add_t-1].complete_count_self - 1;
                                         b_ref, &pEnc->vInterH, &pEnc->vInterV, &pEnc->vInterHV,  
                                         dct_codes);  
2379    
2380                          mb->quant = frame->quant;                          bound += add_s;
2381                          mb->cbp = MBTransQuantInter(&pEnc->mbParam, frame, mb, x, y, dct_codes, qcoeff);                          k += add_t;
2382                          //mb->cbp = MBTransQuantBVOP(&pEnc->mbParam, x, y, dct_codes, qcoeff, &frame->image, frame->quant);                  }
2383    
2384                    for (k = 1; k < pEnc->num_threads; k++) {
2385                            pthread_create(&pEnc->smpData[k].handle, NULL,
2386                                    (void*)SMPMotionEstimationBVOP, (void*)&pEnc->smpData[k]);
2387                    }
2388    
2389                    SMPMotionEstimationBVOP(&pEnc->smpData[0]);
2390    
2391                          if ((mb->mode == MODE_INTERPOLATE || mb->mode == MODE_DIRECT) &&                  for (k = 1; k < pEnc->num_threads; k++) {
2392                                  mb->cbp == 0 &&                          pthread_join(pEnc->smpData[k].handle, &status);
                                 mb->mvs[0].x == 0 &&  
                                 mb->mvs[0].y == 0)  
                         {  
                                 mb->mode = 5;  // skipped  
2393                          }                          }
2394    
2395                          if (mb->mode == MODE_INTERPOLATE || mb->mode == MODE_FORWARD)                  frame->fcode = frame->bcode = 0;
2396                          {                  for (k = 0; k < pEnc->num_threads; k++) {
2397                                  mb->pmvs[0].x = mb->mvs[0].x - forward.x;                          if (pEnc->smpData[k].minfcode > frame->fcode)
2398                                  mb->pmvs[0].y = mb->mvs[0].y - forward.y;                                  frame->fcode = pEnc->smpData[k].minfcode;
2399                                  forward.x = mb->mvs[0].x;                          if (pEnc->smpData[k].minbcode > frame->bcode)
2400                                  forward.y = mb->mvs[0].y;                                  frame->bcode = pEnc->smpData[k].minbcode;
2401                          }                          }
2402            } else {
2403    
2404                          if (mb->mode == MODE_INTERPOLATE || mb->mode == MODE_BACKWARD)                  MotionEstimationBVOP(&pEnc->mbParam, frame,
2405                          {                                                           ((int32_t)(pEnc->current->stamp - frame->stamp)),                              /* time_bp */
2406                                  mb->b_pmvs[0].x = mb->b_mvs[0].x - backward.x;                                                           ((int32_t)(pEnc->current->stamp - pEnc->reference->stamp)),    /* time_pp */
2407                                  mb->b_pmvs[0].y = mb->b_mvs[0].y - backward.y;                                                           pEnc->reference->mbs, f_ref,
2408                                  backward.x = mb->b_mvs[0].x;                                                           &pEnc->f_refh, &pEnc->f_refv, &pEnc->f_refhv,
2409                                  backward.y = mb->b_mvs[0].y;                                                           pEnc->current, b_ref, &pEnc->vInterH,
2410                                                             &pEnc->vInterV, &pEnc->vInterHV,
2411                                                             pEnc->num_slices);
2412                          }                          }
2413            stop_motion_timer();
2414    
2415  //                      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);          set_timecodes(frame, pEnc->reference,pEnc->mbParam.fbase);
2416            BitstreamWriteVopHeader(bs, &pEnc->mbParam, frame, 1, frame->quant);
2417    
2418                          start_timer();          /* reset stats */
2419                          MBCodingBVOP(mb, qcoeff, frame->fcode, frame->bcode, bs, &pEnc->sStat);          frame->sStat.iTextBits = 0;
2420                          stop_coding_timer();          frame->sStat.iMVBits = 0;
2421            frame->sStat.iMvSum = 0;
2422            frame->sStat.iMvCount = 0;
2423            frame->sStat.kblks = frame->sStat.mblks = frame->sStat.ublks = 0;
2424            frame->sStat.mblks = pEnc->mbParam.mb_width * pEnc->mbParam.mb_height;
2425            frame->sStat.kblks = frame->sStat.ublks = 0;
2426    
2427            /* multithreaded inter coding - dispatch threads */
2428            bound = 0;
2429            slices_per_thread = (num_slices*1024 / num_threads);
2430    
2431            for (k = 0; k < num_threads; k++) {
2432                    int add = ((slices_per_thread + 512) >> 10);
2433    
2434                    slices_per_thread += ((num_slices*1024 / num_threads) - add*1024);
2435    
2436                    pEnc->smpData[k].pEnc = (void *) pEnc;
2437                    pEnc->smpData[k].current = frame;
2438                    pEnc->smpData[k].stop_y = (((bound+add) * mb_height + (num_slices-1)) / num_slices);
2439                    pEnc->smpData[k].start_y = ((bound * mb_height + (num_slices-1)) / num_slices);
2440                    bound += add;
2441    
2442                    /* todo: sort out temp space once and for all */
2443                    pEnc->smpData[k].RefQ = ((k&1) ? pEnc->vInterV.u : pEnc->vInterV.v) + 16*(k>>1)*pParam->edged_width;
2444    
2445                    if (k > 0) {
2446                            BitstreamReset(pEnc->smpData[k].bs);
2447                            pEnc->smpData[k].sStat->iTextBits = pEnc->smpData[k].sStat->kblks =
2448                            pEnc->smpData[k].sStat->mblks = pEnc->smpData[k].sStat->ublks = pEnc->smpData[k].sStat->iMVBits = 0;
2449                  }                  }
2450          }          }
2451    
2452          emms();          for (k = 1; k < num_threads; k++) {
2453                    pthread_create(&pEnc->smpData[k].handle, NULL,
2454                            (void*)SliceCodeB, (void*)&pEnc->smpData[k]);
2455            }
2456    
2457          // TODO: dynamic fcode/bcode ???          pEnc->smpData[0].bs = bs;
2458            pEnc->smpData[0].sStat = &frame->sStat;
2459            SliceCodeB(&pEnc->smpData[0]);
2460    
2461          *pBits = BitstreamPos(bs) - *pBits;          for (k = 1; k < num_threads; k++) {
2462                    pthread_join(pEnc->smpData[k].handle, &status);
2463            }
2464    
2465            frame->length = BitstreamLength(bs) - (bits/8);
2466    
2467            /* reassemble the pieces together */
2468            SerializeBitstreams(pEnc, frame, bs, num_threads);
2469    
2470    #ifdef BFRAMES_DEC_DEBUG
2471            if (!first){
2472                    first=1;
2473                    if (fp)
2474                            fclose(fp);
2475  }  }
2476  #endif  #endif
2477    }

Legend:
Removed from v.1.32  
changed lines
  Added in v.1.137

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