]> granicus.if.org Git - libvpx/blob - examples/vp9_spatial_svc_encoder.c
Merge "vp8: apply clang-tidy google-readability-braces-around-statements"
[libvpx] / examples / vp9_spatial_svc_encoder.c
1 /*
2  *  Copyright (c) 2012 The WebM project authors. 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 /*
12  * This is an example demonstrating how to implement a multi-layer
13  * VP9 encoding scheme based on spatial scalability for video applications
14  * that benefit from a scalable bitstream.
15  */
16
17 #include <math.h>
18 #include <stdarg.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <time.h>
22
23 #include "../args.h"
24 #include "../tools_common.h"
25 #include "../video_writer.h"
26
27 #include "../vpx_ports/vpx_timer.h"
28 #include "vpx/svc_context.h"
29 #include "vpx/vp8cx.h"
30 #include "vpx/vpx_encoder.h"
31 #include "../vpxstats.h"
32 #include "vp9/encoder/vp9_encoder.h"
33 #define OUTPUT_RC_STATS 1
34
35 static const arg_def_t skip_frames_arg =
36     ARG_DEF("s", "skip-frames", 1, "input frames to skip");
37 static const arg_def_t frames_arg =
38     ARG_DEF("f", "frames", 1, "number of frames to encode");
39 static const arg_def_t threads_arg =
40     ARG_DEF("th", "threads", 1, "number of threads to use");
41 #if OUTPUT_RC_STATS
42 static const arg_def_t output_rc_stats_arg =
43     ARG_DEF("rcstat", "output_rc_stats", 1, "output rc stats");
44 #endif
45 static const arg_def_t width_arg = ARG_DEF("w", "width", 1, "source width");
46 static const arg_def_t height_arg = ARG_DEF("h", "height", 1, "source height");
47 static const arg_def_t timebase_arg =
48     ARG_DEF("t", "timebase", 1, "timebase (num/den)");
49 static const arg_def_t bitrate_arg = ARG_DEF(
50     "b", "target-bitrate", 1, "encoding bitrate, in kilobits per second");
51 static const arg_def_t spatial_layers_arg =
52     ARG_DEF("sl", "spatial-layers", 1, "number of spatial SVC layers");
53 static const arg_def_t temporal_layers_arg =
54     ARG_DEF("tl", "temporal-layers", 1, "number of temporal SVC layers");
55 static const arg_def_t temporal_layering_mode_arg =
56     ARG_DEF("tlm", "temporal-layering-mode", 1,
57             "temporal layering scheme."
58             "VP9E_TEMPORAL_LAYERING_MODE");
59 static const arg_def_t kf_dist_arg =
60     ARG_DEF("k", "kf-dist", 1, "number of frames between keyframes");
61 static const arg_def_t scale_factors_arg =
62     ARG_DEF("r", "scale-factors", 1, "scale factors (lowest to highest layer)");
63 static const arg_def_t passes_arg =
64     ARG_DEF("p", "passes", 1, "Number of passes (1/2)");
65 static const arg_def_t pass_arg =
66     ARG_DEF(NULL, "pass", 1, "Pass to execute (1/2)");
67 static const arg_def_t fpf_name_arg =
68     ARG_DEF(NULL, "fpf", 1, "First pass statistics file name");
69 static const arg_def_t min_q_arg =
70     ARG_DEF(NULL, "min-q", 1, "Minimum quantizer");
71 static const arg_def_t max_q_arg =
72     ARG_DEF(NULL, "max-q", 1, "Maximum quantizer");
73 static const arg_def_t min_bitrate_arg =
74     ARG_DEF(NULL, "min-bitrate", 1, "Minimum bitrate");
75 static const arg_def_t max_bitrate_arg =
76     ARG_DEF(NULL, "max-bitrate", 1, "Maximum bitrate");
77 static const arg_def_t lag_in_frame_arg =
78     ARG_DEF(NULL, "lag-in-frames", 1,
79             "Number of frame to input before "
80             "generating any outputs");
81 static const arg_def_t rc_end_usage_arg =
82     ARG_DEF(NULL, "rc-end-usage", 1, "0 - 3: VBR, CBR, CQ, Q");
83 static const arg_def_t speed_arg =
84     ARG_DEF("sp", "speed", 1, "speed configuration");
85 static const arg_def_t aqmode_arg =
86     ARG_DEF("aq", "aqmode", 1, "aq-mode off/on");
87
88 #if CONFIG_VP9_HIGHBITDEPTH
89 static const struct arg_enum_list bitdepth_enum[] = {
90   { "8", VPX_BITS_8 }, { "10", VPX_BITS_10 }, { "12", VPX_BITS_12 }, { NULL, 0 }
91 };
92
93 static const arg_def_t bitdepth_arg = ARG_DEF_ENUM(
94     "d", "bit-depth", 1, "Bit depth for codec 8, 10 or 12. ", bitdepth_enum);
95 #endif  // CONFIG_VP9_HIGHBITDEPTH
96
97 static const arg_def_t *svc_args[] = { &frames_arg,
98                                        &width_arg,
99                                        &height_arg,
100                                        &timebase_arg,
101                                        &bitrate_arg,
102                                        &skip_frames_arg,
103                                        &spatial_layers_arg,
104                                        &kf_dist_arg,
105                                        &scale_factors_arg,
106                                        &passes_arg,
107                                        &pass_arg,
108                                        &fpf_name_arg,
109                                        &min_q_arg,
110                                        &max_q_arg,
111                                        &min_bitrate_arg,
112                                        &max_bitrate_arg,
113                                        &temporal_layers_arg,
114                                        &temporal_layering_mode_arg,
115                                        &lag_in_frame_arg,
116                                        &threads_arg,
117                                        &aqmode_arg,
118 #if OUTPUT_RC_STATS
119                                        &output_rc_stats_arg,
120 #endif
121
122 #if CONFIG_VP9_HIGHBITDEPTH
123                                        &bitdepth_arg,
124 #endif
125                                        &speed_arg,
126                                        &rc_end_usage_arg,
127                                        NULL };
128
129 static const uint32_t default_frames_to_skip = 0;
130 static const uint32_t default_frames_to_code = 60 * 60;
131 static const uint32_t default_width = 1920;
132 static const uint32_t default_height = 1080;
133 static const uint32_t default_timebase_num = 1;
134 static const uint32_t default_timebase_den = 60;
135 static const uint32_t default_bitrate = 1000;
136 static const uint32_t default_spatial_layers = 5;
137 static const uint32_t default_temporal_layers = 1;
138 static const uint32_t default_kf_dist = 100;
139 static const uint32_t default_temporal_layering_mode = 0;
140 static const uint32_t default_output_rc_stats = 0;
141 static const int32_t default_speed = -1;    // -1 means use library default.
142 static const uint32_t default_threads = 0;  // zero means use library default.
143
144 typedef struct {
145   const char *input_filename;
146   const char *output_filename;
147   uint32_t frames_to_code;
148   uint32_t frames_to_skip;
149   struct VpxInputContext input_ctx;
150   stats_io_t rc_stats;
151   int passes;
152   int pass;
153 } AppInput;
154
155 static const char *exec_name;
156
157 void usage_exit(void) {
158   fprintf(stderr, "Usage: %s <options> input_filename output_filename\n",
159           exec_name);
160   fprintf(stderr, "Options:\n");
161   arg_show_usage(stderr, svc_args);
162   exit(EXIT_FAILURE);
163 }
164
165 static void parse_command_line(int argc, const char **argv_,
166                                AppInput *app_input, SvcContext *svc_ctx,
167                                vpx_codec_enc_cfg_t *enc_cfg) {
168   struct arg arg = { 0 };
169   char **argv = NULL;
170   char **argi = NULL;
171   char **argj = NULL;
172   vpx_codec_err_t res;
173   int passes = 0;
174   int pass = 0;
175   const char *fpf_file_name = NULL;
176   unsigned int min_bitrate = 0;
177   unsigned int max_bitrate = 0;
178   char string_options[1024] = { 0 };
179
180   // initialize SvcContext with parameters that will be passed to vpx_svc_init
181   svc_ctx->log_level = SVC_LOG_DEBUG;
182   svc_ctx->spatial_layers = default_spatial_layers;
183   svc_ctx->temporal_layers = default_temporal_layers;
184   svc_ctx->temporal_layering_mode = default_temporal_layering_mode;
185 #if OUTPUT_RC_STATS
186   svc_ctx->output_rc_stat = default_output_rc_stats;
187 #endif
188   svc_ctx->speed = default_speed;
189   svc_ctx->threads = default_threads;
190
191   // start with default encoder configuration
192   res = vpx_codec_enc_config_default(vpx_codec_vp9_cx(), enc_cfg, 0);
193   if (res) {
194     die("Failed to get config: %s\n", vpx_codec_err_to_string(res));
195   }
196   // update enc_cfg with app default values
197   enc_cfg->g_w = default_width;
198   enc_cfg->g_h = default_height;
199   enc_cfg->g_timebase.num = default_timebase_num;
200   enc_cfg->g_timebase.den = default_timebase_den;
201   enc_cfg->rc_target_bitrate = default_bitrate;
202   enc_cfg->kf_min_dist = default_kf_dist;
203   enc_cfg->kf_max_dist = default_kf_dist;
204   enc_cfg->rc_end_usage = VPX_CQ;
205
206   // initialize AppInput with default values
207   app_input->frames_to_code = default_frames_to_code;
208   app_input->frames_to_skip = default_frames_to_skip;
209
210   // process command line options
211   argv = argv_dup(argc - 1, argv_ + 1);
212   for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step) {
213     arg.argv_step = 1;
214
215     if (arg_match(&arg, &frames_arg, argi)) {
216       app_input->frames_to_code = arg_parse_uint(&arg);
217     } else if (arg_match(&arg, &width_arg, argi)) {
218       enc_cfg->g_w = arg_parse_uint(&arg);
219     } else if (arg_match(&arg, &height_arg, argi)) {
220       enc_cfg->g_h = arg_parse_uint(&arg);
221     } else if (arg_match(&arg, &timebase_arg, argi)) {
222       enc_cfg->g_timebase = arg_parse_rational(&arg);
223     } else if (arg_match(&arg, &bitrate_arg, argi)) {
224       enc_cfg->rc_target_bitrate = arg_parse_uint(&arg);
225     } else if (arg_match(&arg, &skip_frames_arg, argi)) {
226       app_input->frames_to_skip = arg_parse_uint(&arg);
227     } else if (arg_match(&arg, &spatial_layers_arg, argi)) {
228       svc_ctx->spatial_layers = arg_parse_uint(&arg);
229     } else if (arg_match(&arg, &temporal_layers_arg, argi)) {
230       svc_ctx->temporal_layers = arg_parse_uint(&arg);
231 #if OUTPUT_RC_STATS
232     } else if (arg_match(&arg, &output_rc_stats_arg, argi)) {
233       svc_ctx->output_rc_stat = arg_parse_uint(&arg);
234 #endif
235     } else if (arg_match(&arg, &speed_arg, argi)) {
236       svc_ctx->speed = arg_parse_uint(&arg);
237     } else if (arg_match(&arg, &aqmode_arg, argi)) {
238       svc_ctx->aqmode = arg_parse_uint(&arg);
239     } else if (arg_match(&arg, &threads_arg, argi)) {
240       svc_ctx->threads = arg_parse_uint(&arg);
241     } else if (arg_match(&arg, &temporal_layering_mode_arg, argi)) {
242       svc_ctx->temporal_layering_mode = enc_cfg->temporal_layering_mode =
243           arg_parse_int(&arg);
244       if (svc_ctx->temporal_layering_mode) {
245         enc_cfg->g_error_resilient = 1;
246       }
247     } else if (arg_match(&arg, &kf_dist_arg, argi)) {
248       enc_cfg->kf_min_dist = arg_parse_uint(&arg);
249       enc_cfg->kf_max_dist = enc_cfg->kf_min_dist;
250     } else if (arg_match(&arg, &scale_factors_arg, argi)) {
251       snprintf(string_options, sizeof(string_options), "%s scale-factors=%s",
252                string_options, arg.val);
253     } else if (arg_match(&arg, &passes_arg, argi)) {
254       passes = arg_parse_uint(&arg);
255       if (passes < 1 || passes > 2) {
256         die("Error: Invalid number of passes (%d)\n", passes);
257       }
258     } else if (arg_match(&arg, &pass_arg, argi)) {
259       pass = arg_parse_uint(&arg);
260       if (pass < 1 || pass > 2) {
261         die("Error: Invalid pass selected (%d)\n", pass);
262       }
263     } else if (arg_match(&arg, &fpf_name_arg, argi)) {
264       fpf_file_name = arg.val;
265     } else if (arg_match(&arg, &min_q_arg, argi)) {
266       snprintf(string_options, sizeof(string_options), "%s min-quantizers=%s",
267                string_options, arg.val);
268     } else if (arg_match(&arg, &max_q_arg, argi)) {
269       snprintf(string_options, sizeof(string_options), "%s max-quantizers=%s",
270                string_options, arg.val);
271     } else if (arg_match(&arg, &min_bitrate_arg, argi)) {
272       min_bitrate = arg_parse_uint(&arg);
273     } else if (arg_match(&arg, &max_bitrate_arg, argi)) {
274       max_bitrate = arg_parse_uint(&arg);
275     } else if (arg_match(&arg, &lag_in_frame_arg, argi)) {
276       enc_cfg->g_lag_in_frames = arg_parse_uint(&arg);
277     } else if (arg_match(&arg, &rc_end_usage_arg, argi)) {
278       enc_cfg->rc_end_usage = arg_parse_uint(&arg);
279 #if CONFIG_VP9_HIGHBITDEPTH
280     } else if (arg_match(&arg, &bitdepth_arg, argi)) {
281       enc_cfg->g_bit_depth = arg_parse_enum_or_int(&arg);
282       switch (enc_cfg->g_bit_depth) {
283         case VPX_BITS_8:
284           enc_cfg->g_input_bit_depth = 8;
285           enc_cfg->g_profile = 0;
286           break;
287         case VPX_BITS_10:
288           enc_cfg->g_input_bit_depth = 10;
289           enc_cfg->g_profile = 2;
290           break;
291         case VPX_BITS_12:
292           enc_cfg->g_input_bit_depth = 12;
293           enc_cfg->g_profile = 2;
294           break;
295         default:
296           die("Error: Invalid bit depth selected (%d)\n", enc_cfg->g_bit_depth);
297           break;
298       }
299 #endif  // CONFIG_VP9_HIGHBITDEPTH
300     } else {
301       ++argj;
302     }
303   }
304
305   // There will be a space in front of the string options
306   if (strlen(string_options) > 0)
307     vpx_svc_set_options(svc_ctx, string_options + 1);
308
309   if (passes == 0 || passes == 1) {
310     if (pass) {
311       fprintf(stderr, "pass is ignored since there's only one pass\n");
312     }
313     enc_cfg->g_pass = VPX_RC_ONE_PASS;
314   } else {
315     if (pass == 0) {
316       die("pass must be specified when passes is 2\n");
317     }
318
319     if (fpf_file_name == NULL) {
320       die("fpf must be specified when passes is 2\n");
321     }
322
323     if (pass == 1) {
324       enc_cfg->g_pass = VPX_RC_FIRST_PASS;
325       if (!stats_open_file(&app_input->rc_stats, fpf_file_name, 0)) {
326         fatal("Failed to open statistics store");
327       }
328     } else {
329       enc_cfg->g_pass = VPX_RC_LAST_PASS;
330       if (!stats_open_file(&app_input->rc_stats, fpf_file_name, 1)) {
331         fatal("Failed to open statistics store");
332       }
333       enc_cfg->rc_twopass_stats_in = stats_get(&app_input->rc_stats);
334     }
335     app_input->passes = passes;
336     app_input->pass = pass;
337   }
338
339   if (enc_cfg->rc_target_bitrate > 0) {
340     if (min_bitrate > 0) {
341       enc_cfg->rc_2pass_vbr_minsection_pct =
342           min_bitrate * 100 / enc_cfg->rc_target_bitrate;
343     }
344     if (max_bitrate > 0) {
345       enc_cfg->rc_2pass_vbr_maxsection_pct =
346           max_bitrate * 100 / enc_cfg->rc_target_bitrate;
347     }
348   }
349
350   // Check for unrecognized options
351   for (argi = argv; *argi; ++argi)
352     if (argi[0][0] == '-' && strlen(argi[0]) > 1)
353       die("Error: Unrecognized option %s\n", *argi);
354
355   if (argv[0] == NULL || argv[1] == 0) {
356     usage_exit();
357   }
358   app_input->input_filename = argv[0];
359   app_input->output_filename = argv[1];
360   free(argv);
361
362   if (enc_cfg->g_w < 16 || enc_cfg->g_w % 2 || enc_cfg->g_h < 16 ||
363       enc_cfg->g_h % 2)
364     die("Invalid resolution: %d x %d\n", enc_cfg->g_w, enc_cfg->g_h);
365
366   printf(
367       "Codec %s\nframes: %d, skip: %d\n"
368       "layers: %d\n"
369       "width %d, height: %d,\n"
370       "num: %d, den: %d, bitrate: %d,\n"
371       "gop size: %d\n",
372       vpx_codec_iface_name(vpx_codec_vp9_cx()), app_input->frames_to_code,
373       app_input->frames_to_skip, svc_ctx->spatial_layers, enc_cfg->g_w,
374       enc_cfg->g_h, enc_cfg->g_timebase.num, enc_cfg->g_timebase.den,
375       enc_cfg->rc_target_bitrate, enc_cfg->kf_max_dist);
376 }
377
378 #if OUTPUT_RC_STATS
379 // For rate control encoding stats.
380 struct RateControlStats {
381   // Number of input frames per layer.
382   int layer_input_frames[VPX_MAX_LAYERS];
383   // Total (cumulative) number of encoded frames per layer.
384   int layer_tot_enc_frames[VPX_MAX_LAYERS];
385   // Number of encoded non-key frames per layer.
386   int layer_enc_frames[VPX_MAX_LAYERS];
387   // Framerate per layer (cumulative).
388   double layer_framerate[VPX_MAX_LAYERS];
389   // Target average frame size per layer (per-frame-bandwidth per layer).
390   double layer_pfb[VPX_MAX_LAYERS];
391   // Actual average frame size per layer.
392   double layer_avg_frame_size[VPX_MAX_LAYERS];
393   // Average rate mismatch per layer (|target - actual| / target).
394   double layer_avg_rate_mismatch[VPX_MAX_LAYERS];
395   // Actual encoding bitrate per layer (cumulative).
396   double layer_encoding_bitrate[VPX_MAX_LAYERS];
397   // Average of the short-time encoder actual bitrate.
398   // TODO(marpan): Should we add these short-time stats for each layer?
399   double avg_st_encoding_bitrate;
400   // Variance of the short-time encoder actual bitrate.
401   double variance_st_encoding_bitrate;
402   // Window (number of frames) for computing short-time encoding bitrate.
403   int window_size;
404   // Number of window measurements.
405   int window_count;
406 };
407
408 // Note: these rate control stats assume only 1 key frame in the
409 // sequence (i.e., first frame only).
410 static void set_rate_control_stats(struct RateControlStats *rc,
411                                    vpx_codec_enc_cfg_t *cfg) {
412   unsigned int sl, tl;
413   // Set the layer (cumulative) framerate and the target layer (non-cumulative)
414   // per-frame-bandwidth, for the rate control encoding stats below.
415   const double framerate = cfg->g_timebase.den / cfg->g_timebase.num;
416
417   for (sl = 0; sl < cfg->ss_number_layers; ++sl) {
418     for (tl = 0; tl < cfg->ts_number_layers; ++tl) {
419       const int layer = sl * cfg->ts_number_layers + tl;
420       const int tlayer0 = sl * cfg->ts_number_layers;
421       if (cfg->ts_number_layers == 1)
422         rc->layer_framerate[layer] = framerate;
423       else
424         rc->layer_framerate[layer] = framerate / cfg->ts_rate_decimator[tl];
425       if (tl > 0) {
426         rc->layer_pfb[layer] =
427             1000.0 * (cfg->layer_target_bitrate[layer] -
428                       cfg->layer_target_bitrate[layer - 1]) /
429             (rc->layer_framerate[layer] - rc->layer_framerate[layer - 1]);
430       } else {
431         rc->layer_pfb[tlayer0] = 1000.0 * cfg->layer_target_bitrate[tlayer0] /
432                                  rc->layer_framerate[tlayer0];
433       }
434       rc->layer_input_frames[layer] = 0;
435       rc->layer_enc_frames[layer] = 0;
436       rc->layer_tot_enc_frames[layer] = 0;
437       rc->layer_encoding_bitrate[layer] = 0.0;
438       rc->layer_avg_frame_size[layer] = 0.0;
439       rc->layer_avg_rate_mismatch[layer] = 0.0;
440     }
441   }
442   rc->window_count = 0;
443   rc->window_size = 15;
444   rc->avg_st_encoding_bitrate = 0.0;
445   rc->variance_st_encoding_bitrate = 0.0;
446 }
447
448 static void printout_rate_control_summary(struct RateControlStats *rc,
449                                           vpx_codec_enc_cfg_t *cfg,
450                                           int frame_cnt) {
451   unsigned int sl, tl;
452   int tot_num_frames = 0;
453   double perc_fluctuation = 0.0;
454   printf("Total number of processed frames: %d\n\n", frame_cnt - 1);
455   printf("Rate control layer stats for sl%d tl%d layer(s):\n\n",
456          cfg->ss_number_layers, cfg->ts_number_layers);
457   for (sl = 0; sl < cfg->ss_number_layers; ++sl) {
458     for (tl = 0; tl < cfg->ts_number_layers; ++tl) {
459       const int layer = sl * cfg->ts_number_layers + tl;
460       const int num_dropped =
461           (tl > 0)
462               ? (rc->layer_input_frames[layer] - rc->layer_enc_frames[layer])
463               : (rc->layer_input_frames[layer] - rc->layer_enc_frames[layer] -
464                  1);
465       if (!sl) tot_num_frames += rc->layer_input_frames[layer];
466       rc->layer_encoding_bitrate[layer] = 0.001 * rc->layer_framerate[layer] *
467                                           rc->layer_encoding_bitrate[layer] /
468                                           tot_num_frames;
469       rc->layer_avg_frame_size[layer] =
470           rc->layer_avg_frame_size[layer] / rc->layer_enc_frames[layer];
471       rc->layer_avg_rate_mismatch[layer] = 100.0 *
472                                            rc->layer_avg_rate_mismatch[layer] /
473                                            rc->layer_enc_frames[layer];
474       printf("For layer#: sl%d tl%d \n", sl, tl);
475       printf("Bitrate (target vs actual): %d %f.0 kbps\n",
476              cfg->layer_target_bitrate[layer],
477              rc->layer_encoding_bitrate[layer]);
478       printf("Average frame size (target vs actual): %f %f bits\n",
479              rc->layer_pfb[layer], rc->layer_avg_frame_size[layer]);
480       printf("Average rate_mismatch: %f\n", rc->layer_avg_rate_mismatch[layer]);
481       printf(
482           "Number of input frames, encoded (non-key) frames, "
483           "and percent dropped frames: %d %d %f.0 \n",
484           rc->layer_input_frames[layer], rc->layer_enc_frames[layer],
485           100.0 * num_dropped / rc->layer_input_frames[layer]);
486       printf("\n");
487     }
488   }
489   rc->avg_st_encoding_bitrate = rc->avg_st_encoding_bitrate / rc->window_count;
490   rc->variance_st_encoding_bitrate =
491       rc->variance_st_encoding_bitrate / rc->window_count -
492       (rc->avg_st_encoding_bitrate * rc->avg_st_encoding_bitrate);
493   perc_fluctuation = 100.0 * sqrt(rc->variance_st_encoding_bitrate) /
494                      rc->avg_st_encoding_bitrate;
495   printf("Short-time stats, for window of %d frames: \n", rc->window_size);
496   printf("Average, rms-variance, and percent-fluct: %f %f %f \n",
497          rc->avg_st_encoding_bitrate, sqrt(rc->variance_st_encoding_bitrate),
498          perc_fluctuation);
499   if (frame_cnt != tot_num_frames)
500     die(
501         "Error: Number of input frames not equal to output encoded frames != "
502         "%d tot_num_frames = %d\n",
503         frame_cnt, tot_num_frames);
504 }
505
506 vpx_codec_err_t parse_superframe_index(const uint8_t *data, size_t data_sz,
507                                        uint32_t sizes[8], int *count) {
508   // A chunk ending with a byte matching 0xc0 is an invalid chunk unless
509   // it is a super frame index. If the last byte of real video compression
510   // data is 0xc0 the encoder must add a 0 byte. If we have the marker but
511   // not the associated matching marker byte at the front of the index we have
512   // an invalid bitstream and need to return an error.
513
514   uint8_t marker;
515
516   marker = *(data + data_sz - 1);
517   *count = 0;
518
519   if ((marker & 0xe0) == 0xc0) {
520     const uint32_t frames = (marker & 0x7) + 1;
521     const uint32_t mag = ((marker >> 3) & 0x3) + 1;
522     const size_t index_sz = 2 + mag * frames;
523
524     // This chunk is marked as having a superframe index but doesn't have
525     // enough data for it, thus it's an invalid superframe index.
526     if (data_sz < index_sz) return VPX_CODEC_CORRUPT_FRAME;
527
528     {
529       const uint8_t marker2 = *(data + data_sz - index_sz);
530
531       // This chunk is marked as having a superframe index but doesn't have
532       // the matching marker byte at the front of the index therefore it's an
533       // invalid chunk.
534       if (marker != marker2) return VPX_CODEC_CORRUPT_FRAME;
535     }
536
537     {
538       // Found a valid superframe index.
539       uint32_t i, j;
540       const uint8_t *x = &data[data_sz - index_sz + 1];
541
542       for (i = 0; i < frames; ++i) {
543         uint32_t this_sz = 0;
544
545         for (j = 0; j < mag; ++j) this_sz |= (*x++) << (j * 8);
546         sizes[i] = this_sz;
547       }
548       *count = frames;
549     }
550   }
551   return VPX_CODEC_OK;
552 }
553 #endif
554
555 // Example pattern for spatial layers and 2 temporal layers used in the
556 // bypass/flexible mode. The pattern corresponds to the pattern
557 // VP9E_TEMPORAL_LAYERING_MODE_0101 (temporal_layering_mode == 2) used in
558 // non-flexible mode.
559 void set_frame_flags_bypass_mode(int sl, int tl, int num_spatial_layers,
560                                  int is_key_frame,
561                                  vpx_svc_ref_frame_config_t *ref_frame_config) {
562   for (sl = 0; sl < num_spatial_layers; ++sl) {
563     if (!tl) {
564       if (!sl) {
565         ref_frame_config->frame_flags[sl] =
566             VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_GF |
567             VP8_EFLAG_NO_UPD_ARF;
568       } else {
569         if (is_key_frame) {
570           ref_frame_config->frame_flags[sl] =
571               VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_ARF |
572               VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
573         } else {
574           ref_frame_config->frame_flags[sl] =
575               VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
576         }
577       }
578     } else if (tl == 1) {
579       if (!sl) {
580         ref_frame_config->frame_flags[sl] =
581             VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_LAST |
582             VP8_EFLAG_NO_UPD_GF;
583       } else {
584         ref_frame_config->frame_flags[sl] =
585             VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF;
586       }
587     }
588     if (tl == 0) {
589       ref_frame_config->lst_fb_idx[sl] = sl;
590       if (sl)
591         ref_frame_config->gld_fb_idx[sl] = sl - 1;
592       else
593         ref_frame_config->gld_fb_idx[sl] = 0;
594       ref_frame_config->alt_fb_idx[sl] = 0;
595     } else if (tl == 1) {
596       ref_frame_config->lst_fb_idx[sl] = sl;
597       ref_frame_config->gld_fb_idx[sl] = num_spatial_layers + sl - 1;
598       ref_frame_config->alt_fb_idx[sl] = num_spatial_layers + sl;
599     }
600   }
601 }
602
603 int main(int argc, const char **argv) {
604   AppInput app_input = { 0 };
605   VpxVideoWriter *writer = NULL;
606   VpxVideoInfo info = { 0 };
607   vpx_codec_ctx_t codec;
608   vpx_codec_enc_cfg_t enc_cfg;
609   SvcContext svc_ctx;
610   uint32_t i;
611   uint32_t frame_cnt = 0;
612   vpx_image_t raw;
613   vpx_codec_err_t res;
614   int pts = 0;            /* PTS starts at 0 */
615   int frame_duration = 1; /* 1 timebase tick per frame */
616   FILE *infile = NULL;
617   int end_of_stream = 0;
618   int frames_received = 0;
619 #if OUTPUT_RC_STATS
620   VpxVideoWriter *outfile[VPX_TS_MAX_LAYERS] = { NULL };
621   struct RateControlStats rc;
622   vpx_svc_layer_id_t layer_id;
623   vpx_svc_ref_frame_config_t ref_frame_config;
624   int sl, tl;
625   double sum_bitrate = 0.0;
626   double sum_bitrate2 = 0.0;
627   double framerate = 30.0;
628 #endif
629   struct vpx_usec_timer timer;
630   int64_t cx_time = 0;
631   memset(&svc_ctx, 0, sizeof(svc_ctx));
632   svc_ctx.log_print = 1;
633   exec_name = argv[0];
634   parse_command_line(argc, argv, &app_input, &svc_ctx, &enc_cfg);
635
636 // Allocate image buffer
637 #if CONFIG_VP9_HIGHBITDEPTH
638   if (!vpx_img_alloc(&raw, enc_cfg.g_input_bit_depth == 8 ? VPX_IMG_FMT_I420
639                                                           : VPX_IMG_FMT_I42016,
640                      enc_cfg.g_w, enc_cfg.g_h, 32)) {
641     die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
642   }
643 #else
644   if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, enc_cfg.g_w, enc_cfg.g_h, 32)) {
645     die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
646   }
647 #endif  // CONFIG_VP9_HIGHBITDEPTH
648
649   if (!(infile = fopen(app_input.input_filename, "rb")))
650     die("Failed to open %s for reading\n", app_input.input_filename);
651
652   // Initialize codec
653   if (vpx_svc_init(&svc_ctx, &codec, vpx_codec_vp9_cx(), &enc_cfg) !=
654       VPX_CODEC_OK)
655     die("Failed to initialize encoder\n");
656
657 #if OUTPUT_RC_STATS
658   if (svc_ctx.output_rc_stat) {
659     set_rate_control_stats(&rc, &enc_cfg);
660     framerate = enc_cfg.g_timebase.den / enc_cfg.g_timebase.num;
661   }
662 #endif
663
664   info.codec_fourcc = VP9_FOURCC;
665   info.time_base.numerator = enc_cfg.g_timebase.num;
666   info.time_base.denominator = enc_cfg.g_timebase.den;
667
668   if (!(app_input.passes == 2 && app_input.pass == 1)) {
669     // We don't save the bitstream for the 1st pass on two pass rate control
670     writer =
671         vpx_video_writer_open(app_input.output_filename, kContainerIVF, &info);
672     if (!writer)
673       die("Failed to open %s for writing\n", app_input.output_filename);
674   }
675 #if OUTPUT_RC_STATS
676   // For now, just write temporal layer streams.
677   // TODO(wonkap): do spatial by re-writing superframe.
678   if (svc_ctx.output_rc_stat) {
679     for (tl = 0; tl < enc_cfg.ts_number_layers; ++tl) {
680       char file_name[PATH_MAX];
681
682       snprintf(file_name, sizeof(file_name), "%s_t%d.ivf",
683                app_input.output_filename, tl);
684       outfile[tl] = vpx_video_writer_open(file_name, kContainerIVF, &info);
685       if (!outfile[tl]) die("Failed to open %s for writing", file_name);
686     }
687   }
688 #endif
689
690   // skip initial frames
691   for (i = 0; i < app_input.frames_to_skip; ++i) vpx_img_read(&raw, infile);
692
693   if (svc_ctx.speed != -1)
694     vpx_codec_control(&codec, VP8E_SET_CPUUSED, svc_ctx.speed);
695   if (svc_ctx.threads)
696     vpx_codec_control(&codec, VP9E_SET_TILE_COLUMNS, (svc_ctx.threads >> 1));
697   if (svc_ctx.speed >= 5 && svc_ctx.aqmode == 1)
698     vpx_codec_control(&codec, VP9E_SET_AQ_MODE, 3);
699
700   // Encode frames
701   while (!end_of_stream) {
702     vpx_codec_iter_t iter = NULL;
703     const vpx_codec_cx_pkt_t *cx_pkt;
704     if (frame_cnt >= app_input.frames_to_code || !vpx_img_read(&raw, infile)) {
705       // We need one extra vpx_svc_encode call at end of stream to flush
706       // encoder and get remaining data
707       end_of_stream = 1;
708     }
709
710     // For BYPASS/FLEXIBLE mode, set the frame flags (reference and updates)
711     // and the buffer indices for each spatial layer of the current
712     // (super)frame to be encoded. The temporal layer_id for the current frame
713     // also needs to be set.
714     // TODO(marpan): Should rename the "VP9E_TEMPORAL_LAYERING_MODE_BYPASS"
715     // mode to "VP9E_LAYERING_MODE_BYPASS".
716     if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
717       layer_id.spatial_layer_id = 0;
718       // Example for 2 temporal layers.
719       if (frame_cnt % 2 == 0)
720         layer_id.temporal_layer_id = 0;
721       else
722         layer_id.temporal_layer_id = 1;
723       // Note that we only set the temporal layer_id, since we are calling
724       // the encode for the whole superframe. The encoder will internally loop
725       // over all the spatial layers for the current superframe.
726       vpx_codec_control(&codec, VP9E_SET_SVC_LAYER_ID, &layer_id);
727       set_frame_flags_bypass_mode(sl, layer_id.temporal_layer_id,
728                                   svc_ctx.spatial_layers, frame_cnt == 0,
729                                   &ref_frame_config);
730       vpx_codec_control(&codec, VP9E_SET_SVC_REF_FRAME_CONFIG,
731                         &ref_frame_config);
732       // Keep track of input frames, to account for frame drops in rate control
733       // stats/metrics.
734       for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
735         ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
736                                 layer_id.temporal_layer_id];
737       }
738     }
739
740     vpx_usec_timer_start(&timer);
741     res = vpx_svc_encode(
742         &svc_ctx, &codec, (end_of_stream ? NULL : &raw), pts, frame_duration,
743         svc_ctx.speed >= 5 ? VPX_DL_REALTIME : VPX_DL_GOOD_QUALITY);
744     vpx_usec_timer_mark(&timer);
745     cx_time += vpx_usec_timer_elapsed(&timer);
746
747     printf("%s", vpx_svc_get_message(&svc_ctx));
748     fflush(stdout);
749     if (res != VPX_CODEC_OK) {
750       die_codec(&codec, "Failed to encode frame");
751     }
752
753     while ((cx_pkt = vpx_codec_get_cx_data(&codec, &iter)) != NULL) {
754       switch (cx_pkt->kind) {
755         case VPX_CODEC_CX_FRAME_PKT: {
756           SvcInternal_t *const si = (SvcInternal_t *)svc_ctx.internal;
757           if (cx_pkt->data.frame.sz > 0) {
758 #if OUTPUT_RC_STATS
759             uint32_t sizes[8];
760             int count = 0;
761 #endif
762             vpx_video_writer_write_frame(writer, cx_pkt->data.frame.buf,
763                                          cx_pkt->data.frame.sz,
764                                          cx_pkt->data.frame.pts);
765 #if OUTPUT_RC_STATS
766             // TODO(marpan/wonkap): Put this (to line728) in separate function.
767             if (svc_ctx.output_rc_stat) {
768               vpx_codec_control(&codec, VP9E_GET_SVC_LAYER_ID, &layer_id);
769               parse_superframe_index(cx_pkt->data.frame.buf,
770                                      cx_pkt->data.frame.sz, sizes, &count);
771               // Note computing input_layer_frames here won't account for frame
772               // drops in rate control stats.
773               // TODO(marpan): Fix this for non-bypass mode so we can get stats
774               // for dropped frames.
775               if (svc_ctx.temporal_layering_mode !=
776                   VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
777                 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
778                   ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
779                                           layer_id.temporal_layer_id];
780                 }
781               }
782               for (tl = layer_id.temporal_layer_id;
783                    tl < enc_cfg.ts_number_layers; ++tl) {
784                 vpx_video_writer_write_frame(
785                     outfile[tl], cx_pkt->data.frame.buf, cx_pkt->data.frame.sz,
786                     cx_pkt->data.frame.pts);
787               }
788
789               for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
790                 for (tl = layer_id.temporal_layer_id;
791                      tl < enc_cfg.ts_number_layers; ++tl) {
792                   const int layer = sl * enc_cfg.ts_number_layers + tl;
793                   ++rc.layer_tot_enc_frames[layer];
794                   rc.layer_encoding_bitrate[layer] += 8.0 * sizes[sl];
795                   // Keep count of rate control stats per layer, for non-key
796                   // frames.
797                   if (tl == layer_id.temporal_layer_id &&
798                       !(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY)) {
799                     rc.layer_avg_frame_size[layer] += 8.0 * sizes[sl];
800                     rc.layer_avg_rate_mismatch[layer] +=
801                         fabs(8.0 * sizes[sl] - rc.layer_pfb[layer]) /
802                         rc.layer_pfb[layer];
803                     ++rc.layer_enc_frames[layer];
804                   }
805                 }
806               }
807
808               // Update for short-time encoding bitrate states, for moving
809               // window of size rc->window, shifted by rc->window / 2.
810               // Ignore first window segment, due to key frame.
811               if (frame_cnt > rc.window_size) {
812                 tl = layer_id.temporal_layer_id;
813                 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
814                   sum_bitrate += 0.001 * 8.0 * sizes[sl] * framerate;
815                 }
816                 if (frame_cnt % rc.window_size == 0) {
817                   rc.window_count += 1;
818                   rc.avg_st_encoding_bitrate += sum_bitrate / rc.window_size;
819                   rc.variance_st_encoding_bitrate +=
820                       (sum_bitrate / rc.window_size) *
821                       (sum_bitrate / rc.window_size);
822                   sum_bitrate = 0.0;
823                 }
824               }
825
826               // Second shifted window.
827               if (frame_cnt > rc.window_size + rc.window_size / 2) {
828                 tl = layer_id.temporal_layer_id;
829                 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
830                   sum_bitrate2 += 0.001 * 8.0 * sizes[sl] * framerate;
831                 }
832
833                 if (frame_cnt > 2 * rc.window_size &&
834                     frame_cnt % rc.window_size == 0) {
835                   rc.window_count += 1;
836                   rc.avg_st_encoding_bitrate += sum_bitrate2 / rc.window_size;
837                   rc.variance_st_encoding_bitrate +=
838                       (sum_bitrate2 / rc.window_size) *
839                       (sum_bitrate2 / rc.window_size);
840                   sum_bitrate2 = 0.0;
841                 }
842               }
843             }
844 #endif
845           }
846
847           printf("SVC frame: %d, kf: %d, size: %d, pts: %d\n", frames_received,
848                  !!(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY),
849                  (int)cx_pkt->data.frame.sz, (int)cx_pkt->data.frame.pts);
850           if (enc_cfg.ss_number_layers == 1 && enc_cfg.ts_number_layers == 1)
851             si->bytes_sum[0] += (int)cx_pkt->data.frame.sz;
852           ++frames_received;
853           break;
854         }
855         case VPX_CODEC_STATS_PKT: {
856           stats_write(&app_input.rc_stats, cx_pkt->data.twopass_stats.buf,
857                       cx_pkt->data.twopass_stats.sz);
858           break;
859         }
860         default: { break; }
861       }
862     }
863
864     if (!end_of_stream) {
865       ++frame_cnt;
866       pts += frame_duration;
867     }
868   }
869
870   // Compensate for the extra frame count for the bypass mode.
871   if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
872     for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
873       const int layer =
874           sl * enc_cfg.ts_number_layers + layer_id.temporal_layer_id;
875       --rc.layer_input_frames[layer];
876     }
877   }
878
879   printf("Processed %d frames\n", frame_cnt);
880   fclose(infile);
881 #if OUTPUT_RC_STATS
882   if (svc_ctx.output_rc_stat) {
883     printout_rate_control_summary(&rc, &enc_cfg, frame_cnt);
884     printf("\n");
885   }
886 #endif
887   if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec");
888   if (app_input.passes == 2) stats_close(&app_input.rc_stats, 1);
889   if (writer) {
890     vpx_video_writer_close(writer);
891   }
892 #if OUTPUT_RC_STATS
893   if (svc_ctx.output_rc_stat) {
894     for (tl = 0; tl < enc_cfg.ts_number_layers; ++tl) {
895       vpx_video_writer_close(outfile[tl]);
896     }
897   }
898 #endif
899   printf("Frame cnt and encoding time/FPS stats for encoding: %d %f %f \n",
900          frame_cnt, 1000 * (float)cx_time / (double)(frame_cnt * 1000000),
901          1000000 * (double)frame_cnt / (double)cx_time);
902   vpx_img_free(&raw);
903   // display average size, psnr
904   printf("%s", vpx_svc_dump_statistics(&svc_ctx));
905   vpx_svc_release(&svc_ctx);
906   return EXIT_SUCCESS;
907 }