irc_rate_control_api.c revision 8d3d303c7942ced6a987a52db8977d768dc3605f
1/******************************************************************************
2 *
3 * Copyright (C) 2015 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 *****************************************************************************
18 * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
19*/
20
21/*****************************************************************************/
22/* Includes */
23/*****************************************************************************/
24
25/* System include files */
26#include "stdio.h"
27
28/* User include files */
29#include "irc_datatypes.h"
30#include "irc_common.h"
31#include "irc_cntrl_param.h"
32#include "irc_mem_req_and_acq.h"
33#include "irc_rd_model.h"
34#include "irc_est_sad.h"
35#include "irc_fixed_point_error_bits.h"
36#include "irc_vbr_storage_vbv.h"
37#include "irc_picture_type.h"
38#include "irc_bit_allocation.h"
39#include "irc_mb_model_based.h"
40#include "irc_cbr_buffer_control.h"
41#include "irc_vbr_str_prms.h"
42#include "irc_rate_control_api.h"
43#include "irc_rate_control_api_structs.h"
44#include "irc_trace_support.h"
45
46#define DEV_Q   4       /*Q format(Shift) for Deviation range factor */
47#define HI_DEV_FCTR     22  /* 1.4*16 */
48#define LO_DEV_FCTR     12  /* 0.75*16 */
49#define GET_HI_DEV_QP(Qprev) (( ((WORD32) Qprev)*HI_DEV_FCTR + (1<<(DEV_Q-1)))>>DEV_Q)
50#define GET_LO_DEV_QP(Qprev) (( ((WORD32) Qprev)*LO_DEV_FCTR + (1<<(DEV_Q-1)))>>DEV_Q)
51#define CLIP_QP(Qc, hi_d, lo_d) (((Qc) < (lo_d))?((lo_d)):(((Qc) > (hi_d))?(hi_d):(Qc)))
52
53/*****************************************************************************/
54/* Restricts the quantization parameter variation within delta */
55/*****************************************************************************/
56/* static WORD32 restrict_swing(WORD32 cur_qp, WORD32 prev_qp, WORD32 delta_qp)
57 {
58 if((cur_qp) - (prev_qp) > (delta_qp)) (cur_qp) = (prev_qp) + (delta_qp) ;
59 if((prev_qp) - (cur_qp) > (delta_qp)) (cur_qp) = (prev_qp) - (delta_qp) ;
60 return cur_qp;
61 }*/
62
63/*****************************************************************************
64 Function Name : rate_control_get_init_free_memtab
65 Description   : Takes or gives memtab
66 Inputs        : pps_rate_control_api -  pointer to RC api pointer
67 ps_memtab            -  Memtab pointer
68 i4_use_base          -  Set during init, else 0
69 i4_fill_base         -  Set during free, else 0
70 *****************************************************************************/
71WORD32 irc_rate_control_num_fill_use_free_memtab(rate_control_handle *pps_rate_control_api,
72                                                 itt_memtab_t *ps_memtab,
73                                                 ITT_FUNC_TYPE_E e_func_type)
74{
75    WORD32 i4_mem_tab_idx = 0, i;
76    static rate_control_api_t s_temp_rc_api;
77
78    /*
79     * Hack for al alloc, during which we dont have any state memory.
80     * Dereferencing can cause issues
81     */
82    if(e_func_type == GET_NUM_MEMTAB || e_func_type == FILL_MEMTAB)
83        (*pps_rate_control_api) = &s_temp_rc_api;
84
85    /*for src rate control state structure*/
86    if(e_func_type != GET_NUM_MEMTAB)
87    {
88        fill_memtab(&ps_memtab[i4_mem_tab_idx], sizeof(rate_control_api_t),
89                    ALIGN_128_BYTE, PERSISTENT, DDR);
90        use_or_fill_base(&ps_memtab[0], (void**)pps_rate_control_api,
91                         e_func_type);
92    }
93    i4_mem_tab_idx++;
94
95    /* Get the memory requirement of lower modules */
96    i4_mem_tab_idx += irc_ba_num_fill_use_free_memtab(
97                    &pps_rate_control_api[0]->ps_bit_allocation,
98                    &ps_memtab[i4_mem_tab_idx], e_func_type);
99
100    i4_mem_tab_idx += irc_cbr_buffer_num_fill_use_free_memtab(
101                    &pps_rate_control_api[0]->ps_cbr_buffer,
102                    &ps_memtab[i4_mem_tab_idx], e_func_type);
103
104    i4_mem_tab_idx += irc_est_sad_num_fill_use_free_memtab(
105                    &pps_rate_control_api[0]->ps_est_sad,
106                    &ps_memtab[i4_mem_tab_idx], e_func_type);
107
108    i4_mem_tab_idx += irc_mbrc_num_fill_use_free_memtab(
109                    &pps_rate_control_api[0]->ps_mb_rate_control,
110                    &ps_memtab[i4_mem_tab_idx], e_func_type);
111
112    i4_mem_tab_idx += irc_vbr_vbv_num_fill_use_free_memtab(
113                    &pps_rate_control_api[0]->ps_vbr_storage_vbv,
114                    &ps_memtab[i4_mem_tab_idx], e_func_type);
115
116    for(i = 0; i < MAX_PIC_TYPE; i++)
117    {
118        i4_mem_tab_idx += irc_rd_model_num_fill_use_free_memtab(
119                        &pps_rate_control_api[0]->aps_rd_model[i],
120                        &ps_memtab[i4_mem_tab_idx], e_func_type);
121    }
122    i4_mem_tab_idx += irc_pic_handling_num_fill_use_free_memtab(
123                    &pps_rate_control_api[0]->ps_pic_handling,
124                    &ps_memtab[i4_mem_tab_idx], e_func_type);
125
126    return (i4_mem_tab_idx);
127}
128
129/*****************************************************************************
130 Function Name : irc_initialise_rate_control
131 Description   : Initialise the rate control structure
132 Inputs        : ps_rate_control_api   - api struct
133                 e_rate_control_type   - VBR, CBR (NLDRC/LDRC), VBR_STREAMING
134                 u1_is_mb_level_rc_on  - enabling mb level RC
135                 u4_avg_bit_rate       - bit rate to achieved across the entire
136                                         file size
137                 u4_peak_bit_rate      - max possible drain rate
138                 u4_frame_rate         - number of frames in 1000 seconds
139                 u4_intra_frame_interval - num frames between two I frames
140                 *au1_init_qp          - init_qp for I,P,B
141 *****************************************************************************/
142void irc_initialise_rate_control(rate_control_api_t *ps_rate_control_api,
143                                 rc_type_e e_rate_control_type,
144                                 UWORD8 u1_is_mb_level_rc_on,
145                                 UWORD32 u4_avg_bit_rate,
146                                 UWORD32 *pu4_peak_bit_rate,
147                                 UWORD32 u4_min_bit_rate,
148                                 UWORD32 u4_frame_rate,
149                                 UWORD32 u4_max_delay,
150                                 UWORD32 u4_intra_frame_interval,
151                                 UWORD8 *pu1_init_qp,
152                                 UWORD32 u4_max_vbv_buff_size,
153                                 WORD32 i4_max_inter_frm_int,
154                                 WORD32 i4_is_gop_closed,
155                                 UWORD8 *pu1_min_max_qp,
156                                 WORD32 i4_use_est_intra_sad,
157                                 UWORD32 u4_src_ticks,
158                                 UWORD32 u4_tgt_ticks)
159{
160    WORD32 i;
161    UWORD32 u4_frms_in_delay_prd = (u4_frame_rate * u4_max_delay) / 1000000;
162    ps_rate_control_api->e_rc_type = e_rate_control_type;
163    ps_rate_control_api->u1_is_mb_level_rc_on = u1_is_mb_level_rc_on;
164
165    trace_printf((const WORD8*)"RC type = %d\n", e_rate_control_type);
166
167    /* Set the avg_bitrate_changed flag for each pic_type to 0 */
168    for(i = 0; i < MAX_PIC_TYPE; i++)
169    {
170        ps_rate_control_api->au1_avg_bitrate_changed[i] = 0;
171    }
172
173    /* Initialize the pic_handling module */
174    irc_init_pic_handling(ps_rate_control_api->ps_pic_handling,
175                          (WORD32)u4_intra_frame_interval, i4_max_inter_frm_int,
176                          i4_is_gop_closed);
177
178    /*** Initialize the rate control modules  ***/
179    if(ps_rate_control_api->e_rc_type != CONST_QP)
180    {
181        UWORD32 au4_num_pics_in_delay_prd[MAX_PIC_TYPE];
182
183        /* Initialize the model parameter structures */
184        for(i = 0; i < MAX_PIC_TYPE; i++)
185        {
186            irc_init_frm_rc_rd_model(ps_rate_control_api->aps_rd_model[i],
187                                     MAX_FRAMES_MODELLED);
188        }
189
190        /* Initialize the buffer mechanism */
191        if((ps_rate_control_api->e_rc_type == VBR_STORAGE)
192                        || (ps_rate_control_api->e_rc_type
193                                        == VBR_STORAGE_DVD_COMP))
194        {
195            /* Assuming both the peak bit rates are same for a VBR_STORAGE and
196             VBR_STORAGE_DVD_COMP */
197            if(pu4_peak_bit_rate[0] != pu4_peak_bit_rate[1])
198            {
199                trace_printf((const WORD8*)"For VBR_STORAGE and VBR_STORAGE_DVD_COMP the peak bit rates should be same\n");
200            }
201            irc_init_vbr_vbv(ps_rate_control_api->ps_vbr_storage_vbv,
202                             (WORD32)pu4_peak_bit_rate[0],
203                             (WORD32)u4_frame_rate,
204                             (WORD32)u4_max_vbv_buff_size);
205        }
206        else if(ps_rate_control_api->e_rc_type == CBR_NLDRC)
207        {
208            UWORD32 u4_avg_bit_rate_copy[MAX_NUM_DRAIN_RATES];
209            for(i = 0; i < MAX_NUM_DRAIN_RATES; i++)
210            {
211                u4_avg_bit_rate_copy[i] = u4_avg_bit_rate;
212            }
213            /* In case of CBR the num pics in delay is ignored */
214            for(i = 0; i < MAX_PIC_TYPE; i++)
215                au4_num_pics_in_delay_prd[i] = 0;
216
217            irc_init_cbr_buffer(ps_rate_control_api->ps_cbr_buffer,
218                                u4_max_delay, u4_frame_rate,
219                                (WORD32 *)u4_avg_bit_rate_copy,
220                                au4_num_pics_in_delay_prd,
221                                u4_max_vbv_buff_size);
222        }
223        else if(ps_rate_control_api->e_rc_type == VBR_STREAMING)
224        {
225            irc_init_vbv_str_prms(&ps_rate_control_api->s_vbr_str_prms,
226                                  u4_intra_frame_interval, u4_src_ticks,
227                                  u4_tgt_ticks, u4_frms_in_delay_prd);
228
229            /* Get the number of pics of each type in delay period */
230            irc_get_vsp_num_pics_in_dly_prd(
231                            &ps_rate_control_api->s_vbr_str_prms,
232                            au4_num_pics_in_delay_prd);
233
234            irc_init_cbr_buffer(ps_rate_control_api->ps_cbr_buffer,
235                                u4_max_delay, u4_frame_rate,
236                                (WORD32 *)pu4_peak_bit_rate,
237                                au4_num_pics_in_delay_prd,
238                                u4_max_vbv_buff_size);
239        }
240
241        /* Initialize the SAD estimation module */
242        irc_init_est_sad(ps_rate_control_api->ps_est_sad, i4_use_est_intra_sad);
243
244        /* Initialize the bit allocation module according to VBR or CBR */
245        if((ps_rate_control_api->e_rc_type == VBR_STORAGE)
246                        || (ps_rate_control_api->e_rc_type == VBR_STREAMING)
247                        || (ps_rate_control_api->e_rc_type
248                                        == VBR_STORAGE_DVD_COMP))
249        {
250            irc_ba_init_bit_allocation(ps_rate_control_api->ps_bit_allocation,
251                                       ps_rate_control_api->ps_pic_handling,
252                                       VBR_BIT_ALLOC_PERIOD, u4_avg_bit_rate,
253                                       u4_frame_rate,
254                                       (WORD32 *)pu4_peak_bit_rate,
255                                       u4_min_bit_rate);
256        }
257        else if(ps_rate_control_api->e_rc_type == CBR_NLDRC)
258        {
259            irc_ba_init_bit_allocation(ps_rate_control_api->ps_bit_allocation,
260                                       ps_rate_control_api->ps_pic_handling,
261                                       CBR_BIT_ALLOC_PERIOD, u4_avg_bit_rate,
262                                       u4_frame_rate,
263                                       (WORD32 *)pu4_peak_bit_rate,
264                                       u4_min_bit_rate);
265        }
266
267        /*
268         * u1_scd_detected will be initialized to 1 when a Scene change is
269         * detected
270         */
271        ps_rate_control_api->u1_scd_detected = 0;
272    }
273
274    /* Initialize the init_qp */
275    for(i = 0; i < MAX_PIC_TYPE; i++)
276    {
277        ps_rate_control_api->au1_init_qp[i] = pu1_init_qp[i];
278        ps_rate_control_api->au1_prev_frm_qp[i] = pu1_init_qp[i];
279        ps_rate_control_api->au1_min_max_qp[(i << 1)] =
280                        pu1_min_max_qp[(i << 1)];
281        ps_rate_control_api->au1_min_max_qp[(i << 1) + 1] = pu1_min_max_qp[(i
282                        << 1) + 1];
283    }
284
285    /* Initialize the is_first_frm_encoded */
286    for(i = 0; i < MAX_PIC_TYPE; i++)
287    {
288        ps_rate_control_api->au1_is_first_frm_coded[i] = 0;
289    }
290    ps_rate_control_api->u1_is_first_frm = 1;
291
292    /*
293     * Control flag for delayed impact after a change in peak bitrate has been
294     * made
295     */
296    ps_rate_control_api->u4_frms_in_delay_prd_for_peak_bit_rate_change = 0;
297    for(i = 0; i < MAX_NUM_DRAIN_RATES; i++)
298    {
299        ps_rate_control_api->au4_new_peak_bit_rate[i] = pu4_peak_bit_rate[i];
300    }
301
302    /* Initialize the mb level rate control module */
303    irc_init_mb_level_rc(ps_rate_control_api->ps_mb_rate_control);
304    ps_rate_control_api->i4_prev_frm_est_bits = u4_avg_bit_rate * 1000
305                    / u4_frame_rate;
306
307    ps_rate_control_api->prev_ref_pic_type = I_PIC;
308}
309
310/******************************************************************************
311 *Description   : calls irc_add_pic_to_stack
312 ******************************************************************************/
313void irc_add_picture_to_stack(rate_control_api_t *rate_control_api,
314                              WORD32 i4_enc_pic_id)
315{
316    /* Call the routine to add the pic to stack in encode order */
317    irc_add_pic_to_stack(rate_control_api->ps_pic_handling, i4_enc_pic_id);
318}
319
320void irc_add_picture_to_stack_re_enc(rate_control_api_t *rate_control_api,
321                                     WORD32 i4_enc_pic_id,
322                                     picture_type_e e_pic_type)
323{
324    /*
325     * In case of a re-encoder, the pics will come in the encode order itself.
326     * So, there is no need to buffer the pics up
327     */
328    irc_add_pic_to_stack_re_enc(rate_control_api->ps_pic_handling,
329                                i4_enc_pic_id, e_pic_type);
330}
331
332/*******************************************************************************
333 Description   : Decides the picture type based on the state
334 ******************************************************************************/
335void irc_get_picture_details(rate_control_handle rate_control_api,
336                             WORD32 *pi4_pic_id,
337                             WORD32 *pi4_pic_disp_order_no,
338                             picture_type_e *pe_pic_type)
339{
340    /* Call to get the pic_details */
341    irc_get_pic_from_stack(rate_control_api->ps_pic_handling, pi4_pic_id,
342                           pi4_pic_disp_order_no, pe_pic_type);
343}
344
345/*******************************************************************************
346 *  Description   : Gets the frame level qp for the given picture type
347 ******************************************************************************/
348UWORD8 irc_get_frame_level_qp(rate_control_api_t *ps_rate_control_api,
349                              picture_type_e e_pic_type,
350                              WORD32 i4_ud_max_bits)
351{
352    UWORD8 u1_frame_qp, i;
353
354    if((ps_rate_control_api->e_rc_type != VBR_STORAGE)
355                    && (ps_rate_control_api->e_rc_type != VBR_STORAGE_DVD_COMP)
356                    && (ps_rate_control_api->e_rc_type != CBR_NLDRC)
357                    && (ps_rate_control_api->e_rc_type != CONST_QP)
358                    && (ps_rate_control_api->e_rc_type != VBR_STREAMING))
359    {
360        trace_printf((const WORD8*)(const WORD8*)" Only VBR,NLDRC and CONST QP supported for now \n");
361        return (0);
362    }
363
364    if(ps_rate_control_api->e_rc_type != CONST_QP)
365    {
366        UWORD8 u1_is_first_frm_coded = 1;
367
368        /* Check whether at least one frame of a each picture type gets encoded*/
369        /* Check whether it is an IPP or IPB kind of encoding */
370        if((ps_rate_control_api->au1_is_first_frm_coded[I_PIC]
371                        && ps_rate_control_api->au1_is_first_frm_coded[P_PIC])
372                        || ((irc_pic_type_get_intra_frame_interval(
373                                        ps_rate_control_api->ps_pic_handling)
374                                        == 1)
375                                        && (ps_rate_control_api->au1_is_first_frm_coded[I_PIC])))
376        {
377            if(e_pic_type != B_PIC)
378                u1_is_first_frm_coded = 1;
379            else
380            {
381                for(i = 0; i < MAX_PIC_TYPE; i++)
382                {
383                    u1_is_first_frm_coded &=
384                                    ps_rate_control_api->au1_is_first_frm_coded[i];
385                }
386            }
387        }
388        else
389        {
390            u1_is_first_frm_coded = 0;
391        }
392
393        if(u1_is_first_frm_coded)
394        {
395            WORD32 i4_cur_est_texture_bits, i4_cur_est_header_bits;
396            WORD32 i4_cur_est_bits;
397            UWORD32 u4_estimated_sad;
398
399            /* Force I frame updation of rem_bits_in_frame*/
400            if(irc_get_forced_I_frame_cur_frm_flag(
401                            ps_rate_control_api->ps_pic_handling) == 1)
402            {
403                irc_ba_change_rem_bits_in_prd_at_force_I_frame(
404                                ps_rate_control_api->ps_bit_allocation,
405                                ps_rate_control_api->ps_pic_handling);
406                irc_reset_forced_I_frame_cur_frm_flag(
407                                ps_rate_control_api->ps_pic_handling);
408            }
409
410            /* Get the estimated texture bits allocated for the current frame*/
411            i4_cur_est_texture_bits = irc_ba_get_cur_frm_est_texture_bits(
412                            ps_rate_control_api->ps_bit_allocation,
413                            ps_rate_control_api->aps_rd_model,
414                            ps_rate_control_api->ps_est_sad,
415                            ps_rate_control_api->ps_pic_handling, e_pic_type);
416
417            /* Get the estimated header bits*/
418            i4_cur_est_header_bits = irc_ba_get_cur_frm_est_header_bits(
419                            ps_rate_control_api->ps_bit_allocation, e_pic_type);
420
421            /* Total estimated bits */
422            i4_cur_est_bits = i4_cur_est_header_bits + i4_cur_est_texture_bits;
423
424            trace_printf((const WORD8*)"ft %d, etb = %d, eb %d, ", e_pic_type,
425                         i4_cur_est_texture_bits, i4_cur_est_bits);
426
427            /* Threshold the estimated bits based on the buffer fullness*/
428            if(ps_rate_control_api->e_rc_type == VBR_STORAGE)
429            {
430                WORD32 i4_cur_frm_max_bit_possible;
431                i4_cur_frm_max_bit_possible = irc_get_max_target_bits(
432                                ps_rate_control_api->ps_vbr_storage_vbv);
433
434                if(i4_cur_est_bits > i4_cur_frm_max_bit_possible)
435                {
436                    /* Assuming header would consume the same amount of bits */
437                    i4_cur_est_texture_bits = i4_cur_frm_max_bit_possible
438                                    - i4_cur_est_header_bits;
439                }
440            }
441            else if(ps_rate_control_api->e_rc_type == VBR_STORAGE_DVD_COMP)
442            {
443                WORD32 i4_rem_bits_in_gop, i4_rem_frms_in_gop, i;
444                WORD32 i4_cur_frm_max_bit_possible,
445                                ai4_rem_frms_in_gop[MAX_PIC_TYPE];
446                irc_pic_type_get_rem_frms_in_gop(
447                                ps_rate_control_api->ps_pic_handling,
448                                ai4_rem_frms_in_gop);
449                i4_rem_bits_in_gop = irc_get_rem_bits_in_period(
450                                ps_rate_control_api);
451                i4_rem_frms_in_gop = 0;
452                for(i = 0; i < MAX_PIC_TYPE; i++)
453                    i4_rem_frms_in_gop += ai4_rem_frms_in_gop[i];
454
455                /* Threshold the bits based on estimated buffer fullness */
456                i4_cur_frm_max_bit_possible = irc_get_max_tgt_bits_dvd_comp(
457                                ps_rate_control_api->ps_vbr_storage_vbv,
458                                i4_rem_bits_in_gop, i4_rem_frms_in_gop,
459                                e_pic_type);
460
461                if(i4_cur_est_bits > i4_cur_frm_max_bit_possible)
462                {
463                    /* Assuming header would consume the same amount of bits */
464                    i4_cur_est_texture_bits = i4_cur_frm_max_bit_possible
465                                    - i4_cur_est_header_bits;
466
467                }
468            }
469            else if(ps_rate_control_api->e_rc_type == CBR_NLDRC)
470            {
471                WORD32 i4_cur_frm_bits_acc_buffer =
472                                irc_cbr_buffer_constraint_check(
473                                                ps_rate_control_api->ps_cbr_buffer,
474                                                i4_cur_est_bits, e_pic_type);
475
476                /* Assuming the header would consume the same amount of bits */
477                i4_cur_est_texture_bits = i4_cur_frm_bits_acc_buffer
478                                - i4_cur_est_header_bits;
479
480            }
481            else if(ps_rate_control_api->e_rc_type == VBR_STREAMING)
482            {
483                WORD32 i4_cur_frm_bits_acc_buffer =
484                                irc_vbr_stream_buffer_constraint_check(
485                                                ps_rate_control_api->ps_cbr_buffer,
486                                                i4_cur_est_bits, e_pic_type);
487
488                /* Assuming the header would consume the same amount of bits */
489                i4_cur_est_texture_bits = i4_cur_frm_bits_acc_buffer
490                                - i4_cur_est_header_bits;
491            }
492
493            trace_printf((const WORD8*)"emtb = %d, ", i4_cur_est_texture_bits);
494
495            /*
496             * If the estimated texture bits go to values less than zero
497             * due to buffer underflow, make the estimated target bits to go
498             * to zero
499             */
500            if(i4_cur_est_texture_bits < 0)
501                i4_cur_est_texture_bits = 0;
502
503            ps_rate_control_api->i4_prev_frm_est_bits = (i4_cur_est_texture_bits
504                            + i4_cur_est_header_bits);
505
506            /* Clip est_texture_bits according to the user-defined max value */
507            if((i4_cur_est_texture_bits
508                            > (i4_ud_max_bits - i4_cur_est_header_bits))
509                            && (e_pic_type != I_PIC))
510            {
511                i4_cur_est_texture_bits = (i4_ud_max_bits
512                                - i4_cur_est_header_bits);
513                trace_printf((const WORD8*)"udcb = %d, ",
514                             i4_ud_max_bits - i4_cur_est_header_bits);
515            }
516
517            /* Calculate the estimated SAD for corresponding frame*/
518            u4_estimated_sad = irc_get_est_sad(ps_rate_control_api->ps_est_sad,
519                                               e_pic_type);
520
521            /* Query the model for the Qp for the corresponding frame*/
522
523            /*
524             * The check is because the model gives a negative QP when the
525             * i4_cur_est_texture_bits is less than or equal to 0
526             * [This is a bug in the model]. As a temporary fix, the frame QP
527             * is being set to the max QP allowed
528             */
529            if(i4_cur_est_texture_bits > 0)
530            {
531                u1_frame_qp = irc_find_qp_for_target_bits(
532                                ps_rate_control_api->aps_rd_model[e_pic_type],
533                                i4_cur_est_texture_bits,
534                                u4_estimated_sad,
535                                ps_rate_control_api->au1_min_max_qp[(e_pic_type
536                                                << 1)],
537                                ps_rate_control_api->au1_min_max_qp[(e_pic_type
538                                                << 1) + 1]);
539            }
540            else
541            {
542                u1_frame_qp = ps_rate_control_api->au1_min_max_qp[(e_pic_type
543                                << 1) + 1];
544            }
545
546            trace_printf((const WORD8*)"ehb %d, etb %d, fqp %d, es %d, eb %d, ",
547                         i4_cur_est_header_bits, i4_cur_est_texture_bits,
548                         u1_frame_qp, u4_estimated_sad, i4_cur_est_bits);
549
550            /* Restricting the QP swing if the average bit rate has changed */
551            if(ps_rate_control_api->au1_avg_bitrate_changed[e_pic_type] == 0)
552            {
553                WORD32 prev_qp;
554                WORD32 hi_dev_qp, lo_dev_qp;
555                /* Restricting the qp swing */
556                prev_qp = ps_rate_control_api->au1_prev_frm_qp[ps_rate_control_api->prev_ref_pic_type];
557
558                if(ps_rate_control_api->prev_ref_pic_type != e_pic_type)
559                {
560                    if(e_pic_type == I_PIC)
561                    {
562                        /*
563                         * Constrain I-frame QP to be within specified limit of
564                         * prev_ref_qp/Kp
565                         */
566                        prev_qp = (P_TO_I_RATIO * prev_qp + (1 << (K_Q - 1)))
567                                        >> (K_Q);
568                    }
569                    else if(e_pic_type == P_PIC)
570                    {
571                        /*
572                         * Constrain P-frame QP to be within specified limit of
573                         * Kp*prev_ref_qp
574                         */
575                        prev_qp = (I_TO_P_RATIO * prev_qp + (1 << (K_Q - 1)))
576                                        >> (K_Q);
577                    }
578                    else if(ps_rate_control_api->prev_ref_pic_type == P_PIC)
579                    {
580                        /* current frame is B-pic */
581                        /* Constrain B-frame QP to be within specified limit of
582                         * prev_ref_qp/Kb
583                         */
584                        prev_qp = (P_TO_B_RATIO * prev_qp + (1 << (K_Q - 1)))
585                                        >> (K_Q);
586                    }
587                    else /* if(ps_rate_control_api->prev_ref_pic_type == I_PIC*/
588                    {
589                        /* current frame is B-pic */
590                        /*
591                         * Constrain B-frame QP to be within specified limit of
592                         * prev_ref_qp/Kb
593                         */
594                        prev_qp = (P_TO_B_RATIO * I_TO_P_RATIO * prev_qp
595                                        + (1 << (K_Q + K_Q - 1)))
596                                        >> (K_Q + K_Q);
597                    }
598                }
599
600                hi_dev_qp = GET_HI_DEV_QP(prev_qp);
601                /*
602                 * For lower QPs due to scale factor and fixed point arithmetic,
603                 * the hi_dev_qp can be same as that of the prev qp and in which
604                 * case it gets stuck in the lower most qp and thus not allowing
605                 * QPs not to change. To avoid this,for lower qps the hi_dev_qp
606                 * should be made slightly more than prev_qp
607                 */
608                if(prev_qp == hi_dev_qp)
609                {
610                    hi_dev_qp += 1;
611                }
612                lo_dev_qp = GET_LO_DEV_QP(prev_qp);
613                u1_frame_qp = (UWORD8)CLIP_QP((WORD32)u1_frame_qp, hi_dev_qp, lo_dev_qp);
614            }
615            else
616            {
617                ps_rate_control_api->au1_avg_bitrate_changed[e_pic_type] = 0;
618            }
619        }
620        else
621        {
622            /*
623             * The u1_is_first_frm_coded gets reset
624             *  a) at start of sequence
625             *  b) whenever there is a scene change.
626             *     In both cases since we do not have any estimate about the
627             *     current frame, we just send in the previous frame qp value.IN
628             *     Scene change case the previous QP is incremented by 4 , This is
629             *     done because the Scene changed VOP will have over consumed and
630             *     chances of future frames skipping is very high. For the init
631             *     case, the previous frame QP is initialized with the init qp
632             */
633            if((ps_rate_control_api->u1_scd_detected)
634                            && (ps_rate_control_api->e_rc_type != CONST_QP))
635            {
636                /*
637                 * If scene change is detected, I frame Qp would have been
638                 * updated
639                 */
640                 /* Use a QP calculated in the prev update fxn */
641                u1_frame_qp = ps_rate_control_api->u1_frm_qp_after_scd;
642            }
643            else
644            {
645                u1_frame_qp = ps_rate_control_api->au1_prev_frm_qp[e_pic_type];
646            }
647        }
648    }
649    else
650    {
651        u1_frame_qp = ps_rate_control_api->au1_init_qp[e_pic_type];
652    }
653
654    trace_printf((const WORD8*)"fqp %d\n", u1_frame_qp);
655
656    return (u1_frame_qp);
657}
658
659/*******************************************************************************
660 *Function Name : irc_get_buffer_status
661 *Description   : Gets the state of VBV buffer
662 *Outputs       : 0 = normal, 1 = underflow, 2= overflow
663 *Returns       : vbv_buf_status_e
664 ******************************************************************************/
665vbv_buf_status_e irc_get_buffer_status(rate_control_api_t *ps_rate_control_api,
666                                       WORD32 i4_total_frame_bits,
667                                       picture_type_e e_pic_type,
668                                       WORD32 *pi4_num_bits_to_prevent_vbv_underflow)
669{
670    vbv_buf_status_e e_buf_status = VBV_NORMAL;
671
672    /* Get the buffer status for the current total consumed bits and error bits*/
673    if(ps_rate_control_api->e_rc_type == VBR_STORAGE_DVD_COMP)
674    {
675        e_buf_status = irc_get_vbv_buffer_status(
676                        ps_rate_control_api->ps_vbr_storage_vbv,
677                        i4_total_frame_bits,
678                        pi4_num_bits_to_prevent_vbv_underflow);
679
680        trace_printf((const WORD8*)"e_buf_status = %d\n", e_buf_status);
681    }
682    else if(ps_rate_control_api->e_rc_type == VBR_STORAGE)
683    {
684        /* For VBR case since there is not underflow returning the max value */
685        pi4_num_bits_to_prevent_vbv_underflow[0] = irc_get_max_vbv_buf_size(
686                        ps_rate_control_api->ps_vbr_storage_vbv);
687        e_buf_status = VBV_NORMAL;
688    }
689    else if(ps_rate_control_api->e_rc_type == CBR_NLDRC)
690    {
691        e_buf_status = irc_get_cbr_buffer_status(
692                        ps_rate_control_api->ps_cbr_buffer, i4_total_frame_bits,
693                        pi4_num_bits_to_prevent_vbv_underflow, e_pic_type);
694
695    }
696    else if(ps_rate_control_api->e_rc_type == VBR_STREAMING)
697    {
698        /* For VBR_streaming, error bits are computed according to peak bitrate*/
699        e_buf_status = irc_get_cbr_buffer_status(
700                        ps_rate_control_api->ps_cbr_buffer, i4_total_frame_bits,
701                        pi4_num_bits_to_prevent_vbv_underflow, e_pic_type);
702    }
703    return e_buf_status;
704}
705
706/*******************************************************************************
707 Function Name : irc_update_pic_handling_state
708 Description   : If the forward path and the backward path of rate control
709 ******************************************************************************/
710void irc_update_pic_handling_state(rate_control_api_t *ps_rate_control_api,
711                                   picture_type_e e_pic_type)
712{
713    irc_update_pic_handling(ps_rate_control_api->ps_pic_handling, e_pic_type);
714}
715
716/******************************************************************************
717 Function Name : irc_update_frame_level_info
718 Description   : Updates the frame level information into the rate control
719                 structure
720 ******************************************************************************/
721void irc_update_frame_level_info(rate_control_api_t *ps_rate_control_api,
722                                 picture_type_e e_pic_type,
723                                 WORD32 *pi4_mb_type_sad,
724                                 WORD32 i4_total_frame_bits,
725                                 WORD32 i4_model_updation_hdr_bits,
726                                 WORD32 *pi4_mb_type_tex_bits,
727                                 WORD32 *pi4_tot_mb_type_qp,
728                                 WORD32 *pi4_tot_mb_in_type,
729                                 WORD32 i4_avg_activity,
730                                 UWORD8 u1_is_scd,
731                                 WORD32 i4_is_it_a_skip,
732                                 WORD32 i4_intra_frm_cost,
733                                 WORD32 i4_is_pic_handling_done)
734{
735    UWORD8 u1_num_skips = 0;
736    WORD32 i;
737    UWORD32 u4_frame_sad = 0;
738    WORD32 i4_tot_texture_bits = 0;
739    WORD32 i4_tot_mbs = 0;
740    WORD32 i4_avg_qp = 0;
741
742    /* SCD not supported in case of IPB encoder */
743    if(u1_is_scd && (irc_pic_type_get_inter_frame_interval(
744                                    ps_rate_control_api->ps_pic_handling) > 1))
745    {
746        u1_is_scd = 0;
747    }
748    trace_printf((const WORD8*)"i4_total_frame_bits %d\n", i4_total_frame_bits);
749
750    if(!i4_is_it_a_skip && !i4_is_pic_handling_done)
751    {
752        /* Update the pic_handling struct */
753        irc_update_pic_handling(ps_rate_control_api->ps_pic_handling,
754                                e_pic_type);
755    }
756
757    if(ps_rate_control_api->e_rc_type != CONST_QP)
758    {
759        if(!i4_is_it_a_skip)
760        {
761            WORD32 i4_new_period_flag;
762            /******************************************************************
763             Calculate the total values from the individual values
764             ******************************************************************/
765            for(i = 0; i < MAX_MB_TYPE; i++)
766                u4_frame_sad += pi4_mb_type_sad[i];
767            for(i = 0; i < MAX_MB_TYPE; i++)
768                i4_tot_texture_bits += pi4_mb_type_tex_bits[i];
769            for(i = 0; i < MAX_MB_TYPE; i++)
770                i4_avg_qp += pi4_tot_mb_type_qp[i];
771            for(i = 0; i < MAX_MB_TYPE; i++)
772                i4_tot_mbs += pi4_tot_mb_in_type[i];
773            i4_avg_qp /= i4_tot_mbs; /* Calculate the average QP */
774
775            if(ps_rate_control_api->u1_is_mb_level_rc_on)
776            {
777                /*
778                 * The model needs to take into consideration the average
779                 * activity of the entire frame while estimating the QP. Thus
780                 * the frame sad values are scaled by the average activity
781                 * before updating it into the model.
782                 */
783                if(!i4_avg_activity)
784                    i4_avg_activity = 1;
785                i4_intra_frm_cost *= i4_avg_activity;
786                u4_frame_sad *= i4_avg_activity;
787            }
788
789            /******************************************************************
790             Update the bit allocation module
791             NOTE: For bit allocation module, the pic_type should not be
792             modified to that of 'I', in case of a SCD.
793             ******************************************************************/
794            i4_new_period_flag = irc_is_last_frame_in_gop(
795                            ps_rate_control_api->ps_pic_handling);
796            irc_ba_update_cur_frm_consumed_bits(
797                            ps_rate_control_api->ps_bit_allocation,
798                            ps_rate_control_api->ps_pic_handling,
799                            i4_total_frame_bits, i4_model_updation_hdr_bits,
800                            e_pic_type, u1_is_scd, i4_new_period_flag);
801
802            if(1 == i4_new_period_flag
803                            && ((ps_rate_control_api->e_rc_type == VBR_STORAGE)
804                                            || (ps_rate_control_api->e_rc_type
805                                                            == VBR_STORAGE_DVD_COMP)))
806            {
807                irc_ba_check_and_update_bit_allocation(
808                                ps_rate_control_api->ps_bit_allocation,
809                                ps_rate_control_api->ps_pic_handling,
810                                irc_get_cur_vbv_buf_size(
811                                                ps_rate_control_api->ps_vbr_storage_vbv),
812                                irc_get_max_vbv_buf_size(
813                                                ps_rate_control_api->ps_vbr_storage_vbv),
814                                irc_get_max_bits_per_tgt_frm(
815                                                ps_rate_control_api->ps_vbr_storage_vbv),
816                                i4_total_frame_bits);
817            }
818        }
819
820        /**********************************************************************
821         Update the buffer status
822         *********************************************************************/
823        /*
824         * This update is done after overflow and underflow handling to
825         *  account for the actual bits dumped
826         */
827        if((ps_rate_control_api->e_rc_type == VBR_STORAGE)
828                        || (ps_rate_control_api->e_rc_type
829                                        == VBR_STORAGE_DVD_COMP))
830        {
831            irc_update_vbr_vbv(ps_rate_control_api->ps_vbr_storage_vbv,
832                               i4_total_frame_bits);
833        }
834        else if(ps_rate_control_api->e_rc_type == CBR_NLDRC)
835        {
836            irc_update_cbr_buffer(ps_rate_control_api->ps_cbr_buffer,
837                                  i4_total_frame_bits, e_pic_type);
838        }
839        else if(ps_rate_control_api->e_rc_type == VBR_STREAMING)
840        {
841            UWORD32 au4_num_pics_in_delay_prd[MAX_PIC_TYPE];
842
843            irc_get_vsp_num_pics_in_dly_prd(
844                            &ps_rate_control_api->s_vbr_str_prms,
845                            au4_num_pics_in_delay_prd);
846
847            irc_update_cbr_buffer(ps_rate_control_api->ps_cbr_buffer,
848                                  i4_total_frame_bits, e_pic_type);
849
850            irc_update_vbr_str_prms(&ps_rate_control_api->s_vbr_str_prms,
851                                    e_pic_type);
852
853            irc_change_cbr_vbv_num_pics_in_delay_period(
854                            ps_rate_control_api->ps_cbr_buffer,
855                            au4_num_pics_in_delay_prd);
856
857            /*
858             * If the change_in_peak_bitrate flag is set, after the delay period
859             * update the peak_bitrate and the buffer parameters
860             */
861            if(!ps_rate_control_api->u4_frms_in_delay_prd_for_peak_bit_rate_change)
862            {
863                irc_ba_change_ba_peak_bit_rate(
864                                ps_rate_control_api->ps_bit_allocation,
865                                (WORD32 *)&ps_rate_control_api->au4_new_peak_bit_rate[0]);
866                irc_change_cbr_vbv_bit_rate(
867                                ps_rate_control_api->ps_cbr_buffer,
868                                (WORD32 *)&ps_rate_control_api->au4_new_peak_bit_rate[0]);
869            }
870            if(ps_rate_control_api->u4_frms_in_delay_prd_for_peak_bit_rate_change)
871                ps_rate_control_api->u4_frms_in_delay_prd_for_peak_bit_rate_change--;
872        }
873
874        if(!i4_is_it_a_skip)
875        {
876            /*******************************************************************
877             Handle the SCENE CHANGE DETECTED
878             1) Make the picture type as I, so that updation happens as if it is
879                an I frame
880             2) Reset model, SAD and flag to restart the estimation process
881             ******************************************************************/
882            if(u1_is_scd)
883            {
884                WORD32 i4_frm_qp_after_scd;
885                UWORD32 u4_prev_I_frm_sad;
886
887                e_pic_type = I_PIC;
888
889                /* Scale scd qp based on SCD Frm sad and previous I Frm sad */
890                /* frm_qp_after_scd = (avg_qp * cur_frm_sad)/prev_I_frm_sad */
891
892                /*
893                 * QP for the next frame should take care of
894                 * 1) due to scene change, the current picture has consumed more
895                 *      bits
896                 * 2) relative complexity of the previous scene and the current
897                 *     scene
898                 */
899
900                /* Get the intra SAD for the previous scene */
901                u4_prev_I_frm_sad = irc_get_est_sad(
902                                ps_rate_control_api->ps_est_sad, I_PIC);
903
904                /*
905                 * Scale the QP based on the SAD ratio of the current pic and
906                 * previous scene intra SAD
907                 */
908                X_PROD_Y_DIV_Z(i4_avg_qp, u4_frame_sad, u4_prev_I_frm_sad,
909                               i4_frm_qp_after_scd);
910
911                /* Limit the next frame qp by 50% across both the sides */
912                if(i4_frm_qp_after_scd > ((i4_avg_qp * 3) >> 1))
913                {
914                    i4_frm_qp_after_scd = (i4_avg_qp * 3) >> 1;
915                }
916                else if(i4_frm_qp_after_scd < (i4_avg_qp >> 1))
917                {
918                    i4_frm_qp_after_scd = (i4_avg_qp >> 1);
919                }
920
921                /*
922                 * Ensure that the next frame QP is within the min_max limit of
923                 * QP allowed
924                 */
925                if(i4_frm_qp_after_scd
926                                > ps_rate_control_api->au1_min_max_qp[(e_pic_type
927                                                << 1) + 1])
928                {
929                    i4_frm_qp_after_scd =
930                                    ps_rate_control_api->au1_min_max_qp[(e_pic_type
931                                                    << 1) + 1];
932                }
933                else if(i4_frm_qp_after_scd
934                                < ps_rate_control_api->au1_min_max_qp[(e_pic_type
935                                                << 1)])
936                {
937                    i4_frm_qp_after_scd =
938                                    ps_rate_control_api->au1_min_max_qp[(e_pic_type
939                                                    << 1)];
940                }
941
942                /* Update the state var */
943                ps_rate_control_api->u1_frm_qp_after_scd =
944                                (UWORD8)i4_frm_qp_after_scd;
945
946                /* re-set model */
947                for(i = 0; i < MAX_PIC_TYPE; i++)
948                {
949                    irc_reset_frm_rc_rd_model(
950                                    ps_rate_control_api->aps_rd_model[i]);
951                }
952
953                /* Reset the SAD estimation module */
954                irc_reset_est_sad(ps_rate_control_api->ps_est_sad);
955
956                /* Reset flag */
957                for(i = 0; i < MAX_PIC_TYPE; i++)
958                {
959                    ps_rate_control_api->au1_is_first_frm_coded[i] = 0;
960                }
961
962                /* Reset the MB Rate control */
963                irc_init_mb_level_rc(ps_rate_control_api->ps_mb_rate_control);
964
965                /*Set u1_scd_detected flag*/
966                ps_rate_control_api->u1_scd_detected = 1;
967
968                /*
969                 * Adjust the average QP for the frame based on bits
970                 * consumption
971                 */
972                /*
973                 *  Initialize the QP for each picture type according to the
974                 * average QP of the SCD pic
975                 */
976                ps_rate_control_api->au1_prev_frm_qp[I_PIC] = (UWORD8)i4_avg_qp;
977
978                trace_printf((const WORD8*)"SCD DETECTED\n");
979            }
980            else
981            {
982                ps_rate_control_api->u1_scd_detected = 0;
983                /**************************************************************
984                 Update the Qp used by the current frame
985                 **************************************************************/
986                ps_rate_control_api->au1_prev_frm_qp[e_pic_type] =
987                                (UWORD8)i4_avg_qp;
988            }
989
990            /********************************************************************
991             Update the model of the correponding picture type
992             NOTE: For SCD, we force the frame type from 'P' to that of a 'I'
993             ******************************************************************/
994            /*
995             * For very simple sequences no bits are consumed by texture. These
996             * frames do not add any information to the model and so not added
997             */
998            if(i4_tot_texture_bits && u4_frame_sad)
999            {
1000                irc_add_frame_to_rd_model(
1001                                ps_rate_control_api->aps_rd_model[e_pic_type],
1002                                i4_tot_texture_bits, (UWORD8)i4_avg_qp,
1003                                u4_frame_sad, u1_num_skips);
1004
1005                /*
1006                 * At least one proper frame in added into the model. Until that
1007                 * keep using the initial QP
1008                 */
1009                ps_rate_control_api->au1_is_first_frm_coded[e_pic_type] = 1;
1010            }
1011
1012            if(i4_avg_activity)
1013            {
1014                /* Update the mb_level model */
1015                irc_mb_update_frame_level(
1016                                ps_rate_control_api->ps_mb_rate_control,
1017                                i4_avg_activity);
1018            }
1019
1020            /******************************************************************
1021             Update the sad estimation module
1022             NOTE: For SCD, we force the frame type from 'P' to that of a 'I'
1023             ******************************************************************/
1024            if(u4_frame_sad)
1025            {
1026                irc_update_actual_sad(ps_rate_control_api->ps_est_sad,
1027                                      u4_frame_sad, e_pic_type);
1028
1029                irc_update_actual_sad_for_intra(ps_rate_control_api->ps_est_sad,
1030                                                i4_intra_frm_cost);
1031            }
1032
1033            /*
1034             * Update the variable which denotes that a frame has been
1035             * encountered
1036             */
1037            ps_rate_control_api->u1_is_first_frm = 0;
1038
1039        }
1040    }
1041
1042    /* Store the prev encoded picture type for restricting Qp swing */
1043    if((e_pic_type == I_PIC) || (e_pic_type == P_PIC))
1044    {
1045        ps_rate_control_api->prev_ref_pic_type = e_pic_type;
1046    }
1047
1048    trace_printf((const WORD8*)"ft %d,hb %d,tb %d,qp %d,fs %d\n", e_pic_type,
1049                 i4_model_updation_hdr_bits, i4_tot_texture_bits, i4_avg_qp,
1050                 u4_frame_sad);
1051
1052    return;
1053}
1054
1055/*******************************************************************************
1056 MB Level API functions
1057 ******************************************************************************/
1058
1059/******************************************************************************
1060 Function Name : irc_init_mb_rc_frame_level
1061 Description   : Initialise the frame level details required for a mb level
1062 ******************************************************************************/
1063
1064void irc_init_mb_rc_frame_level(rate_control_api_t *ps_rate_control_api,
1065                                UWORD8 u1_frame_qp)
1066{
1067    irc_mb_init_frame_level(ps_rate_control_api->ps_mb_rate_control,
1068                            u1_frame_qp);
1069}
1070
1071/******************************************************************************
1072 Function Name : irc_get_mb_level_qp
1073 Description   : Get the mb level qp
1074 *****************************************************************************/
1075void irc_get_mb_level_qp(rate_control_api_t *ps_rate_control_api,
1076                         WORD32 i4_cur_mb_activity,
1077                         WORD32 *pi4_mb_qp,
1078                         picture_type_e e_pic_type)
1079{
1080    if(ps_rate_control_api->u1_is_mb_level_rc_on)
1081    {
1082        irc_get_mb_qp(ps_rate_control_api->ps_mb_rate_control,
1083                      i4_cur_mb_activity, pi4_mb_qp);
1084
1085        /* Truncating the QP to the Max and Min Qp values possible */
1086        if(pi4_mb_qp[1] < ps_rate_control_api->au1_min_max_qp[e_pic_type << 1])
1087        {
1088            pi4_mb_qp[1] = ps_rate_control_api->au1_min_max_qp[e_pic_type << 1];
1089        }
1090        if(pi4_mb_qp[1]
1091                        > ps_rate_control_api->au1_min_max_qp[(e_pic_type << 1)
1092                                        + 1])
1093        {
1094            pi4_mb_qp[1] = ps_rate_control_api->au1_min_max_qp[(e_pic_type << 1)
1095                            + 1];
1096        }
1097    }
1098    else
1099    {
1100        WORD32 i4_qp;
1101        i4_qp = irc_get_frm_level_qp(ps_rate_control_api->ps_mb_rate_control);
1102        /* Both the qp are used for */
1103        pi4_mb_qp[0] = i4_qp; /* Used as feedback for the rate control */
1104        pi4_mb_qp[1] = i4_qp; /* Used for quantising the MB*/
1105    }
1106}
1107
1108/****************************************************************************
1109 Function Name : irc_get_bits_to_stuff
1110 Description   : Gets the bits to stuff to prevent Underflow of Encoder Buffer
1111 *****************************************************************************/
1112WORD32 irc_get_bits_to_stuff(rate_control_api_t *ps_rate_control_api,
1113                             WORD32 i4_tot_consumed_bits,
1114                             picture_type_e e_pic_type)
1115{
1116    WORD32 i4_bits_to_stuff;
1117    /* Get the CBR bits to stuff*/
1118    i4_bits_to_stuff = irc_get_cbr_bits_to_stuff(
1119                    ps_rate_control_api->ps_cbr_buffer, i4_tot_consumed_bits,
1120                    e_pic_type);
1121    return i4_bits_to_stuff;
1122}
1123
1124/****************************************************************************
1125 Function Name : irc_get_prev_frm_est_bits
1126 Description   : Returns previous frame estimated bits
1127 *****************************************************************************/
1128WORD32 irc_get_prev_frm_est_bits(rate_control_api_t *ps_rate_control_api)
1129{
1130    return (ps_rate_control_api->i4_prev_frm_est_bits);
1131}
1132
1133/******************************************************************************
1134 Control Level API functions
1135 Logic: The control call sets the state structure of the rate control api
1136         accordingly such that the next process call would implement the same.
1137 ******************************************************************************/
1138
1139void irc_change_inter_frm_int_call(rate_control_api_t *ps_rate_control_api,
1140                                   WORD32 i4_inter_frm_int)
1141{
1142    irc_pic_handling_register_new_inter_frm_interval(
1143                    ps_rate_control_api->ps_pic_handling, i4_inter_frm_int);
1144}
1145
1146void irc_change_intra_frm_int_call(rate_control_api_t *ps_rate_control_api,
1147                                   WORD32 i4_intra_frm_int)
1148{
1149    irc_pic_handling_register_new_int_frm_interval(
1150                    ps_rate_control_api->ps_pic_handling, i4_intra_frm_int);
1151
1152    if(ps_rate_control_api->e_rc_type == VBR_STREAMING)
1153    {
1154        irc_change_vsp_ifi(&ps_rate_control_api->s_vbr_str_prms,
1155                           i4_intra_frm_int);
1156    }
1157}
1158
1159/****************************************************************************
1160 Function Name : irc_change_avg_bit_rate
1161 Description   : Whenever the average bit rate changes, the excess bits is
1162                 between the changed bit rate and the old one is re-distributed
1163                 in the bit allocation module
1164 *****************************************************************************/
1165void irc_change_avg_bit_rate(rate_control_api_t *ps_rate_control_api,
1166                             UWORD32 u4_average_bit_rate)
1167{
1168    int i;
1169    if(ps_rate_control_api->e_rc_type != CONST_QP)
1170    {
1171        /*
1172         * Bit Allocation Module: distribute the excess/deficit bits between the
1173         * old and the new frame rate to all the remaining frames
1174         */
1175        irc_ba_change_remaining_bits_in_period(
1176                        ps_rate_control_api->ps_bit_allocation,
1177                        ps_rate_control_api->ps_pic_handling,
1178                        u4_average_bit_rate,
1179                        irc_ba_get_frame_rate(
1180                                        ps_rate_control_api->ps_bit_allocation),
1181                        (WORD32 *)(ps_rate_control_api->au4_new_peak_bit_rate));
1182    }
1183    if(ps_rate_control_api->e_rc_type == CBR_NLDRC)
1184    {
1185        UWORD32 u4_average_bit_rate_copy[MAX_NUM_DRAIN_RATES];
1186        for(i = 0; i < MAX_NUM_DRAIN_RATES; i++)
1187        {
1188            u4_average_bit_rate_copy[i] = u4_average_bit_rate;
1189        }
1190        irc_change_cbr_vbv_bit_rate(ps_rate_control_api->ps_cbr_buffer,
1191                                    (WORD32 *)(u4_average_bit_rate_copy));
1192    }
1193
1194    /*
1195     * This is done only for average bitrate changing somewhere after the model
1196     * stabilizes.Here it is assumed that user will not do this call after
1197     * first few frames. If we dont have this check, what would happen is since
1198     * the model has not stabilized, also bitrate has changed before the first
1199     * frame, we dont restrict the qp. Qp can go to very bad values after init
1200     * qp since if swing is disabled.
1201     * This check will become buggy if change bitrate is called say somewhere
1202     * after first two frames.Bottom line - RC init is done during create and
1203     * this call is done just before first process.And we want to differentiate
1204     * between this call done before first process and the call which is done
1205     * during run time
1206     */
1207    if(ps_rate_control_api->u1_is_first_frm == 0)
1208    {
1209        for(i = 0; i < MAX_PIC_TYPE; i++)
1210        {
1211            ps_rate_control_api->au1_avg_bitrate_changed[i] = 1;
1212        }
1213    }
1214}
1215
1216/****************************************************************************
1217 Function Name : irc_change_frame_rate
1218 Description   : Does the necessary changes whenever there is a change in
1219                 frame rate
1220 *****************************************************************************/
1221void irc_change_frame_rate(rate_control_api_t *ps_rate_control_api,
1222                           UWORD32 u4_frame_rate,
1223                           UWORD32 u4_src_ticks,
1224                           UWORD32 u4_tgt_ticks)
1225{
1226
1227    if(ps_rate_control_api->e_rc_type != CONST_QP)
1228    {
1229        UWORD32 u4_frms_in_delay_prd = ((u4_frame_rate
1230                        * irc_get_cbr_buffer_delay(
1231                                        ps_rate_control_api->ps_cbr_buffer))
1232                        / 1000000);
1233        if((ps_rate_control_api->e_rc_type == VBR_STORAGE)
1234                        || (ps_rate_control_api->e_rc_type
1235                                        == VBR_STORAGE_DVD_COMP))
1236        {
1237            irc_change_vbr_vbv_frame_rate(
1238                            ps_rate_control_api->ps_vbr_storage_vbv,
1239                            u4_frame_rate);
1240        }
1241        else if(ps_rate_control_api->e_rc_type == CBR_NLDRC)
1242        {
1243            irc_change_cbr_vbv_tgt_frame_rate(
1244                            ps_rate_control_api->ps_cbr_buffer, u4_frame_rate);
1245        }
1246        else if(ps_rate_control_api->e_rc_type == VBR_STREAMING)
1247        {
1248            UWORD32 au4_num_pics_in_delay_prd[MAX_PIC_TYPE];
1249            irc_change_vsp_tgt_ticks(&ps_rate_control_api->s_vbr_str_prms,
1250                                     u4_tgt_ticks);
1251            irc_change_vsp_src_ticks(&ps_rate_control_api->s_vbr_str_prms,
1252                                     u4_src_ticks);
1253            irc_change_vsp_fidp(&ps_rate_control_api->s_vbr_str_prms,
1254                                u4_frms_in_delay_prd);
1255
1256            irc_get_vsp_num_pics_in_dly_prd(
1257                            &ps_rate_control_api->s_vbr_str_prms,
1258                            au4_num_pics_in_delay_prd);
1259            irc_change_cbr_vbv_tgt_frame_rate(
1260                            ps_rate_control_api->ps_cbr_buffer, u4_frame_rate);
1261            irc_change_cbr_vbv_num_pics_in_delay_period(
1262                            ps_rate_control_api->ps_cbr_buffer,
1263                            au4_num_pics_in_delay_prd);
1264        }
1265
1266        /*
1267         * Bit Allocation Module: distribute the excess/deficit bits between the
1268         * old and the new frame rate to all the remaining frames
1269         */
1270        irc_ba_change_remaining_bits_in_period(
1271                        ps_rate_control_api->ps_bit_allocation,
1272                        ps_rate_control_api->ps_pic_handling,
1273                        irc_ba_get_bit_rate(
1274                                        ps_rate_control_api->ps_bit_allocation),
1275                        u4_frame_rate,
1276                        (WORD32 *)(ps_rate_control_api->au4_new_peak_bit_rate));
1277    }
1278}
1279
1280/****************************************************************************
1281 Function Name : irc_change_frm_rate_for_bit_alloc
1282 Description   : Does the necessary changes only in the bit_allocation module
1283                 there is a change in frame rate
1284 *****************************************************************************/
1285void irc_change_frm_rate_for_bit_alloc(rate_control_api_t *ps_rate_control_api,
1286                                       UWORD32 u4_frame_rate)
1287{
1288
1289    if(ps_rate_control_api->e_rc_type != CONST_QP)
1290    {
1291        /*
1292         * Bit Allocation Module: distribute the excess/deficit bits between the
1293         * old and the new frame rate to all the remaining frames
1294         */
1295        irc_ba_change_remaining_bits_in_period(
1296                        ps_rate_control_api->ps_bit_allocation,
1297                        ps_rate_control_api->ps_pic_handling,
1298                        irc_ba_get_bit_rate(
1299                                        ps_rate_control_api->ps_bit_allocation),
1300                        u4_frame_rate,
1301                        (WORD32 *)(ps_rate_control_api->au4_new_peak_bit_rate));
1302
1303        if(ps_rate_control_api->e_rc_type == VBR_STORAGE
1304                        || ps_rate_control_api->e_rc_type
1305                                        == VBR_STORAGE_DVD_COMP)
1306        {
1307            irc_change_vbr_max_bits_per_tgt_frm(
1308                            ps_rate_control_api->ps_vbr_storage_vbv,
1309                            u4_frame_rate);
1310        }
1311    }
1312}
1313
1314void irc_change_init_qp(rate_control_api_t *ps_rate_control_api,
1315                        UWORD8 *pu1_init_qp)
1316{
1317    WORD32 i;
1318    /* Initialize the init_qp */
1319    for(i = 0; i < MAX_PIC_TYPE; i++)
1320    {
1321        ps_rate_control_api->au1_init_qp[i] = pu1_init_qp[i];
1322        ps_rate_control_api->au1_prev_frm_qp[i] = pu1_init_qp[i];
1323    }
1324}
1325
1326void irc_change_min_max_qp(rate_control_api_t *ps_rate_control_api,
1327                           UWORD8 *pu1_min_max_qp)
1328{
1329    WORD32 i;
1330    for(i = 0; i < MAX_PIC_TYPE; i++)
1331    {
1332        ps_rate_control_api->au1_min_max_qp[(i << 1)] =
1333                        pu1_min_max_qp[(i << 1)];
1334        ps_rate_control_api->au1_min_max_qp[(i << 1) + 1] = pu1_min_max_qp[(i
1335                        << 1) + 1];
1336    }
1337}
1338
1339/****************************************************************************
1340 Function Name : irc_change_peak_bit_rate
1341 Description   : Does the necessary changes whenever there is a change in
1342                 peak bit rate
1343 *****************************************************************************/
1344WORD32 irc_change_peak_bit_rate(rate_control_api_t *ps_rate_control_api,
1345                                UWORD32 *pu4_peak_bit_rate)
1346{
1347    WORD32 i4_ret_val = RC_OK;
1348    int i;
1349
1350    /*
1351     * Buffer Mechanism Module: Re-initialize the number of bits consumed per
1352     * frame
1353     */
1354    if(ps_rate_control_api->e_rc_type == VBR_STORAGE
1355                    || ps_rate_control_api->e_rc_type == VBR_STORAGE_DVD_COMP)
1356    {
1357        /* Send the new peak bit rate and the old frame rate */
1358        irc_change_vbr_vbv_bit_rate(ps_rate_control_api->ps_vbr_storage_vbv,
1359                                    pu4_peak_bit_rate[0]);
1360        irc_ba_change_ba_peak_bit_rate(ps_rate_control_api->ps_bit_allocation,
1361                                       (WORD32 *)pu4_peak_bit_rate);
1362
1363        for(i = 0; i < MAX_NUM_DRAIN_RATES; i++)
1364        {
1365            ps_rate_control_api->au4_new_peak_bit_rate[i] =
1366                            pu4_peak_bit_rate[i];
1367        }
1368    }
1369    else if(ps_rate_control_api->e_rc_type == VBR_STREAMING)
1370    {
1371        if(ps_rate_control_api->u4_frms_in_delay_prd_for_peak_bit_rate_change)
1372        {
1373            /*
1374             * Means that change in peak bit rate has been made twice before the
1375             * previous change could take effect
1376             */
1377            i4_ret_val = RC_BENIGN_ERR;
1378        }
1379        /*
1380         * If the change happens before encoding the first frame make the
1381         * effect immediately else delay the effect
1382         */
1383        if(ps_rate_control_api->u1_is_first_frm)
1384        {
1385            for(i = 0; i < MAX_NUM_DRAIN_RATES; i++)
1386            {
1387                ps_rate_control_api->au4_new_peak_bit_rate[i] =
1388                                pu4_peak_bit_rate[i];
1389            }
1390            irc_ba_change_ba_peak_bit_rate(
1391                            ps_rate_control_api->ps_bit_allocation,
1392                            (WORD32 *)pu4_peak_bit_rate);
1393            irc_change_cbr_vbv_bit_rate(ps_rate_control_api->ps_cbr_buffer,
1394                                        (WORD32 *)pu4_peak_bit_rate);
1395        }
1396        else
1397        {
1398            UWORD32 au4_num_pics_in_delay_prd[MAX_NUM_DRAIN_RATES];
1399            /*
1400             * Else store the number of frames after which the effect should
1401             * happen and then update the peak bitrate
1402             */
1403            ps_rate_control_api->u4_frms_in_delay_prd_for_peak_bit_rate_change =
1404                            irc_get_vsp_num_pics_in_dly_prd(
1405                                            &ps_rate_control_api->s_vbr_str_prms,
1406                                            au4_num_pics_in_delay_prd);
1407            for(i = 0; i < MAX_NUM_DRAIN_RATES; i++)
1408            {
1409                ps_rate_control_api->au4_new_peak_bit_rate[i] =
1410                                pu4_peak_bit_rate[i];
1411            }
1412        }
1413    }
1414
1415    return (i4_ret_val);
1416}
1417
1418void irc_change_buffer_delay(rate_control_api_t *ps_rate_control_api,
1419                             UWORD32 u4_buffer_delay)
1420{
1421    UWORD32 u4_frms_in_delay_prd = ((irc_ba_get_frame_rate(
1422                    ps_rate_control_api->ps_bit_allocation) * u4_buffer_delay)
1423                    / 1000000);
1424
1425    /* Initialize the rate control modules */
1426    if(ps_rate_control_api->e_rc_type == CBR_NLDRC)
1427    {
1428        irc_change_cbr_buffer_delay(ps_rate_control_api->ps_cbr_buffer,
1429                                    u4_buffer_delay);
1430    }
1431    else if(ps_rate_control_api->e_rc_type == VBR_STORAGE
1432                    || ps_rate_control_api->e_rc_type == VBR_STORAGE_DVD_COMP)
1433    {
1434        UWORD32 au4_num_pics_in_delay_prd[MAX_PIC_TYPE];
1435
1436        irc_change_vsp_fidp(&ps_rate_control_api->s_vbr_str_prms,
1437                            u4_frms_in_delay_prd);
1438
1439        /* Get the number of pics of each type in delay period */
1440        irc_get_vsp_num_pics_in_dly_prd(&ps_rate_control_api->s_vbr_str_prms,
1441                                        au4_num_pics_in_delay_prd);
1442
1443        irc_change_cbr_vbv_num_pics_in_delay_period(
1444                        ps_rate_control_api->ps_cbr_buffer,
1445                        au4_num_pics_in_delay_prd);
1446    }
1447}
1448
1449/* Getter functions to get the current rate control parameters */
1450UWORD32 irc_get_frame_rate(rate_control_api_t *ps_rate_control_api)
1451{
1452    return (irc_ba_get_frame_rate(ps_rate_control_api->ps_bit_allocation));
1453}
1454
1455UWORD32 irc_get_bit_rate(rate_control_api_t *ps_rate_control_api)
1456{
1457    return (irc_ba_get_bit_rate(ps_rate_control_api->ps_bit_allocation));
1458}
1459
1460UWORD32 irc_get_peak_bit_rate(rate_control_api_t *ps_rate_control_api,
1461                              WORD32 i4_index)
1462{
1463    return (ps_rate_control_api->au4_new_peak_bit_rate[i4_index]);
1464}
1465
1466UWORD32 irc_get_intra_frame_interval(rate_control_api_t *ps_rate_control_api)
1467{
1468    return (irc_pic_type_get_intra_frame_interval(
1469                    ps_rate_control_api->ps_pic_handling));
1470}
1471
1472UWORD32 irc_get_inter_frame_interval(rate_control_api_t *ps_rate_control_api)
1473{
1474    return (irc_pic_type_get_inter_frame_interval(
1475                    ps_rate_control_api->ps_pic_handling));
1476}
1477
1478rc_type_e irc_get_rc_type(rate_control_api_t *ps_rate_control_api)
1479{
1480    return (ps_rate_control_api->e_rc_type);
1481}
1482
1483WORD32 irc_get_bits_per_frame(rate_control_api_t *ps_rate_control_api)
1484{
1485    WORD32 i4_bits_per_frm;
1486
1487    X_PROD_Y_DIV_Z(irc_ba_get_bit_rate(ps_rate_control_api->ps_bit_allocation),
1488                   (UWORD32)1000,
1489                   irc_ba_get_frame_rate(ps_rate_control_api->ps_bit_allocation),
1490                   i4_bits_per_frm);
1491
1492    return (i4_bits_per_frm);
1493}
1494
1495UWORD32 irc_get_max_delay(rate_control_api_t *ps_rate_control_api)
1496{
1497    return (irc_get_cbr_buffer_delay(ps_rate_control_api->ps_cbr_buffer));
1498}
1499
1500UWORD32 irc_get_seq_no(rate_control_api_t *ps_rate_control_api)
1501{
1502    return (irc_pic_type_get_disp_order_no(ps_rate_control_api->ps_pic_handling));
1503}
1504
1505UWORD32 irc_get_rem_frames_in_gop(rate_control_api_t *ps_rate_control_api)
1506{
1507    WORD32 ai4_rem_frms_in_period[MAX_PIC_TYPE];
1508    WORD32 j;
1509    UWORD32 u4_rem_frms_in_period = 0;
1510
1511    /* Get the rem_frms_in_gop & the frms_in_gop from the pic_type state struct */
1512    irc_pic_type_get_rem_frms_in_gop(ps_rate_control_api->ps_pic_handling,
1513                                     ai4_rem_frms_in_period);
1514
1515    /* Depending on the number of gops in a period, find the num_frms_in_prd */
1516    for(j = 0; j < MAX_PIC_TYPE; j++)
1517    {
1518        u4_rem_frms_in_period += ai4_rem_frms_in_period[j];
1519    }
1520
1521    return (u4_rem_frms_in_period);
1522}
1523
1524/****************************************************************************
1525 Function Name : irc_flush_buf_frames
1526 Description   : API call to flush the buffered up frames
1527 *****************************************************************************/
1528void irc_flush_buf_frames(rate_control_api_t *ps_rate_control_api)
1529{
1530    irc_flush_frame_from_pic_stack(ps_rate_control_api->ps_pic_handling);
1531}
1532
1533/****************************************************************************
1534 Function Name : irc_flush_buf_frames
1535 Description   : API call to flush the buffered up frames
1536 *****************************************************************************/
1537
1538void irc_post_encode_frame_skip(rate_control_api_t *ps_rate_control_api,
1539                                picture_type_e e_pic_type)
1540{
1541    irc_skip_encoded_frame(ps_rate_control_api->ps_pic_handling, e_pic_type);
1542}
1543
1544/****************************************************************************
1545 Function Name : irc_force_I_frame
1546 Description   : API call to force an I frame
1547 *****************************************************************************/
1548void irc_force_I_frame(rate_control_api_t *ps_rate_control_api)
1549{
1550    irc_set_force_I_frame_flag(ps_rate_control_api->ps_pic_handling);
1551}
1552
1553/****************************************************************************
1554 * Function Name : rc_get_rem_bits_in_gop
1555 * Description   : API call to get remaining bits in GOP
1556 * *****************************************************************************/
1557WORD32 irc_get_rem_bits_in_period(rate_control_api_t *ps_rate_control_api)
1558{
1559    return (irc_ba_get_rem_bits_in_period(
1560                    ps_rate_control_api->ps_bit_allocation,
1561                    ps_rate_control_api->ps_pic_handling));
1562}
1563
1564/****************************************************************************
1565 * Function Name : irc_get_vbv_buf_fullness
1566 * Description   : API call to get VBV buffer fullness
1567 ******************************************************************************/
1568WORD32 irc_get_vbv_buf_fullness(rate_control_api_t *ps_rate_control_api)
1569{
1570    return (irc_get_cur_vbv_buf_size(ps_rate_control_api->ps_vbr_storage_vbv));
1571}
1572
1573WORD32 irc_get_vbv_buf_size(rate_control_api_t *ps_rate_control_api)
1574{
1575    if(ps_rate_control_api->e_rc_type == CBR_NLDRC
1576                    || ps_rate_control_api->e_rc_type == VBR_STREAMING)
1577    {
1578        return (irc_get_cbr_buffer_size(ps_rate_control_api->ps_cbr_buffer));
1579    }
1580    else
1581    {
1582        return (irc_get_max_vbv_buf_size(
1583                        ps_rate_control_api->ps_vbr_storage_vbv));
1584    }
1585}
1586
1587WORD32 irc_get_vbv_fulness_with_cur_bits(rate_control_api_t *ps_rate_control_api,
1588                                         UWORD32 u4_bits)
1589{
1590    return (irc_vbv_get_vbv_buf_fullness(
1591                    ps_rate_control_api->ps_vbr_storage_vbv, u4_bits));
1592}
1593
1594void irc_set_avg_mb_act(rate_control_api_t *ps_rate_control_api,
1595                        WORD32 i4_avg_activity)
1596{
1597    irc_mb_update_frame_level(ps_rate_control_api->ps_mb_rate_control,
1598                              i4_avg_activity);
1599    return;
1600}
1601