svc_encodeframe.c 34.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 *  Copyright (c) 2013 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

/**
 * @file
 * VP9 SVC encoding support via libvpx
 */

16
#include <assert.h>
17
#include <math.h>
18 19 20 21 22 23 24 25 26
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define VPX_DISABLE_CTRL_TYPECHECKS 1
#define VPX_CODEC_DISABLE_COMPAT 1
#include "vpx/svc_context.h"
#include "vpx/vp8cx.h"
#include "vpx/vpx_encoder.h"
27
#include "vpx_mem/vpx_mem.h"
28

29
#ifdef __MINGW32__
30
#define strtok_r strtok_s
31
#ifndef MINGW_HAS_SECURE_API
32 33
// proto from /usr/x86_64-w64-mingw32/include/sec_api/string_s.h
_CRTIMP char *__cdecl strtok_s(char *str, const char *delim, char **context);
34 35
#endif  /* MINGW_HAS_SECURE_API */
#endif  /* __MINGW32__ */
36 37 38 39 40 41 42 43 44 45

#ifdef _MSC_VER
#define strdup _strdup
#define strtok_r strtok_s
#endif

#define SVC_REFERENCE_FRAMES 8
#define SUPERFRAME_SLOTS (8)
#define SUPERFRAME_BUFFER_SIZE (SUPERFRAME_SLOTS * sizeof(uint32_t) + 2)
#define OPTION_BUFFER_SIZE 256
46
#define COMPONENTS 4  // psnr & sse statistics maintained for total, y, u, v
47 48 49 50

static const char *DEFAULT_QUANTIZER_VALUES = "60,53,39,33,27";
static const char *DEFAULT_SCALE_FACTORS = "4/16,5/16,7/16,11/16,16/16";

51 52 53 54 55 56 57 58
// One encoded frame
typedef struct FrameData {
  void                     *buf;    // compressed data buffer
  size_t                    size;  // length of compressed data
  vpx_codec_frame_flags_t   flags;    /**< flags for this frame */
  struct FrameData         *next;
} FrameData;

59 60 61
typedef struct SvcInternal {
  char options[OPTION_BUFFER_SIZE];        // set by vpx_svc_set_options
  char quantizers[OPTION_BUFFER_SIZE];     // set by vpx_svc_set_quantizers
62 63
  char quantizers_keyframe[OPTION_BUFFER_SIZE];  // set by
                                                 // vpx_svc_set_quantizers
64 65 66 67 68
  char scale_factors[OPTION_BUFFER_SIZE];  // set by vpx_svc_set_scale_factors

  // values extracted from option, quantizers
  int scaling_factor_num[VPX_SS_MAX_LAYERS];
  int scaling_factor_den[VPX_SS_MAX_LAYERS];
69
  int quantizer_keyframe[VPX_SS_MAX_LAYERS];
70 71 72
  int quantizer[VPX_SS_MAX_LAYERS];

  // accumulated statistics
73 74 75
  double psnr_sum[VPX_SS_MAX_LAYERS][COMPONENTS];   // total/Y/U/V
  uint64_t sse_sum[VPX_SS_MAX_LAYERS][COMPONENTS];
  uint32_t bytes_sum[VPX_SS_MAX_LAYERS];
76 77 78 79 80 81 82 83

  // codec encoding values
  int width;    // width of highest layer
  int height;   // height of highest layer
  int kf_dist;  // distance between keyframes

  // state variables
  int encode_frame_count;
84
  int frame_received;
85 86 87 88 89 90
  int frame_within_gop;
  vpx_enc_frame_flags_t enc_frame_flags;
  int layers;
  int layer;
  int is_keyframe;

91 92
  FrameData *frame_list;
  FrameData *frame_temp;
93

94 95 96 97
  char *rc_stats_buf;
  size_t rc_stats_buf_size;
  size_t rc_stats_buf_used;

98 99 100 101
  char message_buffer[2048];
  vpx_codec_ctx_t *codec_ctx;
} SvcInternal;

102 103 104 105 106 107
// create FrameData from encoder output
static struct FrameData *fd_create(void *buf, size_t size,
                                   vpx_codec_frame_flags_t flags) {
  struct FrameData *const frame_data =
      (struct FrameData *)vpx_malloc(sizeof(*frame_data));
  if (frame_data == NULL) {
108 109
    return NULL;
  }
110 111 112
  frame_data->buf = vpx_malloc(size);
  if (frame_data->buf == NULL) {
    vpx_free(frame_data);
113 114
    return NULL;
  }
115 116 117 118
  vpx_memcpy(frame_data->buf, buf, size);
  frame_data->size = size;
  frame_data->flags = flags;
  return frame_data;
119 120
}

121 122 123 124 125 126
// free FrameData
static void fd_free(struct FrameData *p) {
  if (p) {
    if (p->buf)
      vpx_free(p->buf);
    vpx_free(p);
127 128 129
  }
}

130 131 132
// add FrameData to list
static void fd_list_add(struct FrameData **list, struct FrameData *layer_data) {
  struct FrameData **p = list;
133 134 135 136 137 138

  while (*p != NULL) p = &(*p)->next;
  *p = layer_data;
  layer_data->next = NULL;
}

139 140 141
// free FrameData list
static void fd_free_list(struct FrameData *list) {
  struct FrameData *p = list;
142 143 144

  while (p) {
    list = list->next;
145
    fd_free(p);
146 147 148 149 150 151 152
    p = list;
  }
}

static SvcInternal *get_svc_internal(SvcContext *svc_ctx) {
  if (svc_ctx == NULL) return NULL;
  if (svc_ctx->internal == NULL) {
153
    SvcInternal *const si = (SvcInternal *)malloc(sizeof(*si));
154 155 156 157 158
    if (si != NULL) {
      memset(si, 0, sizeof(*si));
    }
    svc_ctx->internal = si;
  }
159
  return (SvcInternal *)svc_ctx->internal;
160 161 162 163
}

