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.

379 lines
15KB

  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/internal.h"
  27. #include "libavutil/intreadwrite.h"
  28. #include "libavutil/mathematics.h"
  29. #include "avcodec.h"
  30. #include "internal.h"
  31. #include "libopenh264.h"
  32. #if !OPENH264_VER_AT_LEAST(1, 6)
  33. #define SM_SIZELIMITED_SLICE SM_DYN_SLICE
  34. #endif
  35. #define TARGET_BITRATE_DEFAULT 2*1000*1000
  36. typedef struct SVCContext {
  37. const AVClass *av_class;
  38. ISVCEncoder *encoder;
  39. int slice_mode;
  40. int loopfilter;
  41. char *profile;
  42. int max_nal_size;
  43. int skip_frames;
  44. int skipped;
  45. int cabac;
  46. // rate control mode
  47. int rc_mode;
  48. } SVCContext;
  49. #define OFFSET(x) offsetof(SVCContext, x)
  50. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  51. static const AVOption options[] = {
  52. #if OPENH264_VER_AT_LEAST(1, 6)
  53. { "slice_mode", "set slice mode", OFFSET(slice_mode), AV_OPT_TYPE_INT, { .i64 = SM_FIXEDSLCNUM_SLICE }, SM_SINGLE_SLICE, SM_RESERVED, VE, "slice_mode" },
  54. #else
  55. { "slice_mode", "set slice mode", OFFSET(slice_mode), AV_OPT_TYPE_INT, { .i64 = SM_AUTO_SLICE }, SM_SINGLE_SLICE, SM_RESERVED, VE, "slice_mode" },
  56. #endif
  57. { "fixed", "a fixed number of slices", 0, AV_OPT_TYPE_CONST, { .i64 = SM_FIXEDSLCNUM_SLICE }, 0, 0, VE, "slice_mode" },
  58. #if OPENH264_VER_AT_LEAST(1, 6)
  59. { "dyn", "Size limited (compatibility name)", 0, AV_OPT_TYPE_CONST, { .i64 = SM_SIZELIMITED_SLICE }, 0, 0, VE, "slice_mode" },
  60. { "sizelimited", "Size limited", 0, AV_OPT_TYPE_CONST, { .i64 = SM_SIZELIMITED_SLICE }, 0, 0, VE, "slice_mode" },
  61. #else
  62. { "rowmb", "one slice per row of macroblocks", 0, AV_OPT_TYPE_CONST, { .i64 = SM_ROWMB_SLICE }, 0, 0, VE, "slice_mode" },
  63. { "auto", "automatic number of slices according to number of threads", 0, AV_OPT_TYPE_CONST, { .i64 = SM_AUTO_SLICE }, 0, 0, VE, "slice_mode" },
  64. { "dyn", "Dynamic slicing", 0, AV_OPT_TYPE_CONST, { .i64 = SM_DYN_SLICE }, 0, 0, VE, "slice_mode" },
  65. #endif
  66. { "loopfilter", "enable loop filter", OFFSET(loopfilter), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, VE },
  67. { "profile", "set profile restrictions", OFFSET(profile), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
  68. { "max_nal_size", "set maximum NAL size in bytes", OFFSET(max_nal_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
  69. { "allow_skip_frames", "allow skipping frames to hit the target bitrate", OFFSET(skip_frames), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
  70. { "cabac", "Enable cabac", OFFSET(cabac), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
  71. { "rc_mode", "Select rate control mode", OFFSET(rc_mode), AV_OPT_TYPE_INT, { .i64 = RC_QUALITY_MODE }, RC_OFF_MODE, RC_TIMESTAMP_MODE, VE, "rc_mode" },
  72. { "off", "bit rate control off", 0, AV_OPT_TYPE_CONST, { .i64 = RC_OFF_MODE }, 0, 0, VE, "rc_mode" },
  73. { "quality", "quality mode", 0, AV_OPT_TYPE_CONST, { .i64 = RC_QUALITY_MODE }, 0, 0, VE, "rc_mode" },
  74. { "bitrate", "bitrate mode", 0, AV_OPT_TYPE_CONST, { .i64 = RC_BITRATE_MODE }, 0, 0, VE, "rc_mode" },
  75. { "buffer", "using buffer status to adjust the video quality (no bitrate control)", 0, AV_OPT_TYPE_CONST, { .i64 = RC_BUFFERBASED_MODE }, 0, 0, VE, "rc_mode" },
  76. #if OPENH264_VER_AT_LEAST(1, 4)
  77. { "timestamp", "bit rate control based on timestamp", 0, AV_OPT_TYPE_CONST, { .i64 = RC_TIMESTAMP_MODE }, 0, 0, VE, "rc_mode" },
  78. #endif
  79. { NULL }
  80. };
  81. static const AVClass class = {
  82. .class_name = "libopenh264enc",
  83. .item_name = av_default_item_name,
  84. .option = options,
  85. .version = LIBAVUTIL_VERSION_INT,
  86. };
  87. static av_cold int svc_encode_close(AVCodecContext *avctx)
  88. {
  89. SVCContext *s = avctx->priv_data;
  90. if (s->encoder)
  91. WelsDestroySVCEncoder(s->encoder);
  92. if (s->skipped > 0)
  93. av_log(avctx, AV_LOG_WARNING, "%d frames skipped\n", s->skipped);
  94. return 0;
  95. }
  96. static av_cold int svc_encode_init(AVCodecContext *avctx)
  97. {
  98. SVCContext *s = avctx->priv_data;
  99. SEncParamExt param = { 0 };
  100. int err;
  101. int log_level;
  102. WelsTraceCallback callback_function;
  103. AVCPBProperties *props;
  104. if ((err = ff_libopenh264_check_version(avctx)) < 0)
  105. return err;
  106. if (WelsCreateSVCEncoder(&s->encoder)) {
  107. av_log(avctx, AV_LOG_ERROR, "Unable to create encoder\n");
  108. return AVERROR_UNKNOWN;
  109. }
  110. // Pass all libopenh264 messages to our callback, to allow ourselves to filter them.
  111. log_level = WELS_LOG_DETAIL;
  112. (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_LEVEL, &log_level);
  113. // Set the logging callback function to one that uses av_log() (see implementation above).
  114. callback_function = (WelsTraceCallback) ff_libopenh264_trace_callback;
  115. (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_CALLBACK, &callback_function);
  116. // Set the AVCodecContext as the libopenh264 callback context so that it can be passed to av_log().
  117. (*s->encoder)->SetOption(s->encoder, ENCODER_OPTION_TRACE_CALLBACK_CONTEXT, &avctx);
  118. (*s->encoder)->GetDefaultParams(s->encoder, &param);
  119. #if FF_API_CODER_TYPE
  120. FF_DISABLE_DEPRECATION_WARNINGS
  121. if (!s->cabac)
  122. s->cabac = avctx->coder_type == FF_CODER_TYPE_AC;
  123. FF_ENABLE_DEPRECATION_WARNINGS
  124. #endif
  125. param.fMaxFrameRate = 1/av_q2d(avctx->time_base);
  126. param.iPicWidth = avctx->width;
  127. param.iPicHeight = avctx->height;
  128. param.iTargetBitrate = avctx->bit_rate > 0 ? avctx->bit_rate : TARGET_BITRATE_DEFAULT;
  129. param.iMaxBitrate = FFMAX(avctx->rc_max_rate, avctx->bit_rate);
  130. param.iRCMode = s->rc_mode;
  131. if (avctx->qmax >= 0)
  132. param.iMaxQp = av_clip(avctx->qmax, 1, 51);
  133. if (avctx->qmin >= 0)
  134. param.iMinQp = av_clip(avctx->qmin, 1, param.iMaxQp);
  135. param.iTemporalLayerNum = 1;
  136. param.iSpatialLayerNum = 1;
  137. param.bEnableDenoise = 0;
  138. param.bEnableBackgroundDetection = 1;
  139. param.bEnableAdaptiveQuant = 1;
  140. param.bEnableFrameSkip = s->skip_frames;
  141. param.bEnableLongTermReference = 0;
  142. param.iLtrMarkPeriod = 30;
  143. if (avctx->gop_size >= 0)
  144. param.uiIntraPeriod = avctx->gop_size;
  145. #if OPENH264_VER_AT_LEAST(1, 4)
  146. param.eSpsPpsIdStrategy = CONSTANT_ID;
  147. #else
  148. param.bEnableSpsPpsIdAddition = 0;
  149. #endif
  150. param.bPrefixNalAddingCtrl = 0;
  151. param.iLoopFilterDisableIdc = !s->loopfilter;
  152. param.iEntropyCodingModeFlag = 0;
  153. param.iMultipleThreadIdc = avctx->thread_count;
  154. if (s->profile && !strcmp(s->profile, "main"))
  155. param.iEntropyCodingModeFlag = 1;
  156. else if (!s->profile && s->cabac)
  157. param.iEntropyCodingModeFlag = 1;
  158. param.sSpatialLayers[0].iVideoWidth = param.iPicWidth;
  159. param.sSpatialLayers[0].iVideoHeight = param.iPicHeight;
  160. param.sSpatialLayers[0].fFrameRate = param.fMaxFrameRate;
  161. param.sSpatialLayers[0].iSpatialBitrate = param.iTargetBitrate;
  162. param.sSpatialLayers[0].iMaxSpatialBitrate = param.iMaxBitrate;
  163. #if OPENH264_VER_AT_LEAST(1, 7)
  164. if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den) {
  165. // Table E-1.
  166. static const AVRational sar_idc[] = {
  167. { 0, 0 }, // Unspecified (never written here).
  168. { 1, 1 }, { 12, 11 }, { 10, 11 }, { 16, 11 },
  169. { 40, 33 }, { 24, 11 }, { 20, 11 }, { 32, 11 },
  170. { 80, 33 }, { 18, 11 }, { 15, 11 }, { 64, 33 },
  171. { 160, 99 }, // Last 3 are unknown to openh264: { 4, 3 }, { 3, 2 }, { 2, 1 },
  172. };
  173. static const ESampleAspectRatio asp_idc[] = {
  174. ASP_UNSPECIFIED,
  175. ASP_1x1, ASP_12x11, ASP_10x11, ASP_16x11,
  176. ASP_40x33, ASP_24x11, ASP_20x11, ASP_32x11,
  177. ASP_80x33, ASP_18x11, ASP_15x11, ASP_64x33,
  178. ASP_160x99,
  179. };
  180. int num, den, i;
  181. av_reduce(&num, &den, avctx->sample_aspect_ratio.num,
  182. avctx->sample_aspect_ratio.den, 65535);
  183. for (i = 1; i < FF_ARRAY_ELEMS(sar_idc); i++) {
  184. if (num == sar_idc[i].num &&
  185. den == sar_idc[i].den)
  186. break;
  187. }
  188. if (i == FF_ARRAY_ELEMS(sar_idc)) {
  189. param.sSpatialLayers[0].eAspectRatio = ASP_EXT_SAR;
  190. param.sSpatialLayers[0].sAspectRatioExtWidth = num;
  191. param.sSpatialLayers[0].sAspectRatioExtHeight = den;
  192. } else {
  193. param.sSpatialLayers[0].eAspectRatio = asp_idc[i];
  194. }
  195. param.sSpatialLayers[0].bAspectRatioPresent = true;
  196. } else {
  197. param.sSpatialLayers[0].bAspectRatioPresent = false;
  198. }
  199. #endif
  200. if ((avctx->slices > 1) && (s->max_nal_size)) {
  201. av_log(avctx, AV_LOG_ERROR,
  202. "Invalid combination -slices %d and -max_nal_size %d.\n",
  203. avctx->slices, s->max_nal_size);
  204. return AVERROR(EINVAL);
  205. }
  206. if (avctx->slices > 1)
  207. s->slice_mode = SM_FIXEDSLCNUM_SLICE;
  208. if (s->max_nal_size)
  209. s->slice_mode = SM_SIZELIMITED_SLICE;
  210. #if OPENH264_VER_AT_LEAST(1, 6)
  211. param.sSpatialLayers[0].sSliceArgument.uiSliceMode = s->slice_mode;
  212. param.sSpatialLayers[0].sSliceArgument.uiSliceNum = avctx->slices;
  213. #else
  214. param.sSpatialLayers[0].sSliceCfg.uiSliceMode = s->slice_mode;
  215. param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceNum = avctx->slices;
  216. #endif
  217. if (s->slice_mode == SM_SIZELIMITED_SLICE) {
  218. if (s->max_nal_size) {
  219. param.uiMaxNalSize = s->max_nal_size;
  220. #if OPENH264_VER_AT_LEAST(1, 6)
  221. param.sSpatialLayers[0].sSliceArgument.uiSliceSizeConstraint = s->max_nal_size;
  222. #else
  223. param.sSpatialLayers[0].sSliceCfg.sSliceArgument.uiSliceSizeConstraint = s->max_nal_size;
  224. #endif
  225. } else {
  226. av_log(avctx, AV_LOG_ERROR, "Invalid -max_nal_size, "
  227. "specify a valid max_nal_size to use -slice_mode dyn\n");
  228. return AVERROR(EINVAL);
  229. }
  230. }
  231. if ((*s->encoder)->InitializeExt(s->encoder, &param) != cmResultSuccess) {
  232. av_log(avctx, AV_LOG_ERROR, "Initialize failed\n");
  233. return AVERROR_UNKNOWN;
  234. }
  235. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  236. SFrameBSInfo fbi = { 0 };
  237. int i, size = 0;
  238. (*s->encoder)->EncodeParameterSets(s->encoder, &fbi);
  239. for (i = 0; i < fbi.sLayerInfo[0].iNalCount; i++)
  240. size += fbi.sLayerInfo[0].pNalLengthInByte[i];
  241. avctx->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
  242. if (!avctx->extradata)
  243. return AVERROR(ENOMEM);
  244. avctx->extradata_size = size;
  245. memcpy(avctx->extradata, fbi.sLayerInfo[0].pBsBuf, size);
  246. }
  247. props = ff_add_cpb_side_data(avctx);
  248. if (!props)
  249. return AVERROR(ENOMEM);
  250. props->max_bitrate = param.iMaxBitrate;
  251. props->avg_bitrate = param.iTargetBitrate;
  252. return 0;
  253. }
  254. static int svc_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  255. const AVFrame *frame, int *got_packet)
  256. {
  257. SVCContext *s = avctx->priv_data;
  258. SFrameBSInfo fbi = { 0 };
  259. int i, ret;
  260. int encoded;
  261. SSourcePicture sp = { 0 };
  262. int size = 0, layer, first_layer = 0;
  263. int layer_size[MAX_LAYER_NUM_OF_FRAME] = { 0 };
  264. sp.iColorFormat = videoFormatI420;
  265. for (i = 0; i < 3; i++) {
  266. sp.iStride[i] = frame->linesize[i];
  267. sp.pData[i] = frame->data[i];
  268. }
  269. sp.iPicWidth = avctx->width;
  270. sp.iPicHeight = avctx->height;
  271. if (frame->pict_type == AV_PICTURE_TYPE_I) {
  272. (*s->encoder)->ForceIntraFrame(s->encoder, true);
  273. }
  274. encoded = (*s->encoder)->EncodeFrame(s->encoder, &sp, &fbi);
  275. if (encoded != cmResultSuccess) {
  276. av_log(avctx, AV_LOG_ERROR, "EncodeFrame failed\n");
  277. return AVERROR_UNKNOWN;
  278. }
  279. if (fbi.eFrameType == videoFrameTypeSkip) {
  280. s->skipped++;
  281. av_log(avctx, AV_LOG_DEBUG, "frame skipped\n");
  282. return 0;
  283. }
  284. first_layer = 0;
  285. // Normal frames are returned with one single layer, while IDR
  286. // frames have two layers, where the first layer contains the SPS/PPS.
  287. // If using global headers, don't include the SPS/PPS in the returned
  288. // packet - thus, only return one layer.
  289. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)
  290. first_layer = fbi.iLayerNum - 1;
  291. for (layer = first_layer; layer < fbi.iLayerNum; layer++) {
  292. for (i = 0; i < fbi.sLayerInfo[layer].iNalCount; i++)
  293. layer_size[layer] += fbi.sLayerInfo[layer].pNalLengthInByte[i];
  294. size += layer_size[layer];
  295. }
  296. av_log(avctx, AV_LOG_DEBUG, "%d slices\n", fbi.sLayerInfo[fbi.iLayerNum - 1].iNalCount);
  297. if ((ret = ff_alloc_packet2(avctx, avpkt, size, size))) {
  298. av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
  299. return ret;
  300. }
  301. size = 0;
  302. for (layer = first_layer; layer < fbi.iLayerNum; layer++) {
  303. memcpy(avpkt->data + size, fbi.sLayerInfo[layer].pBsBuf, layer_size[layer]);
  304. size += layer_size[layer];
  305. }
  306. avpkt->pts = frame->pts;
  307. if (fbi.eFrameType == videoFrameTypeIDR)
  308. avpkt->flags |= AV_PKT_FLAG_KEY;
  309. *got_packet = 1;
  310. return 0;
  311. }
  312. static const AVCodecDefault svc_enc_defaults[] = {
  313. { "b", "0" },
  314. { "g", "-1" },
  315. { "qmin", "-1" },
  316. { "qmax", "-1" },
  317. { NULL },
  318. };
  319. AVCodec ff_libopenh264_encoder = {
  320. .name = "libopenh264",
  321. .long_name = NULL_IF_CONFIG_SMALL("OpenH264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),
  322. .type = AVMEDIA_TYPE_VIDEO,
  323. .id = AV_CODEC_ID_H264,
  324. .priv_data_size = sizeof(SVCContext),
  325. .init = svc_encode_init,
  326. .encode2 = svc_encode_frame,
  327. .close = svc_encode_close,
  328. .capabilities = AV_CODEC_CAP_AUTO_THREADS,
  329. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE | FF_CODEC_CAP_INIT_CLEANUP,
  330. .pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P,
  331. AV_PIX_FMT_NONE },
  332. .defaults = svc_enc_defaults,
  333. .priv_class = &class,
  334. .wrapper_name = "libopenh264",
  335. };