]> git.sesse.net Git - ffmpeg/blob - libavcodec/libopenh264enc.c
Merge commit '1b709f23fb5f505c834d4c855703225795def01d'
[ffmpeg] / libavcodec / libopenh264enc.c
1 /*
2  * OpenH264 video encoder
3  * Copyright (C) 2014 Martin Storsjo
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 } SVCContext;
41
42 #define OPENH264_VER_AT_LEAST(maj, min) \
43     ((OPENH264_MAJOR  > (maj)) || \
44      (OPENH264_MAJOR == (maj) && OPENH264_MINOR >= (min)))
45
46 #define OFFSET(x) offsetof(SVCContext, x)
47 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
48 static const AVOption options[] = {
49     { "slice_mode", "set slice mode", OFFSET(slice_mode), AV_OPT_TYPE_INT, { .i64 = SM_AUTO_SLICE }, SM_SINGLE_SLICE, SM_RESERVED, VE, "slice_mode" },
50         { "fixed", "a fixed number of slices", 0, AV_OPT_TYPE_CONST, { .i64 = SM_FIXEDSLCNUM_SLICE }, 0, 0, VE, "slice_mode" },
51         { "rowmb", "one slice per row of macroblocks", 0, AV_OPT_TYPE_CONST, { .i64 = SM_ROWMB_SLICE }, 0, 0, VE, "slice_mode" },
52         { "auto", "automatic number of slices according to number of threads", 0, AV_OPT_TYPE_CONST, { .i64 = SM_AUTO_SLICE }, 0, 0, VE, "slice_mode" },
53     { "loopfilter", "enable loop filter", OFFSET(loopfilter), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, VE },
54     { "profile", "set profile restrictions", OFFSET(profile), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
55     { NULL }
56 };
57
58 static const AVClass class = {
59     "libopenh264enc", av_default_item_name, options, LIBAVUTIL_VERSION_INT
60 };
61
62 // Convert ffmpeg log level to equivalent libopenh264 log level.  Given the
63 // conversions below, you must set the ffmpeg log level to something greater
64 // than AV_LOG_DEBUG if you want to see WELS_LOG_DETAIL messages.
65 static int ffmpeg_to_libopenh264_log_level  (
66     int ffmpeg_log_level
67     )
68 {
69     if      (ffmpeg_log_level >  AV_LOG_DEBUG)   return WELS_LOG_DETAIL;
70     else if (ffmpeg_log_level >= AV_LOG_DEBUG)   return WELS_LOG_DEBUG;
71     else if (ffmpeg_log_level >= AV_LOG_INFO)    return WELS_LOG_INFO;
72     else if (ffmpeg_log_level >= AV_LOG_WARNING) return WELS_LOG_WARNING;
73     else if (ffmpeg_log_level >= AV_LOG_ERROR)   return WELS_LOG_ERROR;
74     else                                         return WELS_LOG_QUIET;
75 }
76
77 // Convert libopenh264 log level to equivalent ffmpeg log level.
78 static int libopenh264_to_ffmpeg_log_level  (
79     int libopenh264_log_level
80     )
81 {
82     if      (libopenh264_log_level >= WELS_LOG_DETAIL)  return AV_LOG_TRACE;
83     else if (libopenh264_log_level >= WELS_LOG_DEBUG)   return AV_LOG_DEBUG;
84     else if (libopenh264_log_level >= WELS_LOG_INFO)    return AV_LOG_INFO;
85     else if (libopenh264_log_level >= WELS_LOG_WARNING) return AV_LOG_WARNING;
86     else if (libopenh264_log_level >= WELS_LOG_ERROR)   return AV_LOG_ERROR;
87     else                                                return AV_LOG_QUIET;
88 }
89
90 // This function will be provided to the libopenh264 library.  The function will be called
91 // when libopenh264 wants to log a message (error, warning, info, etc.).  The signature for
92 // this function (defined in .../codec/api/svc/codec_api.h) is:
93 //
94 //        typedef void (*WelsTraceCallback) (void* ctx, int level, const char* string);
95
96 static void libopenh264_trace_callback  (
97     void *          ctx,
98     int             level,
99     char const *    msg
100     )
101 {
102     // The message will be logged only if the requested EQUIVALENT ffmpeg log level is
103     // less than or equal to the current ffmpeg log level.  Note, however, that before
104     // this function is called, welsCodecTrace::CodecTrace() will have already discarded
105     // the message (and this function will not be called) if the requested libopenh264
106     // log level "level" is greater than the current libopenh264 log level.
107     int equiv_ffmpeg_log_level = libopenh264_to_ffmpeg_log_level(level);
108     if (equiv_ffmpeg_log_level <= av_log_get_level())
109         av_log(ctx, equiv_ffmpeg_log_level, "%s\n", msg);
110 }
111
112 static av_cold int svc_encode_close(AVCodecContext *avctx)
113 {
114     SVCContext *s = avctx->priv_data;
115
116     if (s->encoder)
117         WelsDestroySVCEncoder(s->encoder);
118     return 0;
119 }
120
121 static av_cold int svc_encode_init(AVCodecContext *avctx)
122 {
123     SVCContext *s = avctx->priv_data;
124     SEncParamExt param = { 0 };
125     int err = AVERROR_UNKNOWN;
126     int equiv_libopenh264_log_level;
127     WelsTraceCallback callback_function;
128
129     // Mingw GCC < 4.7 on x86_32 uses an incorrect/buggy ABI for the WelsGetCodecVersion
130     // function (for functions returning larger structs), thus skip the check in those
131     // configurations.
132 #if !defined(_WIN32) || !defined(__GNUC__) || !ARCH_X86_32 || AV_GCC_VERSION_AT_LEAST(4, 7)
133     OpenH264Version libver = WelsGetCodecVersion();
134     if (memcmp(&libver, &g_stCodecVersion, sizeof(libver))) {
135         av_log(avctx, AV_LOG_ERROR, "Incorrect library version loaded\n");
136         return AVERROR(EINVAL);
137     }
138 #endif
139
140     if (WelsCreateSVCEncoder(&s->encoder)) {
141         av_log(avctx, AV_LOG_ERROR, "Unable to create encoder\n");
142         return AVERROR_UNKNOWN;
143     }
144
145     // Set libopenh264 message logging level for this instance of the encoder using
146     // the current ffmpeg log level converted to the equivalent libopenh264 level.
147     //
148     // The client should have the ffmpeg level set to the desired value before creating
149     // the libopenh264 encoder.  Once the encoder has been created, the libopenh264
150     // log level is fixed for that encoder.  Changing the ffmpeg log level to a LOWER
151     // value, in the expectation that higher level libopenh264 messages will no longer
152     // be logged, WILL have the expected effect.  However, changing the ffmpeg log level
153     // to a HIGHER value, in the expectation that higher level libopenh264 messages will
154     // now be logged, WILL NOT have the expected effect.  This is because the higher
155     // level messages will be discarded by the libopenh264 logging system before our
156     // message logging callback function can be invoked.
157     equiv_libopenh264_log_level = ffmpeg_to_libopenh264_log_level(av_log_get_level());
158     (*s->encoder)->SetOption(s->encoder,ENCODER_OPTION_TRACE_LEVEL,&equiv_libopenh264_log_level);
159
160     // Set the logging callback function to one that uses av_log() (see implementation above).
161     callback_function = (WelsTraceCallback) libopenh264_trace_callback;
162     (*s->encoder)->SetOption(s->encoder,ENCODER_OPTION_TRACE_CALLBACK,(void *)&callback_function);
163
164     // Set the AVCodecContext as the libopenh264 callback context so that it can be passed to av_log().
165     (*s->encoder)->SetOption(s->encoder,ENCODER_OPTION_TRACE_CALLBACK_CONTEXT,(void *)&avctx);
166
167     (*s->encoder)->GetDefaultParams(s->encoder, &param);
168
169     param.fMaxFrameRate              = 1/av_q2d(avctx->time_base);
170     param.iPicWidth                  = avctx->width;
171     param.iPicHeight                 = avctx->height;
172     param.iTargetBitrate             = avctx->bit_rate;
173     param.iMaxBitrate                = FFMAX(avctx->rc_max_rate, avctx->bit_rate);
174     param.iRCMode                    = RC_QUALITY_MODE;
175     param.iTemporalLayerNum          = 1;
176     param.iSpatialLayerNum           = 1;
177     param.bEnableDenoise             = 0;
178     param.bEnableBackgroundDetection = 1;
179     param.bEnableAdaptiveQuant       = 1;
180     param.bEnableFrameSkip           = 0;
181     param.bEnableLongTermReference   = 0;
182     param.iLtrMarkPeriod             = 30;
183     param.uiIntraPeriod              = avctx->gop_size;
184 #if OPENH264_VER_AT_LEAST(1, 4)
185     param.eSpsPpsIdStrategy          = CONSTANT_ID;
186 #else
187     param.bEnableSpsPpsIdAddition    = 0;
188 #endif
189     param.bPrefixNalAddingCtrl       = 0;
190     param.iLoopFilterDisableIdc      = !s->loopfilter;
191     param.iEntropyCodingModeFlag     = 0;
192     param.iMultipleThreadIdc         = avctx->thread_count;
193     if (s->profile && !strcmp(s->profile, "main"))
194         param.iEntropyCodingModeFlag = 1;
195     else if (!s->profile && avctx->coder_type == FF_CODER_TYPE_AC)
196         param.iEntropyCodingModeFlag = 1;
197
198     param.sSpatialLayers[0].iVideoWidth         = param.iPicWidth;
199     param.sSpatialLayers[0].iVideoHeight        = param.iPicHeight;
200     param.sSpatialLayers[0].fFrameRate          = param.fMaxFrameRate;
201     param.sSpatialLayers[0].iSpatialBitrate     = param.iTargetBitrate;
202     param.sSpatialLayers[0].iMaxSpatialBitrate  = param.iMaxBitrate;
203
204     if (avctx->slices > 1)
205         s->slice_mode = SM_FIXEDSLCNUM_SLICE;
206     param.sSpatialLayers[0].sSliceCfg.uiSliceMode               = s->slice_mode;
207     param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceNum = avctx->slices;
208
209     if ((*s->encoder)->InitializeExt(s->encoder, &param) != cmResultSuccess) {
210         av_log(avctx, AV_LOG_ERROR, "Initialize failed\n");
211         goto fail;
212     }
213
214     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
215         SFrameBSInfo fbi = { 0 };
216         int i, size = 0;
217         (*s->encoder)->EncodeParameterSets(s->encoder, &fbi);
218         for (i = 0; i < fbi.sLayerInfo[0].iNalCount; i++)
219             size += fbi.sLayerInfo[0].pNalLengthInByte[i];
220         avctx->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
221         if (!avctx->extradata) {
222             err = AVERROR(ENOMEM);
223             goto fail;
224         }
225         avctx->extradata_size = size;
226         memcpy(avctx->extradata, fbi.sLayerInfo[0].pBsBuf, size);
227     }
228
229     return 0;
230
231 fail:
232     svc_encode_close(avctx);
233     return err;
234 }
235
236 static int svc_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
237                             const AVFrame *frame, int *got_packet)
238 {
239     SVCContext *s = avctx->priv_data;
240     SFrameBSInfo fbi = { 0 };
241     int i, ret;
242     int encoded;
243     SSourcePicture sp = { 0 };
244     int size = 0, layer, first_layer = 0;
245     int layer_size[MAX_LAYER_NUM_OF_FRAME] = { 0 };
246
247     sp.iColorFormat = videoFormatI420;
248     for (i = 0; i < 3; i++) {
249         sp.iStride[i] = frame->linesize[i];
250         sp.pData[i]   = frame->data[i];
251     }
252     sp.iPicWidth  = avctx->width;
253     sp.iPicHeight = avctx->height;
254
255     encoded = (*s->encoder)->EncodeFrame(s->encoder, &sp, &fbi);
256     if (encoded != cmResultSuccess) {
257         av_log(avctx, AV_LOG_ERROR, "EncodeFrame failed\n");
258         return AVERROR_UNKNOWN;
259     }
260     if (fbi.eFrameType == videoFrameTypeSkip) {
261         av_log(avctx, AV_LOG_DEBUG, "frame skipped\n");
262         return 0;
263     }
264     first_layer = 0;
265     // Normal frames are returned with one single layer, while IDR
266     // frames have two layers, where the first layer contains the SPS/PPS.
267     // If using global headers, don't include the SPS/PPS in the returned
268     // packet - thus, only return one layer.
269     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)
270         first_layer = fbi.iLayerNum - 1;
271
272     for (layer = first_layer; layer < fbi.iLayerNum; layer++) {
273         for (i = 0; i < fbi.sLayerInfo[layer].iNalCount; i++)
274             layer_size[layer] += fbi.sLayerInfo[layer].pNalLengthInByte[i];
275         size += layer_size[layer];
276     }
277     av_log(avctx, AV_LOG_DEBUG, "%d slices\n", fbi.sLayerInfo[fbi.iLayerNum - 1].iNalCount);
278
279     if ((ret = ff_alloc_packet2(avctx, avpkt, size, size))) {
280         av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
281         return ret;
282     }
283     size = 0;
284     for (layer = first_layer; layer < fbi.iLayerNum; layer++) {
285         memcpy(avpkt->data + size, fbi.sLayerInfo[layer].pBsBuf, layer_size[layer]);
286         size += layer_size[layer];
287     }
288     avpkt->pts = frame->pts;
289     if (fbi.eFrameType == videoFrameTypeIDR)
290         avpkt->flags |= AV_PKT_FLAG_KEY;
291     *got_packet = 1;
292     return 0;
293 }
294
295 AVCodec ff_libopenh264_encoder = {
296     .name           = "libopenh264",
297     .long_name      = NULL_IF_CONFIG_SMALL("OpenH264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
298     .type           = AVMEDIA_TYPE_VIDEO,
299     .id             = AV_CODEC_ID_H264,
300     .priv_data_size = sizeof(SVCContext),
301     .init           = svc_encode_init,
302     .encode2        = svc_encode_frame,
303     .close          = svc_encode_close,
304     .capabilities   = AV_CODEC_CAP_AUTO_THREADS,
305     .pix_fmts       = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P,
306                                                     AV_PIX_FMT_NONE },
307     .priv_class     = &class,
308 };