static const SvcInternal *get_const_svc_internal(const SvcContext *svc_ctx) {
  if (svc_ctx == NULL) return NULL;
164
  return (const SvcInternal *)svc_ctx->internal;
165 166 167 168 169 170 171
}

static void svc_log_reset(SvcContext *svc_ctx) {
  SvcInternal *const si = (SvcInternal *)svc_ctx->internal;
  si->message_buffer[0] = '\0';
}

172 173
static int svc_log(SvcContext *svc_ctx, SVC_LOG_LEVEL level,
                   const char *fmt, ...) {
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  char buf[512];
  int retval = 0;
  va_list ap;
  SvcInternal *const si = get_svc_internal(svc_ctx);

  if (level > svc_ctx->log_level) {
    return retval;
  }

  va_start(ap, fmt);
  retval = vsnprintf(buf, sizeof(buf), fmt, ap);
  va_end(ap);

  if (svc_ctx->log_print) {
    printf("%s", buf);
  } else {
    strncat(si->message_buffer, buf,
            sizeof(si->message_buffer) - strlen(si->message_buffer) - 1);
  }

  if (level == SVC_LOG_ERROR) {
    si->codec_ctx->err_detail = si->message_buffer;
  }
  return retval;
}

static vpx_codec_err_t set_option_encoding_mode(SvcContext *svc_ctx,
                                                const char *value_str) {
  if (strcmp(value_str, "i") == 0) {
    svc_ctx->encoding_mode = INTER_LAYER_PREDICTION_I;
  } else if (strcmp(value_str, "alt-ip") == 0) {
    svc_ctx->encoding_mode = ALT_INTER_LAYER_PREDICTION_IP;
  } else if (strcmp(value_str, "ip") == 0) {
    svc_ctx->encoding_mode = INTER_LAYER_PREDICTION_IP;
  } else if (strcmp(value_str, "gf") == 0) {
    svc_ctx->encoding_mode = USE_GOLDEN_FRAME;
  } else {
    svc_log(svc_ctx, SVC_LOG_ERROR, "invalid encoding mode: %s", value_str);
    return VPX_CODEC_INVALID_PARAM;
  }
  return VPX_CODEC_OK;
}

static vpx_codec_err_t parse_quantizer_values(SvcContext *svc_ctx,
218 219
                                              const char *quantizer_values,
                                              const int is_keyframe) {
220 221 222 223 224 225
  char *input_string;
  char *token;
  const char *delim = ",";
  char *save_ptr;
  int found = 0;
  int i, q;
226
  vpx_codec_err_t res = VPX_CODEC_OK;
227 228 229
  SvcInternal *const si = get_svc_internal(svc_ctx);

  if (quantizer_values == NULL || strlen(quantizer_values) == 0) {
230 231 232 233 234
    if (is_keyframe) {
      // If there non settings for key frame, we will apply settings from
      // non key frame. So just simply return here.
      return VPX_CODEC_INVALID_PARAM;
    }
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    input_string = strdup(DEFAULT_QUANTIZER_VALUES);
  } else {
    input_string = strdup(quantizer_values);
  }

  token = strtok_r(input_string, delim, &save_ptr);
  for (i = 0; i < svc_ctx->spatial_layers; ++i) {
    if (token != NULL) {
      q = atoi(token);
      if (q <= 0 || q > 100) {
        svc_log(svc_ctx, SVC_LOG_ERROR,
                "svc-quantizer-values: invalid value %s\n", token);
        res = VPX_CODEC_INVALID_PARAM;
        break;
      }
      token = strtok_r(NULL, delim, &save_ptr);
      found = i + 1;
    } else {
      q = 0;
    }
255 256 257 258 259 260
    if (is_keyframe) {
      si->quantizer_keyframe[i + VPX_SS_MAX_LAYERS - svc_ctx->spatial_layers]
      = q;
    } else {
      si->quantizer[i + VPX_SS_MAX_LAYERS - svc_ctx->spatial_layers] = q;
    }
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
  }
  if (res == VPX_CODEC_OK && found != svc_ctx->spatial_layers) {
    svc_log(svc_ctx, SVC_LOG_ERROR,
            "svc: quantizers: %d values required, but only %d specified\n",
            svc_ctx->spatial_layers, found);
    res = VPX_CODEC_INVALID_PARAM;
  }
  free(input_string);
  return res;
}

static void log_invalid_scale_factor(SvcContext *svc_ctx, const char *value) {
  svc_log(svc_ctx, SVC_LOG_ERROR, "svc scale-factors: invalid value %s\n",
          value);
}

static vpx_codec_err_t parse_scale_factors(SvcContext *svc_ctx,
                                           const char *scale_factors) {
  char *input_string;
  char *token;
  const char *delim = ",";
  char *save_ptr;
  int found = 0;
  int i;
  int64_t num, den;
286
  vpx_codec_err_t res = VPX_CODEC_OK;
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
  SvcInternal *const si = get_svc_internal(svc_ctx);

  if (scale_factors == NULL || strlen(scale_factors) == 0) {
    input_string = strdup(DEFAULT_SCALE_FACTORS);
  } else {
    input_string = strdup(scale_factors);
  }
  token = strtok_r(input_string, delim, &save_ptr);
  for (i = 0; i < svc_ctx->spatial_layers; ++i) {
    num = den = 0;
    if (token != NULL) {
      num = strtol(token, &token, 10);
      if (num <= 0) {
        log_invalid_scale_factor(svc_ctx, token);
        res = VPX_CODEC_INVALID_PARAM;
        break;
      }
      if (*token++ != '/') {
        log_invalid_scale_factor(svc_ctx, token);
        res = VPX_CODEC_INVALID_PARAM;
        break;
      }
      den = strtol(token, &token, 10);
      if (den <= 0) {
        log_invalid_scale_factor(svc_ctx, token);
        res = VPX_CODEC_INVALID_PARAM;
        break;
      }
      token = strtok_r(NULL, delim, &save_ptr);
      found = i + 1;
    }
    si->scaling_factor_num[i + VPX_SS_MAX_LAYERS - svc_ctx->spatial_layers] =
        (int)num;
    si->scaling_factor_den[i + VPX_SS_MAX_LAYERS - svc_ctx->spatial_layers] =
        (int)den;
  }
  if (res == VPX_CODEC_OK && found != svc_ctx->spatial_layers) {
    svc_log(svc_ctx, SVC_LOG_ERROR,
            "svc: scale-factors: %d values required, but only %d specified\n",
            svc_ctx->spatial_layers, found);
    res = VPX_CODEC_INVALID_PARAM;
  }
  free(input_string);
  return res;
}

