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 
util_frametype(vbr_control_t * state)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 
util_creditsframes(vbr_control_t * state)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 
vbrSetDefaults(vbr_control_t * state)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 
vbrInit(vbr_control_t * state)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 
vbrGetQuant(vbr_control_t * state)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 
vbrGetIntra(vbr_control_t * state)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 
vbrUpdate(vbr_control_t * state,int quant,int intra,int header_bytes,int total_bytes,int kblocks,int mblocks,int ublocks)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 
vbrFinish(vbr_control_t * state)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 
vbr_init_dummy(void * sstate)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 
vbr_update_dummy(void * state,int quant,int intra,int header_bytes,int total_bytes,int kblocks,int mblocks,int ublocks)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 
vbr_finish_dummy(void * state)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 
vbr_getquant_1pass(void * state)483 static int vbr_getquant_1pass(void *state)
484 {
485 
486 	return(0);
487 
488 }
489 
vbr_getintra_1pass(void * state)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 
vbr_init_2pass1(void * sstate)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 
vbr_getquant_2pass1(void * state)542 static int vbr_getquant_2pass1(void *state)
543 {
544 
545 	return(2);
546 
547 }
548 
vbr_getintra_2pass1(void * state)549 static int vbr_getintra_2pass1(void *state)
550 {
551 
552 	return(-1);
553 
554 }
555 
vbr_update_2pass1(void * sstate,int quant,int intra,int header_bytes,int total_bytes,int kblocks,int mblocks,int ublocks)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 
vbr_finish_2pass1(void * sstate)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 
vbr_init_2pass2(void * sstate)636 static int vbr_init_2pass2(void *sstate)
637 {
638 	int c, n, pos_firstframe, credits_frames;
639 	long long credits1_bytes;
640 	long long credits2_bytes;
641 	long long desired;
642 	long long total_bytes;
643 	long long itotal_bytes;
644 	long long start_curved;
645 	long long end_curved;
646 	double total1;
647 	double total2;
648 
649 	vbr_control_t *state = sstate;
650 	state->pass1_file = NULL;
651 
652 	/* Check the filename */
653 	if(state->filename == NULL || state->filename[0] == '\0')
654 		goto err_out;
655 
656 	/* Initialize safe defaults for 2pass 2 */
657 	state->pass1_file = NULL;
658 	state->nb_frames = 0;
659 	state->nb_keyframes = 0;
660 
661 	/* Open the 1st pass file */
662 	state->pass1_file = fopen(state->filename, "r");
663 	if(state->pass1_file == NULL)
664 		goto err_out;
665 
666 	/* Get the file version and check against current version */
667 	if (fscanf(state->pass1_file, "# ASCII XviD vbr stat file version %d\n", &n) != 1)
668 		goto err_out;
669 
670 	if(n != VBR_VERSION)
671 		goto err_out;
672 
673 	/* Skip the blank commented line */
674 	c = n = 0;
675 	do {
676 
677 		c = fgetc(state->pass1_file);
678 
679 		if(c == EOF) {
680 			goto err_out;
681 		}
682 
683 		if(c == '\n') n++;
684 
685 	}while(n < 1);
686 
687 
688 	/* Get the number of frames */
689 	if (fscanf(state->pass1_file, "# frames : %d\n", &state->nb_frames) != 1)
690 		goto err_out;
691 
692 	/* Compute the desired size */
693 	state->desired_size = (long long)
694 		(((long long)state->nb_frames * (long long)state->desired_bitrate) /
695 		 (state->fps * 8.0));
696 
697 	/* Get the number of keyframes */
698 	if (fscanf(state->pass1_file, "# keyframes : %d\n", &state->nb_keyframes) != 1)
699 		goto err_out;
700 
701 	/* Allocate memory space for the keyframe_location array */
702 	if(state->nb_keyframes < 0 ||
703            state->nb_keyframes >= 0x7fffffff / sizeof(int) ||
704            (state->keyframe_locations
705 	    = malloc((state->nb_keyframes+1)*sizeof(int))) == NULL) {
706 		goto err_out;
707 	}
708 
709 	/* Skip the blank commented line and the colum description */
710 	c = n = 0;
711 	do {
712 
713 		c = fgetc(state->pass1_file);
714 
715 		if(c == EOF) {
716 			goto err_out;
717 		}
718 
719 		if(c == '\n') n++;
720 
721 	}while(n < 2);
722 
723 	/* Save position for future use */
724 	pos_firstframe = ftell(state->pass1_file);
725 
726 	/* Read and initialize some variables */
727 	credits1_bytes = credits2_bytes = 0;
728 	total_bytes = itotal_bytes = 0;
729 	start_curved = end_curved = 0;
730 	credits_frames = 0;
731 
732 	for(state->cur_frame = c = 0; state->cur_frame<state->nb_frames; state->cur_frame++) {
733 
734 		int quant, keyframe, frame_hbytes, frame_bytes;
735 		int kblocks, mblocks, ublocks;
736 
737 		if (fscanf(state->pass1_file, "%d %d %d %d %d %d %d\n",
738 		       &quant, &keyframe, &frame_hbytes, &frame_bytes,
739 		       &kblocks, &mblocks, &ublocks) != 7)
740 			goto err_out;
741 
742 		/* Is the frame in the beginning credits */
743 		if(util_frametype(state) == FRAME_TYPE_STARTING_CREDITS) {
744 			credits1_bytes += frame_bytes;
745 			credits_frames++;
746 			continue;
747 		}
748 
749 		/* Is the frame in the eding credits */
750 		if(util_frametype(state) == FRAME_TYPE_ENDING_CREDITS) {
751 			credits2_bytes += frame_bytes;
752 			credits_frames++;
753 			continue;
754 		}
755 
756 		/* We only care about Keyframes when not in credits */
757 		if(keyframe) {
758 			itotal_bytes +=	frame_bytes + frame_bytes *
759 				state->keyframe_boost / 100;
760 			total_bytes  += frame_bytes *
761 				state->keyframe_boost / 100;
762 			state->keyframe_locations[c++] = state->cur_frame;
763 		}
764 
765 		total_bytes += frame_bytes;
766 
767 	}
768 
769 	/*
770 	 * Last frame is treated like an I Frame so we can dispatch overflow
771 	 * all other the last film segment
772 	 */
773 	state->keyframe_locations[c] = state->cur_frame;
774 
775 	desired = state->desired_size;
776 
777 	switch(state->credits_mode) {
778 	case VBR_CREDITS_MODE_QUANT :
779 
780 		state->movie_curve = (double)
781 			(total_bytes - credits1_bytes - credits2_bytes) /
782 			(desired  - credits1_bytes - credits2_bytes);
783 
784 		start_curved = credits1_bytes;
785 		end_curved   = credits2_bytes;
786 
787 		break;
788 	case VBR_CREDITS_MODE_SIZE:
789 
790 		/* start curve = (start / start desired size) */
791 		state->credits_start_curve = (double)
792 			(credits1_bytes / state->credits_start_size);
793 
794 		/* end curve = (end / end desired size) */
795 		state->credits_end_curve = (double)
796 			(credits2_bytes / state->credits_end_size);
797 
798 		start_curved = (long long)
799 			(credits1_bytes / state->credits_start_curve);
800 
801 		end_curved   = (long long)
802 			(credits2_bytes / state->credits_end_curve);
803 
804 		/* movie curve=(total-credits)/(desired_size-curved credits) */
805 		state->movie_curve = (double)
806 			(total_bytes - credits1_bytes - credits2_bytes) /
807 			(desired - start_curved - end_curved);
808 
809 		break;
810 	case VBR_CREDITS_MODE_RATE:
811 	default:
812 
813 		/* credits curve = (total/desired_size)*(100/credits_rate) */
814 		state->credits_start_curve = state->credits_end_curve =
815 			((double)total_bytes / desired) *
816 			((double)100 / state->credits_quant_ratio);
817 
818 		start_curved =
819 			(long long)(credits1_bytes/state->credits_start_curve);
820 
821 		end_curved   =
822 			(long long)(credits2_bytes/state->credits_end_curve);
823 
824 		state->movie_curve = (double)
825 			(total_bytes - credits1_bytes - credits2_bytes) /
826 			(desired - start_curved - end_curved);
827 
828 		break;
829 	}
830 
831 	/*
832 	 * average frame size = (desired - curved credits - curved keyframes) /
833 	 *                      (frames - credits frames - keyframes)
834 	 */
835 	state->average_frame = (double)
836 		(desired - start_curved - end_curved -
837 		 (itotal_bytes / state->movie_curve)) /
838 		(state->nb_frames - util_creditsframes(state) -
839 		 state->nb_keyframes);
840 
841 	/* Initialize alt curve parameters */
842 	if (state->use_alt_curve) {
843 
844 		state->alt_curve_low =
845 			state->average_frame - state->average_frame *
846 			(double)(state->alt_curve_low_dist / 100.0);
847 
848 		state->alt_curve_low_diff =
849 			state->average_frame - state->alt_curve_low;
850 
851 		state->alt_curve_high =
852 			state->average_frame + state->average_frame *
853 			(double)(state->alt_curve_high_dist / 100.0);
854 
855 		state->alt_curve_high_diff =
856 			state->alt_curve_high - state->average_frame;
857 
858 		if (state->alt_curve_use_auto) {
859 
860 			if (state->movie_curve > 1.0)	{
861 
862 				state->alt_curve_min_rel_qual =
863 					(int)(100.0 - (100.0 - 100.0 / state->movie_curve) *
864 					      (double)state->alt_curve_auto_str / 100.0);
865 
866 				if (state->alt_curve_min_rel_qual < 20)
867 					state->alt_curve_min_rel_qual = 20;
868 			}
869 			else {
870 				state->alt_curve_min_rel_qual = 100;
871 			}
872 
873 		}
874 
875 		state->alt_curve_mid_qual =
876 		(1.0 + (double)state->alt_curve_min_rel_qual / 100.0) / 2.0;
877 
878 		state->alt_curve_qual_dev = 1.0 - state->alt_curve_mid_qual;
879 
880 		if (state->alt_curve_low_dist > 100) {
881 
882 			switch(state->alt_curve_type) {
883 			case VBR_ALT_CURVE_AGGRESIVE:
884 				/* Sine Curve (high aggressiveness) */
885 				state->alt_curve_qual_dev *=
886 					2.0 /
887 					(1.0 +  sin(DEG2RAD * (state->average_frame * 90.0 / state->alt_curve_low_diff)));
888 
889 				state->alt_curve_mid_qual =
890 					1.0 - state->alt_curve_qual_dev *
891 					sin(DEG2RAD * (state->average_frame * 90.0 / state->alt_curve_low_diff));
892 				break;
893 
894 			default:
895 			case VBR_ALT_CURVE_LINEAR:
896 				/* Linear (medium aggressiveness) */
897 				state->alt_curve_qual_dev *=
898 					2.0 /
899 					(1.0 + state->average_frame / state->alt_curve_low_diff);
900 
901 				state->alt_curve_mid_qual =
902 					1.0 - state->alt_curve_qual_dev *
903 					state->average_frame / state->alt_curve_low_diff;
904 
905 				break;
906 
907 			case VBR_ALT_CURVE_SOFT:
908 				/* Cosine Curve (low aggressiveness) */
909 				state->alt_curve_qual_dev *=
910 					2.0 /
911 					(1.0 + (1.0 - cos(DEG2RAD * (state->average_frame * 90.0 / state->alt_curve_low_diff))));
912 
913 				state->alt_curve_mid_qual =
914 					1.0 - state->alt_curve_qual_dev *
915 					(1.0 - cos(DEG2RAD * (state->average_frame * 90.0 / state->alt_curve_low_diff)));
916 
917 				break;
918 			}
919 		}
920 	}
921 
922 	/* Go to the first non credits frame stats line into file */
923 	fseek(state->pass1_file, pos_firstframe, SEEK_SET);
924 
925 	/* Perform prepass to compensate for over/undersizing */
926 	total1 = total2 = 0.0;
927 	for(state->cur_frame=0; state->cur_frame<state->nb_frames; state->cur_frame++) {
928 
929 		int quant, keyframe, frame_hbytes, frame_bytes;
930 		int kblocks, mblocks, ublocks;
931 
932 		if (fscanf(state->pass1_file, "%d %d %d %d %d %d %d\n",
933 		       &quant, &keyframe, &frame_hbytes, &frame_bytes,
934 		       &kblocks, &mblocks, &ublocks) != 7)
935 			goto err_out;
936 
937 		if(util_frametype(state) != FRAME_TYPE_NORMAL_MOVIE)
938 			continue;
939 
940 		if(!keyframe) {
941 
942 			double dbytes = frame_bytes / state->movie_curve;
943 			total1 += dbytes;
944 
945 			if (state->use_alt_curve) {
946 
947 				if (dbytes > state->average_frame) {
948 
949 					if (dbytes >= state->alt_curve_high) {
950 						total2 += dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev);
951 					}
952 					else {
953 
954 						switch(state->alt_curve_type) {
955 						case VBR_ALT_CURVE_AGGRESIVE:
956 
957 							total2 +=
958 								dbytes *
959 								(state->alt_curve_mid_qual - state->alt_curve_qual_dev *
960 								 sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff)));
961 							break;
962 						default:
963 						case VBR_ALT_CURVE_LINEAR:
964 
965 							total2 +=
966 								dbytes *
967 								(state->alt_curve_mid_qual - state->alt_curve_qual_dev *
968 								 (dbytes - state->average_frame) / state->alt_curve_high_diff);
969 							break;
970 						case VBR_ALT_CURVE_SOFT:
971 							total2 +=
972 								dbytes *
973 								(state->alt_curve_mid_qual - state->alt_curve_qual_dev *
974 								 (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff))));
975 						}
976 					}
977 				}
978 				else {
979 
980 					if (dbytes <= state->alt_curve_low) {
981 						total2 += dbytes;
982 					}
983 					else {
984 
985 						switch(state->alt_curve_type) {
986 						case VBR_ALT_CURVE_AGGRESIVE:
987 							total2 +=
988 								dbytes *
989 								(state->alt_curve_mid_qual - state->alt_curve_qual_dev *
990 								 sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff)));
991 							break;
992 						default:
993 						case VBR_ALT_CURVE_LINEAR:
994 							total2 +=
995 								dbytes *
996 								(state->alt_curve_mid_qual - state->alt_curve_qual_dev *
997 								 (dbytes - state->average_frame) / state->alt_curve_low_diff);
998 							break;
999 						case VBR_ALT_CURVE_SOFT:
1000 							total2 +=
1001 								dbytes *
1002 								(state->alt_curve_mid_qual + state->alt_curve_qual_dev *
1003 								 (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff))));
1004 						}
1005 					}
1006 				}
1007 			}
1008 			else {
1009 				if (dbytes > state->average_frame) {
1010 					total2 +=
1011 						((double)dbytes +
1012 						 (state->average_frame - dbytes) *
1013 						 state->curve_compression_high / 100.0);
1014 				}
1015 				else {
1016 					total2 +=
1017 						((double)dbytes +
1018 						 (state->average_frame - dbytes) *
1019 						 state->curve_compression_low / 100.0);
1020 				}
1021 			}
1022 		}
1023 	}
1024 
1025 	state->curve_comp_scale = total1 / total2;
1026 
1027 	if (state->use_alt_curve) {
1028 
1029 		double curve_temp, dbytes;
1030 		int newquant;
1031 		int oldquant = 1;
1032 
1033 		if (state->alt_curve_use_auto_bonus_bias)
1034 			state->alt_curve_bonus_bias = state->alt_curve_min_rel_qual;
1035 
1036 		state->curve_bias_bonus =
1037 			(total1 - total2) * (double)state->alt_curve_bonus_bias /
1038 			(100.0 * (double)(state->nb_frames - util_creditsframes(state) - state->nb_keyframes));
1039 		state->curve_comp_scale =
1040 			((total1 - total2) * (1.0 - (double)state->alt_curve_bonus_bias / 100.0) + total2) /
1041 			total2;
1042 
1043 
1044 		for (n=1; n <= (int)(state->alt_curve_high*2) + 1; n++) {
1045 			dbytes = n;
1046 			if (dbytes > state->average_frame)
1047 			{
1048 				if (dbytes >= state->alt_curve_high) {
1049 					curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev);
1050 				}
1051 				else {
1052 					switch(state->alt_curve_type) {
1053 					case VBR_ALT_CURVE_AGGRESIVE:
1054 						curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1055 								       sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff)));
1056 						break;
1057 					default:
1058 					case VBR_ALT_CURVE_LINEAR:
1059 						curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1060 								       (dbytes - state->average_frame) / state->alt_curve_high_diff);
1061 						break;
1062 					case VBR_ALT_CURVE_SOFT:
1063 						curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1064 								       (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_high_diff))));
1065 					}
1066 				}
1067 			}
1068 			else {
1069 				if (dbytes <= state->alt_curve_low) {
1070 					curve_temp = dbytes;
1071 				}
1072 				else {
1073 					switch(state->alt_curve_type) {
1074 					case VBR_ALT_CURVE_AGGRESIVE:
1075 						curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1076 								       sin(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff)));
1077 						break;
1078 					default:
1079 					case VBR_ALT_CURVE_LINEAR:
1080 						curve_temp = dbytes * (state->alt_curve_mid_qual - state->alt_curve_qual_dev *
1081 								       (dbytes - state->average_frame) / state->alt_curve_low_diff);
1082 						break;
1083 					case VBR_ALT_CURVE_SOFT:
1084 						curve_temp = dbytes * (state->alt_curve_mid_qual + state->alt_curve_qual_dev *
1085 								       (1.0 - cos(DEG2RAD * ((dbytes - state->average_frame) * 90.0 / state->alt_curve_low_diff))));
1086 					}
1087 				}
1088 			}
1089 
1090 			if (state->movie_curve > 1.0)
1091 				dbytes *= state->movie_curve;
1092 
1093 			newquant = (int)(dbytes * 2.0 / (curve_temp * state->curve_comp_scale + state->curve_bias_bonus));
1094 			if (newquant > 1)
1095 			{
1096 				if (newquant != oldquant)
1097 				{
1098 					oldquant = newquant;
1099 				}
1100 
1101 			}
1102 
1103 		}
1104 
1105 	}
1106 
1107 	state->overflow = 0;
1108 	state->KFoverflow = 0;
1109 	state->KFoverflow_partial = 0;
1110 	state->KF_idx = 1;
1111 
1112 	for (n=0 ; n < 32 ; n++) {
1113 		state->quant_error[n] = 0.0;
1114 		state->quant_count[n] = 0;
1115 	}
1116 
1117 	state->curve_comp_error = 0.0;
1118 	state->last_quant = 0;
1119 
1120 	/*
1121 	 * Above this frame size limit, normal vbr rules will not apply
1122 	 * This means :
1123 	 *      1 - Quant can de/increase more than -/+2 between 2 frames
1124 	 *      2 - Leads to artifacts because of 1
1125 	 */
1126 	state->max_framesize = state->twopass_max_bitrate/state->fps;
1127 
1128 	/* Get back to the beginning of frame statistics */
1129 	fseek(state->pass1_file, pos_firstframe, SEEK_SET);
1130 
1131 	/*
1132 	 * Small hack : We have to get next frame stats before the
1133 	 * getintra/quant calls
1134 	 * User clients update the data when they call vbrUpdate
1135 	 * we are just bypassing this because we don't have to update
1136 	 * the overflow and so on...
1137 	 */
1138 	{
1139 
1140 		/* Fake vars */
1141 		int next_hbytes, next_kblocks, next_mblocks, next_ublocks;
1142 
1143 		fscanf(state->pass1_file, "%d %d %d %d %d %d %d\n",
1144 		       &state->pass1_quant, &state->pass1_intra, &next_hbytes,
1145 		       &state->pass1_bytes, &next_kblocks, &next_mblocks,
1146 		       &next_ublocks);
1147 
1148 	}
1149 
1150 	/* Initialize the frame counter */
1151 	state->cur_frame = 0;
1152 	state->last_keyframe = 0;
1153 
1154 	return(0);
1155 
1156 err_out:
1157 	if (state->pass1_file)
1158 		fclose(state->pass1_file);
1159 	state->pass1_file = NULL;
1160 	return -1;
1161 }
1162 
vbr_getquant_2pass2(void * sstate)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 
vbr_getintra_2pass2(void * sstate)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 
vbr_update_2pass2(void * sstate,int quant,int intra,int header_bytes,int total_bytes,int kblocks,int mblocks,int ublocks)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 	if (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) != 7)
1558 		return -1;
1559 
1560 	/* Save the last Keyframe pos */
1561 	if(intra)
1562 		state->last_keyframe = state->cur_frame;
1563 
1564 	/* Ok next frame */
1565 	state->cur_frame++;
1566 
1567 	return(0);
1568 
1569 }
1570 
vbr_finish_2pass2(void * sstate)1571 static int vbr_finish_2pass2(void *sstate)
1572 {
1573 
1574 	vbr_control_t *state = sstate;
1575 
1576 	if(state->pass1_file == NULL)
1577 		return(-1);
1578 
1579 	/* Close the file */
1580 	if(fclose(state->pass1_file) != 0)
1581 		return(-1);
1582 
1583 	/* Free the memory */
1584 	free(state->keyframe_locations);
1585 
1586 	return(0);
1587 
1588 }
1589 
1590 
1591 /******************************************************************************
1592  * Fixed quant mode - Most of the functions will be dummy functions
1593  *****************************************************************************/
1594 
vbr_init_fixedquant(void * sstate)1595 static int vbr_init_fixedquant(void *sstate)
1596 {
1597 
1598 	vbr_control_t *state = sstate;
1599 
1600 	if(state->fixed_quant < 1)
1601 		state->fixed_quant = 1;
1602 
1603 	if(state->fixed_quant > 31)
1604 		state->fixed_quant = 31;
1605 
1606 	state->cur_frame = 0;
1607 
1608 	return(0);
1609 
1610 }
1611 
vbr_getquant_fixedquant(void * sstate)1612 static int vbr_getquant_fixedquant(void *sstate)
1613 {
1614 
1615 	vbr_control_t *state = sstate;
1616 
1617 	/* Credits' frame ? */
1618 	if(util_frametype(state) != FRAME_TYPE_NORMAL_MOVIE) {
1619 
1620 		int quant;
1621 
1622 		switch(state->credits_mode) {
1623 		case VBR_CREDITS_MODE_RATE:
1624 			quant = state->fixed_quant * state->credits_quant_ratio;
1625 			break;
1626 		case VBR_CREDITS_MODE_QUANT:
1627 			quant = state->credits_fixed_quant;
1628 			break;
1629 		default:
1630 			quant = state->fixed_quant;
1631 
1632 		}
1633 
1634 		return(quant);
1635 
1636 	}
1637 
1638 	/* No credit frame - return fixed quant */
1639 	return(state->fixed_quant);
1640 
1641 }
1642 
vbr_getintra_fixedquant(void * state)1643 static int vbr_getintra_fixedquant(void *state)
1644 {
1645 
1646 	return(-1);
1647 
1648 }
1649