You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

325 lines
14KB

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