/**
 * Parse SVC encoding options
 * Format: encoding-mode=<svc_mode>,layers=<layer_count>
 *         scale-factors=<n1>/<d1>,<n2>/<d2>,...
 *         quantizers=<q1>,<q2>,...
 * svc_mode = [i|ip|alt_ip|gf]
 */
static vpx_codec_err_t parse_options(SvcContext *svc_ctx, const char *options) {
  char *input_string;
  char *option_name;
  char *option_value;
  char *input_ptr;
345
  int is_keyframe_qaunt_set = 0;
346
  vpx_codec_err_t res = VPX_CODEC_OK;
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370

  if (options == NULL) return VPX_CODEC_OK;
  input_string = strdup(options);

  // parse option name
  option_name = strtok_r(input_string, "=", &input_ptr);
  while (option_name != NULL) {
    // parse option value
    option_value = strtok_r(NULL, " ", &input_ptr);
    if (option_value == NULL) {
      svc_log(svc_ctx, SVC_LOG_ERROR, "option missing value: %s\n",
              option_name);
      res = VPX_CODEC_INVALID_PARAM;
      break;
    }
    if (strcmp("encoding-mode", option_name) == 0) {
      res = set_option_encoding_mode(svc_ctx, option_value);
      if (res != VPX_CODEC_OK) break;
    } else if (strcmp("layers", option_name) == 0) {
      svc_ctx->spatial_layers = atoi(option_value);
    } else if (strcmp("scale-factors", option_name) == 0) {
      res = parse_scale_factors(svc_ctx, option_value);
      if (res != VPX_CODEC_OK) break;
    } else if (strcmp("quantizers", option_name) == 0) {
371
      res = parse_quantizer_values(svc_ctx, option_value, 0);
372
      if (res != VPX_CODEC_OK) break;
373 374 375 376 377 378 379 380 381
      if (!is_keyframe_qaunt_set) {
        SvcInternal *const si = get_svc_internal(svc_ctx);
        memcpy(get_svc_internal(svc_ctx)->quantizer_keyframe, si->quantizer,
               sizeof(si->quantizer));
      }
    } else if (strcmp("quantizers-keyframe", option_name) == 0) {
      res = parse_quantizer_values(svc_ctx, option_value, 1);
      if (res != VPX_CODEC_OK) break;
      is_keyframe_qaunt_set = 1;
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    } else {
      svc_log(svc_ctx, SVC_LOG_ERROR, "invalid option: %s\n", option_name);
      res = VPX_CODEC_INVALID_PARAM;
      break;
    }
    option_name = strtok_r(NULL, "=", &input_ptr);
  }
  free(input_string);
  return res;
}

vpx_codec_err_t vpx_svc_set_options(SvcContext *svc_ctx, const char *options) {
  SvcInternal *const si = get_svc_internal(svc_ctx);
  if (svc_ctx == NULL || options == NULL || si == NULL) {
    return VPX_CODEC_INVALID_PARAM;
  }
  strncpy(si->options, options, sizeof(si->options));
  si->options[sizeof(si->options) - 1] = '\0';
  return VPX_CODEC_OK;
}

vpx_codec_err_t vpx_svc_set_quantizers(SvcContext *svc_ctx,
404 405
                                       const char *quantizers,
                                       const int is_for_keyframe) {
406 407 408 409
  SvcInternal *const si = get_svc_internal(svc_ctx);
  if (svc_ctx == NULL || quantizers == NULL || si == NULL) {
    return VPX_CODEC_INVALID_PARAM;
  }
410 411 412 413 414 415 416
  if (is_for_keyframe) {
    strncpy(si->quantizers_keyframe, quantizers, sizeof(si->quantizers));
    si->quantizers_keyframe[sizeof(si->quantizers_keyframe) - 1] = '\0';
  } else {
    strncpy(si->quantizers, quantizers, sizeof(si->quantizers));
    si->quantizers[sizeof(si->quantizers) - 1] = '\0';
  }
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
  return VPX_CODEC_OK;
}

vpx_codec_err_t vpx_svc_set_scale_factors(SvcContext *svc_ctx,
                                          const char *scale_factors) {
  SvcInternal *const si = get_svc_internal(svc_ctx);
  if (svc_ctx == NULL || scale_factors == NULL || si == NULL) {
    return VPX_CODEC_INVALID_PARAM;
  }
  strncpy(si->scale_factors, scale_factors, sizeof(si->scale_factors));
  si->scale_factors[sizeof(si->scale_factors) - 1] = '\0';
  return VPX_CODEC_OK;
}

