• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2019, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #include "aom_ports/system_state.h"
13 
14 #include "av1/encoder/encoder.h"
15 #include "av1/encoder/level.h"
16 
17 #define UNDEFINED_LEVEL                                                 \
18   {                                                                     \
19     .level = SEQ_LEVEL_MAX, .max_picture_size = 0, .max_h_size = 0,     \
20     .max_v_size = 0, .max_display_rate = 0, .max_decode_rate = 0,       \
21     .max_header_rate = 0, .main_mbps = 0, .high_mbps = 0, .main_cr = 0, \
22     .high_cr = 0, .max_tiles = 0, .max_tile_cols = 0                    \
23   }
24 
25 static const AV1LevelSpec av1_level_defs[SEQ_LEVELS] = {
26   { .level = SEQ_LEVEL_2_0,
27     .max_picture_size = 147456,
28     .max_h_size = 2048,
29     .max_v_size = 1152,
30     .max_display_rate = 4423680L,
31     .max_decode_rate = 5529600L,
32     .max_header_rate = 150,
33     .main_mbps = 1.5,
34     .high_mbps = 0,
35     .main_cr = 2.0,
36     .high_cr = 0,
37     .max_tiles = 8,
38     .max_tile_cols = 4 },
39   { .level = SEQ_LEVEL_2_1,
40     .max_picture_size = 278784,
41     .max_h_size = 2816,
42     .max_v_size = 1584,
43     .max_display_rate = 8363520L,
44     .max_decode_rate = 10454400L,
45     .max_header_rate = 150,
46     .main_mbps = 3.0,
47     .high_mbps = 0,
48     .main_cr = 2.0,
49     .high_cr = 0,
50     .max_tiles = 8,
51     .max_tile_cols = 4 },
52   UNDEFINED_LEVEL,
53   UNDEFINED_LEVEL,
54   { .level = SEQ_LEVEL_3_0,
55     .max_picture_size = 665856,
56     .max_h_size = 4352,
57     .max_v_size = 2448,
58     .max_display_rate = 19975680L,
59     .max_decode_rate = 24969600L,
60     .max_header_rate = 150,
61     .main_mbps = 6.0,
62     .high_mbps = 0,
63     .main_cr = 2.0,
64     .high_cr = 0,
65     .max_tiles = 16,
66     .max_tile_cols = 6 },
67   { .level = SEQ_LEVEL_3_1,
68     .max_picture_size = 1065024,
69     .max_h_size = 5504,
70     .max_v_size = 3096,
71     .max_display_rate = 31950720L,
72     .max_decode_rate = 39938400L,
73     .max_header_rate = 150,
74     .main_mbps = 10.0,
75     .high_mbps = 0,
76     .main_cr = 2.0,
77     .high_cr = 0,
78     .max_tiles = 16,
79     .max_tile_cols = 6 },
80   UNDEFINED_LEVEL,
81   UNDEFINED_LEVEL,
82   { .level = SEQ_LEVEL_4_0,
83     .max_picture_size = 2359296,
84     .max_h_size = 6144,
85     .max_v_size = 3456,
86     .max_display_rate = 70778880L,
87     .max_decode_rate = 77856768L,
88     .max_header_rate = 300,
89     .main_mbps = 12.0,
90     .high_mbps = 30.0,
91     .main_cr = 4.0,
92     .high_cr = 4.0,
93     .max_tiles = 32,
94     .max_tile_cols = 8 },
95   { .level = SEQ_LEVEL_4_1,
96     .max_picture_size = 2359296,
97     .max_h_size = 6144,
98     .max_v_size = 3456,
99     .max_display_rate = 141557760L,
100     .max_decode_rate = 155713536L,
101     .max_header_rate = 300,
102     .main_mbps = 20.0,
103     .high_mbps = 50.0,
104     .main_cr = 4.0,
105     .high_cr = 4.0,
106     .max_tiles = 32,
107     .max_tile_cols = 8 },
108   UNDEFINED_LEVEL,
109   UNDEFINED_LEVEL,
110   { .level = SEQ_LEVEL_5_0,
111     .max_picture_size = 8912896,
112     .max_h_size = 8192,
113     .max_v_size = 4352,
114     .max_display_rate = 267386880L,
115     .max_decode_rate = 273715200L,
116     .max_header_rate = 300,
117     .main_mbps = 30.0,
118     .high_mbps = 100.0,
119     .main_cr = 6.0,
120     .high_cr = 4.0,
121     .max_tiles = 64,
122     .max_tile_cols = 8 },
123   { .level = SEQ_LEVEL_5_1,
124     .max_picture_size = 8912896,
125     .max_h_size = 8192,
126     .max_v_size = 4352,
127     .max_display_rate = 534773760L,
128     .max_decode_rate = 547430400L,
129     .max_header_rate = 300,
130     .main_mbps = 40.0,
131     .high_mbps = 160.0,
132     .main_cr = 8.0,
133     .high_cr = 4.0,
134     .max_tiles = 64,
135     .max_tile_cols = 8 },
136   { .level = SEQ_LEVEL_5_2,
137     .max_picture_size = 8912896,
138     .max_h_size = 8192,
139     .max_v_size = 4352,
140     .max_display_rate = 1069547520L,
141     .max_decode_rate = 1094860800L,
142     .max_header_rate = 300,
143     .main_mbps = 60.0,
144     .high_mbps = 240.0,
145     .main_cr = 8.0,
146     .high_cr = 4.0,
147     .max_tiles = 64,
148     .max_tile_cols = 8 },
149   { .level = SEQ_LEVEL_5_3,
150     .max_picture_size = 8912896,
151     .max_h_size = 8192,
152     .max_v_size = 4352,
153     .max_display_rate = 1069547520L,
154     .max_decode_rate = 1176502272L,
155     .max_header_rate = 300,
156     .main_mbps = 60.0,
157     .high_mbps = 240.0,
158     .main_cr = 8.0,
159     .high_cr = 4.0,
160     .max_tiles = 64,
161     .max_tile_cols = 8 },
162   { .level = SEQ_LEVEL_6_0,
163     .max_picture_size = 35651584,
164     .max_h_size = 16384,
165     .max_v_size = 8704,
166     .max_display_rate = 1069547520L,
167     .max_decode_rate = 1176502272L,
168     .max_header_rate = 300,
169     .main_mbps = 60.0,
170     .high_mbps = 240.0,
171     .main_cr = 8.0,
172     .high_cr = 4.0,
173     .max_tiles = 128,
174     .max_tile_cols = 16 },
175   { .level = SEQ_LEVEL_6_1,
176     .max_picture_size = 35651584,
177     .max_h_size = 16384,
178     .max_v_size = 8704,
179     .max_display_rate = 2139095040L,
180     .max_decode_rate = 2189721600L,
181     .max_header_rate = 300,
182     .main_mbps = 100.0,
183     .high_mbps = 480.0,
184     .main_cr = 8.0,
185     .high_cr = 4.0,
186     .max_tiles = 128,
187     .max_tile_cols = 16 },
188   { .level = SEQ_LEVEL_6_2,
189     .max_picture_size = 35651584,
190     .max_h_size = 16384,
191     .max_v_size = 8704,
192     .max_display_rate = 4278190080L,
193     .max_decode_rate = 4379443200L,
194     .max_header_rate = 300,
195     .main_mbps = 160.0,
196     .high_mbps = 800.0,
197     .main_cr = 8.0,
198     .high_cr = 4.0,
199     .max_tiles = 128,
200     .max_tile_cols = 16 },
201   { .level = SEQ_LEVEL_6_3,
202     .max_picture_size = 35651584,
203     .max_h_size = 16384,
204     .max_v_size = 8704,
205     .max_display_rate = 4278190080L,
206     .max_decode_rate = 4706009088L,
207     .max_header_rate = 300,
208     .main_mbps = 160.0,
209     .high_mbps = 800.0,
210     .main_cr = 8.0,
211     .high_cr = 4.0,
212     .max_tiles = 128,
213     .max_tile_cols = 16 },
214   UNDEFINED_LEVEL,
215   UNDEFINED_LEVEL,
216   UNDEFINED_LEVEL,
217   UNDEFINED_LEVEL,
218 };
219 
220 typedef enum {
221   LUMA_PIC_SIZE_TOO_LARGE,
222   LUMA_PIC_H_SIZE_TOO_LARGE,
223   LUMA_PIC_V_SIZE_TOO_LARGE,
224   LUMA_PIC_H_SIZE_TOO_SMALL,
225   LUMA_PIC_V_SIZE_TOO_SMALL,
226   TOO_MANY_TILE_COLUMNS,
227   TOO_MANY_TILES,
228   TILE_RATE_TOO_HIGH,
229   TILE_TOO_LARGE,
230   SUPERRES_TILE_WIDTH_TOO_LARGE,
231   CROPPED_TILE_WIDTH_TOO_SMALL,
232   CROPPED_TILE_HEIGHT_TOO_SMALL,
233   TILE_WIDTH_INVALID,
234   FRAME_HEADER_RATE_TOO_HIGH,
235   DISPLAY_RATE_TOO_HIGH,
236   DECODE_RATE_TOO_HIGH,
237   CR_TOO_SMALL,
238   TILE_SIZE_HEADER_RATE_TOO_HIGH,
239   BITRATE_TOO_HIGH,
240   DECODER_MODEL_FAIL,
241 
242   TARGET_LEVEL_FAIL_IDS,
243   TARGET_LEVEL_OK,
244 } TARGET_LEVEL_FAIL_ID;
245 
246 static const char *level_fail_messages[TARGET_LEVEL_FAIL_IDS] = {
247   "The picture size is too large.",
248   "The picture width is too large.",
249   "The picture height is too large.",
250   "The picture width is too small.",
251   "The picture height is too small.",
252   "Too many tile columns are used.",
253   "Too many tiles are used.",
254   "The tile rate is too high.",
255   "The tile size is too large.",
256   "The superres tile width is too large.",
257   "The cropped tile width is less than 8.",
258   "The cropped tile height is less than 8.",
259   "The tile width is invalid.",
260   "The frame header rate is too high.",
261   "The display luma sample rate is too high.",
262   "The decoded luma sample rate is too high.",
263   "The compression ratio is too small.",
264   "The product of max tile size and header rate is too high.",
265   "The bitrate is too high.",
266   "The decoder model fails.",
267 };
268 
get_max_bitrate(const AV1LevelSpec * const level_spec,int tier,BITSTREAM_PROFILE profile)269 static double get_max_bitrate(const AV1LevelSpec *const level_spec, int tier,
270                               BITSTREAM_PROFILE profile) {
271   if (level_spec->level < SEQ_LEVEL_4_0) tier = 0;
272   const double bitrate_basis =
273       (tier ? level_spec->high_mbps : level_spec->main_mbps) * 1e6;
274   const double bitrate_profile_factor =
275       profile == PROFILE_0 ? 1.0 : (profile == PROFILE_1 ? 2.0 : 3.0);
276   return bitrate_basis * bitrate_profile_factor;
277 }
278 
av1_get_max_bitrate_for_level(AV1_LEVEL level_index,int tier,BITSTREAM_PROFILE profile)279 double av1_get_max_bitrate_for_level(AV1_LEVEL level_index, int tier,
280                                      BITSTREAM_PROFILE profile) {
281   assert(is_valid_seq_level_idx(level_index));
282   return get_max_bitrate(&av1_level_defs[level_index], tier, profile);
283 }
284 
av1_get_max_tiles_for_level(AV1_LEVEL level_index,int * const max_tiles,int * const max_tile_cols)285 void av1_get_max_tiles_for_level(AV1_LEVEL level_index, int *const max_tiles,
286                                  int *const max_tile_cols) {
287   assert(is_valid_seq_level_idx(level_index));
288   const AV1LevelSpec *const level_spec = &av1_level_defs[level_index];
289   *max_tiles = level_spec->max_tiles;
290   *max_tile_cols = level_spec->max_tile_cols;
291 }
292 
293 // We assume time t to be valid if and only if t >= 0.0.
294 // So INVALID_TIME can be defined as anything less than 0.
295 #define INVALID_TIME (-1.0)
296 
297 // This corresponds to "free_buffer" in the spec.
release_buffer(DECODER_MODEL * const decoder_model,int idx)298 static void release_buffer(DECODER_MODEL *const decoder_model, int idx) {
299   assert(idx >= 0 && idx < BUFFER_POOL_MAX_SIZE);
300   FRAME_BUFFER *const this_buffer = &decoder_model->frame_buffer_pool[idx];
301   this_buffer->decoder_ref_count = 0;
302   this_buffer->player_ref_count = 0;
303   this_buffer->display_index = -1;
304   this_buffer->presentation_time = INVALID_TIME;
305 }
306 
initialize_buffer_pool(DECODER_MODEL * const decoder_model)307 static void initialize_buffer_pool(DECODER_MODEL *const decoder_model) {
308   for (int i = 0; i < BUFFER_POOL_MAX_SIZE; ++i) {
309     release_buffer(decoder_model, i);
310   }
311   for (int i = 0; i < REF_FRAMES; ++i) {
312     decoder_model->vbi[i] = -1;
313   }
314 }
315 
get_free_buffer(DECODER_MODEL * const decoder_model)316 static int get_free_buffer(DECODER_MODEL *const decoder_model) {
317   for (int i = 0; i < BUFFER_POOL_MAX_SIZE; ++i) {
318     const FRAME_BUFFER *const this_buffer =
319         &decoder_model->frame_buffer_pool[i];
320     if (this_buffer->decoder_ref_count == 0 &&
321         this_buffer->player_ref_count == 0)
322       return i;
323   }
324   return -1;
325 }
326 
update_ref_buffers(DECODER_MODEL * const decoder_model,int idx,int refresh_frame_flags)327 static void update_ref_buffers(DECODER_MODEL *const decoder_model, int idx,
328                                int refresh_frame_flags) {
329   FRAME_BUFFER *const this_buffer = &decoder_model->frame_buffer_pool[idx];
330   for (int i = 0; i < REF_FRAMES; ++i) {
331     if (refresh_frame_flags & (1 << i)) {
332       const int pre_idx = decoder_model->vbi[i];
333       if (pre_idx != -1) {
334         --decoder_model->frame_buffer_pool[pre_idx].decoder_ref_count;
335       }
336       decoder_model->vbi[i] = idx;
337       ++this_buffer->decoder_ref_count;
338     }
339   }
340 }
341 
342 // The time (in seconds) required to decode a frame.
time_to_decode_frame(const AV1_COMMON * const cm,int64_t max_decode_rate)343 static double time_to_decode_frame(const AV1_COMMON *const cm,
344                                    int64_t max_decode_rate) {
345   if (cm->show_existing_frame) return 0.0;
346 
347   const FRAME_TYPE frame_type = cm->current_frame.frame_type;
348   int luma_samples = 0;
349   if (frame_type == KEY_FRAME || frame_type == INTRA_ONLY_FRAME) {
350     luma_samples = cm->superres_upscaled_width * cm->height;
351   } else {
352     const int spatial_layer_dimensions_present_flag = 0;
353     if (spatial_layer_dimensions_present_flag) {
354       assert(0 && "Spatial layer dimensions not supported yet.");
355     } else {
356       const SequenceHeader *const seq_params = &cm->seq_params;
357       const int max_frame_width = seq_params->max_frame_width;
358       const int max_frame_height = seq_params->max_frame_height;
359       luma_samples = max_frame_width * max_frame_height;
360     }
361   }
362 
363   return luma_samples / (double)max_decode_rate;
364 }
365 
366 // Release frame buffers that are no longer needed for decode or display.
367 // It corresponds to "start_decode_at_removal_time" in the spec.
release_processed_frames(DECODER_MODEL * const decoder_model,double removal_time)368 static void release_processed_frames(DECODER_MODEL *const decoder_model,
369                                      double removal_time) {
370   for (int i = 0; i < BUFFER_POOL_MAX_SIZE; ++i) {
371     FRAME_BUFFER *const this_buffer = &decoder_model->frame_buffer_pool[i];
372     if (this_buffer->player_ref_count > 0) {
373       if (this_buffer->presentation_time >= 0.0 &&
374           this_buffer->presentation_time <= removal_time) {
375         this_buffer->player_ref_count = 0;
376         if (this_buffer->decoder_ref_count == 0) {
377           release_buffer(decoder_model, i);
378         }
379       }
380     }
381   }
382 }
383 
frames_in_buffer_pool(const DECODER_MODEL * const decoder_model)384 static int frames_in_buffer_pool(const DECODER_MODEL *const decoder_model) {
385   int frames_in_pool = 0;
386   for (int i = 0; i < BUFFER_POOL_MAX_SIZE; ++i) {
387     const FRAME_BUFFER *const this_buffer =
388         &decoder_model->frame_buffer_pool[i];
389     if (this_buffer->decoder_ref_count > 0 ||
390         this_buffer->player_ref_count > 0) {
391       ++frames_in_pool;
392     }
393   }
394   return frames_in_pool;
395 }
396 
get_presentation_time(const DECODER_MODEL * const decoder_model,int display_index)397 static double get_presentation_time(const DECODER_MODEL *const decoder_model,
398                                     int display_index) {
399   if (decoder_model->mode == SCHEDULE_MODE) {
400     assert(0 && "SCHEDULE_MODE NOT SUPPORTED");
401     return INVALID_TIME;
402   } else {
403     const double initial_presentation_delay =
404         decoder_model->initial_presentation_delay;
405     // Can't decide presentation time until the initial presentation delay is
406     // known.
407     if (initial_presentation_delay < 0.0) return INVALID_TIME;
408 
409     return initial_presentation_delay +
410            display_index * decoder_model->num_ticks_per_picture *
411                decoder_model->display_clock_tick;
412   }
413 }
414 
415 #define MAX_TIME 1e16
time_next_buffer_is_free(const DECODER_MODEL * const decoder_model)416 double time_next_buffer_is_free(const DECODER_MODEL *const decoder_model) {
417   if (decoder_model->num_decoded_frame == 0) {
418     return (double)decoder_model->decoder_buffer_delay / 90000.0;
419   }
420 
421   double buf_free_time = MAX_TIME;
422   for (int i = 0; i < BUFFER_POOL_MAX_SIZE; ++i) {
423     const FRAME_BUFFER *const this_buffer =
424         &decoder_model->frame_buffer_pool[i];
425     if (this_buffer->decoder_ref_count == 0) {
426       if (this_buffer->player_ref_count == 0) {
427         return decoder_model->current_time;
428       }
429       const double presentation_time = this_buffer->presentation_time;
430       if (presentation_time >= 0.0 && presentation_time < buf_free_time) {
431         buf_free_time = presentation_time;
432       }
433     }
434   }
435   return buf_free_time < MAX_TIME ? buf_free_time : INVALID_TIME;
436 }
437 #undef MAX_TIME
438 
get_removal_time(const DECODER_MODEL * const decoder_model)439 static double get_removal_time(const DECODER_MODEL *const decoder_model) {
440   if (decoder_model->mode == SCHEDULE_MODE) {
441     assert(0 && "SCHEDULE_MODE IS NOT SUPPORTED YET");
442     return INVALID_TIME;
443   } else {
444     return time_next_buffer_is_free(decoder_model);
445   }
446 }
447 
av1_decoder_model_print_status(const DECODER_MODEL * const decoder_model)448 void av1_decoder_model_print_status(const DECODER_MODEL *const decoder_model) {
449   printf(
450       "\n status %d, num_frame %3d, num_decoded_frame %3d, "
451       "num_shown_frame %3d, current time %6.2f, frames in buffer %2d, "
452       "presentation delay %6.2f, total interval %6.2f\n",
453       decoder_model->status, decoder_model->num_frame,
454       decoder_model->num_decoded_frame, decoder_model->num_shown_frame,
455       decoder_model->current_time, frames_in_buffer_pool(decoder_model),
456       decoder_model->initial_presentation_delay,
457       decoder_model->dfg_interval_queue.total_interval);
458   for (int i = 0; i < 10; ++i) {
459     const FRAME_BUFFER *const this_buffer =
460         &decoder_model->frame_buffer_pool[i];
461     printf("buffer %d, decode count %d, display count %d, present time %6.4f\n",
462            i, this_buffer->decoder_ref_count, this_buffer->player_ref_count,
463            this_buffer->presentation_time);
464   }
465 }
466 
467 // op_index is the operating point index.
av1_decoder_model_init(const AV1_COMP * const cpi,AV1_LEVEL level,int op_index,DECODER_MODEL * const decoder_model)468 void av1_decoder_model_init(const AV1_COMP *const cpi, AV1_LEVEL level,
469                             int op_index, DECODER_MODEL *const decoder_model) {
470   aom_clear_system_state();
471 
472   decoder_model->status = DECODER_MODEL_OK;
473   decoder_model->level = level;
474 
475   const AV1_COMMON *const cm = &cpi->common;
476   const SequenceHeader *const seq_params = &cm->seq_params;
477   decoder_model->bit_rate = get_max_bitrate(
478       av1_level_defs + level, seq_params->tier[op_index], seq_params->profile);
479 
480   // TODO(huisu or anyone): implement SCHEDULE_MODE.
481   decoder_model->mode = RESOURCE_MODE;
482   decoder_model->encoder_buffer_delay = 20000;
483   decoder_model->decoder_buffer_delay = 70000;
484   decoder_model->is_low_delay_mode = false;
485 
486   decoder_model->first_bit_arrival_time = 0.0;
487   decoder_model->last_bit_arrival_time = 0.0;
488   decoder_model->coded_bits = 0;
489 
490   decoder_model->removal_time = INVALID_TIME;
491   decoder_model->presentation_time = INVALID_TIME;
492   decoder_model->decode_samples = 0;
493   decoder_model->display_samples = 0;
494   decoder_model->max_decode_rate = 0.0;
495   decoder_model->max_display_rate = 0.0;
496 
497   decoder_model->num_frame = -1;
498   decoder_model->num_decoded_frame = -1;
499   decoder_model->num_shown_frame = -1;
500   decoder_model->current_time = 0.0;
501 
502   initialize_buffer_pool(decoder_model);
503 
504   DFG_INTERVAL_QUEUE *const dfg_interval_queue =
505       &decoder_model->dfg_interval_queue;
506   dfg_interval_queue->total_interval = 0.0;
507   dfg_interval_queue->head = 0;
508   dfg_interval_queue->size = 0;
509 
510   if (seq_params->timing_info_present) {
511     decoder_model->num_ticks_per_picture =
512         seq_params->timing_info.num_ticks_per_picture;
513     decoder_model->display_clock_tick =
514         seq_params->timing_info.num_units_in_display_tick /
515         seq_params->timing_info.time_scale;
516   } else {
517     decoder_model->num_ticks_per_picture = 1;
518     decoder_model->display_clock_tick = 1.0 / cpi->framerate;
519   }
520 
521   decoder_model->initial_display_delay =
522       seq_params->op_params[op_index].initial_display_delay;
523   decoder_model->initial_presentation_delay = INVALID_TIME;
524   decoder_model->decode_rate = av1_level_defs[level].max_decode_rate;
525 }
526 
av1_decoder_model_process_frame(const AV1_COMP * const cpi,size_t coded_bits,DECODER_MODEL * const decoder_model)527 void av1_decoder_model_process_frame(const AV1_COMP *const cpi,
528                                      size_t coded_bits,
529                                      DECODER_MODEL *const decoder_model) {
530   if (!decoder_model || decoder_model->status != DECODER_MODEL_OK) return;
531 
532   aom_clear_system_state();
533 
534   const AV1_COMMON *const cm = &cpi->common;
535   const int luma_pic_size = cm->superres_upscaled_width * cm->height;
536   const int show_existing_frame = cm->show_existing_frame;
537   const int show_frame = cm->show_frame || show_existing_frame;
538   ++decoder_model->num_frame;
539   if (!show_existing_frame) ++decoder_model->num_decoded_frame;
540   if (show_frame) ++decoder_model->num_shown_frame;
541   decoder_model->coded_bits += coded_bits;
542 
543   int display_idx = -1;
544   if (show_existing_frame) {
545     display_idx = decoder_model->vbi[cpi->existing_fb_idx_to_show];
546     if (display_idx < 0) {
547       decoder_model->status = DECODE_EXISTING_FRAME_BUF_EMPTY;
548       return;
549     }
550     if (decoder_model->frame_buffer_pool[display_idx].frame_type == KEY_FRAME) {
551       update_ref_buffers(decoder_model, display_idx, 0xFF);
552     }
553   } else {
554     const double removal_time = get_removal_time(decoder_model);
555     if (removal_time < 0.0) {
556       decoder_model->status = DECODE_FRAME_BUF_UNAVAILABLE;
557       return;
558     }
559 
560     const int previous_decode_samples = decoder_model->decode_samples;
561     const double previous_removal_time = decoder_model->removal_time;
562     assert(previous_removal_time < removal_time);
563     decoder_model->removal_time = removal_time;
564     decoder_model->decode_samples = luma_pic_size;
565     const double this_decode_rate =
566         previous_decode_samples / (removal_time - previous_removal_time);
567     decoder_model->max_decode_rate =
568         AOMMAX(decoder_model->max_decode_rate, this_decode_rate);
569 
570     // A frame with show_existing_frame being false indicates the end of a DFG.
571     // Update the bits arrival time of this DFG.
572     const double buffer_delay = (decoder_model->encoder_buffer_delay +
573                                  decoder_model->decoder_buffer_delay) /
574                                 90000.0;
575     const double latest_arrival_time = removal_time - buffer_delay;
576     decoder_model->first_bit_arrival_time =
577         AOMMAX(decoder_model->last_bit_arrival_time, latest_arrival_time);
578     decoder_model->last_bit_arrival_time =
579         decoder_model->first_bit_arrival_time +
580         (double)decoder_model->coded_bits / decoder_model->bit_rate;
581     // Smoothing buffer underflows if the last bit arrives after the removal
582     // time.
583     if (decoder_model->last_bit_arrival_time > removal_time &&
584         !decoder_model->is_low_delay_mode) {
585       decoder_model->status = SMOOTHING_BUFFER_UNDERFLOW;
586       return;
587     }
588     // Reset the coded bits for the next DFG.
589     decoder_model->coded_bits = 0;
590 
591     // Check if the smoothing buffer overflows.
592     DFG_INTERVAL_QUEUE *const queue = &decoder_model->dfg_interval_queue;
593     if (queue->size >= DFG_INTERVAL_QUEUE_SIZE) {
594       assert(0);
595     }
596     const double first_bit_arrival_time = decoder_model->first_bit_arrival_time;
597     const double last_bit_arrival_time = decoder_model->last_bit_arrival_time;
598     // Remove the DFGs with removal time earlier than last_bit_arrival_time.
599     while (queue->buf[queue->head].removal_time <= last_bit_arrival_time &&
600            queue->size > 0) {
601       if (queue->buf[queue->head].removal_time - first_bit_arrival_time +
602               queue->total_interval >
603           1.0) {
604         decoder_model->status = SMOOTHING_BUFFER_OVERFLOW;
605         return;
606       }
607       queue->total_interval -= queue->buf[queue->head].last_bit_arrival_time -
608                                queue->buf[queue->head].first_bit_arrival_time;
609       queue->head = (queue->head + 1) % DFG_INTERVAL_QUEUE_SIZE;
610       --queue->size;
611     }
612     // Push current DFG into the queue.
613     const int queue_index =
614         (queue->head + queue->size++) % DFG_INTERVAL_QUEUE_SIZE;
615     queue->buf[queue_index].first_bit_arrival_time = first_bit_arrival_time;
616     queue->buf[queue_index].last_bit_arrival_time = last_bit_arrival_time;
617     queue->buf[queue_index].removal_time = removal_time;
618     queue->total_interval += last_bit_arrival_time - first_bit_arrival_time;
619     // The smoothing buffer can hold at most "bit_rate" bits, which is
620     // equivalent to 1 second of total interval.
621     if (queue->total_interval > 1.0) {
622       decoder_model->status = SMOOTHING_BUFFER_OVERFLOW;
623       return;
624     }
625 
626     release_processed_frames(decoder_model, removal_time);
627     decoder_model->current_time =
628         removal_time + time_to_decode_frame(cm, decoder_model->decode_rate);
629 
630     const int cfbi = get_free_buffer(decoder_model);
631     if (cfbi < 0) {
632       decoder_model->status = DECODE_FRAME_BUF_UNAVAILABLE;
633       return;
634     }
635     const CurrentFrame *const current_frame = &cm->current_frame;
636     decoder_model->frame_buffer_pool[cfbi].frame_type =
637         cm->current_frame.frame_type;
638     display_idx = cfbi;
639     update_ref_buffers(decoder_model, cfbi, current_frame->refresh_frame_flags);
640 
641     if (decoder_model->initial_presentation_delay < 0.0) {
642       // Display can begin after required number of frames have been buffered.
643       if (frames_in_buffer_pool(decoder_model) >=
644           decoder_model->initial_display_delay) {
645         decoder_model->initial_presentation_delay = decoder_model->current_time;
646         // Update presentation time for each shown frame in the frame buffer.
647         for (int i = 0; i < BUFFER_POOL_MAX_SIZE; ++i) {
648           FRAME_BUFFER *const this_buffer =
649               &decoder_model->frame_buffer_pool[i];
650           if (this_buffer->player_ref_count == 0) continue;
651           assert(this_buffer->display_index >= 0);
652           this_buffer->presentation_time =
653               get_presentation_time(decoder_model, this_buffer->display_index);
654         }
655       }
656     }
657   }
658 
659   // Display.
660   if (show_frame) {
661     assert(display_idx >= 0 && display_idx < BUFFER_POOL_MAX_SIZE);
662     FRAME_BUFFER *const this_buffer =
663         &decoder_model->frame_buffer_pool[display_idx];
664     ++this_buffer->player_ref_count;
665     this_buffer->display_index = decoder_model->num_shown_frame;
666     const double presentation_time =
667         get_presentation_time(decoder_model, this_buffer->display_index);
668     this_buffer->presentation_time = presentation_time;
669     if (presentation_time >= 0.0 &&
670         decoder_model->current_time > presentation_time) {
671       decoder_model->status = DISPLAY_FRAME_LATE;
672       return;
673     }
674 
675     const int previous_display_samples = decoder_model->display_samples;
676     const double previous_presentation_time = decoder_model->presentation_time;
677     decoder_model->display_samples = luma_pic_size;
678     decoder_model->presentation_time = presentation_time;
679     if (presentation_time >= 0.0 && previous_presentation_time >= 0.0) {
680       assert(previous_presentation_time < presentation_time);
681       const double this_display_rate =
682           previous_display_samples /
683           (presentation_time - previous_presentation_time);
684       decoder_model->max_display_rate =
685           AOMMAX(decoder_model->max_display_rate, this_display_rate);
686     }
687   }
688 }
689 
av1_init_level_info(AV1_COMP * cpi)690 void av1_init_level_info(AV1_COMP *cpi) {
691   for (int op_index = 0; op_index < MAX_NUM_OPERATING_POINTS; ++op_index) {
692     AV1LevelInfo *const this_level_info =
693         cpi->level_params.level_info[op_index];
694     if (!this_level_info) continue;
695     memset(this_level_info, 0, sizeof(*this_level_info));
696     AV1LevelSpec *const level_spec = &this_level_info->level_spec;
697     level_spec->level = SEQ_LEVEL_MAX;
698     AV1LevelStats *const level_stats = &this_level_info->level_stats;
699     level_stats->min_cropped_tile_width = INT_MAX;
700     level_stats->min_cropped_tile_height = INT_MAX;
701     level_stats->min_frame_width = INT_MAX;
702     level_stats->min_frame_height = INT_MAX;
703     level_stats->tile_width_is_valid = 1;
704     level_stats->min_cr = 1e8;
705 
706     FrameWindowBuffer *const frame_window_buffer =
707         &this_level_info->frame_window_buffer;
708     frame_window_buffer->num = 0;
709     frame_window_buffer->start = 0;
710 
711     const AV1_COMMON *const cm = &cpi->common;
712     const int upscaled_width = cm->superres_upscaled_width;
713     const int height = cm->height;
714     const int pic_size = upscaled_width * height;
715     for (AV1_LEVEL level = SEQ_LEVEL_2_0; level < SEQ_LEVELS; ++level) {
716       DECODER_MODEL *const this_model = &this_level_info->decoder_models[level];
717       const AV1LevelSpec *const spec = &av1_level_defs[level];
718       if (upscaled_width > spec->max_h_size || height > spec->max_v_size ||
719           pic_size > spec->max_picture_size) {
720         // Turn off decoder model for this level as the frame size already
721         // exceeds level constraints.
722         this_model->status = DECODER_MODEL_DISABLED;
723       } else {
724         av1_decoder_model_init(cpi, level, op_index, this_model);
725       }
726     }
727   }
728 }
729 
get_min_cr(const AV1LevelSpec * const level_spec,int tier,int is_still_picture,int64_t decoded_sample_rate)730 static double get_min_cr(const AV1LevelSpec *const level_spec, int tier,
731                          int is_still_picture, int64_t decoded_sample_rate) {
732   if (is_still_picture) return 0.8;
733   if (level_spec->level < SEQ_LEVEL_4_0) tier = 0;
734   const double min_cr_basis = tier ? level_spec->high_cr : level_spec->main_cr;
735   const double speed_adj =
736       (double)decoded_sample_rate / level_spec->max_display_rate;
737   return AOMMAX(min_cr_basis * speed_adj, 0.8);
738 }
739 
av1_get_min_cr_for_level(AV1_LEVEL level_index,int tier,int is_still_picture)740 double av1_get_min_cr_for_level(AV1_LEVEL level_index, int tier,
741                                 int is_still_picture) {
742   assert(is_valid_seq_level_idx(level_index));
743   const AV1LevelSpec *const level_spec = &av1_level_defs[level_index];
744   return get_min_cr(level_spec, tier, is_still_picture,
745                     level_spec->max_decode_rate);
746 }
747 
get_temporal_parallel_params(int scalability_mode_idc,int * temporal_parallel_num,int * temporal_parallel_denom)748 static void get_temporal_parallel_params(int scalability_mode_idc,
749                                          int *temporal_parallel_num,
750                                          int *temporal_parallel_denom) {
751   if (scalability_mode_idc < 0) {
752     *temporal_parallel_num = 1;
753     *temporal_parallel_denom = 1;
754     return;
755   }
756 
757   // TODO(huisu@): handle scalability cases.
758   if (scalability_mode_idc == SCALABILITY_SS) {
759     (void)scalability_mode_idc;
760   } else {
761     (void)scalability_mode_idc;
762   }
763 }
764 
765 #define MAX_TILE_SIZE (4096 * 2304)
766 #define MIN_CROPPED_TILE_WIDTH 8
767 #define MIN_CROPPED_TILE_HEIGHT 8
768 #define MIN_FRAME_WIDTH 16
769 #define MIN_FRAME_HEIGHT 16
770 #define MAX_TILE_SIZE_HEADER_RATE_PRODUCT 588251136
771 
check_level_constraints(const AV1LevelInfo * const level_info,AV1_LEVEL level,int tier,int is_still_picture,BITSTREAM_PROFILE profile,int check_bitrate)772 static TARGET_LEVEL_FAIL_ID check_level_constraints(
773     const AV1LevelInfo *const level_info, AV1_LEVEL level, int tier,
774     int is_still_picture, BITSTREAM_PROFILE profile, int check_bitrate) {
775   const DECODER_MODEL *const decoder_model = &level_info->decoder_models[level];
776   const DECODER_MODEL_STATUS decoder_model_status = decoder_model->status;
777   if (decoder_model_status != DECODER_MODEL_OK &&
778       decoder_model_status != DECODER_MODEL_DISABLED) {
779     return DECODER_MODEL_FAIL;
780   }
781 
782   const AV1LevelSpec *const level_spec = &level_info->level_spec;
783   const AV1LevelSpec *const target_level_spec = &av1_level_defs[level];
784   const AV1LevelStats *const level_stats = &level_info->level_stats;
785   TARGET_LEVEL_FAIL_ID fail_id = TARGET_LEVEL_OK;
786   do {
787     if (level_spec->max_picture_size > target_level_spec->max_picture_size) {
788       fail_id = LUMA_PIC_SIZE_TOO_LARGE;
789       break;
790     }
791 
792     if (level_spec->max_h_size > target_level_spec->max_h_size) {
793       fail_id = LUMA_PIC_H_SIZE_TOO_LARGE;
794       break;
795     }
796 
797     if (level_spec->max_v_size > target_level_spec->max_v_size) {
798       fail_id = LUMA_PIC_V_SIZE_TOO_LARGE;
799       break;
800     }
801 
802     if (level_spec->max_tile_cols > target_level_spec->max_tile_cols) {
803       fail_id = TOO_MANY_TILE_COLUMNS;
804       break;
805     }
806 
807     if (level_spec->max_tiles > target_level_spec->max_tiles) {
808       fail_id = TOO_MANY_TILES;
809       break;
810     }
811 
812     if (level_spec->max_header_rate > target_level_spec->max_header_rate) {
813       fail_id = FRAME_HEADER_RATE_TOO_HIGH;
814       break;
815     }
816 
817     if (decoder_model->max_display_rate >
818         (double)target_level_spec->max_display_rate) {
819       fail_id = DISPLAY_RATE_TOO_HIGH;
820       break;
821     }
822 
823     // TODO(huisu): we are not using max decode rate calculated by the decoder
824     // model because the model in resource availability mode always returns
825     // MaxDecodeRate(as in the level definitions) as the max decode rate.
826     if (level_spec->max_decode_rate > target_level_spec->max_decode_rate) {
827       fail_id = DECODE_RATE_TOO_HIGH;
828       break;
829     }
830 
831     if (level_spec->max_tile_rate > target_level_spec->max_tiles * 120) {
832       fail_id = TILE_RATE_TOO_HIGH;
833       break;
834     }
835 
836     if (level_stats->max_tile_size > MAX_TILE_SIZE) {
837       fail_id = TILE_TOO_LARGE;
838       break;
839     }
840 
841     if (level_stats->max_superres_tile_width > MAX_TILE_WIDTH) {
842       fail_id = SUPERRES_TILE_WIDTH_TOO_LARGE;
843       break;
844     }
845 
846     if (level_stats->min_cropped_tile_width < MIN_CROPPED_TILE_WIDTH) {
847       fail_id = CROPPED_TILE_WIDTH_TOO_SMALL;
848       break;
849     }
850 
851     if (level_stats->min_cropped_tile_height < MIN_CROPPED_TILE_HEIGHT) {
852       fail_id = CROPPED_TILE_HEIGHT_TOO_SMALL;
853       break;
854     }
855 
856     if (level_stats->min_frame_width < MIN_FRAME_WIDTH) {
857       fail_id = LUMA_PIC_H_SIZE_TOO_SMALL;
858       break;
859     }
860 
861     if (level_stats->min_frame_height < MIN_FRAME_HEIGHT) {
862       fail_id = LUMA_PIC_V_SIZE_TOO_SMALL;
863       break;
864     }
865 
866     if (!level_stats->tile_width_is_valid) {
867       fail_id = TILE_WIDTH_INVALID;
868       break;
869     }
870 
871     const double min_cr = get_min_cr(target_level_spec, tier, is_still_picture,
872                                      level_spec->max_decode_rate);
873     if (level_stats->min_cr < min_cr) {
874       fail_id = CR_TOO_SMALL;
875       break;
876     }
877 
878     if (check_bitrate) {
879       // Check average bitrate instead of max_bitrate.
880       const double bitrate_limit =
881           get_max_bitrate(target_level_spec, tier, profile);
882       const double avg_bitrate = level_stats->total_compressed_size * 8.0 /
883                                  level_stats->total_time_encoded;
884       if (avg_bitrate > bitrate_limit) {
885         fail_id = BITRATE_TOO_HIGH;
886         break;
887       }
888     }
889 
890     if (target_level_spec->level > SEQ_LEVEL_5_1) {
891       int temporal_parallel_num;
892       int temporal_parallel_denom;
893       const int scalability_mode_idc = -1;
894       get_temporal_parallel_params(scalability_mode_idc, &temporal_parallel_num,
895                                    &temporal_parallel_denom);
896       const int val = level_stats->max_tile_size * level_spec->max_header_rate *
897                       temporal_parallel_denom / temporal_parallel_num;
898       if (val > MAX_TILE_SIZE_HEADER_RATE_PRODUCT) {
899         fail_id = TILE_SIZE_HEADER_RATE_TOO_HIGH;
900         break;
901       }
902     }
903   } while (0);
904 
905   return fail_id;
906 }
907 
get_tile_stats(const AV1_COMMON * const cm,const TileDataEnc * const tile_data,int * max_tile_size,int * max_superres_tile_width,int * min_cropped_tile_width,int * min_cropped_tile_height,int * tile_width_valid)908 static void get_tile_stats(const AV1_COMMON *const cm,
909                            const TileDataEnc *const tile_data,
910                            int *max_tile_size, int *max_superres_tile_width,
911                            int *min_cropped_tile_width,
912                            int *min_cropped_tile_height,
913                            int *tile_width_valid) {
914   const int tile_cols = cm->tiles.cols;
915   const int tile_rows = cm->tiles.rows;
916   const int superres_scale_denominator = cm->superres_scale_denominator;
917 
918   *max_tile_size = 0;
919   *max_superres_tile_width = 0;
920   *min_cropped_tile_width = INT_MAX;
921   *min_cropped_tile_height = INT_MAX;
922   *tile_width_valid = 1;
923 
924   for (int tile_row = 0; tile_row < tile_rows; ++tile_row) {
925     for (int tile_col = 0; tile_col < tile_cols; ++tile_col) {
926       const TileInfo *const tile_info =
927           &tile_data[tile_row * cm->tiles.cols + tile_col].tile_info;
928       const int tile_width =
929           (tile_info->mi_col_end - tile_info->mi_col_start) * MI_SIZE;
930       const int tile_height =
931           (tile_info->mi_row_end - tile_info->mi_row_start) * MI_SIZE;
932       const int tile_size = tile_width * tile_height;
933       *max_tile_size = AOMMAX(*max_tile_size, tile_size);
934 
935       const int supperres_tile_width =
936           tile_width * superres_scale_denominator / SCALE_NUMERATOR;
937       *max_superres_tile_width =
938           AOMMAX(*max_superres_tile_width, supperres_tile_width);
939 
940       const int cropped_tile_width =
941           cm->width - tile_info->mi_col_start * MI_SIZE;
942       const int cropped_tile_height =
943           cm->height - tile_info->mi_row_start * MI_SIZE;
944       *min_cropped_tile_width =
945           AOMMIN(*min_cropped_tile_width, cropped_tile_width);
946       *min_cropped_tile_height =
947           AOMMIN(*min_cropped_tile_height, cropped_tile_height);
948 
949       const int is_right_most_tile =
950           tile_info->mi_col_end == cm->mi_params.mi_cols;
951       if (!is_right_most_tile) {
952         if (av1_superres_scaled(cm))
953           *tile_width_valid &= tile_width >= 128;
954         else
955           *tile_width_valid &= tile_width >= 64;
956       }
957     }
958   }
959 }
960 
store_frame_record(int64_t ts_start,int64_t ts_end,size_t encoded_size,int pic_size,int frame_header_count,int tiles,int show_frame,int show_existing_frame,FrameWindowBuffer * const buffer)961 static int store_frame_record(int64_t ts_start, int64_t ts_end,
962                               size_t encoded_size, int pic_size,
963                               int frame_header_count, int tiles, int show_frame,
964                               int show_existing_frame,
965                               FrameWindowBuffer *const buffer) {
966   if (buffer->num < FRAME_WINDOW_SIZE) {
967     ++buffer->num;
968   } else {
969     buffer->start = (buffer->start + 1) % FRAME_WINDOW_SIZE;
970   }
971   const int new_idx = (buffer->start + buffer->num - 1) % FRAME_WINDOW_SIZE;
972   FrameRecord *const record = &buffer->buf[new_idx];
973   record->ts_start = ts_start;
974   record->ts_end = ts_end;
975   record->encoded_size_in_bytes = encoded_size;
976   record->pic_size = pic_size;
977   record->frame_header_count = frame_header_count;
978   record->tiles = tiles;
979   record->show_frame = show_frame;
980   record->show_existing_frame = show_existing_frame;
981 
982   return new_idx;
983 }
984 
985 // Count the number of frames encoded in the last "duration" ticks, in display
986 // time.
count_frames(const FrameWindowBuffer * const buffer,int64_t duration)987 static int count_frames(const FrameWindowBuffer *const buffer,
988                         int64_t duration) {
989   const int current_idx = (buffer->start + buffer->num - 1) % FRAME_WINDOW_SIZE;
990   // Assume current frame is shown frame.
991   assert(buffer->buf[current_idx].show_frame);
992 
993   const int64_t current_time = buffer->buf[current_idx].ts_end;
994   const int64_t time_limit = AOMMAX(current_time - duration, 0);
995   int num_frames = 1;
996   int index = current_idx - 1;
997   for (int i = buffer->num - 2; i >= 0; --i, --index, ++num_frames) {
998     if (index < 0) index = FRAME_WINDOW_SIZE - 1;
999     const FrameRecord *const record = &buffer->buf[index];
1000     if (!record->show_frame) continue;
1001     const int64_t ts_start = record->ts_start;
1002     if (ts_start < time_limit) break;
1003   }
1004 
1005   return num_frames;
1006 }
1007 
1008 // Scan previously encoded frames and update level metrics accordingly.
scan_past_frames(const FrameWindowBuffer * const buffer,int num_frames_to_scan,AV1LevelSpec * const level_spec,AV1LevelStats * const level_stats)1009 static void scan_past_frames(const FrameWindowBuffer *const buffer,
1010                              int num_frames_to_scan,
1011                              AV1LevelSpec *const level_spec,
1012                              AV1LevelStats *const level_stats) {
1013   const int num_frames_in_buffer = buffer->num;
1014   int index = (buffer->start + num_frames_in_buffer - 1) % FRAME_WINDOW_SIZE;
1015   int frame_headers = 0;
1016   int tiles = 0;
1017   int64_t display_samples = 0;
1018   int64_t decoded_samples = 0;
1019   size_t encoded_size_in_bytes = 0;
1020   for (int i = 0; i < AOMMIN(num_frames_in_buffer, num_frames_to_scan); ++i) {
1021     const FrameRecord *const record = &buffer->buf[index];
1022     if (!record->show_existing_frame) {
1023       frame_headers += record->frame_header_count;
1024       decoded_samples += record->pic_size;
1025     }
1026     if (record->show_frame) {
1027       display_samples += record->pic_size;
1028     }
1029     tiles += record->tiles;
1030     encoded_size_in_bytes += record->encoded_size_in_bytes;
1031     --index;
1032     if (index < 0) index = FRAME_WINDOW_SIZE - 1;
1033   }
1034   level_spec->max_header_rate =
1035       AOMMAX(level_spec->max_header_rate, frame_headers);
1036   // TODO(huisu): we can now compute max display rate with the decoder model, so
1037   // these couple of lines can be removed. Keep them here for a while for
1038   // debugging purpose.
1039   level_spec->max_display_rate =
1040       AOMMAX(level_spec->max_display_rate, display_samples);
1041   level_spec->max_decode_rate =
1042       AOMMAX(level_spec->max_decode_rate, decoded_samples);
1043   level_spec->max_tile_rate = AOMMAX(level_spec->max_tile_rate, tiles);
1044   level_stats->max_bitrate =
1045       AOMMAX(level_stats->max_bitrate, (int)encoded_size_in_bytes * 8);
1046 }
1047 
av1_update_level_info(AV1_COMP * cpi,size_t size,int64_t ts_start,int64_t ts_end)1048 void av1_update_level_info(AV1_COMP *cpi, size_t size, int64_t ts_start,
1049                            int64_t ts_end) {
1050   AV1_COMMON *const cm = &cpi->common;
1051   const AV1LevelParams *const level_params = &cpi->level_params;
1052 
1053   const int upscaled_width = cm->superres_upscaled_width;
1054   const int width = cm->width;
1055   const int height = cm->height;
1056   const int tile_cols = cm->tiles.cols;
1057   const int tile_rows = cm->tiles.rows;
1058   const int tiles = tile_cols * tile_rows;
1059   const int luma_pic_size = upscaled_width * height;
1060   const int frame_header_count = level_params->frame_header_count;
1061   const int show_frame = cm->show_frame;
1062   const int show_existing_frame = cm->show_existing_frame;
1063 
1064   int max_tile_size;
1065   int min_cropped_tile_width;
1066   int min_cropped_tile_height;
1067   int max_superres_tile_width;
1068   int tile_width_is_valid;
1069   get_tile_stats(cm, cpi->tile_data, &max_tile_size, &max_superres_tile_width,
1070                  &min_cropped_tile_width, &min_cropped_tile_height,
1071                  &tile_width_is_valid);
1072 
1073   aom_clear_system_state();
1074   const double compression_ratio = av1_get_compression_ratio(cm, size);
1075   const double total_time_encoded =
1076       (cpi->time_stamps.prev_end_seen - cpi->time_stamps.first_ever) /
1077       (double)TICKS_PER_SEC;
1078 
1079   const int temporal_layer_id = cm->temporal_layer_id;
1080   const int spatial_layer_id = cm->spatial_layer_id;
1081   const SequenceHeader *const seq_params = &cm->seq_params;
1082   const BITSTREAM_PROFILE profile = seq_params->profile;
1083   const int is_still_picture = seq_params->still_picture;
1084   // update level_stats
1085   // TODO(kyslov@) fix the implementation according to buffer model
1086   for (int i = 0; i < seq_params->operating_points_cnt_minus_1 + 1; ++i) {
1087     if (!is_in_operating_point(seq_params->operating_point_idc[i],
1088                                temporal_layer_id, spatial_layer_id) ||
1089         !((level_params->keep_level_stats >> i) & 1)) {
1090       continue;
1091     }
1092 
1093     AV1LevelInfo *const level_info = level_params->level_info[i];
1094     assert(level_info != NULL);
1095     AV1LevelStats *const level_stats = &level_info->level_stats;
1096 
1097     level_stats->max_tile_size =
1098         AOMMAX(level_stats->max_tile_size, max_tile_size);
1099     level_stats->max_superres_tile_width =
1100         AOMMAX(level_stats->max_superres_tile_width, max_superres_tile_width);
1101     level_stats->min_cropped_tile_width =
1102         AOMMIN(level_stats->min_cropped_tile_width, min_cropped_tile_width);
1103     level_stats->min_cropped_tile_height =
1104         AOMMIN(level_stats->min_cropped_tile_height, min_cropped_tile_height);
1105     level_stats->tile_width_is_valid &= tile_width_is_valid;
1106     level_stats->min_frame_width = AOMMIN(level_stats->min_frame_width, width);
1107     level_stats->min_frame_height =
1108         AOMMIN(level_stats->min_frame_height, height);
1109     level_stats->min_cr = AOMMIN(level_stats->min_cr, compression_ratio);
1110     level_stats->total_compressed_size += (double)size;
1111 
1112     // update level_spec
1113     // TODO(kyslov@) update all spec fields
1114     AV1LevelSpec *const level_spec = &level_info->level_spec;
1115     level_spec->max_picture_size =
1116         AOMMAX(level_spec->max_picture_size, luma_pic_size);
1117     level_spec->max_h_size =
1118         AOMMAX(level_spec->max_h_size, cm->superres_upscaled_width);
1119     level_spec->max_v_size = AOMMAX(level_spec->max_v_size, height);
1120     level_spec->max_tile_cols = AOMMAX(level_spec->max_tile_cols, tile_cols);
1121     level_spec->max_tiles = AOMMAX(level_spec->max_tiles, tiles);
1122 
1123     // Store info. of current frame into FrameWindowBuffer.
1124     FrameWindowBuffer *const buffer = &level_info->frame_window_buffer;
1125     store_frame_record(ts_start, ts_end, size, luma_pic_size,
1126                        frame_header_count, tiles, show_frame,
1127                        show_existing_frame, buffer);
1128     if (show_frame) {
1129       // Count the number of frames encoded in the past 1 second.
1130       const int encoded_frames_in_last_second =
1131           show_frame ? count_frames(buffer, TICKS_PER_SEC) : 0;
1132       scan_past_frames(buffer, encoded_frames_in_last_second, level_spec,
1133                        level_stats);
1134       level_stats->total_time_encoded = total_time_encoded;
1135     }
1136 
1137     DECODER_MODEL *const decoder_models = level_info->decoder_models;
1138     for (AV1_LEVEL level = SEQ_LEVEL_2_0; level < SEQ_LEVELS; ++level) {
1139       av1_decoder_model_process_frame(cpi, size << 3, &decoder_models[level]);
1140     }
1141 
1142     // Check whether target level is met.
1143     const AV1_LEVEL target_level = level_params->target_seq_level_idx[i];
1144     if (target_level < SEQ_LEVELS) {
1145       assert(is_valid_seq_level_idx(target_level));
1146       const int tier = seq_params->tier[i];
1147       const TARGET_LEVEL_FAIL_ID fail_id = check_level_constraints(
1148           level_info, target_level, tier, is_still_picture, profile, 0);
1149       if (fail_id != TARGET_LEVEL_OK) {
1150         const int target_level_major = 2 + (target_level >> 2);
1151         const int target_level_minor = target_level & 3;
1152         aom_internal_error(&cm->error, AOM_CODEC_ERROR,
1153                            "Failed to encode to the target level %d_%d. %s",
1154                            target_level_major, target_level_minor,
1155                            level_fail_messages[fail_id]);
1156       }
1157     }
1158   }
1159 }
1160 
av1_get_seq_level_idx(const SequenceHeader * seq_params,const AV1LevelParams * level_params,int * seq_level_idx)1161 aom_codec_err_t av1_get_seq_level_idx(const SequenceHeader *seq_params,
1162                                       const AV1LevelParams *level_params,
1163                                       int *seq_level_idx) {
1164   const int is_still_picture = seq_params->still_picture;
1165   const BITSTREAM_PROFILE profile = seq_params->profile;
1166   for (int op = 0; op < seq_params->operating_points_cnt_minus_1 + 1; ++op) {
1167     seq_level_idx[op] = (int)SEQ_LEVEL_MAX;
1168     if (!((level_params->keep_level_stats >> op) & 1)) continue;
1169     const int tier = seq_params->tier[op];
1170     const AV1LevelInfo *const level_info = level_params->level_info[op];
1171     assert(level_info != NULL);
1172     for (int level = 0; level < SEQ_LEVELS; ++level) {
1173       if (!is_valid_seq_level_idx(level)) continue;
1174       const TARGET_LEVEL_FAIL_ID fail_id = check_level_constraints(
1175           level_info, level, tier, is_still_picture, profile, 1);
1176       if (fail_id == TARGET_LEVEL_OK) {
1177         seq_level_idx[op] = level;
1178         break;
1179       }
1180     }
1181   }
1182 
1183   return AOM_CODEC_OK;
1184 }
1185