]> granicus.if.org Git - libvpx/blob - examples/svc_encodeframe.c
vp8 encoder: fix some integer overflows
[libvpx] / examples / svc_encodeframe.c
1 /*
2  *  Copyright (c) 2013 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  * @file
13  * VP9 SVC encoding support via libvpx
14  */
15
16 #include <assert.h>
17 #include <math.h>
18 #include <limits.h>
19 #include <stdarg.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #define VPX_DISABLE_CTRL_TYPECHECKS 1
24 #include "../tools_common.h"
25 #include "./vpx_config.h"
26 #include "./svc_context.h"
27 #include "vpx/vp8cx.h"
28 #include "vpx/vpx_encoder.h"
29 #include "vpx_mem/vpx_mem.h"
30 #include "vp9/common/vp9_onyxc_int.h"
31
32 #ifdef __MINGW32__
33 #define strtok_r strtok_s
34 #ifndef MINGW_HAS_SECURE_API
35 // proto from /usr/x86_64-w64-mingw32/include/sec_api/string_s.h
36 _CRTIMP char *__cdecl strtok_s(char *str, const char *delim, char **context);
37 #endif /* MINGW_HAS_SECURE_API */
38 #endif /* __MINGW32__ */
39
40 #ifdef _MSC_VER
41 #define strdup _strdup
42 #define strtok_r strtok_s
43 #endif
44
45 #define SVC_REFERENCE_FRAMES 8
46 #define SUPERFRAME_SLOTS (8)
47 #define SUPERFRAME_BUFFER_SIZE (SUPERFRAME_SLOTS * sizeof(uint32_t) + 2)
48
49 #define MAX_QUANTIZER 63
50
51 static const int DEFAULT_SCALE_FACTORS_NUM[VPX_SS_MAX_LAYERS] = { 4, 5, 7, 11,
52                                                                   16 };
53
54 static const int DEFAULT_SCALE_FACTORS_DEN[VPX_SS_MAX_LAYERS] = { 16, 16, 16,
55                                                                   16, 16 };
56
57 static const int DEFAULT_SCALE_FACTORS_NUM_2x[VPX_SS_MAX_LAYERS] = { 1, 2, 4 };
58
59 static const int DEFAULT_SCALE_FACTORS_DEN_2x[VPX_SS_MAX_LAYERS] = { 4, 4, 4 };
60
61 typedef enum {
62   QUANTIZER = 0,
63   BITRATE,
64   SCALE_FACTOR,
65   AUTO_ALT_REF,
66   ALL_OPTION_TYPES
67 } LAYER_OPTION_TYPE;
68
69 static const int option_max_values[ALL_OPTION_TYPES] = { 63, INT_MAX, INT_MAX,
70                                                          1 };
71
72 static const int option_min_values[ALL_OPTION_TYPES] = { 0, 0, 1, 0 };
73
74 // One encoded frame
75 typedef struct FrameData {
76   void *buf;                     // compressed data buffer
77   size_t size;                   // length of compressed data
78   vpx_codec_frame_flags_t flags; /**< flags for this frame */
79   struct FrameData *next;
80 } FrameData;
81
82 static SvcInternal_t *get_svc_internal(SvcContext *svc_ctx) {
83   if (svc_ctx == NULL) return NULL;
84   if (svc_ctx->internal == NULL) {
85     SvcInternal_t *const si = (SvcInternal_t *)malloc(sizeof(*si));
86     if (si != NULL) {
87       memset(si, 0, sizeof(*si));
88     }
89     svc_ctx->internal = si;
90   }
91   return (SvcInternal_t *)svc_ctx->internal;
92 }
93
94 static const SvcInternal_t *get_const_svc_internal(const SvcContext *svc_ctx) {
95   if (svc_ctx == NULL) return NULL;
96   return (const SvcInternal_t *)svc_ctx->internal;
97 }
98
99 static VPX_TOOLS_FORMAT_PRINTF(3, 4) int svc_log(SvcContext *svc_ctx,
100                                                  SVC_LOG_LEVEL level,
101                                                  const char *fmt, ...) {
102   char buf[512];
103   int retval = 0;
104   va_list ap;
105
106   if (level > svc_ctx->log_level) {
107     return retval;
108   }
109
110   va_start(ap, fmt);
111   retval = vsnprintf(buf, sizeof(buf), fmt, ap);
112   va_end(ap);
113
114   printf("%s", buf);
115
116   return retval;
117 }
118
119 static vpx_codec_err_t extract_option(LAYER_OPTION_TYPE type, char *input,
120                                       int *value0, int *value1) {
121   if (type == SCALE_FACTOR) {
122     *value0 = (int)strtol(input, &input, 10);
123     if (*input++ != '/') return VPX_CODEC_INVALID_PARAM;
124     *value1 = (int)strtol(input, &input, 10);
125
126     if (*value0 < option_min_values[SCALE_FACTOR] ||
127         *value1 < option_min_values[SCALE_FACTOR] ||
128         *value0 > option_max_values[SCALE_FACTOR] ||
129         *value1 > option_max_values[SCALE_FACTOR] ||
130         *value0 > *value1)  // num shouldn't be greater than den
131       return VPX_CODEC_INVALID_PARAM;
132   } else {
133     *value0 = atoi(input);
134     if (*value0 < option_min_values[type] || *value0 > option_max_values[type])
135       return VPX_CODEC_INVALID_PARAM;
136   }
137   return VPX_CODEC_OK;
138 }
139
140 static vpx_codec_err_t parse_layer_options_from_string(SvcContext *svc_ctx,
141                                                        LAYER_OPTION_TYPE type,
142                                                        const char *input,
143                                                        int *option0,
144                                                        int *option1) {
145   int i;
146   vpx_codec_err_t res = VPX_CODEC_OK;
147   char *input_string;
148   char *token;
149   const char *delim = ",";
150   char *save_ptr;
151   int num_layers = svc_ctx->spatial_layers;
152   if (type == BITRATE)
153     num_layers = svc_ctx->spatial_layers * svc_ctx->temporal_layers;
154
155   if (input == NULL || option0 == NULL ||
156       (option1 == NULL && type == SCALE_FACTOR))
157     return VPX_CODEC_INVALID_PARAM;
158
159   input_string = strdup(input);
160   if (input_string == NULL) return VPX_CODEC_MEM_ERROR;
161   token = strtok_r(input_string, delim, &save_ptr);
162   for (i = 0; i < num_layers; ++i) {
163     if (token != NULL) {
164       res = extract_option(type, token, option0 + i, option1 + i);
165       if (res != VPX_CODEC_OK) break;
166       token = strtok_r(NULL, delim, &save_ptr);
167     } else {
168       break;
169     }
170   }
171   if (res == VPX_CODEC_OK && i != num_layers) {
172     svc_log(svc_ctx, SVC_LOG_ERROR,
173             "svc: layer params type: %d    %d values required, "
174             "but only %d specified\n",
175             type, num_layers, i);
176     res = VPX_CODEC_INVALID_PARAM;
177   }
178   free(input_string);
179   return res;
180 }
181
182 /**
183  * Parse SVC encoding options
184  * Format: encoding-mode=<svc_mode>,layers=<layer_count>
185  *         scale-factors=<n1>/<d1>,<n2>/<d2>,...
186  *         quantizers=<q1>,<q2>,...
187  * svc_mode = [i|ip|alt_ip|gf]
188  */
189 static vpx_codec_err_t parse_options(SvcContext *svc_ctx, const char *options) {
190   char *input_string;
191   char *option_name;
192   char *option_value;
193   char *input_ptr = NULL;
194   SvcInternal_t *const si = get_svc_internal(svc_ctx);
195   vpx_codec_err_t res = VPX_CODEC_OK;
196   int i, alt_ref_enabled = 0;
197
198   if (options == NULL) return VPX_CODEC_OK;
199   input_string = strdup(options);
200   if (input_string == NULL) return VPX_CODEC_MEM_ERROR;
201
202   // parse option name
203   option_name = strtok_r(input_string, "=", &input_ptr);
204   while (option_name != NULL) {
205     // parse option value
206     option_value = strtok_r(NULL, " ", &input_ptr);
207     if (option_value == NULL) {
208       svc_log(svc_ctx, SVC_LOG_ERROR, "option missing value: %s\n",
209               option_name);
210       res = VPX_CODEC_INVALID_PARAM;
211       break;
212     }
213     if (strcmp("spatial-layers", option_name) == 0) {
214       svc_ctx->spatial_layers = atoi(option_value);
215     } else if (strcmp("temporal-layers", option_name) == 0) {
216       svc_ctx->temporal_layers = atoi(option_value);
217     } else if (strcmp("scale-factors", option_name) == 0) {
218       res = parse_layer_options_from_string(svc_ctx, SCALE_FACTOR, option_value,
219                                             si->svc_params.scaling_factor_num,
220                                             si->svc_params.scaling_factor_den);
221       if (res != VPX_CODEC_OK) break;
222     } else if (strcmp("max-quantizers", option_name) == 0) {
223       res =
224           parse_layer_options_from_string(svc_ctx, QUANTIZER, option_value,
225                                           si->svc_params.max_quantizers, NULL);
226       if (res != VPX_CODEC_OK) break;
227     } else if (strcmp("min-quantizers", option_name) == 0) {
228       res =
229           parse_layer_options_from_string(svc_ctx, QUANTIZER, option_value,
230                                           si->svc_params.min_quantizers, NULL);
231       if (res != VPX_CODEC_OK) break;
232     } else if (strcmp("auto-alt-refs", option_name) == 0) {
233       res = parse_layer_options_from_string(svc_ctx, AUTO_ALT_REF, option_value,
234                                             si->enable_auto_alt_ref, NULL);
235       if (res != VPX_CODEC_OK) break;
236     } else if (strcmp("bitrates", option_name) == 0) {
237       res = parse_layer_options_from_string(svc_ctx, BITRATE, option_value,
238                                             si->bitrates, NULL);
239       if (res != VPX_CODEC_OK) break;
240     } else if (strcmp("multi-frame-contexts", option_name) == 0) {
241       si->use_multiple_frame_contexts = atoi(option_value);
242     } else {
243       svc_log(svc_ctx, SVC_LOG_ERROR, "invalid option: %s\n", option_name);
244       res = VPX_CODEC_INVALID_PARAM;
245       break;
246     }
247     option_name = strtok_r(NULL, "=", &input_ptr);
248   }
249   free(input_string);
250
251   for (i = 0; i < svc_ctx->spatial_layers; ++i) {
252     if (si->svc_params.max_quantizers[i] > MAX_QUANTIZER ||
253         si->svc_params.max_quantizers[i] < 0 ||
254         si->svc_params.min_quantizers[i] > si->svc_params.max_quantizers[i] ||
255         si->svc_params.min_quantizers[i] < 0)
256       res = VPX_CODEC_INVALID_PARAM;
257   }
258
259   if (si->use_multiple_frame_contexts &&
260       (svc_ctx->spatial_layers > 3 ||
261        svc_ctx->spatial_layers * svc_ctx->temporal_layers > 4))
262     res = VPX_CODEC_INVALID_PARAM;
263
264   for (i = 0; i < svc_ctx->spatial_layers; ++i)
265     alt_ref_enabled += si->enable_auto_alt_ref[i];
266   if (alt_ref_enabled > REF_FRAMES - svc_ctx->spatial_layers) {
267     svc_log(svc_ctx, SVC_LOG_ERROR,
268             "svc: auto alt ref: Maxinum %d(REF_FRAMES - layers) layers could"
269             "enabled auto alt reference frame, but %d layers are enabled\n",
270             REF_FRAMES - svc_ctx->spatial_layers, alt_ref_enabled);
271     res = VPX_CODEC_INVALID_PARAM;
272   }
273
274   return res;
275 }
276
277 vpx_codec_err_t vpx_svc_set_options(SvcContext *svc_ctx, const char *options) {
278   SvcInternal_t *const si = get_svc_internal(svc_ctx);
279   if (svc_ctx == NULL || options == NULL || si == NULL) {
280     return VPX_CODEC_INVALID_PARAM;
281   }
282   strncpy(si->options, options, sizeof(si->options));
283   si->options[sizeof(si->options) - 1] = '\0';
284   return VPX_CODEC_OK;
285 }
286
287 static vpx_codec_err_t assign_layer_bitrates(
288     const SvcContext *svc_ctx, vpx_codec_enc_cfg_t *const enc_cfg) {
289   int i;
290   const SvcInternal_t *const si = get_const_svc_internal(svc_ctx);
291   int sl, tl, spatial_layer_target;
292
293   if (svc_ctx->temporal_layering_mode != 0) {
294     if (si->bitrates[0] != 0) {
295       unsigned int total_bitrate = 0;
296       for (sl = 0; sl < svc_ctx->spatial_layers; ++sl) {
297         total_bitrate += si->bitrates[sl * svc_ctx->temporal_layers +
298                                       svc_ctx->temporal_layers - 1];
299         for (tl = 0; tl < svc_ctx->temporal_layers; ++tl) {
300           enc_cfg->ss_target_bitrate[sl * svc_ctx->temporal_layers] +=
301               (unsigned int)si->bitrates[sl * svc_ctx->temporal_layers + tl];
302           enc_cfg->layer_target_bitrate[sl * svc_ctx->temporal_layers + tl] =
303               si->bitrates[sl * svc_ctx->temporal_layers + tl];
304           if (tl > 0 && (si->bitrates[sl * svc_ctx->temporal_layers + tl] <=
305                          si->bitrates[sl * svc_ctx->temporal_layers + tl - 1]))
306             return VPX_CODEC_INVALID_PARAM;
307         }
308       }
309       if (total_bitrate != enc_cfg->rc_target_bitrate)
310         return VPX_CODEC_INVALID_PARAM;
311     } else {
312       float total = 0;
313       float alloc_ratio[VPX_MAX_LAYERS] = { 0 };
314
315       for (sl = 0; sl < svc_ctx->spatial_layers; ++sl) {
316         if (si->svc_params.scaling_factor_den[sl] > 0) {
317           alloc_ratio[sl] = (float)(pow(2, sl));
318           total += alloc_ratio[sl];
319         }
320       }
321
322       for (sl = 0; sl < svc_ctx->spatial_layers; ++sl) {
323         enc_cfg->ss_target_bitrate[sl] = spatial_layer_target =
324             (unsigned int)(enc_cfg->rc_target_bitrate * alloc_ratio[sl] /
325                            total);
326         if (svc_ctx->temporal_layering_mode == 3) {
327           enc_cfg->layer_target_bitrate[sl * svc_ctx->temporal_layers] =
328               (spatial_layer_target * 6) / 10;  // 60%
329           enc_cfg->layer_target_bitrate[sl * svc_ctx->temporal_layers + 1] =
330               (spatial_layer_target * 8) / 10;  // 80%
331           enc_cfg->layer_target_bitrate[sl * svc_ctx->temporal_layers + 2] =
332               spatial_layer_target;
333         } else if (svc_ctx->temporal_layering_mode == 2 ||
334                    svc_ctx->temporal_layering_mode == 1) {
335           enc_cfg->layer_target_bitrate[sl * svc_ctx->temporal_layers] =
336               spatial_layer_target * 2 / 3;
337           enc_cfg->layer_target_bitrate[sl * svc_ctx->temporal_layers + 1] =
338               spatial_layer_target;
339         } else {
340           // User should explicitly assign bitrates in this case.
341           assert(0);
342         }
343       }
344     }
345   } else {
346     if (si->bitrates[0] != 0) {
347       unsigned int total_bitrate = 0;
348       for (i = 0; i < svc_ctx->spatial_layers; ++i) {
349         enc_cfg->ss_target_bitrate[i] = (unsigned int)si->bitrates[i];
350         enc_cfg->layer_target_bitrate[i] = (unsigned int)si->bitrates[i];
351         total_bitrate += si->bitrates[i];
352       }
353       if (total_bitrate != enc_cfg->rc_target_bitrate)
354         return VPX_CODEC_INVALID_PARAM;
355     } else {
356       float total = 0;
357       float alloc_ratio[VPX_MAX_LAYERS] = { 0 };
358
359       for (i = 0; i < svc_ctx->spatial_layers; ++i) {
360         if (si->svc_params.scaling_factor_den[i] > 0) {
361           alloc_ratio[i] = (float)(si->svc_params.scaling_factor_num[i] * 1.0 /
362                                    si->svc_params.scaling_factor_den[i]);
363
364           alloc_ratio[i] *= alloc_ratio[i];
365           total += alloc_ratio[i];
366         }
367       }
368       for (i = 0; i < VPX_SS_MAX_LAYERS; ++i) {
369         if (total > 0) {
370           enc_cfg->layer_target_bitrate[i] =
371               (unsigned int)(enc_cfg->rc_target_bitrate * alloc_ratio[i] /
372                              total);
373         }
374       }
375     }
376   }
377   return VPX_CODEC_OK;
378 }
379
380 vpx_codec_err_t vpx_svc_init(SvcContext *svc_ctx, vpx_codec_ctx_t *codec_ctx,
381                              vpx_codec_iface_t *iface,
382                              vpx_codec_enc_cfg_t *enc_cfg) {
383   vpx_codec_err_t res;
384   int i, sl, tl;
385   SvcInternal_t *const si = get_svc_internal(svc_ctx);
386   if (svc_ctx == NULL || codec_ctx == NULL || iface == NULL ||
387       enc_cfg == NULL) {
388     return VPX_CODEC_INVALID_PARAM;
389   }
390   if (si == NULL) return VPX_CODEC_MEM_ERROR;
391
392   si->codec_ctx = codec_ctx;
393
394   si->width = enc_cfg->g_w;
395   si->height = enc_cfg->g_h;
396
397   si->kf_dist = enc_cfg->kf_max_dist;
398
399   if (svc_ctx->spatial_layers == 0)
400     svc_ctx->spatial_layers = VPX_SS_DEFAULT_LAYERS;
401   if (svc_ctx->spatial_layers < 1 ||
402       svc_ctx->spatial_layers > VPX_SS_MAX_LAYERS) {
403     svc_log(svc_ctx, SVC_LOG_ERROR, "spatial layers: invalid value: %d\n",
404             svc_ctx->spatial_layers);
405     return VPX_CODEC_INVALID_PARAM;
406   }
407
408   // Note: temporal_layering_mode only applies to one-pass CBR
409   // si->svc_params.temporal_layering_mode = svc_ctx->temporal_layering_mode;
410   if (svc_ctx->temporal_layering_mode == 3) {
411     svc_ctx->temporal_layers = 3;
412   } else if (svc_ctx->temporal_layering_mode == 2 ||
413              svc_ctx->temporal_layering_mode == 1) {
414     svc_ctx->temporal_layers = 2;
415   }
416
417   for (sl = 0; sl < VPX_SS_MAX_LAYERS; ++sl) {
418     si->svc_params.scaling_factor_num[sl] = DEFAULT_SCALE_FACTORS_NUM[sl];
419     si->svc_params.scaling_factor_den[sl] = DEFAULT_SCALE_FACTORS_DEN[sl];
420     si->svc_params.speed_per_layer[sl] = svc_ctx->speed;
421   }
422   if (enc_cfg->rc_end_usage == VPX_CBR && enc_cfg->g_pass == VPX_RC_ONE_PASS &&
423       svc_ctx->spatial_layers <= 3) {
424     for (sl = 0; sl < svc_ctx->spatial_layers; ++sl) {
425       int sl2 = (svc_ctx->spatial_layers == 2) ? sl + 1 : sl;
426       si->svc_params.scaling_factor_num[sl] = DEFAULT_SCALE_FACTORS_NUM_2x[sl2];
427       si->svc_params.scaling_factor_den[sl] = DEFAULT_SCALE_FACTORS_DEN_2x[sl2];
428     }
429     if (svc_ctx->spatial_layers == 1) {
430       si->svc_params.scaling_factor_num[0] = 1;
431       si->svc_params.scaling_factor_den[0] = 1;
432     }
433   }
434   for (tl = 0; tl < svc_ctx->temporal_layers; ++tl) {
435     for (sl = 0; sl < svc_ctx->spatial_layers; ++sl) {
436       i = sl * svc_ctx->temporal_layers + tl;
437       si->svc_params.max_quantizers[i] = MAX_QUANTIZER;
438       si->svc_params.min_quantizers[i] = 0;
439       if (enc_cfg->rc_end_usage == VPX_CBR &&
440           enc_cfg->g_pass == VPX_RC_ONE_PASS) {
441         si->svc_params.max_quantizers[i] = 56;
442         si->svc_params.min_quantizers[i] = 2;
443       }
444     }
445   }
446
447   // Parse aggregate command line options. Options must start with
448   // "layers=xx" then followed by other options
449   res = parse_options(svc_ctx, si->options);
450   if (res != VPX_CODEC_OK) return res;
451
452   if (svc_ctx->spatial_layers < 1) svc_ctx->spatial_layers = 1;
453   if (svc_ctx->spatial_layers > VPX_SS_MAX_LAYERS)
454     svc_ctx->spatial_layers = VPX_SS_MAX_LAYERS;
455
456   if (svc_ctx->temporal_layers < 1) svc_ctx->temporal_layers = 1;
457   if (svc_ctx->temporal_layers > VPX_TS_MAX_LAYERS)
458     svc_ctx->temporal_layers = VPX_TS_MAX_LAYERS;
459
460   if (svc_ctx->temporal_layers * svc_ctx->spatial_layers > VPX_MAX_LAYERS) {
461     svc_log(
462         svc_ctx, SVC_LOG_ERROR,
463         "spatial layers * temporal layers (%d) exceeds the maximum number of "
464         "allowed layers of %d\n",
465         svc_ctx->spatial_layers * svc_ctx->temporal_layers, VPX_MAX_LAYERS);
466     return VPX_CODEC_INVALID_PARAM;
467   }
468   res = assign_layer_bitrates(svc_ctx, enc_cfg);
469   if (res != VPX_CODEC_OK) {
470     svc_log(svc_ctx, SVC_LOG_ERROR,
471             "layer bitrates incorrect: \n"
472             "1) spatial layer bitrates should sum up to target \n"
473             "2) temporal layer bitrates should be increasing within \n"
474             "a spatial layer \n");
475     return VPX_CODEC_INVALID_PARAM;
476   }
477
478   if (svc_ctx->temporal_layers > 1) {
479     int i;
480     for (i = 0; i < svc_ctx->temporal_layers; ++i) {
481       enc_cfg->ts_target_bitrate[i] =
482           enc_cfg->rc_target_bitrate / svc_ctx->temporal_layers;
483       enc_cfg->ts_rate_decimator[i] = 1 << (svc_ctx->temporal_layers - 1 - i);
484     }
485   }
486
487   if (svc_ctx->threads) enc_cfg->g_threads = svc_ctx->threads;
488
489   // Modify encoder configuration
490   enc_cfg->ss_number_layers = svc_ctx->spatial_layers;
491   enc_cfg->ts_number_layers = svc_ctx->temporal_layers;
492
493   if (enc_cfg->rc_end_usage == VPX_CBR) {
494     enc_cfg->rc_resize_allowed = 0;
495     enc_cfg->rc_min_quantizer = 2;
496     enc_cfg->rc_max_quantizer = 56;
497     enc_cfg->rc_undershoot_pct = 50;
498     enc_cfg->rc_overshoot_pct = 50;
499     enc_cfg->rc_buf_initial_sz = 500;
500     enc_cfg->rc_buf_optimal_sz = 600;
501     enc_cfg->rc_buf_sz = 1000;
502   }
503
504   for (tl = 0; tl < svc_ctx->temporal_layers; ++tl) {
505     for (sl = 0; sl < svc_ctx->spatial_layers; ++sl) {
506       i = sl * svc_ctx->temporal_layers + tl;
507       if (enc_cfg->rc_end_usage == VPX_CBR &&
508           enc_cfg->g_pass == VPX_RC_ONE_PASS) {
509         si->svc_params.max_quantizers[i] = enc_cfg->rc_max_quantizer;
510         si->svc_params.min_quantizers[i] = enc_cfg->rc_min_quantizer;
511       }
512     }
513   }
514
515   if (enc_cfg->g_error_resilient == 0 && si->use_multiple_frame_contexts == 0)
516     enc_cfg->g_error_resilient = 1;
517
518   // Initialize codec
519   res = vpx_codec_enc_init(codec_ctx, iface, enc_cfg, VPX_CODEC_USE_PSNR);
520   if (res != VPX_CODEC_OK) {
521     svc_log(svc_ctx, SVC_LOG_ERROR, "svc_enc_init error\n");
522     return res;
523   }
524   if (svc_ctx->spatial_layers > 1 || svc_ctx->temporal_layers > 1) {
525     vpx_codec_control(codec_ctx, VP9E_SET_SVC, 1);
526     vpx_codec_control(codec_ctx, VP9E_SET_SVC_PARAMETERS, &si->svc_params);
527   }
528   return VPX_CODEC_OK;
529 }
530
531 /**
532  * Encode a frame into multiple layers
533  * Create a superframe containing the individual layers
534  */
535 vpx_codec_err_t vpx_svc_encode(SvcContext *svc_ctx, vpx_codec_ctx_t *codec_ctx,
536                                struct vpx_image *rawimg, vpx_codec_pts_t pts,
537                                int64_t duration, int deadline) {
538   vpx_codec_err_t res;
539   vpx_codec_iter_t iter;
540   const vpx_codec_cx_pkt_t *cx_pkt;
541   SvcInternal_t *const si = get_svc_internal(svc_ctx);
542   if (svc_ctx == NULL || codec_ctx == NULL || si == NULL) {
543     return VPX_CODEC_INVALID_PARAM;
544   }
545
546   res =
547       vpx_codec_encode(codec_ctx, rawimg, pts, (uint32_t)duration, 0, deadline);
548   if (res != VPX_CODEC_OK) {
549     return res;
550   }
551   // save compressed data
552   iter = NULL;
553   while ((cx_pkt = vpx_codec_get_cx_data(codec_ctx, &iter))) {
554     switch (cx_pkt->kind) {
555       case VPX_CODEC_PSNR_PKT: {
556       }
557         ++si->psnr_pkt_received;
558         break;
559       default: { break; }
560     }
561   }
562
563   return VPX_CODEC_OK;
564 }
565
566 static double calc_psnr(double d) {
567   if (d == 0) return 100;
568   return -10.0 * log(d) / log(10.0);
569 }
570
571 // dump accumulated statistics and reset accumulated values
572 void vpx_svc_dump_statistics(SvcContext *svc_ctx) {
573   int number_of_frames;
574   int i, j;
575   uint32_t bytes_total = 0;
576   double scale[COMPONENTS];
577   double psnr[COMPONENTS];
578   double mse[COMPONENTS];
579   double y_scale;
580
581   SvcInternal_t *const si = get_svc_internal(svc_ctx);
582   if (svc_ctx == NULL || si == NULL) return;
583
584   number_of_frames = si->psnr_pkt_received;
585   if (number_of_frames <= 0) return;
586
587   svc_log(svc_ctx, SVC_LOG_INFO, "\n");
588   for (i = 0; i < svc_ctx->spatial_layers; ++i) {
589     svc_log(svc_ctx, SVC_LOG_INFO,
590             "Layer %d Average PSNR=[%2.3f, %2.3f, %2.3f, %2.3f], Bytes=[%u]\n",
591             i, si->psnr_sum[i][0] / number_of_frames,
592             si->psnr_sum[i][1] / number_of_frames,
593             si->psnr_sum[i][2] / number_of_frames,
594             si->psnr_sum[i][3] / number_of_frames, si->bytes_sum[i]);
595     // the following psnr calculation is deduced from ffmpeg.c#print_report
596     y_scale = si->width * si->height * 255.0 * 255.0 * number_of_frames;
597     scale[1] = y_scale;
598     scale[2] = scale[3] = y_scale / 4;  // U or V
599     scale[0] = y_scale * 1.5;           // total
600
601     for (j = 0; j < COMPONENTS; j++) {
602       psnr[j] = calc_psnr(si->sse_sum[i][j] / scale[j]);
603       mse[j] = si->sse_sum[i][j] * 255.0 * 255.0 / scale[j];
604     }
605     svc_log(svc_ctx, SVC_LOG_INFO,
606             "Layer %d Overall PSNR=[%2.3f, %2.3f, %2.3f, %2.3f]\n", i, psnr[0],
607             psnr[1], psnr[2], psnr[3]);
608     svc_log(svc_ctx, SVC_LOG_INFO,
609             "Layer %d Overall MSE=[%2.3f, %2.3f, %2.3f, %2.3f]\n", i, mse[0],
610             mse[1], mse[2], mse[3]);
611
612     bytes_total += si->bytes_sum[i];
613     // Clear sums for next time.
614     si->bytes_sum[i] = 0;
615     for (j = 0; j < COMPONENTS; ++j) {
616       si->psnr_sum[i][j] = 0;
617       si->sse_sum[i][j] = 0;
618     }
619   }
620
621   // only display statistics once
622   si->psnr_pkt_received = 0;
623
624   svc_log(svc_ctx, SVC_LOG_INFO, "Total Bytes=[%u]\n", bytes_total);
625 }
626
627 void vpx_svc_release(SvcContext *svc_ctx) {
628   SvcInternal_t *si;
629   if (svc_ctx == NULL) return;
630   // do not use get_svc_internal as it will unnecessarily allocate an
631   // SvcInternal_t if it was not already allocated
632   si = (SvcInternal_t *)svc_ctx->internal;
633   if (si != NULL) {
634     free(si);
635     svc_ctx->internal = NULL;
636   }
637 }