]> git.sesse.net Git - ffmpeg/blob - libavcodec/libopenh264enc.c
lavc: Deprecate coder_type and its symbols
[ffmpeg] / libavcodec / libopenh264enc.c
1 /*
2  * OpenH264 video encoder
3  * Copyright (C) 2014 Martin Storsjo
4  *
5  * This file is part of Libav.
6  *
7  * Libav is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * Libav is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <wels/codec_api.h>
23 #include <wels/codec_ver.h>
24
25 #include "libavutil/attributes.h"
26 #include "libavutil/common.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/mathematics.h"
30
31 #include "avcodec.h"
32 #include "internal.h"
33
34 typedef struct SVCContext {
35     const AVClass *av_class;
36     ISVCEncoder *encoder;
37     int slice_mode;
38     int loopfilter;
39     char *profile;
40     int max_nal_size;
41     int skip_frames;
42     int skipped;
43     int cabac;
44 } SVCContext;
45
46 #define OPENH264_VER_AT_LEAST(maj, min) \
47     ((OPENH264_MAJOR  > (maj)) || \
48      (OPENH264_MAJOR == (maj) && OPENH264_MINOR >= (min)))
49
50 #define OFFSET(x) offsetof(SVCContext, x)
51 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
52 static const AVOption options[] = {
53     { "slice_mode", "Slice mode", OFFSET(slice_mode), AV_OPT_TYPE_INT, { .i64 = SM_AUTO_SLICE }, SM_SINGLE_SLICE, SM_RESERVED, VE, "slice_mode" },
54     { "fixed", "A fixed number of slices", 0, AV_OPT_TYPE_CONST, { .i64 = SM_FIXEDSLCNUM_SLICE }, 0, 0, VE, "slice_mode" },
55     { "rowmb", "One slice per row of macroblocks", 0, AV_OPT_TYPE_CONST, { .i64 = SM_ROWMB_SLICE }, 0, 0, VE, "slice_mode" },
56     { "auto", "Automatic number of slices according to number of threads", 0, AV_OPT_TYPE_CONST, { .i64 = SM_AUTO_SLICE }, 0, 0, VE, "slice_mode" },
57     { "dyn", "Dynamic slicing", 0, AV_OPT_TYPE_CONST, { .i64 = SM_DYN_SLICE }, 0, 0, VE, "slice_mode" },
58     { "loopfilter", "Enable loop filter", OFFSET(loopfilter), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, VE },
59     { "profile", "Set profile restrictions", OFFSET(profile), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
60     { "max_nal_size", "Set maximum NAL size in bytes", OFFSET(max_nal_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
61     { "allow_skip_frames", "Allow skipping frames to hit the target bitrate", OFFSET(skip_frames), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
62     { "cabac", "Enable cabac", OFFSET(cabac), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
63     { NULL }
64 };
65
66 static const AVClass class = {
67     "libopenh264enc", av_default_item_name, options, LIBAVUTIL_VERSION_INT
68 };
69
70 // Convert libopenh264 log level to equivalent libav log level.
71 static int libopenh264_to_libav_log_level(int libopenh264_log_level)
72 {
73     if      (libopenh264_log_level >= WELS_LOG_DETAIL)  return AV_LOG_TRACE;
74     else if (libopenh264_log_level >= WELS_LOG_DEBUG)   return AV_LOG_DEBUG;
75     else if (libopenh264_log_level >= WELS_LOG_INFO)    return AV_LOG_VERBOSE;
76     else if (libopenh264_log_level >= WELS_LOG_WARNING) return AV_LOG_WARNING;
77     else if (libopenh264_log_level >= WELS_LOG_ERROR)   return AV_LOG_ERROR;
78     else                                                return AV_LOG_QUIET;
79 }
80
81 // This function will be provided to the libopenh264 library.  The function will be called
82 // when libopenh264 wants to log a message (error, warning, info, etc.).  The signature for
83 // this function (defined in .../codec/api/svc/codec_api.h) is:
84 //
85 //        typedef void (*WelsTraceCallback) (void* ctx, int level, const char* string);
86
87 static void libopenh264_trace_callback(void *ctx, int level, char const *msg)
88 {
89     // The message will be logged only if the requested EQUIVALENT libav log level is
90     // less than or equal to the current libav log level.
91     int equiv_libav_log_level = libopenh264_to_libav_log_level(level);
92     av_log(ctx, equiv_libav_log_level, "%s\n", msg);
93 }
94
95 static av_cold int svc_encode_close(AVCodecContext *avctx)
96 {
97     SVCContext *s = avctx->priv_data;
98
99     if (s->encoder)
100         WelsDestroySVCEncoder(s->encoder);
101     if (s->skipped > 0)
102         av_log(avctx, AV_LOG_WARNING, "%d frames skipped\n", s->skipped);
103     return 0;
104 }
105
106 static av_cold int svc_encode_init(AVCodecContext *avctx)
107 {
108     SVCContext *s = avctx->priv_data;
109     SEncParamExt param = { 0 };
110     int err = AVERROR_UNKNOWN;
111     int log_level;
112     WelsTraceCallback callback_function;
113     AVCPBProperties *props;
114
115     // Mingw GCC < 4.7 on x86_32 uses an incorrect/buggy ABI for the WelsGetCodecVersion
116     // function (for functions returning larger structs), thus skip the check in those
117     // configurations.
118 #if !defined(_WIN32) || !defined(__GNUC__) || !ARCH_X86_32 || AV_GCC_VERSION_AT_LEAST(4, 7)
119     OpenH264Version libver = WelsGetCodecVersion();
120     if (memcmp(&libver, &g_stCodecVersion, sizeof(libver))) {
121         av_log(avctx, AV_LOG_ERROR, "Incorrect library version loaded\n");
122         return AVERROR(EINVAL);
123     }
124 #endif
125
126     if (WelsCreateSVCEncoder(&s->encoder)) {
127         av_log(avctx, AV_LOG_ERROR, "Unable to create encoder\n");
128         return AVERROR_UNKNOWN;
129     }
130
131     // Pass all libopenh264 messages to our callback, to allow ourselves to filter them.
132     log_level = WELS_LOG_DETAIL;
133     (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_LEVEL, &log_level);
134
135     // Set the logging callback function to one that uses av_log() (see implementation above).
136     callback_function = (WelsTraceCallback) libopenh264_trace_callback;
137     (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_CALLBACK, (void *)&callback_function);
138
139     // Set the AVCodecContext as the libopenh264 callback context so that it can be passed to av_log().
140     (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_CALLBACK_CONTEXT, (void *)&avctx);
141
142     (*s->encoder)->GetDefaultParams(s->encoder, &param);
143
144 #if FF_API_CODER_TYPE
145 FF_DISABLE_DEPRECATION_WARNINGS
146     if (!s->cabac)
147         s->cabac = avctx->coder_type == FF_CODER_TYPE_AC;
148 FF_ENABLE_DEPRECATION_WARNINGS
149 #endif
150
151     param.fMaxFrameRate              = avctx->time_base.den / avctx->time_base.num;
152     param.iPicWidth                  = avctx->width;
153     param.iPicHeight                 = avctx->height;
154     param.iTargetBitrate             = avctx->bit_rate;
155     param.iMaxBitrate                = FFMAX(avctx->rc_max_rate, avctx->bit_rate);
156     param.iRCMode                    = RC_QUALITY_MODE;
157     param.iTemporalLayerNum          = 1;
158     param.iSpatialLayerNum           = 1;
159     param.bEnableDenoise             = 0;
160     param.bEnableBackgroundDetection = 1;
161     param.bEnableAdaptiveQuant       = 1;
162     param.bEnableFrameSkip           = s->skip_frames;
163     param.bEnableLongTermReference   = 0;
164     param.iLtrMarkPeriod             = 30;
165     param.uiIntraPeriod              = avctx->gop_size;
166 #if OPENH264_VER_AT_LEAST(1, 4)
167     param.eSpsPpsIdStrategy          = CONSTANT_ID;
168 #else
169     param.bEnableSpsPpsIdAddition    = 0;
170 #endif
171     param.bPrefixNalAddingCtrl       = 0;
172     param.iLoopFilterDisableIdc      = !s->loopfilter;
173     param.iEntropyCodingModeFlag     = 0;
174     param.iMultipleThreadIdc         = avctx->thread_count;
175     if (s->profile && !strcmp(s->profile, "main"))
176         param.iEntropyCodingModeFlag = 1;
177     else if (!s->profile && s->cabac)
178         param.iEntropyCodingModeFlag = 1;
179
180     param.sSpatialLayers[0].iVideoWidth         = param.iPicWidth;
181     param.sSpatialLayers[0].iVideoHeight        = param.iPicHeight;
182     param.sSpatialLayers[0].fFrameRate          = param.fMaxFrameRate;
183     param.sSpatialLayers[0].iSpatialBitrate     = param.iTargetBitrate;
184     param.sSpatialLayers[0].iMaxSpatialBitrate  = param.iMaxBitrate;
185
186     if ((avctx->slices > 1) && (s->max_nal_size)){
187         av_log(avctx,AV_LOG_ERROR,"Invalid combination -slices %d and -max_nal_size %d.\n",avctx->slices,s->max_nal_size);
188         goto fail;
189     }
190
191     if (avctx->slices > 1)
192         s->slice_mode = SM_FIXEDSLCNUM_SLICE;
193
194     if (s->max_nal_size)
195         s->slice_mode = SM_DYN_SLICE;
196
197     param.sSpatialLayers[0].sSliceCfg.uiSliceMode               = s->slice_mode;
198     param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceNum = avctx->slices;
199
200     if (s->slice_mode == SM_DYN_SLICE) {
201         if (s->max_nal_size){
202             param.uiMaxNalSize = s->max_nal_size;
203             param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceSizeConstraint = s->max_nal_size;
204         } else {
205             if (avctx->rtp_payload_size) {
206                 av_log(avctx,AV_LOG_DEBUG,"Using RTP Payload size for uiMaxNalSize");
207                 param.uiMaxNalSize = avctx->rtp_payload_size;
208                 param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceSizeConstraint = avctx->rtp_payload_size;
209             } else {
210                 av_log(avctx,AV_LOG_ERROR,"Invalid -max_nal_size, specify a valid max_nal_size to use -slice_mode dyn\n");
211                 goto fail;
212             }
213         }
214     }
215
216     if ((*s->encoder)->InitializeExt(s->encoder, &param) != cmResultSuccess) {
217         av_log(avctx, AV_LOG_ERROR, "Initialize failed\n");
218         goto fail;
219     }
220
221     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
222         SFrameBSInfo fbi = { 0 };
223         int i, size = 0;
224         (*s->encoder)->EncodeParameterSets(s->encoder, &fbi);
225         for (i = 0; i < fbi.sLayerInfo[0].iNalCount; i++)
226             size += fbi.sLayerInfo[0].pNalLengthInByte[i];
227         avctx->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
228         if (!avctx->extradata) {
229             err = AVERROR(ENOMEM);
230             goto fail;
231         }
232         avctx->extradata_size = size;
233         memcpy(avctx->extradata, fbi.sLayerInfo[0].pBsBuf, size);
234     }
235
236     props = ff_add_cpb_side_data(avctx);
237     if (!props) {
238         err = AVERROR(ENOMEM);
239         goto fail;
240     }
241     props->max_bitrate = param.iMaxBitrate;
242     props->avg_bitrate = param.iTargetBitrate;
243
244     return 0;
245
246 fail:
247     svc_encode_close(avctx);
248     return err;
249 }
250
251 static int svc_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
252                             const AVFrame *frame, int *got_packet)
253 {
254     SVCContext *s = avctx->priv_data;
255     SFrameBSInfo fbi = { 0 };
256     int i, ret;
257     int encoded;
258     SSourcePicture sp = { 0 };
259     int size = 0, layer, first_layer = 0;
260     int layer_size[MAX_LAYER_NUM_OF_FRAME] = { 0 };
261
262     sp.iColorFormat = videoFormatI420;
263     for (i = 0; i < 3; i++) {
264         sp.iStride[i] = frame->linesize[i];
265         sp.pData[i]   = frame->data[i];
266     }
267     sp.iPicWidth  = avctx->width;
268     sp.iPicHeight = avctx->height;
269
270     encoded = (*s->encoder)->EncodeFrame(s->encoder, &sp, &fbi);
271     if (encoded != cmResultSuccess) {
272         av_log(avctx, AV_LOG_ERROR, "EncodeFrame failed\n");
273         return AVERROR_UNKNOWN;
274     }
275     if (fbi.eFrameType == videoFrameTypeSkip) {
276         s->skipped++;
277         av_log(avctx, AV_LOG_DEBUG, "frame skipped\n");
278         return 0;
279     }
280     first_layer = 0;
281     // Normal frames are returned with one single layer, while IDR
282     // frames have two layers, where the first layer contains the SPS/PPS.
283     // If using global headers, don't include the SPS/PPS in the returned
284     // packet - thus, only return one layer.
285     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)
286         first_layer = fbi.iLayerNum - 1;
287
288     for (layer = first_layer; layer < fbi.iLayerNum; layer++) {
289         for (i = 0; i < fbi.sLayerInfo[layer].iNalCount; i++)
290             layer_size[layer] += fbi.sLayerInfo[layer].pNalLengthInByte[i];
291         size += layer_size[layer];
292     }
293     av_log(avctx, AV_LOG_DEBUG, "%d slices\n", fbi.sLayerInfo[fbi.iLayerNum - 1].iNalCount);
294
295     if ((ret = ff_alloc_packet(avpkt, size))) {
296         av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
297         return ret;
298     }
299     size = 0;
300     for (layer = first_layer; layer < fbi.iLayerNum; layer++) {
301         memcpy(avpkt->data + size, fbi.sLayerInfo[layer].pBsBuf, layer_size[layer]);
302         size += layer_size[layer];
303     }
304     avpkt->pts = frame->pts;
305     if (fbi.eFrameType == videoFrameTypeIDR)
306         avpkt->flags |= AV_PKT_FLAG_KEY;
307     *got_packet = 1;
308     return 0;
309 }
310
311 AVCodec ff_libopenh264_encoder = {
312     .name           = "libopenh264",
313     .long_name      = NULL_IF_CONFIG_SMALL("OpenH264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
314     .type           = AVMEDIA_TYPE_VIDEO,
315     .id             = AV_CODEC_ID_H264,
316     .priv_data_size = sizeof(SVCContext),
317     .init           = svc_encode_init,
318     .encode2        = svc_encode_frame,
319     .close          = svc_encode_close,
320     .capabilities   = AV_CODEC_CAP_AUTO_THREADS,
321     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P,
322                                                     AV_PIX_FMT_NONE },
323     .priv_class     = &class,
324 };