1 /*
2  *  Copyright (c) 2019, Alliance for Open Media. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include <math.h>
12 
13 #include "av1/encoder/encoder.h"
14 
swap_ptr(void * a,void * b)15 static void swap_ptr(void *a, void *b) {
16   void **a_p = (void **)a;
17   void **b_p = (void **)b;
18   void *c = *a_p;
19   *a_p = *b_p;
20   *b_p = c;
21 }
22 
av1_init_layer_context(AV1_COMP * const cpi)23 void av1_init_layer_context(AV1_COMP *const cpi) {
24   AV1_COMMON *const cm = &cpi->common;
25   const AV1EncoderConfig *const oxcf = &cpi->oxcf;
26   SVC *const svc = &cpi->svc;
27   int mi_rows = cpi->common.mi_params.mi_rows;
28   int mi_cols = cpi->common.mi_params.mi_cols;
29   svc->base_framerate = 30.0;
30   svc->current_superframe = 0;
31 
32   for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
33     for (int tl = 0; tl < svc->number_temporal_layers; ++tl) {
34       int layer = LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
35       LAYER_CONTEXT *const lc = &svc->layer_context[layer];
36       RATE_CONTROL *const lrc = &lc->rc;
37       lrc->ni_av_qi = oxcf->worst_allowed_q;
38       lrc->total_actual_bits = 0;
39       lrc->total_target_vs_actual = 0;
40       lrc->ni_tot_qi = 0;
41       lrc->tot_q = 0.0;
42       lrc->avg_q = 0.0;
43       lrc->ni_frames = 0;
44       lrc->decimation_count = 0;
45       lrc->decimation_factor = 0;
46       lrc->worst_quality = av1_quantizer_to_qindex(lc->max_q);
47       lrc->best_quality = av1_quantizer_to_qindex(lc->min_q);
48       for (int i = 0; i < RATE_FACTOR_LEVELS; ++i) {
49         lrc->rate_correction_factors[i] = 1.0;
50       }
51       lc->target_bandwidth = lc->layer_target_bitrate;
52       lrc->last_q[INTER_FRAME] = lrc->worst_quality;
53       lrc->avg_frame_qindex[INTER_FRAME] = lrc->worst_quality;
54       lrc->avg_frame_qindex[KEY_FRAME] = lrc->worst_quality;
55       lrc->buffer_level =
56           oxcf->starting_buffer_level_ms * lc->target_bandwidth / 1000;
57       lrc->bits_off_target = lrc->buffer_level;
58       // Initialize the cyclic refresh parameters. If spatial layers are used
59       // (i.e., ss_number_layers > 1), these need to be updated per spatial
60       // layer. Cyclic refresh is only applied on base temporal layer.
61       if (svc->number_spatial_layers > 1 && tl == 0) {
62         size_t last_coded_q_map_size;
63         lc->sb_index = 0;
64         lc->actual_num_seg1_blocks = 0;
65         lc->actual_num_seg2_blocks = 0;
66         lc->counter_encode_maxq_scene_change = 0;
67         CHECK_MEM_ERROR(cm, lc->map,
68                         aom_malloc(mi_rows * mi_cols * sizeof(*lc->map)));
69         memset(lc->map, 0, mi_rows * mi_cols);
70         last_coded_q_map_size =
71             mi_rows * mi_cols * sizeof(*lc->last_coded_q_map);
72         CHECK_MEM_ERROR(cm, lc->last_coded_q_map,
73                         aom_malloc(last_coded_q_map_size));
74         assert(MAXQ <= 255);
75         memset(lc->last_coded_q_map, MAXQ, last_coded_q_map_size);
76       }
77     }
78   }
79 }
80 
81 // Update the layer context from a change_config() call.
av1_update_layer_context_change_config(AV1_COMP * const cpi,const int64_t target_bandwidth)82 void av1_update_layer_context_change_config(AV1_COMP *const cpi,
83                                             const int64_t target_bandwidth) {
84   const RATE_CONTROL *const rc = &cpi->rc;
85   SVC *const svc = &cpi->svc;
86   int layer = 0;
87   int64_t spatial_layer_target = 0;
88   float bitrate_alloc = 1.0;
89 
90   for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
91     for (int tl = 0; tl < svc->number_temporal_layers; ++tl) {
92       layer = LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
93       LAYER_CONTEXT *const lc = &svc->layer_context[layer];
94       svc->layer_context[layer].target_bandwidth = lc->layer_target_bitrate;
95     }
96     spatial_layer_target = svc->layer_context[layer].target_bandwidth;
97     for (int tl = 0; tl < svc->number_temporal_layers; ++tl) {
98       LAYER_CONTEXT *const lc =
99           &svc->layer_context[sl * svc->number_temporal_layers + tl];
100       RATE_CONTROL *const lrc = &lc->rc;
101       lc->spatial_layer_target_bandwidth = spatial_layer_target;
102       bitrate_alloc = (float)lc->target_bandwidth / target_bandwidth;
103       lrc->starting_buffer_level =
104           (int64_t)(rc->starting_buffer_level * bitrate_alloc);
105       lrc->optimal_buffer_level =
106           (int64_t)(rc->optimal_buffer_level * bitrate_alloc);
107       lrc->maximum_buffer_size =
108           (int64_t)(rc->maximum_buffer_size * bitrate_alloc);
109       lrc->bits_off_target =
110           AOMMIN(lrc->bits_off_target, lrc->maximum_buffer_size);
111       lrc->buffer_level = AOMMIN(lrc->buffer_level, lrc->maximum_buffer_size);
112       lc->framerate = cpi->framerate / lc->framerate_factor;
113       lrc->avg_frame_bandwidth = (int)(lc->target_bandwidth / lc->framerate);
114       lrc->max_frame_bandwidth = rc->max_frame_bandwidth;
115       lrc->worst_quality = av1_quantizer_to_qindex(lc->max_q);
116       lrc->best_quality = av1_quantizer_to_qindex(lc->min_q);
117     }
118   }
119 }
120 
get_layer_context(AV1_COMP * const cpi)121 static LAYER_CONTEXT *get_layer_context(AV1_COMP *const cpi) {
122   return &cpi->svc.layer_context[cpi->svc.spatial_layer_id *
123                                      cpi->svc.number_temporal_layers +
124                                  cpi->svc.temporal_layer_id];
125 }
126 
av1_update_temporal_layer_framerate(AV1_COMP * const cpi)127 void av1_update_temporal_layer_framerate(AV1_COMP *const cpi) {
128   SVC *const svc = &cpi->svc;
129   LAYER_CONTEXT *const lc = get_layer_context(cpi);
130   RATE_CONTROL *const lrc = &lc->rc;
131   const int tl = svc->temporal_layer_id;
132   lc->framerate = cpi->framerate / lc->framerate_factor;
133   lrc->avg_frame_bandwidth = (int)(lc->target_bandwidth / lc->framerate);
134   lrc->max_frame_bandwidth = cpi->rc.max_frame_bandwidth;
135   // Update the average layer frame size (non-cumulative per-frame-bw).
136   if (tl == 0) {
137     lc->avg_frame_size = lrc->avg_frame_bandwidth;
138   } else {
139     int prev_layer = svc->spatial_layer_id * svc->number_temporal_layers +
140                      svc->temporal_layer_id - 1;
141     LAYER_CONTEXT *const lcprev = &svc->layer_context[prev_layer];
142     const double prev_layer_framerate =
143         cpi->framerate / lcprev->framerate_factor;
144     const int64_t prev_layer_target_bandwidth = lcprev->layer_target_bitrate;
145     lc->avg_frame_size =
146         (int)((lc->target_bandwidth - prev_layer_target_bandwidth) /
147               (lc->framerate - prev_layer_framerate));
148   }
149 }
150 
av1_restore_layer_context(AV1_COMP * const cpi)151 void av1_restore_layer_context(AV1_COMP *const cpi) {
152   GF_GROUP *const gf_group = &cpi->gf_group;
153   SVC *const svc = &cpi->svc;
154   LAYER_CONTEXT *const lc = get_layer_context(cpi);
155   const int old_frame_since_key = cpi->rc.frames_since_key;
156   const int old_frame_to_key = cpi->rc.frames_to_key;
157   // Restore layer rate control.
158   cpi->rc = lc->rc;
159   cpi->oxcf.target_bandwidth = lc->target_bandwidth;
160   gf_group->index = lc->group_index;
161   // Reset the frames_since_key and frames_to_key counters to their values
162   // before the layer restore. Keep these defined for the stream (not layer).
163   cpi->rc.frames_since_key = old_frame_since_key;
164   cpi->rc.frames_to_key = old_frame_to_key;
165   // For spatial-svc, allow cyclic-refresh to be applied on the spatial layers,
166   // for the base temporal layer.
167   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
168       svc->number_spatial_layers > 1 && svc->temporal_layer_id == 0) {
169     CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
170     swap_ptr(&cr->map, &lc->map);
171     swap_ptr(&cr->last_coded_q_map, &lc->last_coded_q_map);
172     cr->sb_index = lc->sb_index;
173     cr->actual_num_seg1_blocks = lc->actual_num_seg1_blocks;
174     cr->actual_num_seg2_blocks = lc->actual_num_seg2_blocks;
175   }
176   svc->skip_nonzeromv_last = 0;
177   svc->skip_nonzeromv_gf = 0;
178   // For each reference (LAST/GOLDEN) set the skip_nonzero_last/gf frame flags.
179   // This is to skip testing nonzero-mv for that reference if it was last
180   // refreshed (i.e., buffer slot holding that reference was refreshed) on the
181   // previous spatial layer at the same time (current_superframe).
182   if (svc->external_ref_frame_config) {
183     int ref_frame_idx = svc->ref_idx[LAST_FRAME - 1];
184     if (svc->buffer_time_index[ref_frame_idx] == svc->current_superframe &&
185         svc->buffer_spatial_layer[ref_frame_idx] == svc->spatial_layer_id - 1)
186       svc->skip_nonzeromv_last = 1;
187     ref_frame_idx = svc->ref_idx[GOLDEN_FRAME - 1];
188     if (svc->buffer_time_index[ref_frame_idx] == svc->current_superframe &&
189         svc->buffer_spatial_layer[ref_frame_idx] == svc->spatial_layer_id - 1)
190       svc->skip_nonzeromv_gf = 1;
191   }
192 }
193 
av1_save_layer_context(AV1_COMP * const cpi)194 void av1_save_layer_context(AV1_COMP *const cpi) {
195   GF_GROUP *const gf_group = &cpi->gf_group;
196   SVC *const svc = &cpi->svc;
197   LAYER_CONTEXT *lc = get_layer_context(cpi);
198   lc->rc = cpi->rc;
199   lc->target_bandwidth = (int)cpi->oxcf.target_bandwidth;
200   lc->group_index = gf_group->index;
201   if (svc->spatial_layer_id == 0) svc->base_framerate = cpi->framerate;
202   // For spatial-svc, allow cyclic-refresh to be applied on the spatial layers,
203   // for the base temporal layer.
204   if (cpi->oxcf.aq_mode == CYCLIC_REFRESH_AQ &&
205       cpi->svc.number_spatial_layers > 1 && svc->temporal_layer_id == 0) {
206     CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
207     signed char *temp = lc->map;
208     uint8_t *temp2 = lc->last_coded_q_map;
209     lc->map = cr->map;
210     cr->map = temp;
211     lc->last_coded_q_map = cr->last_coded_q_map;
212     cr->last_coded_q_map = temp2;
213     lc->sb_index = cr->sb_index;
214     lc->actual_num_seg1_blocks = cr->actual_num_seg1_blocks;
215     lc->actual_num_seg2_blocks = cr->actual_num_seg2_blocks;
216   }
217   // For any buffer slot that is refreshed, update it with
218   // the spatial_layer_id and the current_superframe.
219   if (cpi->common.current_frame.frame_type == KEY_FRAME) {
220     // All slots are refreshed on KEY.
221     for (unsigned int i = 0; i < REF_FRAMES; i++) {
222       svc->buffer_time_index[i] = svc->current_superframe;
223       svc->buffer_spatial_layer[i] = svc->spatial_layer_id;
224     }
225   } else if (cpi->svc.external_ref_frame_config) {
226     for (unsigned int i = 0; i < INTER_REFS_PER_FRAME; i++) {
227       int ref_frame_map_idx = svc->ref_idx[i];
228       if (cpi->svc.refresh[ref_frame_map_idx]) {
229         svc->buffer_time_index[ref_frame_map_idx] = svc->current_superframe;
230         svc->buffer_spatial_layer[ref_frame_map_idx] = svc->spatial_layer_id;
231       }
232     }
233   }
234   if (svc->spatial_layer_id == svc->number_spatial_layers - 1)
235     svc->current_superframe++;
236 }
237 
av1_free_svc_cyclic_refresh(AV1_COMP * const cpi)238 void av1_free_svc_cyclic_refresh(AV1_COMP *const cpi) {
239   SVC *const svc = &cpi->svc;
240   for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
241     for (int tl = 0; tl < svc->number_temporal_layers; ++tl) {
242       int layer = LAYER_IDS_TO_IDX(sl, tl, svc->number_temporal_layers);
243       LAYER_CONTEXT *const lc = &svc->layer_context[layer];
244       if (lc->map) aom_free(lc->map);
245       if (lc->last_coded_q_map) aom_free(lc->last_coded_q_map);
246     }
247   }
248 }
249 
250 // Reset on key frame: reset counters, references and buffer updates.
av1_svc_reset_temporal_layers(AV1_COMP * const cpi,int is_key)251 void av1_svc_reset_temporal_layers(AV1_COMP *const cpi, int is_key) {
252   SVC *const svc = &cpi->svc;
253   LAYER_CONTEXT *lc = NULL;
254   for (int sl = 0; sl < svc->number_spatial_layers; ++sl) {
255     for (int tl = 0; tl < svc->number_temporal_layers; ++tl) {
256       lc = &cpi->svc.layer_context[sl * svc->number_temporal_layers + tl];
257       if (is_key) lc->frames_from_key_frame = 0;
258     }
259   }
260   av1_update_temporal_layer_framerate(cpi);
261   av1_restore_layer_context(cpi);
262 }
263 
get_layer_resolution(const int width_org,const int height_org,const int num,const int den,int * width_out,int * height_out)264 static void get_layer_resolution(const int width_org, const int height_org,
265                                  const int num, const int den, int *width_out,
266                                  int *height_out) {
267   int w, h;
268   if (width_out == NULL || height_out == NULL || den == 0) return;
269   w = width_org * num / den;
270   h = height_org * num / den;
271   // Make height and width even.
272   w += w % 2;
273   h += h % 2;
274   *width_out = w;
275   *height_out = h;
276 }
277 
av1_one_pass_cbr_svc_start_layer(AV1_COMP * const cpi)278 void av1_one_pass_cbr_svc_start_layer(AV1_COMP *const cpi) {
279   SVC *const svc = &cpi->svc;
280   LAYER_CONTEXT *lc = NULL;
281   int width = 0, height = 0;
282   lc = &svc->layer_context[svc->spatial_layer_id * svc->number_temporal_layers +
283                            svc->temporal_layer_id];
284   get_layer_resolution(cpi->oxcf.width, cpi->oxcf.height,
285                        lc->scaling_factor_num, lc->scaling_factor_den, &width,
286                        &height);
287   av1_set_size_literal(cpi, width, height);
288 }
289