]> git.sesse.net Git - ffmpeg/blob - libavcodec/libx265.c
libx265: Fix use of uninitialized input picture
[ffmpeg] / libavcodec / libx265.c
1 /*
2  * libx265 encoder
3  *
4  * Copyright (c) 2013-2014 Derek Buitenhuis
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 <x265.h>
24
25 #include "libavutil/internal.h"
26 #include "libavutil/common.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
29 #include "avcodec.h"
30 #include "internal.h"
31
32 typedef struct libx265Context {
33     const AVClass *class;
34
35     x265_encoder *encoder;
36     x265_param   *params;
37     uint8_t      *header;
38     int           header_size;
39
40     char *preset;
41     char *tune;
42     char *x265_opts;
43 } libx265Context;
44
45 static int is_keyframe(NalUnitType naltype)
46 {
47     switch (naltype) {
48     case NAL_UNIT_CODED_SLICE_BLA_W_LP:
49     case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
50     case NAL_UNIT_CODED_SLICE_BLA_N_LP:
51     case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
52     case NAL_UNIT_CODED_SLICE_IDR_N_LP:
53     case NAL_UNIT_CODED_SLICE_CRA:
54         return 1;
55     default:
56         return 0;
57     }
58 }
59
60 static av_cold int libx265_encode_close(AVCodecContext *avctx)
61 {
62     libx265Context *ctx = avctx->priv_data;
63
64     av_frame_free(&avctx->coded_frame);
65     av_freep(&ctx->header);
66
67     x265_param_free(ctx->params);
68
69     if (ctx->encoder)
70         x265_encoder_close(ctx->encoder);
71
72     return 0;
73 }
74
75 static av_cold int libx265_encode_init(AVCodecContext *avctx)
76 {
77     libx265Context *ctx = avctx->priv_data;
78     x265_nal *nal;
79     uint8_t *buf;
80     int nnal;
81     int ret;
82     int i;
83
84     avctx->coded_frame = av_frame_alloc();
85     if (!avctx->coded_frame) {
86         av_log(avctx, AV_LOG_ERROR, "Could not allocate frame.\n");
87         return AVERROR(ENOMEM);
88     }
89
90     ctx->params = x265_param_alloc();
91     if (!ctx->params) {
92         av_log(avctx, AV_LOG_ERROR, "Could not allocate x265 param structure.\n");
93         return AVERROR(ENOMEM);
94     }
95
96     x265_param_default(ctx->params);
97     if (x265_param_default_preset(ctx->params, ctx->preset, ctx->tune) < 0) {
98         av_log(avctx, AV_LOG_ERROR, "Invalid preset or tune.\n");
99         return AVERROR(EINVAL);
100     }
101
102     ctx->params->frameNumThreads = avctx->thread_count;
103     ctx->params->frameRate       = (int) (avctx->time_base.den / avctx->time_base.num);
104     ctx->params->sourceWidth     = avctx->width;
105     ctx->params->sourceHeight    = avctx->height;
106     ctx->params->inputBitDepth   = av_pix_fmt_desc_get(avctx->pix_fmt)->comp[0].depth_minus1 + 1;
107
108     if (avctx->bit_rate > 0) {
109         ctx->params->rc.bitrate         = avctx->bit_rate / 1000;
110         ctx->params->rc.rateControlMode = X265_RC_ABR;
111     }
112
113     if (ctx->x265_opts) {
114         AVDictionary *dict    = NULL;
115         AVDictionaryEntry *en = NULL;
116
117         if (!av_dict_parse_string(&dict, ctx->x265_opts, "=", ":", 0)) {
118             while ((en = av_dict_get(dict, "", en, AV_DICT_IGNORE_SUFFIX))) {
119                 int parse_ret = x265_param_parse(ctx->params, en->key, en->value);
120
121                 switch (parse_ret) {
122                 case X265_PARAM_BAD_NAME:
123                     av_log(avctx, AV_LOG_WARNING,
124                           "Unknown option: %s.\n", en->key);
125                     break;
126                 case X265_PARAM_BAD_VALUE:
127                     av_log(avctx, AV_LOG_WARNING,
128                           "Invalid value for %s: %s.\n", en->key, en->value);
129                     break;
130                 default:
131                     break;
132                 }
133             }
134             av_dict_free(&dict);
135         }
136     }
137
138     ctx->encoder = x265_encoder_open(ctx->params);
139     if (!ctx->encoder) {
140         av_log(avctx, AV_LOG_ERROR, "Cannot open libx265 encoder.\n");
141         libx265_encode_close(avctx);
142         return AVERROR_INVALIDDATA;
143     }
144
145     ret = x265_encoder_headers(ctx->encoder, &nal, &nnal);
146     if (ret < 0) {
147         av_log(avctx, AV_LOG_ERROR, "Cannot encode headers.\n");
148         libx265_encode_close(avctx);
149         return AVERROR_INVALIDDATA;
150     }
151
152     for (i = 0; i < nnal; i++)
153         ctx->header_size += nal[i].sizeBytes;
154
155     ctx->header = av_malloc(ctx->header_size);
156     if (!ctx->header) {
157         av_log(avctx, AV_LOG_ERROR,
158                "Cannot allocate HEVC header of size %d.\n", ctx->header_size);
159         libx265_encode_close(avctx);
160         return AVERROR(ENOMEM);
161     }
162
163     buf = ctx->header;
164     for (i = 0; i < nnal; i++) {
165         memcpy(buf, nal[i].payload, nal[i].sizeBytes);
166         buf += nal[i].sizeBytes;
167     }
168
169     return 0;
170 }
171
172 static int libx265_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
173                                 const AVFrame *pic, int *got_packet)
174 {
175     libx265Context *ctx = avctx->priv_data;
176     x265_picture x265pic;
177     x265_picture x265pic_out = { { 0 } };
178     x265_nal *nal;
179     uint8_t *dst;
180     int payload = 0;
181     int nnal;
182     int ret;
183     int i;
184
185     x265_picture_init(ctx->params, &x265pic);
186
187     if (pic) {
188         for (i = 0; i < 3; i++) {
189            x265pic.planes[i] = pic->data[i];
190            x265pic.stride[i] = pic->linesize[i];
191         }
192
193         x265pic.pts = pic->pts;
194     }
195
196     ret = x265_encoder_encode(ctx->encoder, &nal, &nnal,
197                               pic ? &x265pic : NULL, &x265pic_out);
198     if (ret < 0)
199         return AVERROR_UNKNOWN;
200
201     if (!nnal)
202         return 0;
203
204     for (i = 0; i < nnal; i++)
205         payload += nal[i].sizeBytes;
206
207     payload += ctx->header_size;
208
209     ret = ff_alloc_packet(pkt, payload);
210     if (ret < 0) {
211         av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");
212         return ret;
213     }
214     dst = pkt->data;
215
216     if (ctx->header) {
217         memcpy(dst, ctx->header, ctx->header_size);
218         dst += ctx->header_size;
219
220         av_freep(&ctx->header);
221         ctx->header_size = 0;
222     }
223
224     for (i = 0; i < nnal; i++) {
225         memcpy(dst, nal[i].payload, nal[i].sizeBytes);
226         dst += nal[i].sizeBytes;
227
228         if (is_keyframe(nal[i].type))
229             pkt->flags |= AV_PKT_FLAG_KEY;
230     }
231
232     pkt->pts = x265pic_out.pts;
233     pkt->dts = x265pic_out.dts;
234
235     *got_packet = 1;
236     return 0;
237 }
238
239 static const enum AVPixelFormat x265_csp_eight[] = {
240     AV_PIX_FMT_YUV420P,
241     AV_PIX_FMT_NONE
242 };
243
244 static const enum AVPixelFormat x265_csp_twelve[] = {
245     AV_PIX_FMT_YUV420P,
246     AV_PIX_FMT_YUV420P10,
247     AV_PIX_FMT_NONE
248 };
249
250 static av_cold void libx265_encode_init_csp(AVCodec *codec)
251 {
252     if (x265_max_bit_depth == 8)
253         codec->pix_fmts = x265_csp_eight;
254     else if (x265_max_bit_depth == 12)
255         codec->pix_fmts = x265_csp_twelve;
256 }
257
258 #define OFFSET(x) offsetof(libx265Context, x)
259 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
260 static const AVOption options[] = {
261     { "preset",      "set the x265 preset",                                                         OFFSET(preset),    AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
262     { "tune",        "set the x265 tune parameter",                                                 OFFSET(tune),      AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
263     { "x265-params", "set the x265 configuration using a :-separated list of key=value parameters", OFFSET(x265_opts), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
264     { NULL }
265 };
266
267 static const AVClass class = {
268     .class_name = "libx265",
269     .item_name  = av_default_item_name,
270     .option     = options,
271     .version    = LIBAVUTIL_VERSION_INT,
272 };
273
274 AVCodec ff_libx265_encoder = {
275     .name             = "libx265",
276     .long_name        = NULL_IF_CONFIG_SMALL("libx265 H.265 / HEVC"),
277     .type             = AVMEDIA_TYPE_VIDEO,
278     .id               = AV_CODEC_ID_HEVC,
279     .init             = libx265_encode_init,
280     .init_static_data = libx265_encode_init_csp,
281     .encode2          = libx265_encode_frame,
282     .close            = libx265_encode_close,
283     .priv_data_size   = sizeof(libx265Context),
284     .priv_class       = &class,
285     .capabilities     = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,
286 };