vpx_codec_err_t vpx_svc_init(SvcContext *svc_ctx, vpx_codec_ctx_t *codec_ctx,
                             vpx_codec_iface_t *iface,
                             vpx_codec_enc_cfg_t *enc_cfg) {
  vpx_codec_err_t res;
  SvcInternal *const si = get_svc_internal(svc_ctx);
  if (svc_ctx == NULL || codec_ctx == NULL || iface == NULL ||
      enc_cfg == NULL) {
    return VPX_CODEC_INVALID_PARAM;
  }
  if (si == NULL) return VPX_CODEC_MEM_ERROR;

  si->codec_ctx = codec_ctx;

  si->width = enc_cfg->g_w;
  si->height = enc_cfg->g_h;

  if (enc_cfg->kf_max_dist < 2) {
    svc_log(svc_ctx, SVC_LOG_ERROR, "key frame distance too small: %d\n",
            enc_cfg->kf_max_dist);
    return VPX_CODEC_INVALID_PARAM;
  }
  si->kf_dist = enc_cfg->kf_max_dist;

  if (svc_ctx->spatial_layers == 0)
    svc_ctx->spatial_layers = VPX_SS_DEFAULT_LAYERS;
  if (svc_ctx->spatial_layers < 1 ||
      svc_ctx->spatial_layers > VPX_SS_MAX_LAYERS) {
    svc_log(svc_ctx, SVC_LOG_ERROR, "spatial layers: invalid value: %d\n",
            svc_ctx->spatial_layers);
    return VPX_CODEC_INVALID_PARAM;
  }

463
  res = parse_quantizer_values(svc_ctx, si->quantizers, 0);
464 465
  if (res != VPX_CODEC_OK) return res;

466 467 468 469
  res = parse_quantizer_values(svc_ctx, si->quantizers_keyframe, 1);
  if (res != VPX_CODEC_OK)
    memcpy(si->quantizer_keyframe, si->quantizer, sizeof(si->quantizer));

470 471 472
  res = parse_scale_factors(svc_ctx, si->scale_factors);
  if (res != VPX_CODEC_OK) return res;

473 474
  // Parse aggregate command line options. Options must start with
  // "layers=xx" then followed by other options
475 476 477
  res = parse_options(svc_ctx, si->options);
  if (res != VPX_CODEC_OK) return res;

478 479
  si->layers = svc_ctx->spatial_layers;

480 481 482 483 484 485 486 487 488
  // Assign target bitrate for each layer. We calculate the ratio
  // from the resolution for now.
  // TODO(Minghai): Optimize the mechanism of allocating bits after
  // implementing svc two pass rate control.
  if (si->layers > 1) {
    int i;
    float total = 0;
    float alloc_ratio[VPX_SS_MAX_LAYERS] = {0};

489
    assert(si->layers <= VPX_SS_MAX_LAYERS);
490 491
    for (i = 0; i < si->layers; ++i) {
      int pos = i + VPX_SS_MAX_LAYERS - svc_ctx->spatial_layers;
492 493 494 495 496 497 498
      if (pos < VPX_SS_MAX_LAYERS && si->scaling_factor_den[pos] > 0) {
        alloc_ratio[i] = (float)(si->scaling_factor_num[pos] * 1.0 /
            si->scaling_factor_den[pos]);

        alloc_ratio[i] *= alloc_ratio[i];
        total += alloc_ratio[i];
      }
499 500 501
    }

    for (i = 0; i < si->layers; ++i) {
502 503 504 505
      if (total > 0) {
        enc_cfg->ss_target_bitrate[i] = (unsigned int)
            (enc_cfg->rc_target_bitrate * alloc_ratio[i] / total);
      }
506 507 508
    }
  }

509 510
  // modify encoder configuration
  enc_cfg->ss_number_layers = si->layers;
511
  enc_cfg->ts_number_layers = 1;  // Temporal layers not used in this encoder.
512 513 514 515 516

  // TODO(ivanmaltz): determine if these values need to be set explicitly for
  // svc, or if the normal default/override mechanism can be used
  enc_cfg->rc_dropframe_thresh = 0;
  enc_cfg->rc_resize_allowed = 0;
517 518 519 520 521 522

  if (enc_cfg->g_pass == VPX_RC_ONE_PASS) {
    enc_cfg->rc_min_quantizer = 33;
    enc_cfg->rc_max_quantizer = 33;
  }

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
  enc_cfg->rc_undershoot_pct = 100;
  enc_cfg->rc_overshoot_pct = 15;
  enc_cfg->rc_buf_initial_sz = 500;
  enc_cfg->rc_buf_optimal_sz = 600;
  enc_cfg->rc_buf_sz = 1000;
  enc_cfg->g_error_resilient = 1;

  // Initialize codec
  res = vpx_codec_enc_init(codec_ctx, iface, enc_cfg, VPX_CODEC_USE_PSNR);
  if (res != VPX_CODEC_OK) {
    svc_log(svc_ctx, SVC_LOG_ERROR, "svc_enc_init error\n");
    return res;
  }

  vpx_codec_control(codec_ctx, VP9E_SET_SVC, 1);
  vpx_codec_control(codec_ctx, VP8E_SET_TOKEN_PARTITIONS, 1);
539
  vpx_codec_control(codec_ctx, VP8E_SET_ENABLEAUTOALTREF, 0);
540 541 542 543

  return VPX_CODEC_OK;
}

544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
static void accumulate_frame_size_for_each_layer(SvcInternal *const si,
                                                 const uint8_t *const buf,
                                                 const size_t size) {
  uint8_t marker = buf[size - 1];
  if ((marker & 0xe0) == 0xc0) {
    const uint32_t frames = (marker & 0x7) + 1;
    const uint32_t mag = ((marker >> 3) & 0x3) + 1;
    const size_t index_sz = 2 + mag * frames;

    uint8_t marker2 = buf[size - index_sz];

    if (size >= index_sz && marker2 == marker) {
      // found a valid superframe index
      uint32_t i, j;
      const uint8_t *x = &buf[size - index_sz + 1];

      // frames has a maximum of 8 and mag has a maximum of 4.
      for (i = 0; i < frames; i++) {
        uint32_t this_sz = 0;

        for (j = 0; j < mag; j++)
          this_sz |= (*x++) << (j * 8);
        si->bytes_sum[i] += this_sz;
      }
    }
  }
}

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
// SVC Algorithm flags - these get mapped to VP8_EFLAG_* defined in vp8cx.h

