]> granicus.if.org Git - libvpx/blob - examples/vp9_spatial_svc_encoder.c
Merge changes from topic 'clang-format'
[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("Error: Number of input frames not equal to output encoded frames != "
501         "%d tot_num_frames = %d\n",
502         frame_cnt, tot_num_frames);
503 }
504
505 vpx_codec_err_t parse_superframe_index(const uint8_t *data, size_t data_sz,
506                                        uint32_t sizes[8], int *count) {
507   // A chunk ending with a byte matching 0xc0 is an invalid chunk unless
508   // it is a super frame index. If the last byte of real video compression
509   // data is 0xc0 the encoder must add a 0 byte. If we have the marker but
510   // not the associated matching marker byte at the front of the index we have
511   // an invalid bitstream and need to return an error.
512
513   uint8_t marker;
514
515   marker = *(data + data_sz - 1);
516   *count = 0;
517
518   if ((marker & 0xe0) == 0xc0) {
519     const uint32_t frames = (marker & 0x7) + 1;
520     const uint32_t mag = ((marker >> 3) & 0x3) + 1;
521     const size_t index_sz = 2 + mag * frames;
522
523     // This chunk is marked as having a superframe index but doesn't have
524     // enough data for it, thus it's an invalid superframe index.
525     if (data_sz < index_sz) return VPX_CODEC_CORRUPT_FRAME;
526
527     {
528       const uint8_t marker2 = *(data + data_sz - index_sz);
529
530       // This chunk is marked as having a superframe index but doesn't have
531       // the matching marker byte at the front of the index therefore it's an
532       // invalid chunk.
533       if (marker != marker2) return VPX_CODEC_CORRUPT_FRAME;
534     }
535
536     {
537       // Found a valid superframe index.
538       uint32_t i, j;
539       const uint8_t *x = &data[data_sz - index_sz + 1];
540
541       for (i = 0; i < frames; ++i) {
542         uint32_t this_sz = 0;
543
544         for (j = 0; j < mag; ++j) this_sz |= (*x++) << (j * 8);
545         sizes[i] = this_sz;
546       }
547       *count = frames;
548     }
549   }
550   return VPX_CODEC_OK;
551 }
552 #endif
553
554 // Example pattern for spatial layers and 2 temporal layers used in the
555 // bypass/flexible mode. The pattern corresponds to the pattern
556 // VP9E_TEMPORAL_LAYERING_MODE_0101 (temporal_layering_mode == 2) used in
557 // non-flexible mode.
558 void set_frame_flags_bypass_mode(int sl, int tl, int num_spatial_layers,
559                                  int is_key_frame,
560                                  vpx_svc_ref_frame_config_t *ref_frame_config) {
561   for (sl = 0; sl < num_spatial_layers; ++sl) {
562     if (!tl) {
563       if (!sl) {
564         ref_frame_config->frame_flags[sl] =
565             VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_GF |
566             VP8_EFLAG_NO_UPD_ARF;
567       } else {
568         if (is_key_frame) {
569           ref_frame_config->frame_flags[sl] =
570               VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_ARF |
571               VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
572         } else {
573           ref_frame_config->frame_flags[sl] =
574               VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
575         }
576       }
577     } else if (tl == 1) {
578       if (!sl) {
579         ref_frame_config->frame_flags[sl] =
580             VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_LAST |
581             VP8_EFLAG_NO_UPD_GF;
582       } else {
583         ref_frame_config->frame_flags[sl] =
584             VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF;
585       }
586     }
587     if (tl == 0) {
588       ref_frame_config->lst_fb_idx[sl] = sl;
589       if (sl)
590         ref_frame_config->gld_fb_idx[sl] = sl - 1;
591       else
592         ref_frame_config->gld_fb_idx[sl] = 0;
593       ref_frame_config->alt_fb_idx[sl] = 0;
594     } else if (tl == 1) {
595       ref_frame_config->lst_fb_idx[sl] = sl;
596       ref_frame_config->gld_fb_idx[sl] = num_spatial_layers + sl - 1;
597       ref_frame_config->alt_fb_idx[sl] = num_spatial_layers + sl;
598     }
599   }
600 }
601
602 int main(int argc, const char **argv) {
603   AppInput app_input = { 0 };
604   VpxVideoWriter *writer = NULL;
605   VpxVideoInfo info = { 0 };
606   vpx_codec_ctx_t codec;
607   vpx_codec_enc_cfg_t enc_cfg;
608   SvcContext svc_ctx;
609   uint32_t i;
610   uint32_t frame_cnt = 0;
611   vpx_image_t raw;
612   vpx_codec_err_t res;
613   int pts = 0;            /* PTS starts at 0 */
614   int frame_duration = 1; /* 1 timebase tick per frame */
615   FILE *infile = NULL;
616   int end_of_stream = 0;
617   int frames_received = 0;
618 #if OUTPUT_RC_STATS
619   VpxVideoWriter *outfile[VPX_TS_MAX_LAYERS] = { NULL };
620   struct RateControlStats rc;
621   vpx_svc_layer_id_t layer_id;
622   vpx_svc_ref_frame_config_t ref_frame_config;
623   int sl, tl;
624   double sum_bitrate = 0.0;
625   double sum_bitrate2 = 0.0;
626   double framerate = 30.0;
627 #endif
628   struct vpx_usec_timer timer;
629   int64_t cx_time = 0;
630   memset(&svc_ctx, 0, sizeof(svc_ctx));
631   svc_ctx.log_print = 1;
632   exec_name = argv[0];
633   parse_command_line(argc, argv, &app_input, &svc_ctx, &enc_cfg);
634
635 // Allocate image buffer
636 #if CONFIG_VP9_HIGHBITDEPTH
637   if (!vpx_img_alloc(&raw, enc_cfg.g_input_bit_depth == 8 ? VPX_IMG_FMT_I420
638                                                           : VPX_IMG_FMT_I42016,
639                      enc_cfg.g_w, enc_cfg.g_h, 32)) {
640     die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
641   }
642 #else
643   if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, enc_cfg.g_w, enc_cfg.g_h, 32)) {
644     die("Failed to allocate image %dx%d\n", enc_cfg.g_w, enc_cfg.g_h);
645   }
646 #endif  // CONFIG_VP9_HIGHBITDEPTH
647
648   if (!(infile = fopen(app_input.input_filename, "rb")))
649     die("Failed to open %s for reading\n", app_input.input_filename);
650
651   // Initialize codec
652   if (vpx_svc_init(&svc_ctx, &codec, vpx_codec_vp9_cx(), &enc_cfg) !=
653       VPX_CODEC_OK)
654     die("Failed to initialize encoder\n");
655
656 #if OUTPUT_RC_STATS
657   if (svc_ctx.output_rc_stat) {
658     set_rate_control_stats(&rc, &enc_cfg);
659     framerate = enc_cfg.g_timebase.den / enc_cfg.g_timebase.num;
660   }
661 #endif
662
663   info.codec_fourcc = VP9_FOURCC;
664   info.time_base.numerator = enc_cfg.g_timebase.num;
665   info.time_base.denominator = enc_cfg.g_timebase.den;
666
667   if (!(app_input.passes == 2 && app_input.pass == 1)) {
668     // We don't save the bitstream for the 1st pass on two pass rate control
669     writer =
670         vpx_video_writer_open(app_input.output_filename, kContainerIVF, &info);
671     if (!writer)
672       die("Failed to open %s for writing\n", app_input.output_filename);
673   }
674 #if OUTPUT_RC_STATS
675   // For now, just write temporal layer streams.
676   // TODO(wonkap): do spatial by re-writing superframe.
677   if (svc_ctx.output_rc_stat) {
678     for (tl = 0; tl < enc_cfg.ts_number_layers; ++tl) {
679       char file_name[PATH_MAX];
680
681       snprintf(file_name, sizeof(file_name), "%s_t%d.ivf",
682                app_input.output_filename, tl);
683       outfile[tl] = vpx_video_writer_open(file_name, kContainerIVF, &info);
684       if (!outfile[tl]) die("Failed to open %s for writing", file_name);
685     }
686   }
687 #endif
688
689   // skip initial frames
690   for (i = 0; i < app_input.frames_to_skip; ++i) vpx_img_read(&raw, infile);
691
692   if (svc_ctx.speed != -1)
693     vpx_codec_control(&codec, VP8E_SET_CPUUSED, svc_ctx.speed);
694   if (svc_ctx.threads)
695     vpx_codec_control(&codec, VP9E_SET_TILE_COLUMNS, (svc_ctx.threads >> 1));
696   if (svc_ctx.speed >= 5 && svc_ctx.aqmode == 1)
697     vpx_codec_control(&codec, VP9E_SET_AQ_MODE, 3);
698
699   // Encode frames
700   while (!end_of_stream) {
701     vpx_codec_iter_t iter = NULL;
702     const vpx_codec_cx_pkt_t *cx_pkt;
703     if (frame_cnt >= app_input.frames_to_code || !vpx_img_read(&raw, infile)) {
704       // We need one extra vpx_svc_encode call at end of stream to flush
705       // encoder and get remaining data
706       end_of_stream = 1;
707     }
708
709     // For BYPASS/FLEXIBLE mode, set the frame flags (reference and updates)
710     // and the buffer indices for each spatial layer of the current
711     // (super)frame to be encoded. The temporal layer_id for the current frame
712     // also needs to be set.
713     // TODO(marpan): Should rename the "VP9E_TEMPORAL_LAYERING_MODE_BYPASS"
714     // mode to "VP9E_LAYERING_MODE_BYPASS".
715     if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
716       layer_id.spatial_layer_id = 0;
717       // Example for 2 temporal layers.
718       if (frame_cnt % 2 == 0)
719         layer_id.temporal_layer_id = 0;
720       else
721         layer_id.temporal_layer_id = 1;
722       // Note that we only set the temporal layer_id, since we are calling
723       // the encode for the whole superframe. The encoder will internally loop
724       // over all the spatial layers for the current superframe.
725       vpx_codec_control(&codec, VP9E_SET_SVC_LAYER_ID, &layer_id);
726       set_frame_flags_bypass_mode(sl, layer_id.temporal_layer_id,
727                                   svc_ctx.spatial_layers, frame_cnt == 0,
728                                   &ref_frame_config);
729       vpx_codec_control(&codec, VP9E_SET_SVC_REF_FRAME_CONFIG,
730                         &ref_frame_config);
731       // Keep track of input frames, to account for frame drops in rate control
732       // stats/metrics.
733       for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
734         ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
735                                 layer_id.temporal_layer_id];
736       }
737     }
738
739     vpx_usec_timer_start(&timer);
740     res = vpx_svc_encode(
741         &svc_ctx, &codec, (end_of_stream ? NULL : &raw), pts, frame_duration,
742         svc_ctx.speed >= 5 ? VPX_DL_REALTIME : VPX_DL_GOOD_QUALITY);
743     vpx_usec_timer_mark(&timer);
744     cx_time += vpx_usec_timer_elapsed(&timer);
745
746     printf("%s", vpx_svc_get_message(&svc_ctx));
747     fflush(stdout);
748     if (res != VPX_CODEC_OK) {
749       die_codec(&codec, "Failed to encode frame");
750     }
751
752     while ((cx_pkt = vpx_codec_get_cx_data(&codec, &iter)) != NULL) {
753       switch (cx_pkt->kind) {
754         case VPX_CODEC_CX_FRAME_PKT: {
755           SvcInternal_t *const si = (SvcInternal_t *)svc_ctx.internal;
756           if (cx_pkt->data.frame.sz > 0) {
757 #if OUTPUT_RC_STATS
758             uint32_t sizes[8];
759             int count = 0;
760 #endif
761             vpx_video_writer_write_frame(writer, cx_pkt->data.frame.buf,
762                                          cx_pkt->data.frame.sz,
763                                          cx_pkt->data.frame.pts);
764 #if OUTPUT_RC_STATS
765             // TODO(marpan/wonkap): Put this (to line728) in separate function.
766             if (svc_ctx.output_rc_stat) {
767               vpx_codec_control(&codec, VP9E_GET_SVC_LAYER_ID, &layer_id);
768               parse_superframe_index(cx_pkt->data.frame.buf,
769                                      cx_pkt->data.frame.sz, sizes, &count);
770               // Note computing input_layer_frames here won't account for frame
771               // drops in rate control stats.
772               // TODO(marpan): Fix this for non-bypass mode so we can get stats
773               // for dropped frames.
774               if (svc_ctx.temporal_layering_mode !=
775                   VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
776                 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
777                   ++rc.layer_input_frames[sl * enc_cfg.ts_number_layers +
778                                           layer_id.temporal_layer_id];
779                 }
780               }
781               for (tl = layer_id.temporal_layer_id;
782                    tl < enc_cfg.ts_number_layers; ++tl) {
783                 vpx_video_writer_write_frame(
784                     outfile[tl], cx_pkt->data.frame.buf, cx_pkt->data.frame.sz,
785                     cx_pkt->data.frame.pts);
786               }
787
788               for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
789                 for (tl = layer_id.temporal_layer_id;
790                      tl < enc_cfg.ts_number_layers; ++tl) {
791                   const int layer = sl * enc_cfg.ts_number_layers + tl;
792                   ++rc.layer_tot_enc_frames[layer];
793                   rc.layer_encoding_bitrate[layer] += 8.0 * sizes[sl];
794                   // Keep count of rate control stats per layer, for non-key
795                   // frames.
796                   if (tl == layer_id.temporal_layer_id &&
797                       !(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY)) {
798                     rc.layer_avg_frame_size[layer] += 8.0 * sizes[sl];
799                     rc.layer_avg_rate_mismatch[layer] +=
800                         fabs(8.0 * sizes[sl] - rc.layer_pfb[layer]) /
801                         rc.layer_pfb[layer];
802                     ++rc.layer_enc_frames[layer];
803                   }
804                 }
805               }
806
807               // Update for short-time encoding bitrate states, for moving
808               // window of size rc->window, shifted by rc->window / 2.
809               // Ignore first window segment, due to key frame.
810               if (frame_cnt > rc.window_size) {
811                 tl = layer_id.temporal_layer_id;
812                 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
813                   sum_bitrate += 0.001 * 8.0 * sizes[sl] * framerate;
814                 }
815                 if (frame_cnt % rc.window_size == 0) {
816                   rc.window_count += 1;
817                   rc.avg_st_encoding_bitrate += sum_bitrate / rc.window_size;
818                   rc.variance_st_encoding_bitrate +=
819                       (sum_bitrate / rc.window_size) *
820                       (sum_bitrate / rc.window_size);
821                   sum_bitrate = 0.0;
822                 }
823               }
824
825               // Second shifted window.
826               if (frame_cnt > rc.window_size + rc.window_size / 2) {
827                 tl = layer_id.temporal_layer_id;
828                 for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
829                   sum_bitrate2 += 0.001 * 8.0 * sizes[sl] * framerate;
830                 }
831
832                 if (frame_cnt > 2 * rc.window_size &&
833                     frame_cnt % rc.window_size == 0) {
834                   rc.window_count += 1;
835                   rc.avg_st_encoding_bitrate += sum_bitrate2 / rc.window_size;
836                   rc.variance_st_encoding_bitrate +=
837                       (sum_bitrate2 / rc.window_size) *
838                       (sum_bitrate2 / rc.window_size);
839                   sum_bitrate2 = 0.0;
840                 }
841               }
842             }
843 #endif
844           }
845
846           printf("SVC frame: %d, kf: %d, size: %d, pts: %d\n", frames_received,
847                  !!(cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY),
848                  (int)cx_pkt->data.frame.sz, (int)cx_pkt->data.frame.pts);
849           if (enc_cfg.ss_number_layers == 1 && enc_cfg.ts_number_layers == 1)
850             si->bytes_sum[0] += (int)cx_pkt->data.frame.sz;
851           ++frames_received;
852           break;
853         }
854         case VPX_CODEC_STATS_PKT: {
855           stats_write(&app_input.rc_stats, cx_pkt->data.twopass_stats.buf,
856                       cx_pkt->data.twopass_stats.sz);
857           break;
858         }
859         default: { break; }
860       }
861     }
862
863     if (!end_of_stream) {
864       ++frame_cnt;
865       pts += frame_duration;
866     }
867   }
868
869   // Compensate for the extra frame count for the bypass mode.
870   if (svc_ctx.temporal_layering_mode == VP9E_TEMPORAL_LAYERING_MODE_BYPASS) {
871     for (sl = 0; sl < enc_cfg.ss_number_layers; ++sl) {
872       const int layer =
873           sl * enc_cfg.ts_number_layers + layer_id.temporal_layer_id;
874       --rc.layer_input_frames[layer];
875     }
876   }
877
878   printf("Processed %d frames\n", frame_cnt);
879   fclose(infile);
880 #if OUTPUT_RC_STATS
881   if (svc_ctx.output_rc_stat) {
882     printout_rate_control_summary(&rc, &enc_cfg, frame_cnt);
883     printf("\n");
884   }
885 #endif
886   if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec");
887   if (app_input.passes == 2) stats_close(&app_input.rc_stats, 1);
888   if (writer) {
889     vpx_video_writer_close(writer);
890   }
891 #if OUTPUT_RC_STATS
892   if (svc_ctx.output_rc_stat) {
893     for (tl = 0; tl < enc_cfg.ts_number_layers; ++tl) {
894       vpx_video_writer_close(outfile[tl]);
895     }
896   }
897 #endif
898   printf("Frame cnt and encoding time/FPS stats for encoding: %d %f %f \n",
899          frame_cnt, 1000 * (float)cx_time / (double)(frame_cnt * 1000000),
900          1000000 * (double)frame_cnt / (double)cx_time);
901   vpx_img_free(&raw);
902   // display average size, psnr
903   printf("%s", vpx_svc_dump_statistics(&svc_ctx));
904   vpx_svc_release(&svc_ctx);
905   return EXIT_SUCCESS;
906 }