ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/freemol/trunk/src/mpeg_encode/src/rate.c
Revision: 22
Committed: Mon Jul 7 22:16:37 2008 UTC (11 years, 4 months ago) by wdelano
File size: 26753 byte(s)
Log Message:
initial checkin of mpeg_encode source
Line File contents
1 /*============================================================================*
2 * rate.c *
3 * *
4 * Procedures concerned with rate control *
5 * *
6 * EXPORTED PROCEDURES: *
7 * initRatecontrol() *
8 * targetRateControl() *
9 * updateRateControl() *
10 * MB_RateOut() *
11 * needQScaleChange() *
12 * incNumBlocks() *
13 * incQuant() *
14 * incMacroBlockBits() *
15 * setPictureRate() *
16 * setBitRate() *
17 * getBitRate() *
18 * setBufferSize() *
19 * getBufferSize() *
20 * *
21 * NOTES: *
22 * Naming conventions follow those of MPEG-2 draft algorithm (chap. 10) *
23 *============================================================================*/
24
25
26 /*
27 * Copyright (c) 1995 The Regents of the University of California.
28 * All rights reserved.
29 *
30 * Permission to use, copy, modify, and distribute this software and its
31 * documentation for any purpose, without fee, and without written agreement is
32 * hereby granted, provided that the above copyright notice and the following
33 * two paragraphs appear in all copies of this software.
34 *
35 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
36 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
37 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
38 * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 *
40 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
41 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
42 * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
43 * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
44 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
45 */
46
47 /*==============*
48 * HEADER FILES *
49 *==============*/
50
51 #include <sys/times.h>
52 #include "all.h"
53 #include "mtypes.h"
54 #include "bitio.h"
55 #include "frames.h"
56 #include "prototypes.h"
57 #include "param.h"
58 #include "mheaders.h"
59 #include "fsize.h"
60 #include "postdct.h"
61 #include "mpeg.h"
62 #include "parallel.h"
63 #include "dct.h"
64 #include "rate.h"
65
66
67 /*==================*
68 * GLOBAL VARIABLES *
69 *==================*/
70
71 #define MAX_BIT_RATE 104857600 /* 18 digit number in units of 400 */
72 #define MAX_BUFFER_SIZE 16760832 /* 10 digit number in units of 16k */
73 #define DEFAULT_BUFFER_SIZE 327680 /* maximun for "constrained" bitstream */
74 #define DEFAULT_VBV_FULLNESS 3 /* wait till 1/3 full */
75 #define DEFAULT_PICT_RATE_CODE 5 /* code for 30 Frames/sec */
76 #define DEFAULT_PICT_RATE 30 /* 30 frames per second */
77 #define MAX_VBV_DELAY 32768 /* 16 digits */
78
79
80 /* Variables from Parameter File */
81
82 static int RateControlMode = VARIABLE_RATE;
83 static int32 buffer_size = DEFAULT_BUFFER_SIZE;
84 static int32 bit_rate = -1;
85
86
87 /* Variables for the VBV buffer defined in MPEG specs */
88 static int32 VBV_delay =0; /* delay in units of 1/90000 seconds */
89 static int32 VBV_buffer = 0; /* fullness of the theoretical VBV buffer */
90 static int32 bufferFillRate = 0; /* constant rate at which buffer filled */
91 static int32 frameDelayIncrement = 0; /* number of "delay" units/Frame */
92
93 /* Global complexity measure variables */
94 static int Xi, Xp, Xb; /* Global complexity measure */
95
96 static int Si, Sp, Sb; /* Total # bits for last pict of type (Overhead?) */
97
98 static float Qi, Qp, Qb; /* avg quantizaton for last picture of type */
99
100 /* Target bit allocations for each type of picture*/
101 int Ti, Tp, Tb;
102
103 int current_Tx; /* allocation for current frame */
104
105 /* Count of number of pictures of each type remaining */
106 int GOP_X = 0;
107 int GOP_I = 0;
108 int GOP_P = 0;
109 int GOP_B = 0;
110
111 int Nx = 0;
112 int Ni = 0;
113 int Np = 0;
114 int Nb = 0;
115
116 /* Counters used while encoding frames */
117
118 int rc_numBlocks = 0;
119 int rc_totalQuant = 0;
120 int rc_bitsThisMB;
121 int rc_totalMBBits;
122 int rc_totalFrameBits;
123 int rc_totalOverheadBits = 0;
124
125
126 /* Want to print out Macroblock info every Nth MB */
127 int RC_MB_SAMPLE_RATE = 0;
128
129 static float Ki = .7;
130 static float Kp = 1;
131 static float Kb = 1.4;
132 static int rc_R;
133 static int rc_G;
134
135 /* Rate Control variables */
136
137 /* Virtual buffers for each frame type */
138 static int d0_i; /* Initial fullnesses */
139 static int d0_p;
140 static int d0_b;
141
142 static int lastFrameVirtBuf; /* fullness after last frame of this type */
143 static int currentVirtBuf; /* fullness during current encoding*/
144
145 static int MB_cnt = -1; /* Number of MB's in picture */
146
147 static int rc_Q; /* reference quantization parameter */
148
149 static int reactionParameter; /* Reaction parameter */
150
151 /* Adaptive Quantization variables */
152 static int act_j; /* spatial activity measure */
153 static float N_act; /* Normalised spacial activity */
154 static int avg_act; /* average activity value in last picture encoded */
155 static int total_act_j; /* Sum of activity values in current frame */
156
157 static int var_sblk; /* sub-block activity */
158 static int P_mean; /* Mean value of pixels in 8x8 sub-block */
159
160 static int mquant; /* Raw Quantization value */
161 static int Qscale; /* Clipped, truncated quantization value */
162
163
164
165 /* Output-related variables */
166 #ifdef RC_STATS_FILE
167 static FILE *RC_FILE;
168 #endif
169
170 static char *Frame_header1 = " Fm # Bit GOP V ";
171 static char *Frame_header2 = " # type MBs Alloc left Ni Np Nb N_act buff Q_rc Qscale";
172 static char *Frame_header3 = "---- - ---- ------ ------- -- -- -- ----- ------ ---- ----";
173 static char *Frame_trailer1 = " avg virt % GOP % VBV";
174 static char *Frame_trailer2 = " Sx Qx Xx act N_act buffer alloc left left buf delay";
175 static char *Frame_trailer3 = "------ --.-- ------- --- --.-- ------- --- ------- --- ------- ------";
176
177 static char *MB_header1 = "MB# #bits Q mqt Dj Q_j actj N_act totbits b/MB %alloc %done";
178 static char *MB_header2 = "--- ----- -- --- ------ --- ----- --.-- ------ ---- --- ---";
179
180 static char rc_buffer[101];
181
182 /* EXTERNAL Variables */
183 extern char *framePattern;
184 extern int framePatternLen;
185
186
187 /*===============================*
188 * INTERNAL PROCEDURE prototypes *
189 *===============================*/
190
191 int initGOPRateControl _ANSI_ARGS_((void));
192 int determineMBCount _ANSI_ARGS_((void));
193 void checkBufferFullness _ANSI_ARGS_((int count));
194 void checkSpatialActivity _ANSI_ARGS_((Block blk0, Block blk1, Block blk2, Block blk3));
195 void incNumBlocks _ANSI_ARGS_((int num));
196 void calculateVBVDelay _ANSI_ARGS_((int num));
197 void updateVBVBuffer _ANSI_ARGS_((int frameBits));
198 int BlockExperiments _ANSI_ARGS_((int16 *OrigBlock, int16 *NewBlock, int control));
199
200
201 /*=====================*
202 * EXPORTED PROCEDURES *
203 *=====================*/
204
205 /*===========================================================================*
206 *
207 * initRateControl
208 *
209 * initialize the allocation parameters.
210 *
211 * RETURNS: nothing
212 *
213 * SIDE EFFECTS: many global variables
214 *
215 * NOTES: Get rid of the redundant pattern stuff!!
216 *===========================================================================*/
217 int
218 initRateControl()
219 {
220 int index;
221 int result;
222
223 DBG_PRINT(("\tInitializing Allocation Data\n"));
224
225 #ifdef RC_STATS_FILE
226 RC_FILE = fopen("RC_STATS_FILE", "w");
227 if ( RC_FILE == NULL) {
228 DBG_PRINT(("\tOpen of RC file failed, using stderr\n"));
229 RC_FILE = stderr;
230 fprintf(RC_FILE, "\tOpen of RC file failed, using stderr\n");
231 fflush(RC_FILE);
232 }
233 #endif
234
235 /* Initialize Pattern info */
236 GOP_X = framePatternLen;
237 for ( index = 0; index < framePatternLen; index++ ) {
238 switch( framePattern[index] ) {
239 case 'i':
240 GOP_I++;
241 break;
242 case 'p':
243 GOP_P++;
244 break;
245 case 'b':
246 GOP_B++;
247 break;
248 default:
249 printf("\n\tERROR rate.c - BAD PATTERN!\n");
250 RateControlMode = VARIABLE_RATE;
251 return (0);
252 }
253 }
254 if (GOP_X != (GOP_I + GOP_P + GOP_B )) {
255 printf("\n\tERROR rate.c - Pattern Length Mismatch\n");
256 RateControlMode = VARIABLE_RATE;
257 return (-1);
258 }
259
260 /* Initializing GOP bit allocation */
261 rc_R = 0;
262 rc_G = (bit_rate * GOP_X/frameRateRounded);
263
264 /* Initialize the "global complexity measures" */
265 Xi = (160 * bit_rate/115);
266 Xp = (60 * bit_rate/115);
267 Xb = (42 * bit_rate/115);
268
269 /* Initialize MB counters */
270 rc_totalMBBits= rc_bitsThisMB= rc_totalFrameBits=rc_totalOverheadBits = 0;
271 rc_numBlocks = rc_totalQuant = 0;
272
273 /* init virtual buffers */
274 reactionParameter = (2 * bit_rate / frameRateRounded);
275 d0_i = (10 * reactionParameter / 31);
276 d0_p = (Kp * d0_i);
277 d0_b = (Kb * d0_i);
278
279 lastFrameVirtBuf = d0_i; /* start with I Frame */
280 rc_Q = lastFrameVirtBuf * 31 / reactionParameter;
281
282 /* init spatial activity measures */
283 avg_act = 400; /* Suggested initial value */
284 N_act = 1;
285
286 mquant = rc_Q * N_act;
287
288 frameDelayIncrement = (90000 / frameRateRounded); /* num of "delay" units per frame */
289 bufferFillRate = bit_rate / frameRateRounded; /* VBV buf fills at constant rate */
290 VBV_buffer = buffer_size;
291 DBG_PRINT(("\tVBV- delay: %d, fill rate: %d, delay/Frame: %d units, buffer size: %d\n",
292 VBV_delay, bufferFillRate, frameDelayIncrement, buffer_size));
293
294 result = initGOPRateControl();
295
296 return result;
297 }
298
299 /*===========================================================================*
300 *
301 * initGOPRateControl
302 *
303 * (re)-initialize the RC for the a new Group of Pictures.
304 * New bit allocation, but carry over complexity measures.
305 *
306 * RETURNS: nothing
307 *
308 * SIDE EFFECTS: many global variables
309 *
310 *===========================================================================*/
311 int
312 initGOPRateControl()
313 {
314 DBG_PRINT(("\tInitializing new GOP\n"));
315
316 Nx = GOP_X;
317 Ni = GOP_I;
318 Np = GOP_P;
319 Nb = GOP_B;
320
321 rc_R += rc_G;
322
323 DBG_PRINT(("\tbufsize: %d, bitrate: %d, pictrate: %d, GOP bits: %d\n",
324 buffer_size, bit_rate, frameRateRounded, rc_R));
325 DBG_PRINT(("\tXi: %d, Xp: %d, Xb: %d Nx: %d, Ni: %d, Np: %d, Nb: %d\n",
326 Xi, Xp, Xb, Nx,Ni,Np,Nb));
327 DBG_PRINT(("\td0_i: %d, d0_p: %d, d0_b: %d, avg_act: %d, rc_Q: %d, mquant: %d\n",
328 d0_i, d0_p, d0_b, avg_act, rc_Q, mquant));
329 return 1;
330 }
331
332
333 /*===========================================================================*
334 *
335 * targetRateControl
336 *
337 * Determine the target allocation for given picture type, initiates
338 * variables for rate control process.
339 *
340 * RETURNS: nothing.
341 *
342 * SIDE EFFECTS: many global variables
343 *
344 *===========================================================================*/
345 void
346 targetRateControl(frame)
347 MpegFrame *frame;
348 {
349 float temp1, minimumBits;
350 float tempX, tempY, tempZ;
351 int result;
352 int frameType;
353 char *strPtr;
354
355 minimumBits = (bit_rate / (8 * frameRateRounded));
356
357 /* Check if new GOP */
358 if (Nx == 0) {
359 initGOPRateControl();
360 }
361
362 if (MB_cnt < 0) {MB_cnt = determineMBCount();}
363
364 switch (frame->type) {
365 case TYPE_IFRAME:
366 frameType = 'I';
367
368 /* temp1 = ( rc_R / ( 1+ ((Np * Xp) / (Xi * Kp)) + ((Nb*Xb) / (Xi*Kb))))); */
369
370 tempX = ( (Np * Ki * Xp) / (Xi * Kp) );
371 tempY = ( (Nb * Ki * Xb) / (Xi*Kb) );
372 tempZ = Ni + tempX + tempY;
373 temp1 = (rc_R / tempZ);
374 result = (int) (temp1 > minimumBits ? temp1 : minimumBits);
375 current_Tx = Ti = result;
376 lastFrameVirtBuf = d0_i;
377 break;
378
379 case TYPE_PFRAME:
380 frameType = 'P';
381 tempX = ( (Ni * Kp * Xi) / (Ki * Xp) );
382 tempY = ( (Nb * Kp * Xb) / (Kb * Xp) );
383 tempZ = Np + tempX + tempY;
384 temp1 = (rc_R/ tempZ);
385 result = (int) (temp1 > minimumBits ? temp1 : minimumBits);
386 current_Tx = Tp = result;
387 lastFrameVirtBuf = d0_p;
388 break;
389
390 case TYPE_BFRAME:
391 frameType = 'B';
392 tempX = ( (Ni * Kb * Xi) / (Ki * Xb) );
393 tempY = ( (Np * Kb * Xp) / (Kp * Xb) );
394 tempZ = Nb + tempX + tempY;
395 temp1 = (rc_R/ tempZ);
396 result = (int) (temp1 > minimumBits ? temp1 : minimumBits);
397 current_Tx = Tb = result;
398 lastFrameVirtBuf = d0_b;
399 break;
400
401 default:
402 frameType = 'X';
403 }
404
405 N_act = 1;
406 rc_Q = lastFrameVirtBuf * 31 / reactionParameter;
407 mquant = rc_Q * N_act;
408 Qscale = (mquant > 31 ? 31 : mquant);
409 Qscale = (Qscale < 1 ? 1 : Qscale);
410
411 /* Print headers for Frame info */
412 strPtr = Frame_header1;
413 DBG_PRINT(("%s\n",strPtr));
414 strPtr = Frame_header2;
415 DBG_PRINT(("%s\n",strPtr));
416 strPtr = Frame_header3;
417 DBG_PRINT(("%s\n",strPtr));
418
419 /* Print Frame info */
420 sprintf(rc_buffer, "%4d %1c %4d %6d %7d %2d %2d %2d %2.2f %6d %4d %3d",
421 frame->id,frameType,MB_cnt,current_Tx,rc_R,Ni,Np,Nb, N_act, lastFrameVirtBuf, rc_Q, Qscale);
422
423 #ifdef RC_STATS_FILE
424 fprintf(RC_FILE,"%s\n", rc_buffer);
425 fflush(RC_FILE);
426 #endif
427 DBG_PRINT(("%s\n",rc_buffer));
428
429 /* Print headers for Macroblock info */
430 if (RC_MB_SAMPLE_RATE) {
431 strPtr = MB_header1;
432 DBG_PRINT(("%s\n",strPtr));
433 strPtr = MB_header2;
434 DBG_PRINT(("%s\n",strPtr));
435 } else {
436 return;
437 }
438
439 return;
440 }
441
442
443
444 /*===========================================================================*
445 *
446 * updateRateControl
447 *
448 * Update the statistics kept, after end of frame. Resets
449 * various global variables
450 *
451 * RETURNS: nothing
452 *
453 * SIDE EFFECTS: many global variables
454 *
455 *===========================================================================*/
456 void
457 updateRateControl(type)
458 int type;
459 {
460 int totalBits, frameComplexity, pctAllocUsed, pctGOPUsed;
461 float avgQuant;
462 char *strPtr;
463
464 totalBits = rc_totalFrameBits;
465 avgQuant = ((float) rc_totalQuant / (float) rc_numBlocks);
466 frameComplexity = totalBits * avgQuant;
467 pctAllocUsed = (totalBits *100 / current_Tx);
468 rc_R -= totalBits;
469 pctGOPUsed = (rc_R *100/ rc_G);
470
471 avg_act = (total_act_j / MB_cnt);
472
473 updateVBVBuffer(totalBits);
474
475 switch (type) {
476 case TYPE_IFRAME:
477 Ti = current_Tx;
478 d0_i = currentVirtBuf;
479 Ni--;
480 Si = totalBits;
481 Qi = avgQuant;
482 Xi = frameComplexity;
483 break;
484 case TYPE_PFRAME:
485 Tp = current_Tx;
486 d0_p = currentVirtBuf;
487 Np--;
488 Sp = totalBits;
489 Qp = avgQuant;
490 Xp = frameComplexity;
491 break;
492 case TYPE_BFRAME:
493 Tb = current_Tx;
494 d0_b = currentVirtBuf;
495 Nb--;
496 Sb = totalBits;
497 Qb = avgQuant;
498 Xb = frameComplexity;
499 break;
500 }
501
502
503 /* Print Frame info */
504 strPtr = Frame_trailer1;
505 DBG_PRINT(("%s\n",strPtr));
506 strPtr = Frame_trailer2;
507 DBG_PRINT(("%s\n",strPtr));
508 strPtr = Frame_trailer3;
509 DBG_PRINT(("%s\n",strPtr));
510
511 sprintf(rc_buffer, "%6d %2.2f %6d %3d %2.2f %7d %3d %7d %3d %6d %6d",
512 totalBits, avgQuant, frameComplexity, avg_act, N_act, currentVirtBuf, pctAllocUsed, rc_R, pctGOPUsed, VBV_buffer, VBV_delay);
513 #ifdef RC_STATS_FILE
514 fprintf(RC_FILE,"%s\n", rc_buffer);
515 fflush(RC_FILE);
516 #endif
517 DBG_PRINT(("%s\n",rc_buffer));
518
519 Nx--;
520 rc_totalMBBits= rc_bitsThisMB= rc_totalFrameBits=rc_totalOverheadBits = 0;
521 rc_numBlocks = rc_totalQuant = total_act_j = currentVirtBuf = 0;
522
523 DBG_PRINT(("GOP now has %d bits remaining (%3d%%) for %d frames .. , Ni= %d, Np= %d, Nb= %d\n", rc_R, (rc_R*100/rc_G), (Ni+Np+Nb), Ni, Np, Nb));
524
525 }
526
527
528 /*===========================================================================*
529 *
530 * MB_RateOut
531 *
532 * Prints out sampling of MB rate control data. Every "nth" block
533 * stats are printed, with "n" controled by global RC_MB_SAMPLE_RATE
534 * (NB. "skipped" blocks do not go through this function and thus do not
535 * show up in the sample )
536 *
537 * RETURNS: nothing
538 *
539 * SIDE EFFECTS: none
540 *
541 * NOTES:
542 *
543 *===========================================================================*/
544 void
545 MB_RateOut(type)
546 int type;
547 {
548 int totalBits;
549 int pctUsed, pctDone;
550 int bitsThisMB;
551 int bitsPerMB;
552
553 bitsThisMB = rc_bitsThisMB;
554 totalBits = rc_totalFrameBits;
555 bitsPerMB = (totalBits / rc_numBlocks);
556 pctDone = (rc_numBlocks * 100/ MB_cnt);
557 pctUsed = (totalBits *100/current_Tx);
558
559 sprintf(rc_buffer, "%3d %5d %2d %3d %6d %3d %6d %2.2f %6d %4d %3d %3d\n",
560 (rc_numBlocks - 1), bitsThisMB, Qscale, mquant, currentVirtBuf,
561 rc_Q, act_j, N_act, totalBits, bitsPerMB, pctUsed, pctDone);
562 #ifdef RC_STATS_FILE
563 fprintf(RC_FILE, "%s", rc_buffer);
564 fflush(RC_FILE);
565 #endif
566
567 if ( (RC_MB_SAMPLE_RATE) && ((rc_numBlocks -1) % RC_MB_SAMPLE_RATE)) {
568 DBG_PRINT(("%s\n", rc_buffer));
569 } else {
570 return;
571 }
572 }
573
574
575
576 /*===========================================================================*
577 *
578 * incNumBlocks()
579 *
580 *
581 * RETURNS: nothing
582 *
583 * SIDE EFFECTS: rc_numBlocks
584 *
585 * NOTES:
586 *
587 *===========================================================================*/
588 void incNumBlocks(num)
589 int num;
590 {
591 rc_numBlocks += num;
592 }
593
594
595 /*===========================================================================*
596 *
597 * incMacroBlockBits()
598 *
599 * Increments the number of Macro Block bits and the total of Frame
600 * bits by the number passed.
601 *
602 * RETURNS: nothing
603 *
604 * SIDE EFFECTS: rc_totalMBBits
605 *
606 * NOTES:
607 *
608 *===========================================================================*/
609 void incMacroBlockBits(num)
610 int num;
611 {
612 rc_bitsThisMB = num;
613 rc_totalMBBits += num;
614 rc_totalFrameBits += num;
615 }
616
617
618 /*===========================================================================*
619 *
620 * needQScaleChange(current Q scale, 4 luminance blocks)
621 *
622 *
623 * RETURNS: new Qscale
624 *
625 * SIDE EFFECTS:
626 *
627 *===========================================================================*/
628 int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3)
629 int oldQScale;
630 Block blk0;
631 Block blk1;
632 Block blk2;
633 Block blk3;
634 {
635
636 /* One more MacroBlock seen */
637 rc_numBlocks++; /* this notes each block num in MB */
638
639 checkBufferFullness(oldQScale);
640
641 checkSpatialActivity(blk0, blk1, blk2, blk3);
642
643 mquant = rc_Q * N_act;
644 Qscale = (mquant > 31 ? 31 : mquant);
645 Qscale = (Qscale < 1 ? 1 : Qscale);
646 rc_totalQuant += Qscale;
647
648 if (oldQScale == Qscale)
649 return -1;
650 else
651 return Qscale;
652 }
653
654
655 /*===========================================================================*
656 *
657 * determineMBCount()
658 *
659 * Determines number of Macro Blocks in frame from the frame sizes
660 * passed.
661 *
662 * RETURNS: nothing
663 *
664 * SIDE EFFECTS: sets the count passed
665 *
666 *===========================================================================*/
667 int
668 determineMBCount ()
669 {
670 int y,x;
671
672 x = (Fsize_x +15)/16;
673 y = (Fsize_y +15)/16;
674 return (x * y);
675 }
676
677
678
679 /*===========================================================================*
680 *
681 * void checkBufferFullness ()
682 *
683 * Calculates the fullness of the virtual buffer for each
684 * frame type. Called before encoding each macro block. Along
685 * with the normalisec spatial activity measure (N_act), it
686 * determine the quantization factor for the next macroblock.
687 *
688 * RETURNS: nothing
689 *
690 * SIDE EFFECTS: the "currentVirtBuf" variable
691 *
692 * NOTES:
693 *
694 *===========================================================================*/
695 void checkBufferFullness (oldQScale)
696 int oldQScale;
697 {
698 int temp;
699
700 temp = lastFrameVirtBuf + rc_totalFrameBits;
701 temp -= (current_Tx * rc_numBlocks / MB_cnt);
702 currentVirtBuf = temp;
703
704 rc_Q = (currentVirtBuf * 31 / reactionParameter);
705 return;
706 }
707
708
709 /*===========================================================================*
710 *
711 * void checkSpatialActivity()
712 *
713 * Calcualtes the spatial activity for the four luminance blocks of the
714 * macroblock. Along with the normalised reference quantization parameter
715 * (rc_Q) , it determines the quantization factor for the next macroblock.
716 *
717 * RETURNS: nothing
718 *
719 * SIDE EFFECTS: the Adaptive quantization variables- act_j, N_act.
720 *
721 * NOTES:
722 *
723 *===========================================================================*/
724 void checkSpatialActivity(blk0, blk1, blk2, blk3)
725 Block blk0;
726 Block blk1;
727 Block blk2;
728 Block blk3;
729 {
730 int temp;
731 int16 *blkArray[4];
732 int16 *curBlock;
733 int16 *blk_ptr;
734 int var[4];
735 int i, j;
736
737
738 blkArray[0] = (int16 *) blk0;
739 blkArray[1] = (int16 *) blk1;
740 blkArray[2] = (int16 *) blk2;
741 blkArray[3] = (int16 *) blk3;
742
743
744 for (i =0; i < 4; i++) { /* Compute the activity in each block */
745 curBlock = blkArray[i];
746 blk_ptr = curBlock;
747 P_mean = 0;
748 /* Find the mean pixel value */
749 for (j=0; j < DCTSIZE_SQ; j ++) {
750 P_mean += *(blk_ptr++);
751 /* P_mean += curBlock[j];
752 if (curBlock[j] != *(blk_ptr++)) {
753 printf("\n\tARRAY ERROR: block %d\n", j);
754 }
755 */
756 }
757 P_mean /= DCTSIZE_SQ;
758
759 /* Now find the variance */
760 curBlock = blkArray[i];
761 blk_ptr = curBlock;
762 var[i] = 0;
763 for (j=0; j < DCTSIZE_SQ; j++) {
764 #ifdef notdef
765 if (curBlock[j] != *(blk_ptr++)) {
766 printf("\n\tARRAY ERROR: block %d\n", j);
767 }
768 temp = curBlock[j] - P_mean;
769 #endif
770 temp = *(blk_ptr++) - P_mean;
771 var[i] += (temp * temp);
772 }
773 var[i] /= DCTSIZE_SQ;
774 }
775
776 /* Choose the minimum variance from the 4 blocks and use as the activity */
777 var_sblk = var[0];
778 for (i=1; i < 4; i++) {
779 var_sblk = (var_sblk < var[i] ? var_sblk : var[i]);
780 }
781
782
783 act_j = 1 + var_sblk;
784 total_act_j += act_j;
785 temp = (2 * act_j + avg_act);
786 N_act = ( (float) temp / (float) (act_j + 2*avg_act) );
787
788 return;
789 }
790
791
792
793
794 /*============================================================================*
795 *
796 * getRateMode ()
797 *
798 * Returns the rate mode- interpreted as either Fixed or Variable
799 *
800 * RETURNS: integer
801 *
802 * SIDE EFFECTS: none
803 *
804 *
805 *==========================================================================*/
806 int getRateMode()
807 {
808 return RateControlMode;
809 }
810
811
812 /*===========================================================================*
813 *
814 * setBitRate ()
815 *
816 * Checks the string parsed from the parameter file. Verifies
817 * number and sets global values. MPEG standard specifies that bit rate
818 * be rounded up to nearest 400 bits/sec.
819 *
820 * RETURNS: nothing
821 *
822 * SIDE EFFECTS: global variables
823 *
824 * NOTES: Should this be in the 400-bit units used in sequence header?
825 *
826 *===========================================================================*/
827 void setBitRate (charPtr)
828 char * charPtr;
829 {
830 int rate, rnd;
831
832 rate = atoi(charPtr);
833 if (rate > 0) {
834 RateControlMode = FIXED_RATE;
835 } else {
836 printf("Parameter File Error: invalid BIT_RATE: \"%s\", defaults to Variable ratemode\n",
837 charPtr);
838 RateControlMode = VARIABLE_RATE;
839 bit_rate = -1;
840 }
841 rnd = (rate % 400);
842 rate += (rnd ? 400 -rnd : 0); /* round UP to nearest 400 bps */
843 rate = (rate > MAX_BIT_RATE ? MAX_BIT_RATE : rate);
844 bit_rate = rate;
845 DBG_PRINT(("Bit rate is: %d\n", bit_rate));
846 }
847
848
849
850 /*===========================================================================*
851 *
852 * getBitRate ()
853 *
854 * Returns the bit rate read from the parameter file. This is the
855 * real rate in bits per second, not in 400 bit units as is written to
856 * the sequence header.
857 *
858 * RETURNS: int (-1 if Variable mode operation)
859 *
860 * SIDE EFFECTS: none
861 *
862 *===========================================================================*/
863 int getBitRate ()
864 {
865 return bit_rate;
866 }
867
868
869
870
871 /*===========================================================================*
872 *
873 * setBufferSize ()
874 *
875 * Checks the string parsed from the parameter file. Verifies
876 * number and sets global values.
877 *
878 * RETURNS: nothing
879 *
880 * SIDE EFFECTS: buffer_size global variable.
881 *
882 * NOTES: The global is in bits, NOT the 16kb units used in sequence header
883 *
884 *===========================================================================*/
885 void setBufferSize (charPtr)
886 char * charPtr;
887 {
888 int size;
889
890 size = atoi(charPtr);
891 size = (size > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : size);
892 if (size > 0) {
893 size = (16*1024) * ((size + (16*1024 - 1)) / (16*1024));
894 buffer_size = size;
895 } else {
896 buffer_size = DEFAULT_BUFFER_SIZE;
897 printf("Parameter File Error: invalid BUFFER_SIZE: \"%s\", defaults to : %d\n",
898 charPtr, buffer_size);
899 }
900 DBG_PRINT(("Buffer size is: %d\n", buffer_size));
901 }
902
903
904 /*===========================================================================*
905 *
906 * getBufferSize ()
907 *
908 * returns the buffer size read from the parameter file. Size is
909 * in bits- not in units of 16k as written to the sequence header.
910 *
911 * RETURNS: int (or -1 if invalid)
912 *
913 * SIDE EFFECTS: none
914 *
915 *===========================================================================*/
916 int getBufferSize ()
917 {
918 return buffer_size;
919 }
920
921
922 /*===========================================================================*
923 *
924 * updateVBVBuffer ()
925 *
926 * Update the VBV buffer after each frame. This theoretical
927 * buffer is being filled at constant rate, given by the bit rate.
928 * It is emptied as each frame is grabbed by the decoder. Exception
929 * is that the deocder will wait until the "delay" is over.
930 *
931 * RETURNS: nothing
932 *
933 * SIDE EFFECTS: VBV_buffer
934 *
935 * NOTES:
936 *
937 *===========================================================================*/
938 void updateVBVBuffer (frameBits)
939 int frameBits;
940 {
941 if (VBV_delay) {
942 VBV_delay -= frameDelayIncrement;
943 if (VBV_delay < 0) {
944 VBV_delay = 0;
945 }
946
947 } else {
948 VBV_buffer -= frameBits;
949 }
950 VBV_buffer += bufferFillRate;
951 if (VBV_buffer < 0) {
952 fprintf(stderr, "\tWARNING - VBV buffer underflow (%d)\n", VBV_buffer);
953 }
954 if (VBV_buffer > buffer_size) {
955 fprintf(stderr, "WARNING - VBV buffer overflow (%d > %d)\n",
956 VBV_buffer, buffer_size);
957 }
958 }