X-Git-Url: https://git.sesse.net/?a=blobdiff_plain;f=libavcodec%2Flibvpxenc.c;h=0b8a070304eeb4b4f98acb11d0b2d55a5419d353;hb=6026384047ab8e895d416aab4e2531bd87c0c01d;hp=c823b8ad8bf7520d27c239e6fc3a9553651d492a;hpb=67d466d09b105b2b1d3d8da4c21d8975925741ae;p=ffmpeg diff --git a/libavcodec/libvpxenc.c b/libavcodec/libvpxenc.c index c823b8ad8bf..0b8a070304e 100644 --- a/libavcodec/libvpxenc.c +++ b/libavcodec/libvpxenc.c @@ -100,7 +100,7 @@ typedef struct VPxEncoderContext { int rc_undershoot_pct; int rc_overshoot_pct; - char *vp8_ts_parameters; + AVDictionary *vp8_ts_parameters; // VP9-only int lossless; @@ -116,6 +116,11 @@ typedef struct VPxEncoderContext { int tune_content; int corpus_complexity; int tpl_model; + /** + * If the driver does not support ROI then warn the first time we + * encounter a frame with ROI side data. + */ + int roi_warned; } VPxContext; /** String mappings for enum vp8e_enc_control_id */ @@ -342,8 +347,11 @@ static av_cold int vpx_free(AVCodecContext *avctx) #endif vpx_codec_destroy(&ctx->encoder); - if (ctx->is_alpha) + if (ctx->is_alpha) { vpx_codec_destroy(&ctx->encoder_alpha); + av_freep(&ctx->rawimg_alpha.planes[VPX_PLANE_U]); + av_freep(&ctx->rawimg_alpha.planes[VPX_PLANE_V]); + } av_freep(&ctx->twopass_stats.buf); av_freep(&avctx->stats_out); free_frame_list(ctx->coded_frame_list); @@ -510,6 +518,66 @@ static void set_color_range(AVCodecContext *avctx) #endif #endif +/** + * Set the target bitrate to VPX library default. Also set CRF to 32 if needed. + */ +static void set_vp8_defaults(AVCodecContext *avctx, + struct vpx_codec_enc_cfg *enccfg) +{ + VPxContext *ctx = avctx->priv_data; + av_assert0(!avctx->bit_rate); + avctx->bit_rate = enccfg->rc_target_bitrate * 1000; + if (enccfg->rc_end_usage == VPX_CQ) { + av_log(avctx, AV_LOG_WARNING, + "Bitrate not specified for constrained quality mode, using default of %dkbit/sec\n", + enccfg->rc_target_bitrate); + } else { + enccfg->rc_end_usage = VPX_CQ; + ctx->crf = 32; + av_log(avctx, AV_LOG_WARNING, + "Neither bitrate nor constrained quality specified, using default CRF of %d and bitrate of %dkbit/sec\n", + ctx->crf, enccfg->rc_target_bitrate); + } +} + + +#if CONFIG_LIBVPX_VP9_ENCODER +/** + * Keep the target bitrate at 0 to engage constant quality mode. If CRF is not + * set, use 32. + */ +static void set_vp9_defaults(AVCodecContext *avctx, + struct vpx_codec_enc_cfg *enccfg) +{ + VPxContext *ctx = avctx->priv_data; + av_assert0(!avctx->bit_rate); + if (enccfg->rc_end_usage != VPX_Q && ctx->lossless < 0) { + enccfg->rc_end_usage = VPX_Q; + ctx->crf = 32; + av_log(avctx, AV_LOG_WARNING, + "Neither bitrate nor constrained quality specified, using default CRF of %d\n", + ctx->crf); + } +} +#endif + +/** + * Called when the bitrate is not set. It sets appropriate default values for + * bitrate and CRF. + */ +static void set_vpx_defaults(AVCodecContext *avctx, + struct vpx_codec_enc_cfg *enccfg) +{ + av_assert0(!avctx->bit_rate); +#if CONFIG_LIBVPX_VP9_ENCODER + if (avctx->codec_id == AV_CODEC_ID_VP9) { + set_vp9_defaults(avctx, enccfg); + return; + } +#endif + set_vp8_defaults(avctx, enccfg); +} + static av_cold int vpx_init(AVCodecContext *avctx, const struct vpx_codec_iface *iface) { @@ -580,18 +648,9 @@ static av_cold int vpx_init(AVCodecContext *avctx, if (avctx->bit_rate) { enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000, AV_ROUND_NEAR_INF); -#if CONFIG_LIBVPX_VP9_ENCODER - } else if (enccfg.rc_end_usage == VPX_Q) { -#endif } else { - if (enccfg.rc_end_usage == VPX_CQ) { - enccfg.rc_target_bitrate = 1000000; - } else { - avctx->bit_rate = enccfg.rc_target_bitrate * 1000; - av_log(avctx, AV_LOG_WARNING, - "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n", - enccfg.rc_target_bitrate); - } + // Set bitrate to default value. Also sets CRF to default if needed. + set_vpx_defaults(avctx, &enccfg); } if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) { @@ -698,19 +757,13 @@ FF_ENABLE_DEPRECATION_WARNINGS enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT; - if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8 && ctx->vp8_ts_parameters) { - AVDictionary *dict = NULL; + if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8) { AVDictionaryEntry* en = NULL; - - if (!av_dict_parse_string(&dict, ctx->vp8_ts_parameters, "=", ":", 0)) { - while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) { - if (vp8_ts_param_parse(&enccfg, en->key, en->value) < 0) - av_log(avctx, AV_LOG_WARNING, - "Error parsing option '%s = %s'.\n", - en->key, en->value); - } - - av_dict_free(&dict); + while ((en = av_dict_get(ctx->vp8_ts_parameters, "", en, AV_DICT_IGNORE_SUFFIX))) { + if (vp8_ts_param_parse(&enccfg, en->key, en->value) < 0) + av_log(avctx, AV_LOG_WARNING, + "Error parsing option '%s = %s'.\n", + en->key, en->value); } } @@ -816,10 +869,6 @@ FF_ENABLE_DEPRECATION_WARNINGS ctx->rawimg.bit_depth = enccfg.g_bit_depth; #endif - if (ctx->is_alpha) - vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1, - (unsigned char*)1); - cpb_props = ff_add_cpb_side_data(avctx); if (!cpb_props) return AVERROR(ENOMEM); @@ -978,7 +1027,7 @@ static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out) are only good through the next vpx_codec call */ while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) && (!ctx->is_alpha || - (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) { + (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha)))) { switch (pkt->kind) { case VPX_CODEC_CX_FRAME_PKT: if (!size) { @@ -992,8 +1041,7 @@ static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out) if (size < 0) return size; } else { - struct FrameListData *cx_frame = - av_malloc(sizeof(struct FrameListData)); + struct FrameListData *cx_frame = av_malloc(sizeof(*cx_frame)); if (!cx_frame) { av_log(avctx, AV_LOG_ERROR, @@ -1057,6 +1105,213 @@ static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out) return size; } +static int set_roi_map(AVCodecContext *avctx, const AVFrameSideData *sd, int frame_width, int frame_height, + vpx_roi_map_t *roi_map, int block_size, int segment_cnt) +{ + /** + * range of vpx_roi_map_t.delta_q[i] is [-63, 63] + */ +#define MAX_DELTA_Q 63 + + const AVRegionOfInterest *roi = NULL; + int nb_rois; + uint32_t self_size; + int segment_id; + + /* record the mapping from delta_q to "segment id + 1" in segment_mapping[]. + * the range of delta_q is [-MAX_DELTA_Q, MAX_DELTA_Q], + * and its corresponding array index is [0, 2 * MAX_DELTA_Q], + * and so the length of the mapping array is 2 * MAX_DELTA_Q + 1. + * "segment id + 1", so we can say there's no mapping if the value of array element is zero. + */ + int segment_mapping[2 * MAX_DELTA_Q + 1] = { 0 }; + + memset(roi_map, 0, sizeof(*roi_map)); + + /* segment id 0 in roi_map is reserved for the areas not covered by AVRegionOfInterest. + * segment id 0 in roi_map is also for the areas with AVRegionOfInterest.qoffset near 0. + * (delta_q of segment id 0 is 0). + */ + segment_mapping[MAX_DELTA_Q] = 1; + segment_id = 1; + + roi = (const AVRegionOfInterest*)sd->data; + self_size = roi->self_size; + if (!self_size || sd->size % self_size) { + av_log(avctx, AV_LOG_ERROR, "Invalid AVRegionOfInterest.self_size.\n"); + return AVERROR(EINVAL); + } + nb_rois = sd->size / self_size; + + /* This list must be iterated from zero because regions are + * defined in order of decreasing importance. So discard less + * important areas if they exceed the segment count. + */ + for (int i = 0; i < nb_rois; i++) { + int delta_q; + int mapping_index; + + roi = (const AVRegionOfInterest*)(sd->data + self_size * i); + if (!roi->qoffset.den) { + av_log(avctx, AV_LOG_ERROR, "AVRegionOfInterest.qoffset.den must not be zero.\n"); + return AVERROR(EINVAL); + } + + delta_q = (int)(roi->qoffset.num * 1.0f / roi->qoffset.den * MAX_DELTA_Q); + delta_q = av_clip(delta_q, -MAX_DELTA_Q, MAX_DELTA_Q); + + mapping_index = delta_q + MAX_DELTA_Q; + if (!segment_mapping[mapping_index]) { + if (segment_id == segment_cnt) { + av_log(avctx, AV_LOG_WARNING, + "ROI only supports %d segments (and segment 0 is reserved for non-ROIs), skipping the left ones.\n", + segment_cnt); + break; + } + + segment_mapping[mapping_index] = segment_id + 1; + roi_map->delta_q[segment_id] = delta_q; + segment_id++; + } + } + + roi_map->rows = (frame_height + block_size - 1) / block_size; + roi_map->cols = (frame_width + block_size - 1) / block_size; + roi_map->roi_map = av_mallocz_array(roi_map->rows * roi_map->cols, sizeof(*roi_map->roi_map)); + if (!roi_map->roi_map) { + av_log(avctx, AV_LOG_ERROR, "roi_map alloc failed.\n"); + return AVERROR(ENOMEM); + } + + /* This list must be iterated in reverse, so for the case that + * two regions are overlapping, the more important area takes effect. + */ + for (int i = nb_rois - 1; i >= 0; i--) { + int delta_q; + int mapping_value; + int starty, endy, startx, endx; + + roi = (const AVRegionOfInterest*)(sd->data + self_size * i); + + starty = av_clip(roi->top / block_size, 0, roi_map->rows); + endy = av_clip((roi->bottom + block_size - 1) / block_size, 0, roi_map->rows); + startx = av_clip(roi->left / block_size, 0, roi_map->cols); + endx = av_clip((roi->right + block_size - 1) / block_size, 0, roi_map->cols); + + delta_q = (int)(roi->qoffset.num * 1.0f / roi->qoffset.den * MAX_DELTA_Q); + delta_q = av_clip(delta_q, -MAX_DELTA_Q, MAX_DELTA_Q); + + mapping_value = segment_mapping[delta_q + MAX_DELTA_Q]; + if (mapping_value) { + for (int y = starty; y < endy; y++) + for (int x = startx; x < endx; x++) + roi_map->roi_map[x + y * roi_map->cols] = mapping_value - 1; + } + } + + return 0; +} + +static int vp9_encode_set_roi(AVCodecContext *avctx, int frame_width, int frame_height, const AVFrameSideData *sd) +{ + VPxContext *ctx = avctx->priv_data; + +#ifdef VPX_CTRL_VP9E_SET_ROI_MAP + int version = vpx_codec_version(); + int major = VPX_VERSION_MAJOR(version); + int minor = VPX_VERSION_MINOR(version); + int patch = VPX_VERSION_PATCH(version); + + if (major > 1 || (major == 1 && minor > 8) || (major == 1 && minor == 8 && patch >= 1)) { + vpx_roi_map_t roi_map; + const int segment_cnt = 8; + const int block_size = 8; + int ret; + + if (ctx->aq_mode > 0 || ctx->cpu_used < 5 || ctx->deadline != VPX_DL_REALTIME) { + if (!ctx->roi_warned) { + ctx->roi_warned = 1; + av_log(avctx, AV_LOG_WARNING, "ROI is only enabled when aq_mode is 0, cpu_used >= 5 " + "and deadline is REALTIME, so skipping ROI.\n"); + return AVERROR(EINVAL); + } + } + + ret = set_roi_map(avctx, sd, frame_width, frame_height, &roi_map, block_size, segment_cnt); + if (ret) { + log_encoder_error(avctx, "Failed to set_roi_map.\n"); + return ret; + } + + memset(roi_map.ref_frame, -1, sizeof(roi_map.ref_frame)); + + if (vpx_codec_control(&ctx->encoder, VP9E_SET_ROI_MAP, &roi_map)) { + log_encoder_error(avctx, "Failed to set VP9E_SET_ROI_MAP codec control.\n"); + ret = AVERROR_INVALIDDATA; + } + av_freep(&roi_map.roi_map); + return ret; + } +#endif + + if (!ctx->roi_warned) { + ctx->roi_warned = 1; + av_log(avctx, AV_LOG_WARNING, "ROI is not supported, please upgrade libvpx to version >= 1.8.1. " + "You may need to rebuild ffmpeg.\n"); + } + return 0; +} + +static int vp8_encode_set_roi(AVCodecContext *avctx, int frame_width, int frame_height, const AVFrameSideData *sd) +{ + vpx_roi_map_t roi_map; + const int segment_cnt = 4; + const int block_size = 16; + VPxContext *ctx = avctx->priv_data; + + int ret = set_roi_map(avctx, sd, frame_width, frame_height, &roi_map, block_size, segment_cnt); + if (ret) { + log_encoder_error(avctx, "Failed to set_roi_map.\n"); + return ret; + } + + if (vpx_codec_control(&ctx->encoder, VP8E_SET_ROI_MAP, &roi_map)) { + log_encoder_error(avctx, "Failed to set VP8E_SET_ROI_MAP codec control.\n"); + ret = AVERROR_INVALIDDATA; + } + + av_freep(&roi_map.roi_map); + return ret; +} + +static int realloc_alpha_uv(AVCodecContext *avctx, int width, int height) +{ + VPxContext *ctx = avctx->priv_data; + struct vpx_image *rawimg_alpha = &ctx->rawimg_alpha; + unsigned char **planes = rawimg_alpha->planes; + int *stride = rawimg_alpha->stride; + + if (!planes[VPX_PLANE_U] || + !planes[VPX_PLANE_V] || + width != (int)rawimg_alpha->d_w || + height != (int)rawimg_alpha->d_h) { + av_freep(&planes[VPX_PLANE_U]); + av_freep(&planes[VPX_PLANE_V]); + + vpx_img_wrap(rawimg_alpha, VPX_IMG_FMT_I420, width, height, 1, + (unsigned char*)1); + planes[VPX_PLANE_U] = av_malloc_array(stride[VPX_PLANE_U], height); + planes[VPX_PLANE_V] = av_malloc_array(stride[VPX_PLANE_V], height); + if (!planes[VPX_PLANE_U] || !planes[VPX_PLANE_V]) + return AVERROR(ENOMEM); + + memset(planes[VPX_PLANE_U], 0x80, stride[VPX_PLANE_U] * height); + memset(planes[VPX_PLANE_V], 0x80, stride[VPX_PLANE_V] * height); + } + + return 0; +} + static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame, int *got_packet) { @@ -1068,6 +1323,7 @@ static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt, vpx_enc_frame_flags_t flags = 0; if (frame) { + const AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST); rawimg = &ctx->rawimg; rawimg->planes[VPX_PLANE_Y] = frame->data[0]; rawimg->planes[VPX_PLANE_U] = frame->data[1]; @@ -1076,23 +1332,12 @@ static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt, rawimg->stride[VPX_PLANE_U] = frame->linesize[1]; rawimg->stride[VPX_PLANE_V] = frame->linesize[2]; if (ctx->is_alpha) { - uint8_t *u_plane, *v_plane; rawimg_alpha = &ctx->rawimg_alpha; + res = realloc_alpha_uv(avctx, frame->width, frame->height); + if (res < 0) + return res; rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3]; - u_plane = av_malloc(frame->linesize[1] * frame->height); - v_plane = av_malloc(frame->linesize[2] * frame->height); - if (!u_plane || !v_plane) { - av_free(u_plane); - av_free(v_plane); - return AVERROR(ENOMEM); - } - memset(u_plane, 0x80, frame->linesize[1] * frame->height); - rawimg_alpha->planes[VPX_PLANE_U] = u_plane; - memset(v_plane, 0x80, frame->linesize[2] * frame->height); - rawimg_alpha->planes[VPX_PLANE_V] = v_plane; - rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0]; - rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1]; - rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2]; + rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[3]; } timestamp = frame->pts; #if VPX_IMAGE_ABI_VERSION >= 4 @@ -1113,6 +1358,14 @@ static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt, flags |= strtoul(en->value, NULL, 10); } } + + if (sd) { + if (avctx->codec_id == AV_CODEC_ID_VP8) { + vp8_encode_set_roi(avctx, frame->width, frame->height, sd); + } else { + vp9_encode_set_roi(avctx, frame->width, frame->height, sd); + } + } } res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp, @@ -1146,11 +1399,6 @@ static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt, ctx->twopass_stats.sz); } - if (rawimg_alpha) { - av_freep(&rawimg_alpha->planes[VPX_PLANE_U]); - av_freep(&rawimg_alpha->planes[VPX_PLANE_V]); - } - *got_packet = !!coded_size; return 0; } @@ -1179,7 +1427,7 @@ static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt, { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \ { "partitions", "The frame partitions are independently decodable " \ "by the bool decoder, meaning that partitions can be decoded even " \ - "though earlier partitions have been lost. Note that intra predicition" \ + "though earlier partitions have been lost. Note that intra prediction" \ " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \ { "crf", "Select the quality for constant quality mode", offsetof(VPxContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \ { "static-thresh", "A change threshold on blocks below which they will be skipped by the encoder", OFFSET(static_thresh), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE }, \ @@ -1207,7 +1455,7 @@ static const AVOption vp8_options[] = { "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE}, { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, { "ts-parameters", "Temporal scaling configuration using a " - ":-separated list of key=value parameters", OFFSET(vp8_ts_parameters), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, VE}, + ":-separated list of key=value parameters", OFFSET(vp8_ts_parameters), AV_OPT_TYPE_DICT, {.str=NULL}, 0, 0, VE}, LEGACY_OPTIONS { NULL } }; @@ -1266,6 +1514,7 @@ static const AVOption vp9_options[] = { #undef LEGACY_OPTIONS static const AVCodecDefault defaults[] = { + { "b", "0" }, { "qmin", "-1" }, { "qmax", "-1" }, { "g", "-1" },