4 * Copyright (c) 2015 Tampere University of Technology
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include "libavutil/attributes.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/error.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/internal.h"
33 #include "libavutil/log.h"
34 #include "libavutil/mem.h"
35 #include "libavutil/pixdesc.h"
36 #include "libavutil/opt.h"
40 #include "packet_internal.h"
42 typedef struct LibkvazaarContext {
52 static av_cold int libkvazaar_init(AVCodecContext *avctx)
54 LibkvazaarContext *const ctx = avctx->priv_data;
55 const kvz_api *const api = ctx->api = kvz_api_get(8);
56 kvz_config *cfg = NULL;
57 kvz_encoder *enc = NULL;
59 /* Kvazaar requires width and height to be multiples of eight. */
60 if (avctx->width % 8 || avctx->height % 8) {
61 av_log(avctx, AV_LOG_ERROR,
62 "Video dimensions are not a multiple of 8 (%dx%d).\n",
63 avctx->width, avctx->height);
64 return AVERROR(ENOSYS);
67 ctx->config = cfg = api->config_alloc();
69 av_log(avctx, AV_LOG_ERROR,
70 "Could not allocate kvazaar config structure.\n");
71 return AVERROR(ENOMEM);
74 if (!api->config_init(cfg)) {
75 av_log(avctx, AV_LOG_ERROR,
76 "Could not initialize kvazaar config structure.\n");
80 cfg->width = avctx->width;
81 cfg->height = avctx->height;
83 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
84 cfg->framerate_num = avctx->framerate.num;
85 cfg->framerate_denom = avctx->framerate.den;
87 if (avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
88 av_log(avctx, AV_LOG_ERROR,
89 "Could not set framerate for kvazaar: integer overflow\n");
90 return AVERROR(EINVAL);
92 cfg->framerate_num = avctx->time_base.den;
93 cfg->framerate_denom = avctx->time_base.num * avctx->ticks_per_frame;
95 cfg->target_bitrate = avctx->bit_rate;
96 cfg->vui.sar_width = avctx->sample_aspect_ratio.num;
97 cfg->vui.sar_height = avctx->sample_aspect_ratio.den;
99 if (ctx->kvz_params) {
100 AVDictionary *dict = NULL;
101 if (!av_dict_parse_string(&dict, ctx->kvz_params, "=", ",", 0)) {
102 AVDictionaryEntry *entry = NULL;
103 while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) {
104 if (!api->config_parse(cfg, entry->key, entry->value)) {
105 av_log(avctx, AV_LOG_WARNING, "Invalid option: %s=%s.\n",
106 entry->key, entry->value);
113 ctx->encoder = enc = api->encoder_open(cfg);
115 av_log(avctx, AV_LOG_ERROR, "Could not open kvazaar encoder.\n");
119 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
120 kvz_data_chunk *data_out = NULL;
121 kvz_data_chunk *chunk = NULL;
125 if (!api->encoder_headers(enc, &data_out, &len_out))
126 return AVERROR(ENOMEM);
128 avctx->extradata = p = av_mallocz(len_out + AV_INPUT_BUFFER_PADDING_SIZE);
130 ctx->api->chunk_free(data_out);
131 return AVERROR(ENOMEM);
134 avctx->extradata_size = len_out;
136 for (chunk = data_out; chunk != NULL; chunk = chunk->next) {
137 memcpy(p, chunk->data, chunk->len);
141 ctx->api->chunk_free(data_out);
147 static av_cold int libkvazaar_close(AVCodecContext *avctx)
149 LibkvazaarContext *ctx = avctx->priv_data;
152 ctx->api->encoder_close(ctx->encoder);
153 ctx->api->config_destroy(ctx->config);
156 if (avctx->extradata)
157 av_freep(&avctx->extradata);
162 static int libkvazaar_encode(AVCodecContext *avctx,
164 const AVFrame *frame,
167 LibkvazaarContext *ctx = avctx->priv_data;
168 kvz_picture *input_pic = NULL;
169 kvz_picture *recon_pic = NULL;
170 kvz_frame_info frame_info;
171 kvz_data_chunk *data_out = NULL;
172 uint32_t len_out = 0;
179 if (frame->width != ctx->config->width ||
180 frame->height != ctx->config->height) {
181 av_log(avctx, AV_LOG_ERROR,
182 "Changing video dimensions during encoding is not supported. "
183 "(changed from %dx%d to %dx%d)\n",
184 ctx->config->width, ctx->config->height,
185 frame->width, frame->height);
186 retval = AVERROR_INVALIDDATA;
190 if (frame->format != avctx->pix_fmt) {
191 av_log(avctx, AV_LOG_ERROR,
192 "Changing pixel format during encoding is not supported. "
193 "(changed from %s to %s)\n",
194 av_get_pix_fmt_name(avctx->pix_fmt),
195 av_get_pix_fmt_name(frame->format));
196 retval = AVERROR_INVALIDDATA;
200 // Allocate input picture for kvazaar.
201 input_pic = ctx->api->picture_alloc(frame->width, frame->height);
203 av_log(avctx, AV_LOG_ERROR, "Failed to allocate picture.\n");
204 retval = AVERROR(ENOMEM);
208 // Copy pixels from frame to input_pic.
210 int dst_linesizes[4] = {
216 av_image_copy(input_pic->data, dst_linesizes,
217 (const uint8_t **)frame->data, frame->linesize,
218 frame->format, frame->width, frame->height);
221 input_pic->pts = frame->pts;
224 retval = ctx->api->encoder_encode(ctx->encoder,
230 av_log(avctx, AV_LOG_ERROR, "Failed to encode frame.\n");
231 retval = AVERROR_INVALIDDATA;
234 retval = 0; /* kvazaar returns 1 on success */
237 kvz_data_chunk *chunk = NULL;
238 uint64_t written = 0;
240 retval = ff_alloc_packet2(avctx, avpkt, len_out, len_out);
242 av_log(avctx, AV_LOG_ERROR, "Failed to allocate output packet.\n");
246 for (chunk = data_out; chunk != NULL; chunk = chunk->next) {
247 av_assert0(written + chunk->len <= len_out);
248 memcpy(avpkt->data + written, chunk->data, chunk->len);
249 written += chunk->len;
252 avpkt->pts = recon_pic->pts;
253 avpkt->dts = recon_pic->dts;
255 // IRAP VCL NAL unit types span the range
256 // [BLA_W_LP (16), RSV_IRAP_VCL23 (23)].
257 if (frame_info.nal_unit_type >= KVZ_NAL_BLA_W_LP &&
258 frame_info.nal_unit_type <= KVZ_NAL_RSV_IRAP_VCL23) {
259 avpkt->flags |= AV_PKT_FLAG_KEY;
262 switch (frame_info.slice_type) {
264 pict_type = AV_PICTURE_TYPE_I;
267 pict_type = AV_PICTURE_TYPE_P;
270 pict_type = AV_PICTURE_TYPE_B;
273 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered.\n");
274 return AVERROR_EXTERNAL;
276 #if FF_API_CODED_FRAME
277 FF_DISABLE_DEPRECATION_WARNINGS
278 avctx->coded_frame->pict_type = pict_type;
279 FF_ENABLE_DEPRECATION_WARNINGS
282 ff_side_data_set_encoder_stats(avpkt, frame_info.qp * FF_QP2LAMBDA, NULL, 0, pict_type);
284 #if FF_API_CODED_FRAME
285 FF_DISABLE_DEPRECATION_WARNINGS
286 avctx->coded_frame->quality = frame_info.qp * FF_QP2LAMBDA;
287 FF_ENABLE_DEPRECATION_WARNINGS
294 ctx->api->picture_free(input_pic);
295 ctx->api->picture_free(recon_pic);
296 ctx->api->chunk_free(data_out);
300 static const enum AVPixelFormat pix_fmts[] = {
305 #define OFFSET(x) offsetof(LibkvazaarContext, x)
306 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
307 static const AVOption options[] = {
308 { "kvazaar-params", "Set kvazaar parameters as a comma-separated list of key=value pairs.",
309 OFFSET(kvz_params), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
313 static const AVClass class = {
314 .class_name = "libkvazaar",
315 .item_name = av_default_item_name,
317 .version = LIBAVUTIL_VERSION_INT,
320 static const AVCodecDefault defaults[] = {
325 AVCodec ff_libkvazaar_encoder = {
326 .name = "libkvazaar",
327 .long_name = NULL_IF_CONFIG_SMALL("libkvazaar H.265 / HEVC"),
328 .type = AVMEDIA_TYPE_VIDEO,
329 .id = AV_CODEC_ID_HEVC,
330 .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AUTO_THREADS,
331 .pix_fmts = pix_fmts,
333 .priv_class = &class,
334 .priv_data_size = sizeof(LibkvazaarContext),
335 .defaults = defaults,
337 .init = libkvazaar_init,
338 .encode2 = libkvazaar_encode,
339 .close = libkvazaar_close,
341 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
343 .wrapper_name = "libkvazaar",