// encoder should reference the last frame
#define USE_LAST (1 << 0)

// encoder should reference the alt ref frame
#define USE_ARF (1 << 1)

// encoder should reference the golden frame
#define USE_GF (1 << 2)

// encoder should copy current frame to the last frame buffer
#define UPDATE_LAST (1 << 3)

// encoder should copy current frame to the alt ref frame buffer
#define UPDATE_ARF (1 << 4)

// encoder should copy current frame to the golden frame
#define UPDATE_GF (1 << 5)

static int map_vp8_flags(int svc_flags) {
  int flags = 0;

  if (!(svc_flags & USE_LAST)) flags |= VP8_EFLAG_NO_REF_LAST;
  if (!(svc_flags & USE_ARF)) flags |= VP8_EFLAG_NO_REF_ARF;
  if (!(svc_flags & USE_GF)) flags |= VP8_EFLAG_NO_REF_GF;

  if (svc_flags & UPDATE_LAST) {
    // last is updated automatically
  } else {
    flags |= VP8_EFLAG_NO_UPD_LAST;
  }
  if (svc_flags & UPDATE_ARF) {
    flags |= VP8_EFLAG_FORCE_ARF;
  } else {
    flags |= VP8_EFLAG_NO_UPD_ARF;
  }
  if (svc_flags & UPDATE_GF) {
    flags |= VP8_EFLAG_FORCE_GF;
  } else {
    flags |= VP8_EFLAG_NO_UPD_GF;
  }
  return flags;
}

static void calculate_enc_frame_flags(SvcContext *svc_ctx) {
  vpx_enc_frame_flags_t flags = VPX_EFLAG_FORCE_KF;
  SvcInternal *const si = get_svc_internal(svc_ctx);
  const int is_keyframe = (si->frame_within_gop == 0);

  // keyframe layer zero is identical for all modes
623
  if (is_keyframe && si->layer == 0) {
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    si->enc_frame_flags = VPX_EFLAG_FORCE_KF;
    return;
  }

  switch (svc_ctx->encoding_mode) {
    case ALT_INTER_LAYER_PREDICTION_IP:
      if (si->layer == 0) {
        flags = map_vp8_flags(USE_LAST | UPDATE_LAST);
      } else if (is_keyframe) {
        if (si->layer == si->layers - 1) {
          flags = map_vp8_flags(USE_ARF | UPDATE_LAST);
        } else {
          flags = map_vp8_flags(USE_ARF | UPDATE_LAST | UPDATE_GF);
        }
      } else {
        flags = map_vp8_flags(USE_LAST | USE_ARF | UPDATE_LAST);
      }
      break;
    case INTER_LAYER_PREDICTION_I:
      if (si->layer == 0) {
        flags = map_vp8_flags(USE_LAST | UPDATE_LAST);
      } else if (is_keyframe) {
        flags = map_vp8_flags(USE_ARF | UPDATE_LAST);
      } else {
        flags = map_vp8_flags(USE_LAST | UPDATE_LAST);
      }
      break;
    case INTER_LAYER_PREDICTION_IP:
      if (si->layer == 0) {
        flags = map_vp8_flags(USE_LAST | UPDATE_LAST);
      } else if (is_keyframe) {
        flags = map_vp8_flags(USE_ARF | UPDATE_LAST);
      } else {
        flags = map_vp8_flags(USE_LAST | USE_ARF | UPDATE_LAST);
      }
      break;
    case USE_GOLDEN_FRAME:
      if (2 * si->layers - SVC_REFERENCE_FRAMES <= si->layer) {
        if (si->layer == 0) {
          flags = map_vp8_flags(USE_LAST | USE_GF | UPDATE_LAST);
        } else if (is_keyframe) {
          flags = map_vp8_flags(USE_ARF | UPDATE_LAST | UPDATE_GF);
        } else {
          flags = map_vp8_flags(USE_LAST | USE_ARF | USE_GF | UPDATE_LAST);
        }
      } else {
        if (si->layer == 0) {
          flags = map_vp8_flags(USE_LAST | UPDATE_LAST);
        } else if (is_keyframe) {
          flags = map_vp8_flags(USE_ARF | UPDATE_LAST);
        } else {
          flags = map_vp8_flags(USE_LAST | UPDATE_LAST);
        }
      }
      break;
    default:
      svc_log(svc_ctx, SVC_LOG_ERROR, "unexpected encoding mode: %d\n",
              svc_ctx->encoding_mode);
      break;
  }
  si->enc_frame_flags = flags;
}

vpx_codec_err_t vpx_svc_get_layer_resolution(const SvcContext *svc_ctx,
                                             int layer,
                                             unsigned int *width,
                                             unsigned int *height) {
  int w, h, index, num, den;
  const SvcInternal *const si = get_const_svc_internal(svc_ctx);

  if (svc_ctx == NULL || si == NULL || width == NULL || height == NULL) {
    return VPX_CODEC_INVALID_PARAM;
  }
  if (layer < 0 || layer >= si->layers) return VPX_CODEC_INVALID_PARAM;

  index = layer + VPX_SS_MAX_LAYERS - si->layers;
  num = si->scaling_factor_num[index];
  den = si->scaling_factor_den[index];
  if (num == 0 || den == 0) return VPX_CODEC_INVALID_PARAM;

  w = si->width * num / den;
  h = si->height * num / den;

  // make height and width even to make chrome player happy
  w += w % 2;
  h += h % 2;

  *width = w;
  *height = h;

  return VPX_CODEC_OK;
}

