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

Diff of /trunk/xvidcore/src/encoder.c

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

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

Legend:
Removed from v.4  
changed lines
  Added in v.1565

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