configure: update FFmpeg revision (bc63a76).
[vaapi:mplayer.git] / xvid_vbr.c
1 /******************************************************************************
2  *
3  *   XviD VBR Library
4  *
5  *   Copyright (C) 2002 Edouard Gomez <ed.gomez@wanadoo.fr>
6  *
7  *   The curve treatment algorithm is based on work done by Foxer <email?> and
8  *   Dirk Knop <dknop@gwdg.de> for the XviD vfw dynamic library.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23  *
24  *****************************************************************************/
25
26 /* Standard Headers */
27 #include <stdio.h>
28 #include <string.h>
29 #include <fcntl.h>
30 #include <stdlib.h>
31 #include <math.h>
32
33 /* Local headers */
34 #include "xvid_vbr.h"
35
36 /******************************************************************************
37  * Build time constants
38  *****************************************************************************/
39
40 /*
41  * Portability note
42  * Perhaps the msvc headers define Pi with another constant name
43  */
44 #define DEG2RAD (M_PI / 180.0)
45
46 /* Defaults settings will be computed with the help of these constants */
47 #define DEFAULT_DESIRED_SIZE    700
48 #define DEFAULT_AUDIO_BITRATE   128
49 #define DEFAULT_MOVIE_LENGTH      2
50 #define DEFAULT_TWOPASS_BOOST  1000
51 #define DEFAULT_FPS           25.0f
52 #define DEFAULT_CREDITS_SIZE      0
53
54 #define DEFAULT_XVID_DBG_FILE   "xvid.dbg"
55 #define DEFAULT_XVID_STATS_FILE "xvid.stats"
56
57
58 /******************************************************************************
59  * Local prototypes
60  *****************************************************************************/
61
62 /* Sub vbrInit cases functions */
63 static vbr_init_function vbr_init_dummy;
64 static vbr_init_function vbr_init_2pass1;
65 static vbr_init_function vbr_init_2pass2;
66 static vbr_init_function vbr_init_fixedquant;
67
68 /* Sub vbrGetQuant cases functions */
69 static vbr_get_quant_function vbr_getquant_1pass;
70 static vbr_get_quant_function vbr_getquant_2pass1;
71 static vbr_get_quant_function vbr_getquant_2pass2;
72 static vbr_get_quant_function vbr_getquant_fixedquant;
73
74 /* Sub vbrGetIntra cases functions */
75 static vbr_get_intra_function vbr_getintra_1pass;
76 static vbr_get_intra_function vbr_getintra_2pass1;
77 static vbr_get_intra_function vbr_getintra_2pass2;
78 static vbr_get_intra_function vbr_getintra_fixedquant;
79
80 /* Sub vbrUpdate prototypes */
81 static vbr_update_function vbr_update_dummy;
82 static vbr_update_function vbr_update_2pass1;
83 static vbr_update_function vbr_update_2pass2;
84
85 /* Sub vbrFinish cases functions */
86 static vbr_finish_function vbr_finish_dummy;
87 static vbr_finish_function vbr_finish_2pass1;
88 static vbr_finish_function vbr_finish_2pass2;
89
90 /* Is the encoder in the credits */
91 #define FRAME_TYPE_NORMAL_MOVIE     0x00
92 #define FRAME_TYPE_STARTING_CREDITS 0x01
93 #define FRAME_TYPE_ENDING_CREDITS   0x02
94
95 /******************************************************************************
96  * Inline utility functions
97  *****************************************************************************/
98
99 static inline int util_frametype(vbr_control_t *state)
100 {
101
102         if(state->credits_start) {
103
104                 if(state->cur_frame >= state->credits_start_begin &&
105                    state->cur_frame < state->credits_start_end)
106                         return(FRAME_TYPE_STARTING_CREDITS);
107
108         }
109
110         if(state->credits_end) {
111
112                 if(state->cur_frame >= state->credits_end_begin &&
113                    state->cur_frame < state->credits_end_end)
114                         return(FRAME_TYPE_ENDING_CREDITS);
115
116         }
117
118         return(FRAME_TYPE_NORMAL_MOVIE);
119
120
121 }
122
123 static inline int util_creditsframes(vbr_control_t *state)
124 {
125
126         int frames = 0;
127
128         if(state->credits_start)
129                 frames += state->credits_start_end - state->credits_start_begin;
130         if(state->credits_end)
131                 frames += state->credits_end_end - state->credits_end_begin;
132
133         return(frames);
134
135 }
136
137 /******************************************************************************
138  * Functions
139  *****************************************************************************/
140
141 /*****************************************************************************
142  * Function description :
143  *
144  * This function initialiazes the vbr_control_t with safe defaults for all
145  * modes.
146  *
147  * Return Values :
148  *   = 0
149  ****************************************************************************/
150
151 int vbrSetDefaults(vbr_control_t *state)
152 {
153
154         /* Set all the structure to zero */
155         memset(state, 0, sizeof(*state));
156
157         /* Default mode is CBR */
158         state->mode = VBR_MODE_1PASS;
159
160         /* Default statistic filename */
161         state->filename = DEFAULT_XVID_STATS_FILE;
162
163         /*
164          * Default is a 2hour movie on 700Mo CD-ROM + 128kbit sound track
165          * This represents a target bitrate of 687kbit/s
166          */
167         state->desired_size = DEFAULT_DESIRED_SIZE*1024*1024 -
168                 DEFAULT_MOVIE_LENGTH*3600*DEFAULT_AUDIO_BITRATE*1000/8;
169         state->desired_bitrate = state->desired_size*8/(DEFAULT_MOVIE_LENGTH*3600);
170
171         /* Credits */
172         state->credits_mode = VBR_CREDITS_MODE_RATE;
173         state->credits_start = 0;
174         state->credits_start_begin = 0;
175         state->credits_start_end = 0;
176         state->credits_end = 0;
177         state->credits_end_begin = 0;
178         state->credits_end_end = 0;
179         state->credits_quant_ratio = 20;
180         state->credits_fixed_quant = 20;
181         state->credits_quant_i = 20;
182         state->credits_quant_p = 20;
183         state->credits_start_size = DEFAULT_CREDITS_SIZE*1024*1024;
184         state->credits_end_size = DEFAULT_CREDITS_SIZE*1024*1024;
185
186         /* Keyframe boost */
187         state->keyframe_boost = 0;
188         state->kftreshold = 10;
189         state->kfreduction = 30;
190         state->min_key_interval = 1;
191         state->max_key_interval = (int)DEFAULT_FPS*10;
192
193         /* Normal curve treatment */
194         state->curve_compression_high = 25;
195         state->curve_compression_low = 10;
196
197         /* Alt curve */
198         state->use_alt_curve = 1;
199         state->alt_curve_type = VBR_ALT_CURVE_LINEAR;
200         state->alt_curve_low_dist = 90;
201         state->alt_curve_high_dist = 500;
202         state->alt_curve_min_rel_qual = 50;
203         state->alt_curve_use_auto = 1;
204         state->alt_curve_auto_str = 30;
205         state->alt_curve_use_auto_bonus_bias = 1;
206         state->alt_curve_bonus_bias = 50;
207         state->bitrate_payback_method = VBR_PAYBACK_BIAS;
208         state->bitrate_payback_delay = 250;
209         state->twopass_max_bitrate = DEFAULT_TWOPASS_BOOST*state->desired_bitrate;
210         state->twopass_max_overflow_improvement = 60;
211         state->twopass_max_overflow_degradation = 60;
212         state->max_iquant = 31;
213         state->min_iquant = 2;
214         state->max_pquant = 31;
215         state->min_pquant = 2;
216         state->fixed_quant = 3;
217
218         state->max_framesize = (1.0/(float)DEFAULT_FPS) * state->twopass_max_bitrate / 8;
219
220         state->fps = (float)DEFAULT_FPS;
221
222         return(0);
223
224 }
225
226 /*****************************************************************************
227  * Function description :
228  *
229  * This function initialiaze the vbr_control_t state passed in parameter.
230  *
231  * The initialization depends on state->mode, there are 4 modes allowed.
232  * Each mode description is done in the README file shipped with the lib.
233  *
234  * Return values :
235  *
236  *    =  0 on success
237  *    = -1 on error
238  *****************************************************************************/
239
240 int vbrInit(vbr_control_t *state)
241 {
242
243         if(state == NULL) return(-1);
244
245         /* Function pointers safe initialization */
246         state->init     = NULL;
247         state->getquant = NULL;
248         state->getintra = NULL;
249         state->update   = NULL;
250         state->finish   = NULL;
251
252         if(state->debug) {
253
254                 state->debug_file = fopen(DEFAULT_XVID_DBG_FILE, "w+");
255
256                 if(state->debug_file == NULL)
257                         return(-1);
258
259                 fprintf(state->debug_file, "# XviD Debug output\n");
260                 fprintf(state->debug_file, "# quant | intra | header bytes"
261                         "| total bytes | kblocks | mblocks | ublocks"
262                         "| vbr overflow | vbr kf overflow"
263                         "| vbr kf partial overflow\n\n");
264         }
265
266         /* Function pointers sub case initialization */
267         switch(state->mode) {
268         case VBR_MODE_1PASS:
269                 state->init     = vbr_init_dummy;
270                 state->getquant = vbr_getquant_1pass;
271                 state->getintra = vbr_getintra_1pass;
272                 state->update   = vbr_update_dummy;
273                 state->finish   = vbr_finish_dummy;
274                 break;
275         case VBR_MODE_2PASS_1:
276                 state->init     = vbr_init_2pass1;
277                 state->getquant = vbr_getquant_2pass1;
278                 state->getintra = vbr_getintra_2pass1;
279                 state->update   = vbr_update_2pass1;
280                 state->finish   = vbr_finish_2pass1;
281                 break;
282         case VBR_MODE_FIXED_QUANT:
283                 state->init     = vbr_init_fixedquant;
284                 state->getquant = vbr_getquant_fixedquant;
285                 state->getintra = vbr_getintra_fixedquant;
286                 state->update   = vbr_update_dummy;
287                 state->finish   = vbr_finish_dummy;
288                 break;
289         case VBR_MODE_2PASS_2:
290                 state->init     = vbr_init_2pass2;
291                 state->getintra = vbr_getintra_2pass2;
292                 state->getquant = vbr_getquant_2pass2;
293                 state->update   = vbr_update_2pass2;
294                 state->finish   = vbr_finish_2pass2;
295                 break;
296         default:
297                 return(-1);
298         }
299
300         return(state->init(state));
301
302 }
303
304 /******************************************************************************
305  * Function description :
306  *
307  * This function returns an adapted quantizer according to the current vbr
308  * controler state
309  *
310  * Return values :
311  *  the quantizer value (0 <= value <= 31)
312  *  (0 is a special case, means : let XviD decide)
313  *
314  *****************************************************************************/
315
316 int vbrGetQuant(vbr_control_t *state)
317 {
318
319         /* Returns Zero, so XviD decides alone */
320         if(state == NULL || state->getquant == NULL) return(0);
321
322         return(state->getquant(state));
323
324 }
325
326 /******************************************************************************
327  * Function description :
328  *
329  * This function returns the type of the frame to be encoded next (I or P/B)
330  *
331  * Return values :
332  *  = -1 let the XviD encoder decide wether or not the next frame is I
333  *  =  0 no I frame
334  *  =  1 force keyframe
335  *
336  *****************************************************************************/
337
338 int vbrGetIntra(vbr_control_t *state)
339 {
340
341         /* Returns -1, means let XviD decide */
342         if(state == NULL || state->getintra == NULL) return(-1);
343
344         return(state->getintra(state));
345
346 }
347
348 /******************************************************************************
349  * Function description :
350  *
351  * This function updates the vbr control state according to collected statistics
352  * from XviD core
353  *
354  * Return values :
355  *
356  *    =  0 on success
357  *    = -1 on error
358  *****************************************************************************/
359
360 int vbrUpdate(vbr_control_t *state,
361               int quant,
362               int intra,
363               int header_bytes,
364               int total_bytes,
365               int kblocks,
366               int mblocks,
367               int ublocks)
368 {
369
370         if(state == NULL || state->update == NULL) return(-1);
371
372         if(state->debug && state->debug_file != NULL) {
373                 int idx;
374
375                 fprintf(state->debug_file, "%d %d %d %d %d %d %d %d %d %d\n",
376                         quant, intra, header_bytes, total_bytes, kblocks,
377                         mblocks, ublocks, state->overflow, state->KFoverflow,
378                         state->KFoverflow_partial);
379
380                 idx = quant;
381
382                 if(quant < 1)
383                         idx = 1;
384                 if(quant > 31)
385                         idx = 31;
386
387                 idx--;
388
389                 state->debug_quant_count[idx]++;
390
391         }
392
393         return(state->update(state, quant, intra, header_bytes, total_bytes,
394                              kblocks, mblocks, ublocks));
395
396 }
397
398 /******************************************************************************
399  * Function description :
400  *
401  * This function stops the vbr controller
402  *
403  * Return values :
404  *
405  *    =  0 on success
406  *    = -1 on error
407  *****************************************************************************/
408
409 int vbrFinish(vbr_control_t *state)
410 {
411
412         if(state == NULL || state->finish == NULL) return(-1);
413
414         if(state->debug && state->debug_file != NULL) {
415
416                 int i;
417
418                 fprintf(state->debug_file, "\n\n");
419
420                 for(i=0; i<79; i++)
421                         fprintf(state->debug_file, "#");
422
423                 fprintf(state->debug_file, "\n# Quantizer distribution :\n\n");
424
425                 for(i=0;i<32; i++) {
426
427                         fprintf(state->debug_file, "# quant %d : %d\n",
428                                 i+1,
429                                 state->debug_quant_count[i]);
430
431                 }
432
433                 fclose(state->debug_file);
434
435         }
436
437         return(state->finish(state));
438
439 }
440
441 /******************************************************************************
442  * Dummy functions - Used when a mode does not need such a function
443  *****************************************************************************/
444
445 static int vbr_init_dummy(void *sstate)
446 {
447
448         vbr_control_t *state = sstate;
449
450         state->cur_frame = 0;
451
452         return(0);
453
454 }
455
456 static int vbr_update_dummy(void *state,
457                             int quant,
458                             int intra,
459                             int header_bytes,
460                             int total_bytes,
461                             int kblocks,
462                             int mblocks,
463                             int ublocks)
464 {
465
466         ((vbr_control_t*)state)->cur_frame++;
467
468         return(0);
469
470 }
471
472 static int vbr_finish_dummy(void *state)
473 {
474
475         return(0);
476
477 }
478
479 /******************************************************************************
480  * 1 pass mode - XviD will do its job alone.
481  *****************************************************************************/
482
483 static int vbr_getquant_1pass(void *state)
484 {
485
486         return(0);
487
488 }
489
490 static int vbr_getintra_1pass(void *state)
491 {
492
493         return(-1);
494
495 }
496
497 /******************************************************************************
498  * 2 pass mode - first pass functions
499  *****************************************************************************/
500
501 static int vbr_init_2pass1(void *sstate)
502 {
503
504         FILE *f;
505         vbr_control_t *state = sstate;
506
507         /* Check the filename */
508         if(state->filename == NULL || state->filename[0] == '\0')
509                 return(-1);
510
511         /* Initialize safe defaults for 2pass 1 */
512         state->pass1_file = NULL;
513         state->nb_frames = 0;
514         state->nb_keyframes = 0;
515         state->cur_frame = 0;
516
517         /* Open the 1st pass file */
518         if((f = fopen(state->filename, "w+")) == NULL)
519                 return(-1);
520
521         /*
522          * The File Header
523          *
524          * The extra white spaces will be used during the vbrFinish to write
525          * the resulting number of frames and keyframes (10 spaces == maximum
526          * string length of an int on 32bit machines, i don't think anyone is
527          * encoding more than 4 billion frames :-)
528          */
529         fprintf(f, "# ASCII XviD vbr stat file version %d\n#\n", VBR_VERSION);
530         fprintf(f, "# frames    :           \n");
531         fprintf(f, "# keyframes :           \n");
532         fprintf(f, "#\n# quant | intra | header bytes | total bytes | kblocks |"
533                 " mblocks | ublocks\n\n");
534
535         /* Save file pointer */
536         state->pass1_file   = f;
537
538         return(0);
539
540 }
541
542 static int vbr_getquant_2pass1(void *state)
543 {
544
545         return(2);
546
547 }
548
549 static int vbr_getintra_2pass1(void *state)
550 {
551
552         return(-1);
553
554 }
555
556 static int vbr_update_2pass1(void *sstate,
557                              int quant,
558                              int intra,
559                              int header_bytes,
560                              int total_bytes,
561                              int kblocks,
562                              int mblocks,
563                              int ublocks)
564
565
566 {
567
568         vbr_control_t *state = sstate;
569
570         if(state->pass1_file == NULL)
571                 return(-1);
572
573         /* Writes the resulting statistics */
574         fprintf(state->pass1_file, "%d %d %d %d %d %d %d\n",
575                 quant,
576                 intra,
577                 header_bytes,
578                 total_bytes,
579                 kblocks,
580                 mblocks,
581                 ublocks);
582
583         /* Update vbr control state */
584         if(intra) state->nb_keyframes++;
585         state->nb_frames++;
586         state->cur_frame++;
587
588         return(0);
589
590 }
591
592 static int vbr_finish_2pass1(void *sstate)
593 {
594
595         int c, i;
596         vbr_control_t *state = sstate;
597
598         if(state->pass1_file == NULL)
599                 return(-1);
600
601         /* Goto to the file beginning */
602         fseek(state->pass1_file, 0, SEEK_SET);
603
604         /* Skip the version line and the empty line */
605         c = i = 0;
606         do {
607                 c = fgetc(state->pass1_file);
608
609                 if(c == EOF) return(-1);
610                 if(c == '\n') i++;
611
612         }while(i < 2);
613
614         /* Prepare to write to the stream */
615         fseek( state->pass1_file, 0L, SEEK_CUR );
616
617         /* Overwrite the frame field - safe as we have written extra spaces */
618         fprintf(state->pass1_file, "# frames    : %.10d\n", state->nb_frames);
619
620         /* Overwrite the keyframe field */
621         fprintf(state->pass1_file, "# keyframes : %.10d\n",
622                 state->nb_keyframes);
623
624         /* Close the file */
625         if(fclose(state->pass1_file) != 0)
626                 return(-1);
627
628         return(0);
629
630 }
631
632 /******************************************************************************
633  * 2 pass mode - 2nd pass functions (Need to be finished)
634  *****************************************************************************/
635
636 static int vbr_init_2pass2(void *sstate)
637 {
638
639         FILE *f;
640         int c, n, pos_firstframe, credits_frames;
641         long long credits1_bytes;
642         long long credits2_bytes;
643         long long desired;
644         long long total_bytes;
645         long long itotal_bytes;
646         long long start_curved;
647         long long end_curved;
648         double total1;
649         double total2;
650
651         vbr_control_t *state = sstate;
652
653         /* Check the filename */
654         if(state->filename == NULL || state->filename[0] == '\0')
655                 return(-1);
656
657         /* Initialize safe defaults for 2pass 2 */
658         state->pass1_file = NULL;
659         state->nb_frames = 0;
660         state->nb_keyframes = 0;
661
662         /* Open the 1st pass file */
663         if((f = fopen(state->filename, "r")) == NULL)
664                 return(-1);
665
666         state->pass1_file = f;
667
668         /* Get the file version and check against current version */
669         fscanf(state->pass1_file, "# ASCII XviD vbr stat file version %d\n", &n);
670
671         if(n != VBR_VERSION) {
672                 fclose(state->pass1_file);
673                 state->pass1_file = NULL;
674                 return(-1);
675         }
676
677         /* Skip the blank commented line */
678         c = n = 0;
679         do {
680
681                 c = fgetc(state->pass1_file);
682
683                 if(c == EOF) {
684                         fclose(state->pass1_file);
685                         state->pass1_file = NULL;
686                         return(-1);
687                 }
688
689                 if(c == '\n') n++;
690
691         }while(n < 1);
692
693
694         /* Get the number of frames */
695         fscanf(state->pass1_file, "# frames : %d\n", &state->nb_frames);
696
697         /* Compute the desired size */
698         state->desired_size = (long long)
699                 (((long long)state->nb_frames * (long long)state->desired_bitrate) /
700                  (state->fps * 8.0));
701
702         /* Get the number of keyframes */
703         fscanf(state->pass1_file, "# keyframes : %d\n", &state->nb_keyframes);
704
705         /* Allocate memory space for the keyframe_location array */
706         if((state->keyframe_locations
707             = malloc((state->nb_keyframes+1)*sizeof(int))) == NULL) {
708                 fclose(state->pass1_file);
709                 state->pass1_file = NULL;
710                 return(-1);
711         }
712
713         /* Skip the blank commented line and the colum description */
714         c = n = 0;
715         do {
716
717                 c = fgetc(state->pass1_file);
718
719                 if(c == EOF) {
720                         fclose(state->pass1_file);
721                         state->pass1_file = NULL;
722                         return(-1);
723                 }
724
725                 if(c == '\n') n++;
726
727         }while(n < 2);
728
729         /* Save position for future use */
730         pos_firstframe = ftell(state->pass1_file);
731
732         /* Read and initialize some variables */
733         credits1_bytes = credits2_bytes = 0;
734         total_bytes = itotal_bytes = 0;
735         start_curved = end_curved = 0;
736         credits_frames = 0;
737
738         for(state->cur_frame = c = 0; state->cur_frame<state->nb_frames; state->cur_frame++) {
739
740                 int quant, keyframe, frame_hbytes, frame_bytes;
741                 int kblocks, mblocks, ublocks;
742
743                 fscanf(state->pass1_file, "%d %d %d %d %d %d %d\n",
744                        &quant, &keyframe, &frame_hbytes, &frame_bytes,
745                        &kblocks, &mblocks, &ublocks);
746
747                 /* Is the frame in the beginning credits */
748                 if(util_frametype(state) == FRAME_TYPE_STARTING_CREDITS) {
749                         credits1_bytes += frame_bytes;
750                         credits_frames++;
751                         continue;
752                 }
753
754                 /* Is the frame in the eding credits */
755                 if(util_frametype(state) == FRAME_TYPE_ENDING_CREDITS) {
756                         credits2_bytes += frame_bytes;
757                         credits_frames++;
758                         continue;
759                 }
760
761                 /* We only care about Keyframes when not in credits */
762                 if(keyframe) {
763                         itotal_bytes += frame_bytes + frame_bytes *
764                                 state->keyframe_boost / 100;
765                         total_bytes  += frame_bytes *
766                                 state->keyframe_boost / 100;
767                         state->keyframe_locations[c++] = state->cur_frame;
768                 }
769
770                 total_bytes += frame_bytes;
771
772         }
773
774         /*
775          * Last frame is treated like an I Frame so we can dispatch overflow
776          * all other the last film segment
777          */
778         state->keyframe_locations[c] = state->cur_frame;
779
780         desired = state->desired_size;
781
782         switch(state->credits_mode) {
783         case VBR_CREDITS_MODE_QUANT :
784
785                 state->movie_curve = (double)
786                         (total_bytes - credits1_bytes - credits2_bytes) /
787                         (desired  - credits1_bytes - credits2_bytes);
788
789                 start_curved = credits1_bytes;
790                 end_curved   = credits2_bytes;
791
792                 break;
793         case VBR_CREDITS_MODE_SIZE:
794
795                 /* start curve = (start / start desired size) */
796                 state->credits_start_curve = (double)
797                         (credits1_bytes / state->credits_start_size);
798
799                 /* end curve = (end / end desired size) */
800                 state->credits_end_curve = (double)
801                         (credits2_bytes / state->credits_end_size);
802
803                 start_curved = (long long)
804                         (credits1_bytes / state->credits_start_curve);
805
806                 end_curved   = (long long)
807                         (credits2_bytes / state->credits_end_curve);
808
809                 /* movie curve=(total-credits)/(desired_size-curved credits) */
810                 state->movie_curve = (double)
811                         (total_bytes - credits1_bytes - credits2_bytes) /
812                         (desired - start_curved - end_curved);
813
814                 break;
815         case VBR_CREDITS_MODE_RATE:
816         default:
817
818                 /* credits curve = (total/desired_size)*(100/credits_rate) */
819                 state->credits_start_curve = state->credits_end_curve =
820                         ((double)total_bytes / desired) *
821                         ((double)100 / state->credits_quant_ratio);
822
823                 start_curved =
824                         (long long)(credits1_bytes/state->credits_start_curve);
825
826                 end_curved   =
827                         (long long)(credits2_bytes/state->credits_end_curve);
828
829                 state->movie_curve = (double)
830                         (total_bytes - credits1_bytes - credits2_bytes) /
831                         (desired - start_curved - end_curved);
832
833                 break;
834         }
835
836         /*
837          * average frame size = (desired - curved credits - curved keyframes) /
838          *                      (frames - credits frames - keyframes)
839          */
840         state->average_frame = (double)
841                 (desired - start_curved - end_curved -
842                  (itotal_bytes / state->movie_curve)) /
843                 (state->nb_frames - util_creditsframes(state) -
844                  state->nb_keyframes);
845
846         /* Initialize alt curve parameters */
847         if (state->use_alt_curve) {
848
849                 state->alt_curve_low =
850                         state->average_frame - state->average_frame *
851                         (double)(state->alt_curve_low_dist / 100.0);
852
853                 state->alt_curve_low_diff =
854                         state->average_frame - state->alt_curve_low;
855
856                 state->alt_curve_high =
857                         state->average_frame + state->average_frame *
858                         (double)(state->alt_curve_high_dist / 100.0);
859
860                 state->alt_curve_high_diff =
861                         state->alt_curve_high - state->average_frame;
862
863                 if (state->alt_curve_use_auto) {
864
865                         if (state->movie_curve > 1.0)   {
866
867                                 state->alt_curve_min_rel_qual =
868                                         (int)(100.0 - (100.0 - 100.0 / state->movie_curve) *
869                                               (double)state->alt_curve_auto_str / 100.0);
870
871                                 if (state->alt_curve_min_rel_qual < 20)
872                                         state->alt_curve_min_rel_qual = 20;
873                         }
874                         else {
875                                 state->alt_curve_min_rel_qual = 100;
876                         }
877
878                 }
879
880                 state->alt_curve_mid_qual =
881                 (1.0 + (double)state->alt_curve_min_rel_qual / 100.0) / 2.0;
882
883                 state->alt_curve_qual_dev = 1.0 - state->alt_curve_mid_qual;
884
885                 if (state->alt_curve_low_dist > 100) {
886
887                         switch(state->alt_curve_type) {
888                         case VBR_ALT_CURVE_AGGRESIVE:
889                                 /* Sine Curve (high aggressiveness) */
890                                 state->alt_curve_qual_dev *=
891                                         2.0 /
892                                         (1.0 +  sin(DEG2RAD * (state->average_frame * 90.0 / state->alt_curve_low_diff)));
893
894                                 state->alt_curve_mid_qual =
895                                         1.0 - state->alt_curve_qual_dev *
896                                         sin(DEG2RAD * (state->average_frame * 90.0 / state->alt_curve_low_diff));
897                                 break;
898
899                         default:
900                         case VBR_ALT_CURVE_LINEAR:
901                                 /* Linear (medium aggressiveness) */
902                                 state->alt_curve_qual_dev *=
903                                         2.0 /
904                                         (1.0 + state->average_frame / state->alt_curve_low_diff);
905
906                                 state->alt_curve_mid_qual =
907                                         1.0 - state->alt_curve_qual_dev *
908                                         state->average_frame / state->alt_curve_low_diff;
909
910                                 break;
911
912                         case VBR_ALT_CURVE_SOFT:
913                                 /* Cosine Curve (low aggressiveness) */
914                                 state->alt_curve_qual_dev *=
915                                         2.0 /
916                                         (1.0 + (1.0 - cos(DEG2RAD * (state->average_frame * 90.0 / state->alt_curve_low_diff))));
917
918                                 state->alt_curve_mid_qual =
919                                         1.0 - state->alt_curve_qual_dev *
920                                         (1.0 - cos(DEG2RAD * (state->average_frame * 90.0 / state->alt_curve_low_diff)));
921
922                                 break;
923                         }
924                 }
925         }
926
927         /* Go to the first non credits frame stats line into file */
928         fseek(state->pass1_file, pos_firstframe, SEEK_SET);
929
930         /* Perform prepass to compensate for over/undersizing */
931         total1 = total2 = 0.0;
932         for(state->cur_frame=0; state->cur_frame<state->nb_frames; state->cur_frame++) {
933
934                 int quant, keyframe, frame_hbytes, frame_bytes;
935                 int kblocks, mblocks, ublocks;
936
937                 fscanf(state->pass1_file, "%d %d %d %d %d %d %d\n",
938                        &quant, &keyframe, &frame_hbytes, &frame_bytes,
939                        &kblocks, &mblocks, &ublocks);
940
941                 if(util_frametype(state) != FRAME_TYPE_NORMAL_MOVIE)
942                         continue;
943
944                 if(!keyframe) {
945
946                         double dbytes = frame_bytes / state->movie_curve;
947                         total1 += dbytes;
948
949                         if (state->use_alt_curve) {
950
951                                 if (dbytes > state->average_frame) {
952
953                                         if (dbytes >= state->alt_curve_high) {
954                                                 total2 += dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev);
955                                         }
956                                         else {
957
958                                                 switch(state->alt_curve_type) {
959                                                 case VBR_ALT_CURVE_AGGRESIVE:
960
961                                                         total2 +=
962                                                                 dbytes *
963                                                                 (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
964                                                                  sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff)));
965                                                         break;
966                                                 default:
967                                                 case VBR_ALT_CURVE_LINEAR:
968
969                                                         total2 +=
970                                                                 dbytes *
971                                                                 (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
972                                                                  (dbytes - state->average_frame) / state->alt_curve_high_diff);
973                                                         break;
974                                                 case VBR_ALT_CURVE_SOFT:
975                                                         total2 +=
976                                                                 dbytes *
977                                                                 (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
978                                                                  (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff))));
979                                                 }
980                                         }
981                                 }
982                                 else {
983
984                                         if (dbytes <= state->alt_curve_low) {
985                                                 total2 += dbytes;
986                                         }
987                                         else {
988
989                                                 switch(state->alt_curve_type) {
990                                                 case VBR_ALT_CURVE_AGGRESIVE:
991                                                         total2 +=
992                                                                 dbytes *
993                                                                 (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
994                                                                  sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff)));
995                                                         break;
996                                                 default:
997                                                 case VBR_ALT_CURVE_LINEAR:
998                                                         total2 +=
999                                                                 dbytes *
1000                                                                 (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1001                                                                  (dbytes - state->average_frame) / state->alt_curve_low_diff);
1002                                                         break;
1003                                                 case VBR_ALT_CURVE_SOFT:
1004                                                         total2 +=
1005                                                                 dbytes *
1006                                                                 (state->alt_curve_mid_qual + state->alt_curve_qual_dev *
1007                                                                  (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff))));
1008                                                 }
1009                                         }
1010                                 }
1011                         }
1012                         else {
1013                                 if (dbytes > state->average_frame) {
1014                                         total2 +=
1015                                                 ((double)dbytes +
1016                                                  (state->average_frame - dbytes) *
1017                                                  state->curve_compression_high / 100.0);
1018                                 }
1019                                 else {
1020                                         total2 +=
1021                                                 ((double)dbytes +
1022                                                  (state->average_frame - dbytes) *
1023                                                  state->curve_compression_low / 100.0);
1024                                 }
1025                         }
1026                 }
1027         }
1028
1029         state->curve_comp_scale = total1 / total2;
1030
1031         if (state->use_alt_curve) {
1032
1033                 double curve_temp, dbytes;
1034                 int newquant, percent;
1035                 int oldquant = 1;
1036
1037                 if (state->alt_curve_use_auto_bonus_bias)
1038                         state->alt_curve_bonus_bias = state->alt_curve_min_rel_qual;
1039
1040                 state->curve_bias_bonus =
1041                         (total1 - total2) * (double)state->alt_curve_bonus_bias /
1042                         (100.0 * (double)(state->nb_frames - util_creditsframes(state) - state->nb_keyframes));
1043                 state->curve_comp_scale =
1044                         ((total1 - total2) * (1.0 - (double)state->alt_curve_bonus_bias / 100.0) + total2) /
1045                         total2;
1046
1047
1048                 for (n=1; n <= (int)(state->alt_curve_high*2) + 1; n++) {
1049                         dbytes = n;
1050                         if (dbytes > state->average_frame)
1051                         {
1052                                 if (dbytes >= state->alt_curve_high) {
1053                                         curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev);
1054                                 }
1055                                 else {
1056                                         switch(state->alt_curve_type) {
1057                                         case VBR_ALT_CURVE_AGGRESIVE:
1058                                                 curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1059                                                                        sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff)));
1060                                                 break;
1061                                         default:
1062                                         case VBR_ALT_CURVE_LINEAR:
1063                                                 curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1064                                                                        (dbytes - state->average_frame) / state->alt_curve_high_diff);
1065                                                 break;
1066                                         case VBR_ALT_CURVE_SOFT:
1067                                                 curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1068                                                                        (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff))));
1069                                         }
1070                                 }
1071                         }
1072                         else {
1073                                 if (dbytes <= state->alt_curve_low) {
1074                                         curve_temp = dbytes;
1075                                 }
1076                                 else {
1077                                         switch(state->alt_curve_type) {
1078                                         case VBR_ALT_CURVE_AGGRESIVE:
1079                                                 curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1080                                                                        sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff)));
1081                                                 break;
1082                                         default:
1083                                         case VBR_ALT_CURVE_LINEAR:
1084                                                 curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1085                                                                        (dbytes - state->average_frame) / state->alt_curve_low_diff);
1086                                                 break;
1087                                         case VBR_ALT_CURVE_SOFT:
1088                                                 curve_temp = dbytes * (state->alt_curve_mid_qual + state->alt_curve_qual_dev *
1089                                                                        (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff))));
1090                                         }
1091                                 }
1092                         }
1093
1094                         if (state->movie_curve > 1.0)
1095                                 dbytes *= state->movie_curve;
1096
1097                         newquant = (int)(dbytes * 2.0 / (curve_temp * state->curve_comp_scale + state->curve_bias_bonus));
1098                         if (newquant > 1)
1099                         {
1100                                 if (newquant != oldquant)
1101                                 {
1102                                         oldquant = newquant;
1103                                         percent = (int)((n - state->average_frame) * 100.0 / state->average_frame);
1104                                 }
1105
1106                         }
1107
1108                 }
1109
1110         }
1111
1112         state->overflow = 0;
1113         state->KFoverflow = 0;
1114         state->KFoverflow_partial = 0;
1115         state->KF_idx = 1;
1116
1117         for (n=0 ; n < 32 ; n++) {
1118                 state->quant_error[n] = 0.0;
1119                 state->quant_count[n] = 0;
1120         }
1121
1122         state->curve_comp_error = 0.0;
1123         state->last_quant = 0;
1124
1125         /*
1126          * Above this frame size limit, normal vbr rules will not apply
1127          * This means :
1128          *      1 - Quant can de/increase more than -/+2 between 2 frames
1129          *      2 - Leads to artifacts because of 1
1130          */
1131         state->max_framesize = state->twopass_max_bitrate/state->fps;
1132
1133         /* Get back to the beginning of frame statistics */
1134         fseek(state->pass1_file, pos_firstframe, SEEK_SET);
1135
1136         /*
1137          * Small hack : We have to get next frame stats before the
1138          * getintra/quant calls
1139          * User clients update the data when they call vbrUpdate
1140          * we are just bypassing this because we don't have to update
1141          * the overflow and so on...
1142          */
1143         {
1144
1145                 /* Fake vars */
1146                 int next_hbytes, next_kblocks, next_mblocks, next_ublocks;
1147
1148                 fscanf(state->pass1_file, "%d %d %d %d %d %d %d\n",
1149                        &state->pass1_quant, &state->pass1_intra, &next_hbytes,
1150                        &state->pass1_bytes, &next_kblocks, &next_mblocks,
1151                        &next_ublocks);
1152
1153         }
1154
1155         /* Initialize the frame counter */
1156         state->cur_frame = 0;
1157         state->last_keyframe = 0;
1158
1159         return(0);
1160
1161 }
1162
1163 static int vbr_getquant_2pass2(void *sstate)
1164 {
1165
1166         int quant;
1167         int intra;
1168         int bytes1, bytes2;
1169         int overflow;
1170         int capped_to_max_framesize = 0;
1171         int KFdistance, KF_min_size;
1172         vbr_control_t *state = sstate;
1173
1174         bytes1 = state->pass1_bytes;
1175         overflow = state->overflow / 8;
1176         /* To shut up gcc warning */
1177         bytes2 = bytes1;
1178
1179
1180         if (state->pass1_intra)
1181         {
1182                 overflow = 0;
1183         }
1184
1185         if (util_frametype(state) != FRAME_TYPE_NORMAL_MOVIE) {
1186
1187
1188                 switch (state->credits_mode) {
1189                 case VBR_CREDITS_MODE_QUANT :
1190                         if (state->credits_quant_i != state->credits_quant_p) {
1191                                 quant = state->pass1_intra ?
1192                                         state->credits_quant_i:
1193                                         state->credits_quant_p;
1194                         }
1195                         else {
1196                                 quant = state->credits_quant_p;
1197                         }
1198
1199                         state->bytes1 = bytes1;
1200                         state->bytes2 = bytes1;
1201                         state->desired_bytes2 = bytes1;
1202                         return(quant);
1203                 default:
1204                 case VBR_CREDITS_MODE_RATE :
1205                 case VBR_CREDITS_MODE_SIZE :
1206                         if(util_frametype(state) == FRAME_TYPE_STARTING_CREDITS)
1207                                 bytes2 = (int)(bytes1 / state->credits_start_curve);
1208                         else
1209                                 bytes2 = (int)(bytes1 / state->credits_end_curve);
1210                         break;
1211                 }
1212         }
1213         else {
1214                 /* Foxer: apply curve compression outside credits */
1215                 double dbytes, curve_temp;
1216
1217                 bytes2 = bytes1;
1218
1219                 if (state->pass1_intra)
1220                         dbytes = ((int)(bytes2 + bytes2 * state->keyframe_boost / 100)) /
1221                                 state->movie_curve;
1222                 else
1223                         dbytes = bytes2 / state->movie_curve;
1224
1225                 /* spread the compression error accross payback_delay frames */
1226                 if (state->bitrate_payback_method == VBR_PAYBACK_BIAS)  {
1227                         bytes2 = (int)(state->curve_comp_error / state->bitrate_payback_delay);
1228                 }
1229                 else {
1230                         bytes2 = (int)(state->curve_comp_error * dbytes /
1231                                 state->average_frame / state->bitrate_payback_delay);
1232
1233                         if (labs(bytes2) > fabs(state->curve_comp_error))
1234                                 bytes2 = (int)state->curve_comp_error;
1235                 }
1236
1237                 state->curve_comp_error -= bytes2;
1238
1239                 if (state->use_alt_curve) {
1240
1241                         if (!state->pass1_intra) {
1242
1243                                 if (dbytes > state->average_frame) {
1244                                         if (dbytes >= state->alt_curve_high)
1245                                                 curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev);
1246                                         else {
1247                                                 switch(state->alt_curve_type) {
1248                                                 case VBR_ALT_CURVE_AGGRESIVE:
1249                                                         curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1250                                                                                sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff)));
1251                                                         break;
1252                                                 default:
1253                                                 case VBR_ALT_CURVE_LINEAR:
1254                                                         curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1255                                                                                (dbytes - state->average_frame) / state->alt_curve_high_diff);
1256                                                         break;
1257                                                 case VBR_ALT_CURVE_SOFT:
1258                                                         curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1259                                                                                (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff))));
1260                                                 }
1261                                         }
1262                                 }
1263                                 else {
1264                                         if (dbytes <= state->alt_curve_low)
1265                                                 curve_temp = dbytes;
1266                                         else {
1267                                                 switch(state->alt_curve_type) {
1268                                                 case VBR_ALT_CURVE_AGGRESIVE:
1269                                                         curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1270                                                                                sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff)));
1271                                                         break;
1272                                                 default:
1273                                                 case VBR_ALT_CURVE_LINEAR:
1274                                                         curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1275                                                                                (dbytes - state->average_frame) / state->alt_curve_low_diff);
1276                                                         break;
1277                                                 case VBR_ALT_CURVE_SOFT:
1278                                                         curve_temp = dbytes * (state->alt_curve_mid_qual + state->alt_curve_qual_dev *
1279                                                                                (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff))));
1280                                                 }
1281                                         }
1282                                 }
1283
1284                                 curve_temp = curve_temp * state->curve_comp_scale + state->curve_bias_bonus;
1285
1286                                 bytes2 += ((int)curve_temp);
1287                                 state->curve_comp_error += curve_temp - ((int)curve_temp);
1288
1289                         }
1290                         else {
1291                                 state->curve_comp_error += dbytes - ((int)dbytes);
1292                                 bytes2 += ((int)dbytes);
1293                         }
1294                 }
1295                 else if ((state->curve_compression_high + state->curve_compression_low) &&
1296                         !state->pass1_intra) {
1297
1298                         if (dbytes > state->average_frame) {
1299                                 curve_temp = state->curve_comp_scale *
1300                                         ((double)dbytes + (state->average_frame - dbytes) *
1301                                         state->curve_compression_high / 100.0);
1302                         }
1303                         else {
1304                                 curve_temp = state->curve_comp_scale *
1305                                         ((double)dbytes + (state->average_frame - dbytes) *
1306                                         state->curve_compression_low / 100.0);
1307                         }
1308
1309                         bytes2 += ((int)curve_temp);
1310                         state->curve_comp_error += curve_temp - ((int)curve_temp);
1311                 }
1312                 else {
1313                         state->curve_comp_error += dbytes - ((int)dbytes);
1314                         bytes2 += ((int)dbytes);
1315                 }
1316
1317                 /* cap bytes2 to first pass size, lowers number of quant=1 frames */
1318                 if (bytes2 > bytes1) {
1319                         state->curve_comp_error += bytes2 - bytes1;
1320                         bytes2 = bytes1;
1321                 }
1322                 else if (bytes2 < 1) {
1323                         state->curve_comp_error += --bytes2;
1324                         bytes2 = 1;
1325                 }
1326         }
1327
1328         state->desired_bytes2 = bytes2;
1329
1330         /* Ugly dependence between getquant and getintra */
1331         intra = state->getintra(state);
1332
1333         if(intra) {
1334
1335                 KFdistance = state->keyframe_locations[state->KF_idx] -
1336                         state->keyframe_locations[state->KF_idx - 1];
1337
1338                 if (KFdistance < state->kftreshold) {
1339                         KFdistance = KFdistance - state->min_key_interval;
1340
1341                         if (KFdistance >= 0) {
1342
1343                                 KF_min_size = bytes2 * (100 - state->kfreduction) / 100;
1344                                 if (KF_min_size < 1)
1345                                         KF_min_size = 1;
1346
1347                                 bytes2 = KF_min_size + (bytes2 - KF_min_size) * KFdistance /
1348                                         (state->kftreshold - state->min_key_interval);
1349
1350                                 if (bytes2 < 1)
1351                                         bytes2 = 1;
1352                         }
1353                 }
1354         }
1355
1356         /*
1357          * Foxer: scale overflow in relation to average size, so smaller frames don't get
1358          * too much/little bitrate
1359          */
1360         overflow = (int)((double)overflow * bytes2 / state->average_frame);
1361
1362         /* Foxer: reign in overflow with huge frames */
1363         if (labs(overflow) > labs(state->overflow)) {
1364                 overflow = state->overflow;
1365         }
1366
1367         /* Foxer: make sure overflow doesn't run away */
1368         if(overflow > bytes2 * state->twopass_max_overflow_improvement / 100) {
1369                 bytes2 += (overflow <= bytes2) ? bytes2 * state->twopass_max_overflow_improvement / 100 :
1370                         overflow * state->twopass_max_overflow_improvement / 100;
1371         }
1372         else if(overflow < bytes2 * state->twopass_max_overflow_degradation / -100) {
1373                 bytes2 += bytes2 * state->twopass_max_overflow_degradation / -100;
1374         }
1375         else {
1376                 bytes2 += overflow;
1377         }
1378
1379         if(bytes2 > state->max_framesize) {
1380                 capped_to_max_framesize = 1;
1381                 bytes2 = state->max_framesize;
1382         }
1383
1384         if(bytes2 < 1) {
1385                 bytes2 = 1;
1386         }
1387
1388         state->bytes1 = bytes1;
1389         state->bytes2 = bytes2;
1390
1391         /* very 'simple' quant<->filesize relationship */
1392         quant = state->pass1_quant * bytes1 / bytes2;
1393
1394         if(quant < 1)
1395                 quant = 1;
1396         else if(quant > 31)
1397                 quant = 31;
1398         else if(!state->pass1_intra) {
1399
1400                 /* Foxer: aid desired quantizer precision by accumulating decision error */
1401                 state->quant_error[quant] += ((double)(state->pass1_quant * bytes1) / bytes2) - quant;
1402
1403                 if (state->quant_error[quant] >= 1.0) {
1404                         state->quant_error[quant] -= 1.0;
1405                         quant++;
1406                 }
1407         }
1408
1409         /* we're done with credits */
1410         if(util_frametype(state) != FRAME_TYPE_NORMAL_MOVIE) {
1411                 return(quant);
1412         }
1413
1414         if(intra) {
1415
1416                 if (quant < state->min_iquant)
1417                         quant = state->min_iquant;
1418                 if (quant > state->max_iquant)
1419                         quant = state->max_iquant;
1420         }
1421         else {
1422
1423                 if(quant > state->max_pquant)
1424                         quant = state->max_pquant;
1425                 if(quant < state->min_pquant)
1426                         quant = state->min_pquant;
1427
1428                 /* subsequent frame quants can only be +- 2 */
1429                 if(state->last_quant && capped_to_max_framesize == 0) {
1430                         if (quant > state->last_quant + 2)
1431                                 quant = state->last_quant + 2;
1432                         if (quant < state->last_quant - 2)
1433                                 quant = state->last_quant - 2;
1434                 }
1435         }
1436
1437         return(quant);
1438
1439 }
1440
1441 static int vbr_getintra_2pass2(void *sstate)
1442 {
1443
1444         int intra;
1445         vbr_control_t *state = sstate;
1446
1447
1448         /* Get next intra state (fetched by update) */
1449         intra = state->pass1_intra;
1450
1451         /* During credits, XviD will decide itself */
1452         if(util_frametype(state) != FRAME_TYPE_NORMAL_MOVIE) {
1453
1454
1455                 switch(state->credits_mode) {
1456                 default:
1457                 case VBR_CREDITS_MODE_RATE :
1458                 case VBR_CREDITS_MODE_SIZE :
1459                         intra = -1;
1460                         break;
1461                 case VBR_CREDITS_MODE_QUANT :
1462                         /* Except in this case */
1463                         if (state->credits_quant_i == state->credits_quant_p)
1464                                 intra = -1;
1465                         break;
1466                 }
1467
1468         }
1469
1470         /* Force I Frame when max_key_interval is reached */
1471         if((state->cur_frame - state->last_keyframe) > state->max_key_interval)
1472                 intra = 1;
1473
1474         /*
1475          * Force P or B Frames for frames whose distance is less than the
1476          * requested minimum
1477          */
1478         if((state->cur_frame - state->last_keyframe) < state->min_key_interval)
1479                 intra = 0;
1480
1481
1482         /* Return the given intra mode except for first frame */
1483         return((state->cur_frame==0)?1:intra);
1484
1485 }
1486
1487 static int vbr_update_2pass2(void *sstate,
1488                              int quant,
1489                              int intra,
1490                              int header_bytes,
1491                              int total_bytes,
1492                              int kblocks,
1493                              int mblocks,
1494                              int ublocks)
1495
1496
1497 {
1498
1499
1500         int next_hbytes, next_kblocks, next_mblocks, next_ublocks;
1501         int tempdiv;
1502
1503         vbr_control_t *state = sstate;
1504
1505         /*
1506          * We do not depend on getintra/quant because we have the real results
1507          * from the xvid core
1508          */
1509
1510         if (util_frametype(state) == FRAME_TYPE_NORMAL_MOVIE) {
1511
1512                 state->quant_count[quant]++;
1513
1514                 if (state->pass1_intra) {
1515
1516                         state->overflow += state->KFoverflow;
1517                         state->KFoverflow = state->desired_bytes2 - total_bytes;
1518
1519                         tempdiv = (state->keyframe_locations[state->KF_idx] -
1520                                    state->keyframe_locations[state->KF_idx - 1]);
1521
1522                         /* redistribute correctly (by koepi) */
1523                         if (tempdiv > 1) {
1524                                 /* non-consecutive keyframes */
1525                                 state->KFoverflow_partial = state->KFoverflow /
1526                                         (tempdiv - 1);
1527                         }
1528                         else {
1529                                 state->overflow  += state->KFoverflow;
1530                                 state->KFoverflow = 0;
1531                                 state->KFoverflow_partial = 0;
1532                         }
1533                         state->KF_idx++;
1534
1535                 }
1536                 else {
1537                         state->overflow += state->desired_bytes2 - total_bytes +
1538                                 state->KFoverflow_partial;
1539                         state->KFoverflow -= state->KFoverflow_partial;
1540                 }
1541         }
1542         else {
1543
1544                 state->overflow += state->desired_bytes2 - total_bytes;
1545                 state->overflow += state->KFoverflow;
1546                 state->KFoverflow = 0;
1547                 state->KFoverflow_partial = 0;
1548         }
1549
1550         /* Save old quant */
1551         state->last_quant = quant;
1552
1553         /* Update next frame data */
1554         fscanf(state->pass1_file, "%d %d %d %d %d %d %d\n",
1555                &state->pass1_quant, &state->pass1_intra, &next_hbytes,
1556                &state->pass1_bytes, &next_kblocks, &next_mblocks,
1557                &next_ublocks);
1558
1559         /* Save the last Keyframe pos */
1560         if(intra)
1561                 state->last_keyframe = state->cur_frame;
1562
1563         /* Ok next frame */
1564         state->cur_frame++;
1565
1566         return(0);
1567
1568 }
1569
1570 static int vbr_finish_2pass2(void *sstate)
1571 {
1572
1573         vbr_control_t *state = sstate;
1574
1575         if(state->pass1_file == NULL)
1576                 return(-1);
1577
1578         /* Close the file */
1579         if(fclose(state->pass1_file) != 0)
1580                 return(-1);
1581
1582         /* Free the memory */
1583         free(state->keyframe_locations);
1584
1585         return(0);
1586
1587 }
1588
1589
1590 /******************************************************************************
1591  * Fixed quant mode - Most of the functions will be dummy functions
1592  *****************************************************************************/
1593
1594 static int vbr_init_fixedquant(void *sstate)
1595 {
1596
1597         vbr_control_t *state = sstate;
1598
1599         if(state->fixed_quant < 1)
1600                 state->fixed_quant = 1;
1601
1602         if(state->fixed_quant > 31)
1603                 state->fixed_quant = 31;
1604
1605         state->cur_frame = 0;
1606
1607         return(0);
1608
1609 }
1610
1611 static int vbr_getquant_fixedquant(void *sstate)
1612 {
1613
1614         vbr_control_t *state = sstate;
1615
1616         /* Credits' frame ? */
1617         if(util_frametype(state) != FRAME_TYPE_NORMAL_MOVIE) {
1618
1619                 int quant;
1620
1621                 switch(state->credits_mode) {
1622                 case VBR_CREDITS_MODE_RATE:
1623                         quant = state->fixed_quant * state->credits_quant_ratio;
1624                         break;
1625                 case VBR_CREDITS_MODE_QUANT:
1626                         quant = state->credits_fixed_quant;
1627                         break;
1628                 default:
1629                         quant = state->fixed_quant;
1630
1631                 }
1632
1633                 return(quant);
1634
1635         }
1636
1637         /* No credit frame - return fixed quant */
1638         return(state->fixed_quant);
1639
1640 }
1641
1642 static int vbr_getintra_fixedquant(void *state)
1643 {
1644
1645         return(-1);
1646
1647 }