static void set_svc_parameters(SvcContext *svc_ctx,
                               vpx_codec_ctx_t *codec_ctx) {
  int layer, layer_index;
  vpx_svc_parameters_t svc_params;
  SvcInternal *const si = get_svc_internal(svc_ctx);

  memset(&svc_params, 0, sizeof(svc_params));
724 725
  svc_params.temporal_layer = 0;
  svc_params.spatial_layer = si->layer;
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
  svc_params.flags = si->enc_frame_flags;

  layer = si->layer;
  if (svc_ctx->encoding_mode == ALT_INTER_LAYER_PREDICTION_IP &&
      si->frame_within_gop == 0) {
    // layers 1 & 3 don't exist in this mode, use the higher one
    if (layer == 0 || layer == 2) {
      layer += 1;
    }
  }
  if (VPX_CODEC_OK != vpx_svc_get_layer_resolution(svc_ctx, layer,
                                                   &svc_params.width,
                                                   &svc_params.height)) {
    svc_log(svc_ctx, SVC_LOG_ERROR, "vpx_svc_get_layer_resolution failed\n");
  }
  layer_index = layer + VPX_SS_MAX_LAYERS - si->layers;
742

743 744 745 746 747 748 749 750
  if (codec_ctx->config.enc->g_pass == VPX_RC_ONE_PASS) {
    if (vpx_svc_is_keyframe(svc_ctx)) {
      svc_params.min_quantizer = si->quantizer_keyframe[layer_index];
      svc_params.max_quantizer = si->quantizer_keyframe[layer_index];
    } else {
      svc_params.min_quantizer = si->quantizer[layer_index];
      svc_params.max_quantizer = si->quantizer[layer_index];
    }
751
  } else {
752 753
    svc_params.min_quantizer = codec_ctx->config.enc->rc_min_quantizer;
    svc_params.max_quantizer = codec_ctx->config.enc->rc_max_quantizer;
754 755
  }

756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
  svc_params.distance_from_i_frame = si->frame_within_gop;

  // Use buffer i for layer i LST
  svc_params.lst_fb_idx = si->layer;

  // Use buffer i-1 for layer i Alt (Inter-layer prediction)
  if (si->layer != 0) {
    const int use_higher_layer =
        svc_ctx->encoding_mode == ALT_INTER_LAYER_PREDICTION_IP &&
        si->frame_within_gop == 0;
    svc_params.alt_fb_idx = use_higher_layer ? si->layer - 2 : si->layer - 1;
  }

  if (svc_ctx->encoding_mode == ALT_INTER_LAYER_PREDICTION_IP) {
    svc_params.gld_fb_idx = si->layer + 1;
  } else {
    if (si->layer < 2 * si->layers - SVC_REFERENCE_FRAMES)
      svc_params.gld_fb_idx = svc_params.lst_fb_idx;
    else
      svc_params.gld_fb_idx = 2 * si->layers - 1 - si->layer;
  }

  svc_log(svc_ctx, SVC_LOG_DEBUG, "SVC frame: %d, layer: %d, %dx%d, q: %d\n",
          si->encode_frame_count, si->layer, svc_params.width,
          svc_params.height, svc_params.min_quantizer);

  if (svc_params.flags == VPX_EFLAG_FORCE_KF) {
    svc_log(svc_ctx, SVC_LOG_DEBUG, "flags == VPX_EFLAG_FORCE_KF\n");
  } else {
    svc_log(
        svc_ctx, SVC_LOG_DEBUG, "Using:    LST/GLD/ALT [%2d|%2d|%2d]\n",
        svc_params.flags & VP8_EFLAG_NO_REF_LAST ? -1 : svc_params.lst_fb_idx,
        svc_params.flags & VP8_EFLAG_NO_REF_GF ? -1 : svc_params.gld_fb_idx,
        svc_params.flags & VP8_EFLAG_NO_REF_ARF ? -1 : svc_params.alt_fb_idx);
    svc_log(
        svc_ctx, SVC_LOG_DEBUG, "Updating: LST/GLD/ALT [%2d|%2d|%2d]\n",
        svc_params.flags & VP8_EFLAG_NO_UPD_LAST ? -1 : svc_params.lst_fb_idx,
        svc_params.flags & VP8_EFLAG_NO_UPD_GF ? -1 : svc_params.gld_fb_idx,
        svc_params.flags & VP8_EFLAG_NO_UPD_ARF ? -1 : svc_params.alt_fb_idx);
  }

  vpx_codec_control(codec_ctx, VP9E_SET_SVC_PARAMETERS, &svc_params);
}

/**
 * Encode a frame into multiple layers
 * Create a superframe containing the individual layers
 */
