FFmpeg
Loading...
Searching...
No Matches
libkvazaar.c
Go to the documentation of this file.
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 <stdint.h>
25#include <string.h>
26
28#include "libavutil/avassert.h"
29#include "libavutil/dict.h"
30#include "libavutil/error.h"
31#include "libavutil/imgutils.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 "codec_internal.h"
39#include "encode.h"
40
41typedef struct LibkvazaarContext {
42 const AVClass *class;
43
44 const kvz_api *api;
45 kvz_encoder *encoder;
46 kvz_config *config;
47
50
52{
53 LibkvazaarContext *const ctx = avctx->priv_data;
54 const kvz_api *const api = ctx->api = kvz_api_get(8);
55 kvz_config *cfg = NULL;
56 kvz_encoder *enc = NULL;
57
58 /* Kvazaar requires width and height to be multiples of eight. */
59 if (avctx->width % 8 || avctx->height % 8) {
60 av_log(avctx, AV_LOG_ERROR,
61 "Video dimensions are not a multiple of 8 (%dx%d).\n",
62 avctx->width, avctx->height);
63 return AVERROR(ENOSYS);
64 }
65
66 ctx->config = cfg = api->config_alloc();
67 if (!cfg) {
68 av_log(avctx, AV_LOG_ERROR,
69 "Could not allocate kvazaar config structure.\n");
70 return AVERROR(ENOMEM);
71 }
72
73 if (!api->config_init(cfg)) {
74 av_log(avctx, AV_LOG_ERROR,
75 "Could not initialize kvazaar config structure.\n");
76 return AVERROR_BUG;
77 }
78
79 cfg->width = avctx->width;
80 cfg->height = avctx->height;
81
82 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
83 cfg->framerate_num = avctx->framerate.num;
84 cfg->framerate_denom = avctx->framerate.den;
85 } else {
86 cfg->framerate_num = avctx->time_base.den;
87 cfg->framerate_denom = avctx->time_base.num;
88 }
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 if (avctx->bit_rate) {
93 cfg->rc_algorithm = KVZ_LAMBDA;
94 }
95
96 cfg->vui.fullrange = avctx->color_range == AVCOL_RANGE_JPEG;
97 cfg->vui.colorprim = avctx->color_primaries;
98 cfg->vui.transfer = avctx->color_trc;
99 cfg->vui.colormatrix = avctx->colorspace;
101 cfg->vui.chroma_loc = avctx->chroma_sample_location - 1;
102
103 if (ctx->kvz_params) {
104 AVDictionary *dict = NULL;
105 if (!av_dict_parse_string(&dict, ctx->kvz_params, "=", ",", 0)) {
107 while ((entry = av_dict_iterate(dict, entry))) {
108 if (!api->config_parse(cfg, entry->key, entry->value)) {
109 av_log(avctx, AV_LOG_WARNING, "Invalid option: %s=%s.\n",
110 entry->key, entry->value);
111 }
112 }
113 }
114 av_dict_free(&dict);
115 }
116
117 ctx->encoder = enc = api->encoder_open(cfg);
118 if (!enc) {
119 av_log(avctx, AV_LOG_ERROR, "Could not open kvazaar encoder.\n");
120 return AVERROR_BUG;
121 }
122
123 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
124 kvz_data_chunk *data_out = NULL;
125 kvz_data_chunk *chunk = NULL;
126 uint32_t len_out;
127 uint8_t *p;
128
129 if (!api->encoder_headers(enc, &data_out, &len_out))
130 return AVERROR(ENOMEM);
131
132 avctx->extradata = p = av_mallocz(len_out + AV_INPUT_BUFFER_PADDING_SIZE);
133 if (!p) {
134 ctx->api->chunk_free(data_out);
135 return AVERROR(ENOMEM);
136 }
137
138 avctx->extradata_size = len_out;
139
140 for (chunk = data_out; chunk != NULL; chunk = chunk->next) {
141 memcpy(p, chunk->data, chunk->len);
142 p += chunk->len;
143 }
144
145 ctx->api->chunk_free(data_out);
146 }
147
148 return 0;
149}
150
152{
154
155 if (ctx->api) {
156 ctx->api->encoder_close(ctx->encoder);
157 ctx->api->config_destroy(ctx->config);
158 }
159
160 return 0;
161}
162
164 AVPacket *avpkt,
165 const AVFrame *frame,
166 int *got_packet_ptr)
167{
169 kvz_picture *input_pic = NULL;
170 kvz_picture *recon_pic = NULL;
171 kvz_frame_info frame_info;
172 kvz_data_chunk *data_out = NULL;
173 uint32_t len_out = 0;
174 int retval = 0;
175
176 *got_packet_ptr = 0;
177
178 if (frame) {
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;
187 goto done;
188 }
189
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",
195 av_get_pix_fmt_name(frame->format));
196 retval = AVERROR_INVALIDDATA;
197 goto done;
198 }
199
200 // Allocate input picture for kvazaar.
201 input_pic = ctx->api->picture_alloc(frame->width, frame->height);
202 if (!input_pic) {
203 av_log(avctx, AV_LOG_ERROR, "Failed to allocate picture.\n");
204 retval = AVERROR(ENOMEM);
205 goto done;
206 }
207
208 // Copy pixels from frame to input_pic.
209 {
210 uint8_t *dst[4] = {
211 input_pic->data[0],
212 input_pic->data[1],
213 input_pic->data[2],
214 NULL,
215 };
216 int dst_linesizes[4] = {
217 frame->width,
218 frame->width / 2,
219 frame->width / 2,
220 0
221 };
222 av_image_copy2(dst, dst_linesizes,
223 frame->data, frame->linesize,
224 frame->format, frame->width, frame->height);
225 }
226
227 input_pic->pts = frame->pts;
228 }
229
230 retval = ctx->api->encoder_encode(ctx->encoder,
231 input_pic,
232 &data_out, &len_out,
233 &recon_pic, NULL,
234 &frame_info);
235 if (!retval) {
236 av_log(avctx, AV_LOG_ERROR, "Failed to encode frame.\n");
237 retval = AVERROR_INVALIDDATA;
238 goto done;
239 } else
240 retval = 0; /* kvazaar returns 1 on success */
241
242 if (data_out) {
243 kvz_data_chunk *chunk = NULL;
244 uint64_t written = 0;
245
246 retval = ff_get_encode_buffer(avctx, avpkt, len_out, 0);
247 if (retval < 0) {
248 av_log(avctx, AV_LOG_ERROR, "Failed to allocate output packet.\n");
249 goto done;
250 }
251
252 for (chunk = data_out; chunk != NULL; chunk = chunk->next) {
253 av_assert0(written + chunk->len <= len_out);
254 memcpy(avpkt->data + written, chunk->data, chunk->len);
255 written += chunk->len;
256 }
257
258 avpkt->pts = recon_pic->pts;
259 avpkt->dts = recon_pic->dts;
260 avpkt->flags = 0;
261 // IRAP VCL NAL unit types span the range
262 // [BLA_W_LP (16), RSV_IRAP_VCL23 (23)].
263 if (frame_info.nal_unit_type >= KVZ_NAL_BLA_W_LP &&
264 frame_info.nal_unit_type <= KVZ_NAL_RSV_IRAP_VCL23) {
265 avpkt->flags |= AV_PKT_FLAG_KEY;
266 }
267
268 enum AVPictureType pict_type;
269 switch (frame_info.slice_type) {
270 case KVZ_SLICE_I:
271 pict_type = AV_PICTURE_TYPE_I;
272 break;
273 case KVZ_SLICE_P:
274 pict_type = AV_PICTURE_TYPE_P;
275 break;
276 case KVZ_SLICE_B:
277 pict_type = AV_PICTURE_TYPE_B;
278 break;
279 default:
280 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered.\n");
281 return AVERROR_EXTERNAL;
282 }
283
284 ff_encode_add_stats_side_data(avpkt, frame_info.qp * FF_QP2LAMBDA, NULL, 0, pict_type);
285
286 *got_packet_ptr = 1;
287 }
288
289done:
290 ctx->api->picture_free(input_pic);
291 ctx->api->picture_free(recon_pic);
292 ctx->api->chunk_free(data_out);
293 return retval;
294}
295
296static const enum AVPixelFormat pix_fmts[] = {
299};
300
301#define OFFSET(x) offsetof(LibkvazaarContext, x)
302#define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
303static const AVOption options[] = {
304 { "kvazaar-params", "Set kvazaar parameters as a comma-separated list of key=value pairs.",
305 OFFSET(kvz_params), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
306 { NULL },
307};
308
309static const AVClass class = {
310 .class_name = "libkvazaar",
312 .option = options,
314};
315
316static const FFCodecDefault defaults[] = {
317 { "b", "0" },
318 { NULL },
319};
320
322 .p.name = "libkvazaar",
323 CODEC_LONG_NAME("libkvazaar H.265 / HEVC"),
324 .p.type = AVMEDIA_TYPE_VIDEO,
325 .p.id = AV_CODEC_ID_HEVC,
326 .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
329 .color_ranges = AVCOL_RANGE_MPEG | AVCOL_RANGE_JPEG,
330
331 .p.priv_class = &class,
332 .priv_data_size = sizeof(LibkvazaarContext),
334
337 .close = libkvazaar_close,
338
339 .caps_internal = FF_CODEC_CAP_INIT_CLEANUP |
341
342 .p.wrapper_name = "libkvazaar",
343};
uint8_t ptrdiff_t const uint8_t ptrdiff_t int intptr_t intptr_t int int16_t * dst
Definition dsp.h:87
const FFCodec ff_libkvazaar_encoder
Definition libkvazaar.c:321
#define VE
Definition amfenc_av1.c:30
static const FFCodecDefault defaults[]
Definition amfenc_av1.c:723
#define entry
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
Libavcodec external API header.
static int FUNC frame_info(CodedBitstreamContext *ctx, RWContext *rw, APVRawFrameInfo *current)
#define CODEC_PIXFMTS_ARRAY(array)
#define FF_CODEC_ENCODE_CB(func)
#define CODEC_LONG_NAME(str)
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
#define FF_CODEC_CAP_AUTO_THREADS
Codec handles avctx->thread_count == 0 (auto) internally.
#define NULL
Definition coverity.c:32
static AVFrame * frame
Public dictionary API.
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:608
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
Get a buffer for a packet.
Definition encode.c:106
int ff_encode_add_stats_side_data(AVPacket *pkt, int quality, const int64_t error[], int error_count, enum AVPictureType pict_type)
Definition encode.c:1070
error code definitions
static CheckasmConfig cfg
Definition checkasm.c:74
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
#define AV_CODEC_CAP_OTHER_THREADS
Codec supports multithreading through a method other than slice- or frame-level multithreading.
Definition codec.h:112
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition codec.h:79
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() or get_encode_buffer() for allocating buffers and supports custom allocators.
Definition codec.h:49
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition avcodec.h:318
@ AV_CODEC_ID_HEVC
Definition codec_id.h:223
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:650
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:233
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition dict.c:42
int av_dict_parse_string(AVDictionary **pm, const char *str, const char *key_val_sep, const char *pairs_sep, int flags)
Parse the key/value pairs list and add the parsed entries to a dictionary.
Definition dict.c:210
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition avutil.h:226
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition error.h:59
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition error.h:52
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
const char * av_default_item_name(void *ptr)
Return the context name.
Definition log.c:241
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
static void av_image_copy2(uint8_t *const dst_data[4], const int dst_linesizes[4], uint8_t *const src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height)
Wrapper around av_image_copy() to workaround the limitation that the conversion from uint8_t * const ...
Definition imgutils.h:184
AVPictureType
Definition avutil.h:276
@ AV_PICTURE_TYPE_I
Intra.
Definition avutil.h:278
@ AV_PICTURE_TYPE_P
Predicted.
Definition avutil.h:279
@ AV_PICTURE_TYPE_B
Bi-dir predicted.
Definition avutil.h:280
#define LIBAVUTIL_VERSION_INT
Definition version.h:85
misc image utilities
Macro definitions for various function/variable attributes.
#define av_cold
Definition attributes.h:117
static av_cold int libkvazaar_init(AVCodecContext *avctx)
Definition libkvazaar.c:51
static av_cold int libkvazaar_close(AVCodecContext *avctx)
Definition libkvazaar.c:151
static enum AVPixelFormat pix_fmts[]
Definition libkvazaar.c:296
#define OFFSET(x)
Definition libkvazaar.c:301
static int libkvazaar_encode(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr)
Definition libkvazaar.c:163
Memory handling functions.
AVOptions.
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition pixdesc.c:3380
@ AVCHROMA_LOC_UNSPECIFIED
Definition pixfmt.h:803
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
Definition pixfmt.h:766
@ AVCOL_RANGE_JPEG
Full range content.
Definition pixfmt.h:783
AVPixelFormat
Pixel format.
Definition pixfmt.h:71
@ AV_PIX_FMT_NONE
Definition pixfmt.h:72
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition pixfmt.h:73
Describe the class of an AVClass context structure.
Definition log.h:76
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition log.h:81
main external API structure.
Definition avcodec.h:443
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:643
int width
picture width / height.
Definition avcodec.h:604
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition avcodec.h:681
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition avcodec.h:657
AVRational framerate
Definition avcodec.h:563
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition avcodec.h:628
int64_t bit_rate
the average bitrate
Definition avcodec.h:493
enum AVColorSpace colorspace
YUV colorspace type.
Definition avcodec.h:671
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition avcodec.h:664
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avcodec.h:547
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:500
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
Definition avcodec.h:526
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
Definition avcodec.h:688
int extradata_size
Definition avcodec.h:527
void * priv_data
Definition avcodec.h:470
This structure describes decoded (raw) audio or video data.
Definition frame.h:472
AVOption.
Definition opt.h:428
This structure stores compressed data.
Definition packet.h:580
int flags
A combination of AV_PKT_FLAG values.
Definition packet.h:609
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition packet.h:596
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition packet.h:602
uint8_t * data
Definition packet.h:603
int num
Numerator.
Definition rational.h:59
int den
Denominator.
Definition rational.h:60
const kvz_api * api
Definition libkvazaar.c:44
kvz_config * config
Definition libkvazaar.c:46
kvz_encoder * encoder
Definition libkvazaar.c:45
#define av_mallocz(s)
#define av_log(a,...)
static AVFormatContext * ctx
Definition movenc.c:49