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