]> git.sesse.net Git - ffmpeg/blob - libavcodec/libkvazaar.c
Merge commit '26ec75aec3576daea691dee53a78ec67c0dc4040'
[ffmpeg] / libavcodec / libkvazaar.c
1 /*
2  * libkvazaar encoder
3  *
4  * Copyright (c) 2015 Tampere University of Technology
5  *
6  * This file is part of FFmpeg.
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <kvazaar.h>
24 #include <string.h>
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/error.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/internal.h"
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/opt.h"
33
34 #include "avcodec.h"
35 #include "internal.h"
36
37 typedef struct LibkvazaarContext {
38     const AVClass *class;
39
40     const kvz_api *api;
41     kvz_encoder *encoder;
42     kvz_config *config;
43
44     char *kvz_params;
45 } LibkvazaarContext;
46
47 static av_cold int libkvazaar_init(AVCodecContext *avctx)
48 {
49     LibkvazaarContext *const ctx = avctx->priv_data;
50     const kvz_api *const api = ctx->api = kvz_api_get(8);
51     kvz_config *cfg = NULL;
52     kvz_encoder *enc = NULL;
53
54     /* Kvazaar requires width and height to be multiples of eight. */
55     if (avctx->width % 8 || avctx->height % 8) {
56         av_log(avctx, AV_LOG_ERROR,
57                "Video dimensions are not a multiple of 8 (%dx%d).\n",
58                avctx->width, avctx->height);
59         return AVERROR(ENOSYS);
60     }
61
62     ctx->config = cfg = api->config_alloc();
63     if (!cfg) {
64         av_log(avctx, AV_LOG_ERROR,
65                "Could not allocate kvazaar config structure.\n");
66         return AVERROR(ENOMEM);
67     }
68
69     if (!api->config_init(cfg)) {
70         av_log(avctx, AV_LOG_ERROR,
71                "Could not initialize kvazaar config structure.\n");
72         return AVERROR_BUG;
73     }
74
75     cfg->width  = avctx->width;
76     cfg->height = avctx->height;
77
78     cfg->framerate =
79       avctx->time_base.den / (double)(avctx->time_base.num * avctx->ticks_per_frame);
80     cfg->target_bitrate = avctx->bit_rate;
81     cfg->vui.sar_width  = avctx->sample_aspect_ratio.num;
82     cfg->vui.sar_height = avctx->sample_aspect_ratio.den;
83
84     if (ctx->kvz_params) {
85         AVDictionary *dict = NULL;
86         if (!av_dict_parse_string(&dict, ctx->kvz_params, "=", ",", 0)) {
87             AVDictionaryEntry *entry = NULL;
88             while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) {
89                 if (!api->config_parse(cfg, entry->key, entry->value)) {
90                     av_log(avctx, AV_LOG_WARNING, "Invalid option: %s=%s.\n",
91                            entry->key, entry->value);
92                 }
93             }
94             av_dict_free(&dict);
95         }
96     }
97
98     ctx->encoder = enc = api->encoder_open(cfg);
99     if (!enc) {
100         av_log(avctx, AV_LOG_ERROR, "Could not open kvazaar encoder.\n");
101         return AVERROR_BUG;
102     }
103
104     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
105         kvz_data_chunk *data_out = NULL;
106         kvz_data_chunk *chunk = NULL;
107         uint32_t len_out;
108         uint8_t *p;
109
110         if (!api->encoder_headers(enc, &data_out, &len_out))
111             return AVERROR(ENOMEM);
112
113         avctx->extradata = p = av_mallocz(len_out + AV_INPUT_BUFFER_PADDING_SIZE);
114         if (!p) {
115             ctx->api->chunk_free(data_out);
116             return AVERROR(ENOMEM);
117         }
118
119         avctx->extradata_size = len_out;
120
121         for (chunk = data_out; chunk != NULL; chunk = chunk->next) {
122             memcpy(p, chunk->data, chunk->len);
123             p += chunk->len;
124         }
125
126         ctx->api->chunk_free(data_out);
127     }
128
129     return 0;
130 }
131
132 static av_cold int libkvazaar_close(AVCodecContext *avctx)
133 {
134     LibkvazaarContext *ctx = avctx->priv_data;
135
136     if (ctx->api) {
137       ctx->api->encoder_close(ctx->encoder);
138       ctx->api->config_destroy(ctx->config);
139     }
140
141     if (avctx->extradata)
142         av_freep(&avctx->extradata);
143
144     return 0;
145 }
146
147 static int libkvazaar_encode(AVCodecContext *avctx,
148                              AVPacket *avpkt,
149                              const AVFrame *frame,
150                              int *got_packet_ptr)
151 {
152     LibkvazaarContext *ctx = avctx->priv_data;
153     kvz_picture *input_pic = NULL;
154     kvz_picture *recon_pic = NULL;
155     kvz_frame_info frame_info;
156     kvz_data_chunk *data_out = NULL;
157     uint32_t len_out = 0;
158     int retval = 0;
159
160     *got_packet_ptr = 0;
161
162     if (frame) {
163         if (frame->width != ctx->config->width ||
164                 frame->height != ctx->config->height) {
165             av_log(avctx, AV_LOG_ERROR,
166                    "Changing video dimensions during encoding is not supported. "
167                    "(changed from %dx%d to %dx%d)\n",
168                    ctx->config->width, ctx->config->height,
169                    frame->width, frame->height);
170             retval = AVERROR_INVALIDDATA;
171             goto done;
172         }
173
174         if (frame->format != avctx->pix_fmt) {
175             av_log(avctx, AV_LOG_ERROR,
176                    "Changing pixel format during encoding is not supported. "
177                    "(changed from %s to %s)\n",
178                    av_get_pix_fmt_name(avctx->pix_fmt),
179                    av_get_pix_fmt_name(frame->format));
180             retval = AVERROR_INVALIDDATA;
181             goto done;
182         }
183
184         // Allocate input picture for kvazaar.
185         input_pic = ctx->api->picture_alloc(frame->width, frame->height);
186         if (!input_pic) {
187             av_log(avctx, AV_LOG_ERROR, "Failed to allocate picture.\n");
188             retval = AVERROR(ENOMEM);
189             goto done;
190         }
191
192         // Copy pixels from frame to input_pic.
193         {
194             int dst_linesizes[4] = {
195               frame->width,
196               frame->width / 2,
197               frame->width / 2,
198               0
199             };
200             av_image_copy(input_pic->data, dst_linesizes,
201                           frame->data, frame->linesize,
202                           frame->format, frame->width, frame->height);
203         }
204
205         input_pic->pts = frame->pts;
206     }
207
208     retval = ctx->api->encoder_encode(ctx->encoder,
209                                       input_pic,
210                                       &data_out, &len_out,
211                                       &recon_pic, NULL,
212                                       &frame_info);
213     if (!retval) {
214         av_log(avctx, AV_LOG_ERROR, "Failed to encode frame.\n");
215         retval = AVERROR_INVALIDDATA;
216         goto done;
217     }
218     else
219         retval = 0; /* kvazaar returns 1 on success */
220
221     if (data_out) {
222         kvz_data_chunk *chunk = NULL;
223         uint64_t written = 0;
224
225         retval = ff_alloc_packet(avpkt, len_out);
226         if (retval < 0) {
227             av_log(avctx, AV_LOG_ERROR, "Failed to allocate output packet.\n");
228             goto done;
229         }
230
231         for (chunk = data_out; chunk != NULL; chunk = chunk->next) {
232             av_assert0(written + chunk->len <= len_out);
233             memcpy(avpkt->data + written, chunk->data, chunk->len);
234             written += chunk->len;
235         }
236
237         avpkt->pts = recon_pic->pts;
238         avpkt->dts = recon_pic->dts;
239         avpkt->flags = 0;
240         // IRAP VCL NAL unit types span the range
241         // [BLA_W_LP (16), RSV_IRAP_VCL23 (23)].
242         if (frame_info.nal_unit_type >= KVZ_NAL_BLA_W_LP &&
243                 frame_info.nal_unit_type <= KVZ_NAL_RSV_IRAP_VCL23) {
244             avpkt->flags |= AV_PKT_FLAG_KEY;
245         }
246
247         *got_packet_ptr = 1;
248     }
249
250 done:
251     ctx->api->picture_free(input_pic);
252     ctx->api->picture_free(recon_pic);
253     ctx->api->chunk_free(data_out);
254     return retval;
255 }
256
257 static const enum AVPixelFormat pix_fmts[] = {
258     AV_PIX_FMT_YUV420P,
259     AV_PIX_FMT_NONE
260 };
261
262 #define OFFSET(x) offsetof(LibkvazaarContext, x)
263 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
264 static const AVOption options[] = {
265     { "kvazaar-params", "Set kvazaar parameters as a comma-separated list of key=value pairs.",
266         OFFSET(kvz_params), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
267     { NULL },
268 };
269
270 static const AVClass class = {
271     .class_name = "libkvazaar",
272     .item_name  = av_default_item_name,
273     .option     = options,
274     .version    = LIBAVUTIL_VERSION_INT,
275 };
276
277 static const AVCodecDefault defaults[] = {
278     { "b", "0" },
279     { NULL },
280 };
281
282 AVCodec ff_libkvazaar_encoder = {
283     .name             = "libkvazaar",
284     .long_name        = NULL_IF_CONFIG_SMALL("libkvazaar H.265 / HEVC"),
285     .type             = AVMEDIA_TYPE_VIDEO,
286     .id               = AV_CODEC_ID_HEVC,
287     .capabilities     = AV_CODEC_CAP_DELAY,
288     .pix_fmts         = pix_fmts,
289
290     .priv_class       = &class,
291     .priv_data_size   = sizeof(LibkvazaarContext),
292     .defaults         = defaults,
293
294     .init             = libkvazaar_init,
295     .encode2          = libkvazaar_encode,
296     .close            = libkvazaar_close,
297
298     .caps_internal    = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
299 };