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