vpx_codec_err_t vpx_svc_encode(SvcContext *svc_ctx, vpx_codec_ctx_t *codec_ctx,
                               struct vpx_image *rawimg, vpx_codec_pts_t pts,
                               int64_t duration, int deadline) {
  vpx_codec_err_t res;
  vpx_codec_iter_t iter;
  const vpx_codec_cx_pkt_t *cx_pkt;
810
  int layer_for_psnr = 0;
811
  SvcInternal *const si = get_svc_internal(svc_ctx);
812
  if (svc_ctx == NULL || codec_ctx == NULL || si == NULL) {
813 814 815 816
    return VPX_CODEC_INVALID_PARAM;
  }

  svc_log_reset(svc_ctx);
817
  si->rc_stats_buf_used = 0;
818

819
  si->layers = svc_ctx->spatial_layers;
820
  if (si->encode_frame_count == 0) {
821 822 823 824
    si->frame_within_gop = 0;
  }
  si->is_keyframe = (si->frame_within_gop == 0);

825 826 827 828 829 830
  if (rawimg != NULL) {
    svc_log(svc_ctx, SVC_LOG_DEBUG,
            "vpx_svc_encode  layers: %d, frame_count: %d, "
            "frame_within_gop: %d\n", si->layers, si->encode_frame_count,
            si->frame_within_gop);
  }
831

832 833 834 835 836 837 838 839
  if (rawimg != NULL) {
    // encode each layer
    for (si->layer = 0; si->layer < si->layers; ++si->layer) {
      if (svc_ctx->encoding_mode == ALT_INTER_LAYER_PREDICTION_IP &&
          si->is_keyframe && (si->layer == 1 || si->layer == 3)) {
        svc_log(svc_ctx, SVC_LOG_DEBUG, "Skip encoding layer %d\n", si->layer);
        continue;
      }
840 841 842
      calculate_enc_frame_flags(svc_ctx);
      set_svc_parameters(svc_ctx, codec_ctx);
    }
843
  }
844

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
  res = vpx_codec_encode(codec_ctx, rawimg, pts, (uint32_t)duration, 0,
                         deadline);
  if (res != VPX_CODEC_OK) {
    return res;
  }
  // save compressed data
  iter = NULL;
  while ((cx_pkt = vpx_codec_get_cx_data(codec_ctx, &iter))) {
    switch (cx_pkt->kind) {
      case VPX_CODEC_CX_FRAME_PKT: {
        fd_list_add(&si->frame_list, fd_create(cx_pkt->data.frame.buf,
                                               cx_pkt->data.frame.sz,
                                               cx_pkt->data.frame.flags));
        accumulate_frame_size_for_each_layer(si, cx_pkt->data.frame.buf,
                                             cx_pkt->data.frame.sz);

        svc_log(svc_ctx, SVC_LOG_DEBUG, "SVC frame: %d, kf: %d, size: %d, "
                "pts: %d\n", si->frame_received,
                (cx_pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? 1 : 0,
                (int)cx_pkt->data.frame.sz, (int)cx_pkt->data.frame.pts);

        ++si->frame_received;
        layer_for_psnr = 0;
        break;
      }
      case VPX_CODEC_PSNR_PKT: {
        int i;
        svc_log(svc_ctx, SVC_LOG_DEBUG,
                "SVC frame: %d, layer: %d, PSNR(Total/Y/U/V): "
                "%2.3f  %2.3f  %2.3f  %2.3f \n",
                si->frame_received, layer_for_psnr,
                cx_pkt->data.psnr.psnr[0], cx_pkt->data.psnr.psnr[1],
                cx_pkt->data.psnr.psnr[2], cx_pkt->data.psnr.psnr[3]);
        svc_log(svc_ctx, SVC_LOG_DEBUG,
                "SVC frame: %d, layer: %d, SSE(Total/Y/U/V): "
                "%2.3f  %2.3f  %2.3f  %2.3f \n",
                si->frame_received, layer_for_psnr,
                cx_pkt->data.psnr.sse[0], cx_pkt->data.psnr.sse[1],
                cx_pkt->data.psnr.sse[2], cx_pkt->data.psnr.sse[3]);
        for (i = 0; i < COMPONENTS; i++) {
          si->psnr_sum[layer_for_psnr][i] += cx_pkt->data.psnr.psnr[i];
          si->sse_sum[layer_for_psnr][i] += cx_pkt->data.psnr.sse[i];
887
        }
888 889 890 891 892 893 894 895 896 897 898 899
        ++layer_for_psnr;
        break;
      }
      case VPX_CODEC_STATS_PKT: {
        size_t new_size = si->rc_stats_buf_used +
            cx_pkt->data.twopass_stats.sz;

        if (new_size > si->rc_stats_buf_size) {
          char *p = (char*)realloc(si->rc_stats_buf, new_size);
          if (p == NULL) {
            svc_log(svc_ctx, SVC_LOG_ERROR, "Error allocating stats buf\n");
            return VPX_CODEC_MEM_ERROR;
900
          }
901 902
          si->rc_stats_buf = p;
          si->rc_stats_buf_size = new_size;
903
        }
904

905 906 907 908
        memcpy(si->rc_stats_buf + si->rc_stats_buf_used,
               cx_pkt->data.twopass_stats.buf, cx_pkt->data.twopass_stats.sz);
        si->rc_stats_buf_used += cx_pkt->data.twopass_stats.sz;
        break;
909
      }
910 911
      default: {
        break;
912
      }
913 914
    }
  }
915

916 917 918 919
  if (rawimg != NULL) {
    ++si->frame_within_gop;
    ++si->encode_frame_count;
  }
920 921 922 923 924 925 926 927 928 929

  return VPX_CODEC_OK;
}

const char *vpx_svc_get_message(const SvcContext *svc_ctx) {
  const SvcInternal *const si = get_const_svc_internal(svc_ctx);
  if (svc_ctx == NULL || si == NULL) return NULL;
  return si->message_buffer;
}

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
// We will maintain a list of output frame buffers since with lag_in_frame
// we need to output all frame buffers at the end. vpx_svc_get_buffer() will
// remove a frame buffer from the list the put it to a temporal pointer, which
// will be removed at the next vpx_svc_get_buffer() or when closing encoder.
void *vpx_svc_get_buffer(SvcContext *svc_ctx) {
  SvcInternal *const si = get_svc_internal(svc_ctx);
  if (svc_ctx == NULL || si == NULL || si->frame_list == NULL) return NULL;

  if (si->frame_temp)
    fd_free(si->frame_temp);

  si->frame_temp = si->frame_list;
  si->frame_list = si->frame_list->next;

  return si->frame_temp->buf;
945 946 947 948
}

size_t vpx_svc_get_frame_size(const SvcContext *svc_ctx) {
  const SvcInternal *const si = get_const_svc_internal(svc_ctx);
949 950
  if (svc_ctx == NULL || si == NULL || si->frame_list == NULL) return 0;
  return si->frame_list->size;
951 952 953 954 955 956 957 958 959 960
}

int vpx_svc_get_encode_frame_count(const SvcContext *svc_ctx) {
  const SvcInternal *const si = get_const_svc_internal(svc_ctx);
  if (svc_ctx == NULL || si == NULL) return 0;
  return si->encode_frame_count;
}

int vpx_svc_is_keyframe(const SvcContext *svc_ctx) {
  const SvcInternal *const si = get_const_svc_internal(svc_ctx);
961 962
  if (svc_ctx == NULL || si == NULL || si->frame_list == NULL) return 0;
  return (si->frame_list->flags & VPX_FRAME_IS_KEY) != 0;
963 964 965 966 967 968 969 970
}

void vpx_svc_set_keyframe(SvcContext *svc_ctx) {
  SvcInternal *const si = get_svc_internal(svc_ctx);
  if (svc_ctx == NULL || si == NULL) return;
  si->frame_within_gop = 0;
}

971 972 973 974 975
static double calc_psnr(double d) {
  if (d == 0) return 100;
  return -10.0 * log(d) / log(10.0);
}

976 977 978
// dump accumulated statistics and reset accumulated values
const char *vpx_svc_dump_statistics(SvcContext *svc_ctx) {
  int number_of_frames, number_of_keyframes, encode_frame_count;
979
  int i, j;
980
  uint32_t bytes_total = 0;
981 982 983 984 985
  double scale[COMPONENTS];
  double psnr[COMPONENTS];
  double mse[COMPONENTS];
  double y_scale;

986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
  SvcInternal *const si = get_svc_internal(svc_ctx);
  if (svc_ctx == NULL || si == NULL) return NULL;

  svc_log_reset(svc_ctx);

  encode_frame_count = si->encode_frame_count;
  if (si->encode_frame_count <= 0) return vpx_svc_get_message(svc_ctx);

  svc_log(svc_ctx, SVC_LOG_INFO, "\n");
  number_of_keyframes = encode_frame_count / si->kf_dist + 1;
  for (i = 0; i < si->layers; ++i) {
    number_of_frames = encode_frame_count;

    if (svc_ctx->encoding_mode == ALT_INTER_LAYER_PREDICTION_IP &&
        (i == 1 || i == 3)) {
      number_of_frames -= number_of_keyframes;
    }
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    svc_log(svc_ctx, SVC_LOG_INFO,
            "Layer %d Average PSNR=[%2.3f, %2.3f, %2.3f, %2.3f], Bytes=[%u]\n",
            i, (double)si->psnr_sum[i][0] / number_of_frames,
            (double)si->psnr_sum[i][1] / number_of_frames,
            (double)si->psnr_sum[i][2] / number_of_frames,
            (double)si->psnr_sum[i][3] / number_of_frames, si->bytes_sum[i]);
    // the following psnr calculation is deduced from ffmpeg.c#print_report
    y_scale = si->width * si->height * 255.0 * 255.0 * number_of_frames;
    scale[1] = y_scale;
    scale[2] = scale[3] = y_scale / 4;  // U or V
    scale[0] = y_scale * 1.5;           // total

    for (j = 0; j < COMPONENTS; j++) {
      psnr[j] = calc_psnr(si->sse_sum[i][j] / scale[j]);
      mse[j] = si->sse_sum[i][j] * 255.0 * 255.0 / scale[j];
    }
    svc_log(svc_ctx, SVC_LOG_INFO,
            "Layer %d Overall PSNR=[%2.3f, %2.3f, %2.3f, %2.3f]\n", i, psnr[0],
            psnr[1], psnr[2], psnr[3]);
    svc_log(svc_ctx, SVC_LOG_INFO,
            "Layer %d Overall MSE=[%2.3f, %2.3f, %2.3f, %2.3f]\n", i, mse[0],
            mse[1], mse[2], mse[3]);

    bytes_total += si->bytes_sum[i];
    // clear sums for next time
    si->bytes_sum[i] = 0;
    for (j = 0; j < COMPONENTS; ++j) {
      si->psnr_sum[i][j] = 0;
      si->sse_sum[i][j] = 0;
    }
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
  }

  // only display statistics once
  si->encode_frame_count = 0;

  svc_log(svc_ctx, SVC_LOG_INFO, "Total Bytes=[%u]\n", bytes_total);
  return vpx_svc_get_message(svc_ctx);
}

void vpx_svc_release(SvcContext *svc_ctx) {
  SvcInternal *si;
  if (svc_ctx == NULL) return;
  // do not use get_svc_internal as it will unnecessarily allocate an
  // SvcInternal if it was not already allocated
  si = (SvcInternal *)svc_ctx->internal;
  if (si != NULL) {
1049 1050
    fd_free(si->frame_temp);
    fd_free_list(si->frame_list);
1051 1052 1053
    if (si->rc_stats_buf) {
      free(si->rc_stats_buf);
    }
1054 1055 1056 1057
    free(si);
    svc_ctx->internal = NULL;
  }
}
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

size_t vpx_svc_get_rc_stats_buffer_size(const SvcContext *svc_ctx) {
  const SvcInternal *const si = get_const_svc_internal(svc_ctx);
  if (svc_ctx == NULL || si == NULL) return 0;
  return si->rc_stats_buf_used;
}

char *vpx_svc_get_rc_stats_buffer(const SvcContext *svc_ctx) {
  const SvcInternal *const si = get_const_svc_internal(svc_ctx);
  if (svc_ctx == NULL || si == NULL) return NULL;
  return si->rc_stats_buf;
}