obs-ffmpeg-nvenc.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /******************************************************************************
  2. Copyright (C) 2016 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <util/darray.h>
  15. #include <util/dstr.h>
  16. #include <util/base.h>
  17. #include <media-io/video-io.h>
  18. #include <obs-module.h>
  19. #include <obs-avc.h>
  20. #include <libavutil/opt.h>
  21. #include <libavutil/pixdesc.h>
  22. #include <libavformat/avformat.h>
  23. #include "obs-ffmpeg-formats.h"
  24. #define do_log(level, format, ...) \
  25. blog(level, "[NVENC encoder: '%s'] " format, \
  26. obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
  27. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  28. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  29. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  30. struct nvenc_encoder {
  31. obs_encoder_t *encoder;
  32. AVCodec *nvenc;
  33. AVCodecContext *context;
  34. AVFrame *vframe;
  35. DARRAY(uint8_t) buffer;
  36. uint8_t *header;
  37. size_t header_size;
  38. uint8_t *sei;
  39. size_t sei_size;
  40. int height;
  41. bool first_packet;
  42. bool initialized;
  43. };
  44. static const char *nvenc_getname(void *unused)
  45. {
  46. UNUSED_PARAMETER(unused);
  47. return "NVIDIA NVENC H.264";
  48. }
  49. static inline bool valid_format(enum video_format format)
  50. {
  51. return format == VIDEO_FORMAT_I420 ||
  52. format == VIDEO_FORMAT_NV12 ||
  53. format == VIDEO_FORMAT_I444;
  54. }
  55. static void nvenc_video_info(void *data, struct video_scale_info *info)
  56. {
  57. struct nvenc_encoder *enc = data;
  58. enum video_format pref_format;
  59. pref_format = obs_encoder_get_preferred_video_format(enc->encoder);
  60. if (!valid_format(pref_format)) {
  61. pref_format = valid_format(info->format) ?
  62. info->format : VIDEO_FORMAT_NV12;
  63. }
  64. info->format = pref_format;
  65. }
  66. static bool nvenc_init_codec(struct nvenc_encoder *enc)
  67. {
  68. int ret;
  69. ret = avcodec_open2(enc->context, enc->nvenc, NULL);
  70. if (ret < 0) {
  71. warn("Failed to open NVENC codec: %s", av_err2str(ret));
  72. return false;
  73. }
  74. enc->vframe = av_frame_alloc();
  75. if (!enc->vframe) {
  76. warn("Failed to allocate video frame");
  77. return false;
  78. }
  79. enc->vframe->format = enc->context->pix_fmt;
  80. enc->vframe->width = enc->context->width;
  81. enc->vframe->height = enc->context->height;
  82. enc->vframe->colorspace = enc->context->colorspace;
  83. enc->vframe->color_range = enc->context->color_range;
  84. ret = av_frame_get_buffer(enc->vframe, base_get_alignment());
  85. if (ret < 0) {
  86. warn("Failed to allocate vframe: %s", av_err2str(ret));
  87. return false;
  88. }
  89. enc->initialized = true;
  90. return true;
  91. }
  92. enum RC_MODE {
  93. RC_MODE_CBR,
  94. RC_MODE_VBR,
  95. RC_MODE_CQP,
  96. RC_MODE_LOSSLESS
  97. };
  98. static bool nvenc_update(void *data, obs_data_t *settings)
  99. {
  100. struct nvenc_encoder *enc = data;
  101. const char *rc = obs_data_get_string(settings, "rate_control");
  102. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  103. int cqp = (int)obs_data_get_int(settings, "cqp");
  104. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  105. const char *preset = obs_data_get_string(settings, "preset");
  106. const char *profile = obs_data_get_string(settings, "profile");
  107. int gpu = (int)obs_data_get_int(settings, "gpu");
  108. bool cbr_override = obs_data_get_bool(settings, "cbr");
  109. int bf = (int)obs_data_get_int(settings, "bf");
  110. video_t *video = obs_encoder_video(enc->encoder);
  111. const struct video_output_info *voi = video_output_get_info(video);
  112. struct video_scale_info info;
  113. /* XXX: "cbr" setting has been deprecated */
  114. if (cbr_override) {
  115. warn("\"cbr\" setting has been deprecated for all encoders! "
  116. "Please set \"rate_control\" to \"CBR\" instead. "
  117. "Forcing CBR mode. "
  118. "(Note to all: this is why you shouldn't use strings for "
  119. "common settings)");
  120. rc = "CBR";
  121. }
  122. info.format = voi->format;
  123. info.colorspace = voi->colorspace;
  124. info.range = voi->range;
  125. bool twopass = false;
  126. if (astrcmpi(preset, "mq") == 0) {
  127. twopass = true;
  128. preset = "hq";
  129. }
  130. nvenc_video_info(enc, &info);
  131. av_opt_set_int(enc->context->priv_data, "cbr", false, 0);
  132. av_opt_set(enc->context->priv_data, "profile", profile, 0);
  133. av_opt_set(enc->context->priv_data, "preset", preset, 0);
  134. if (astrcmpi(rc, "cqp") == 0) {
  135. bitrate = 0;
  136. enc->context->global_quality = cqp;
  137. } else if (astrcmpi(rc, "lossless") == 0) {
  138. bitrate = 0;
  139. cqp = 0;
  140. bool hp = (astrcmpi(preset, "hp") == 0 ||
  141. astrcmpi(preset, "llhp") == 0);
  142. av_opt_set(enc->context->priv_data, "preset",
  143. hp ? "losslesshp" : "lossless", 0);
  144. } else if (astrcmpi(rc, "vbr") != 0) { /* CBR by default */
  145. av_opt_set_int(enc->context->priv_data, "cbr", true, 0);
  146. enc->context->rc_max_rate = bitrate * 1000;
  147. enc->context->rc_min_rate = bitrate * 1000;
  148. cqp = 0;
  149. }
  150. av_opt_set(enc->context->priv_data, "level", "auto", 0);
  151. av_opt_set_int(enc->context->priv_data, "2pass", twopass, 0);
  152. av_opt_set_int(enc->context->priv_data, "gpu", gpu, 0);
  153. enc->context->bit_rate = bitrate * 1000;
  154. enc->context->rc_buffer_size = bitrate * 1000;
  155. enc->context->width = obs_encoder_get_width(enc->encoder);
  156. enc->context->height = obs_encoder_get_height(enc->encoder);
  157. enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num};
  158. enc->context->pix_fmt = obs_to_ffmpeg_video_format(info.format);
  159. enc->context->colorspace = info.colorspace == VIDEO_CS_709 ?
  160. AVCOL_SPC_BT709 : AVCOL_SPC_BT470BG;
  161. enc->context->color_range = info.range == VIDEO_RANGE_FULL ?
  162. AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  163. enc->context->max_b_frames = bf;
  164. if (keyint_sec)
  165. enc->context->gop_size = keyint_sec * voi->fps_num /
  166. voi->fps_den;
  167. else
  168. enc->context->gop_size = 250;
  169. enc->height = enc->context->height;
  170. info("settings:\n"
  171. "\trate_control: %s\n"
  172. "\tbitrate: %d\n"
  173. "\tcqp: %d\n"
  174. "\tkeyint: %d\n"
  175. "\tpreset: %s\n"
  176. "\tprofile: %s\n"
  177. "\twidth: %d\n"
  178. "\theight: %d\n"
  179. "\t2-pass: %s\n"
  180. "\tb-frames: %d\n"
  181. "\tGPU: %d\n",
  182. rc, bitrate, cqp, enc->context->gop_size,
  183. preset, profile,
  184. enc->context->width, enc->context->height,
  185. twopass ? "true" : "false",
  186. enc->context->max_b_frames,
  187. gpu);
  188. return nvenc_init_codec(enc);
  189. }
  190. static void nvenc_destroy(void *data)
  191. {
  192. struct nvenc_encoder *enc = data;
  193. if (enc->initialized) {
  194. AVPacket pkt = {0};
  195. int r_pkt = 1;
  196. while (r_pkt) {
  197. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  198. if (avcodec_receive_packet(enc->context, &pkt) < 0)
  199. break;
  200. #else
  201. if (avcodec_encode_video2(enc->context, &pkt, NULL,
  202. &r_pkt) < 0)
  203. break;
  204. #endif
  205. if (r_pkt)
  206. av_packet_unref(&pkt);
  207. }
  208. }
  209. avcodec_close(enc->context);
  210. av_frame_unref(enc->vframe);
  211. av_frame_free(&enc->vframe);
  212. da_free(enc->buffer);
  213. bfree(enc->header);
  214. bfree(enc->sei);
  215. bfree(enc);
  216. }
  217. static void *nvenc_create(obs_data_t *settings, obs_encoder_t *encoder)
  218. {
  219. struct nvenc_encoder *enc;
  220. avcodec_register_all();
  221. enc = bzalloc(sizeof(*enc));
  222. enc->encoder = encoder;
  223. enc->nvenc = avcodec_find_encoder_by_name("h264_nvenc");
  224. if (!enc->nvenc)
  225. enc->nvenc = avcodec_find_encoder_by_name("nvenc_h264");
  226. enc->first_packet = true;
  227. blog(LOG_INFO, "---------------------------------");
  228. if (!enc->nvenc) {
  229. warn("Couldn't find encoder");
  230. goto fail;
  231. }
  232. enc->context = avcodec_alloc_context3(enc->nvenc);
  233. if (!enc->context) {
  234. warn("Failed to create codec context");
  235. goto fail;
  236. }
  237. if (!nvenc_update(enc, settings))
  238. goto fail;
  239. return enc;
  240. fail:
  241. nvenc_destroy(enc);
  242. return NULL;
  243. }
  244. static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame,
  245. int height, enum AVPixelFormat format)
  246. {
  247. int h_chroma_shift, v_chroma_shift;
  248. av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, &v_chroma_shift);
  249. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  250. if (!frame->data[plane])
  251. continue;
  252. int frame_rowsize = (int)frame->linesize[plane];
  253. int pic_rowsize = pic->linesize[plane];
  254. int bytes = frame_rowsize < pic_rowsize ?
  255. frame_rowsize : pic_rowsize;
  256. int plane_height = height >> (plane ? v_chroma_shift : 0);
  257. for (int y = 0; y < plane_height; y++) {
  258. int pos_frame = y * frame_rowsize;
  259. int pos_pic = y * pic_rowsize;
  260. memcpy(pic->data[plane] + pos_pic,
  261. frame->data[plane] + pos_frame,
  262. bytes);
  263. }
  264. }
  265. }
  266. static bool nvenc_encode(void *data, struct encoder_frame *frame,
  267. struct encoder_packet *packet, bool *received_packet)
  268. {
  269. struct nvenc_encoder *enc = data;
  270. AVPacket av_pkt = {0};
  271. int got_packet;
  272. int ret;
  273. av_init_packet(&av_pkt);
  274. copy_data(enc->vframe, frame, enc->height, enc->context->pix_fmt);
  275. enc->vframe->pts = frame->pts;
  276. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  277. ret = avcodec_send_frame(enc->context, enc->vframe);
  278. if (ret == 0)
  279. ret = avcodec_receive_packet(enc->context, &av_pkt);
  280. got_packet = (ret == 0);
  281. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  282. ret = 0;
  283. #else
  284. ret = avcodec_encode_video2(enc->context, &av_pkt, enc->vframe,
  285. &got_packet);
  286. #endif
  287. if (ret < 0) {
  288. warn("nvenc_encode: Error encoding: %s", av_err2str(ret));
  289. return false;
  290. }
  291. if (got_packet && av_pkt.size) {
  292. if (enc->first_packet) {
  293. uint8_t *new_packet;
  294. size_t size;
  295. enc->first_packet = false;
  296. obs_extract_avc_headers(av_pkt.data, av_pkt.size,
  297. &new_packet, &size,
  298. &enc->header, &enc->header_size,
  299. &enc->sei, &enc->sei_size);
  300. da_copy_array(enc->buffer, new_packet, size);
  301. bfree(new_packet);
  302. } else {
  303. da_copy_array(enc->buffer, av_pkt.data, av_pkt.size);
  304. }
  305. packet->pts = av_pkt.pts;
  306. packet->dts = av_pkt.dts;
  307. packet->data = enc->buffer.array;
  308. packet->size = enc->buffer.num;
  309. packet->type = OBS_ENCODER_VIDEO;
  310. packet->keyframe = obs_avc_keyframe(packet->data, packet->size);
  311. *received_packet = true;
  312. } else {
  313. *received_packet = false;
  314. }
  315. av_packet_unref(&av_pkt);
  316. return true;
  317. }
  318. void nvenc_defaults(obs_data_t *settings)
  319. {
  320. obs_data_set_default_int(settings, "bitrate", 2500);
  321. obs_data_set_default_int(settings, "max_bitrate", 5000);
  322. obs_data_set_default_int(settings, "keyint_sec", 0);
  323. obs_data_set_default_int(settings, "cqp", 20);
  324. obs_data_set_default_string(settings, "rate_control", "CBR");
  325. obs_data_set_default_string(settings, "preset", "hq");
  326. obs_data_set_default_string(settings, "profile", "high");
  327. obs_data_set_default_bool(settings, "psycho_aq", true);
  328. obs_data_set_default_int(settings, "gpu", 0);
  329. obs_data_set_default_int(settings, "bf", 2);
  330. }
  331. static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
  332. obs_data_t *settings)
  333. {
  334. const char *rc = obs_data_get_string(settings, "rate_control");
  335. bool cqp = astrcmpi(rc, "CQP") == 0;
  336. bool vbr = astrcmpi(rc, "VBR") == 0;
  337. bool lossless = astrcmpi(rc, "lossless") == 0;
  338. size_t count;
  339. p = obs_properties_get(ppts, "bitrate");
  340. obs_property_set_visible(p, !cqp && !lossless);
  341. p = obs_properties_get(ppts, "max_bitrate");
  342. obs_property_set_visible(p, vbr);
  343. p = obs_properties_get(ppts, "cqp");
  344. obs_property_set_visible(p, cqp);
  345. p = obs_properties_get(ppts, "preset");
  346. count = obs_property_list_item_count(p);
  347. for (size_t i = 0; i < count; i++) {
  348. bool compatible = (i == 0 || i == 3);
  349. obs_property_list_item_disable(p, i, lossless && !compatible);
  350. }
  351. return true;
  352. }
  353. obs_properties_t *nvenc_properties_internal(bool ffmpeg)
  354. {
  355. obs_properties_t *props = obs_properties_create();
  356. obs_property_t *p;
  357. p = obs_properties_add_list(props, "rate_control",
  358. obs_module_text("RateControl"),
  359. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  360. obs_property_list_add_string(p, "CBR", "CBR");
  361. obs_property_list_add_string(p, "CQP", "CQP");
  362. obs_property_list_add_string(p, "VBR", "VBR");
  363. obs_property_list_add_string(p, obs_module_text("Lossless"),
  364. "lossless");
  365. obs_property_set_modified_callback(p, rate_control_modified);
  366. obs_properties_add_int(props, "bitrate",
  367. obs_module_text("Bitrate"), 50, 300000, 50);
  368. obs_properties_add_int(props, "max_bitrate",
  369. obs_module_text("MaxBitrate"), 50, 300000, 50);
  370. obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"),
  371. 1, 30, 1);
  372. obs_properties_add_int(props, "keyint_sec",
  373. obs_module_text("KeyframeIntervalSec"), 0, 10, 1);
  374. p = obs_properties_add_list(props, "preset", obs_module_text("Preset"),
  375. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  376. #define add_preset(val) \
  377. obs_property_list_add_string(p, obs_module_text("NVENC.Preset." val), \
  378. val)
  379. add_preset("mq");
  380. add_preset("hq");
  381. add_preset("default");
  382. add_preset("hp");
  383. add_preset("ll");
  384. add_preset("llhq");
  385. add_preset("llhp");
  386. #undef add_preset
  387. p = obs_properties_add_list(props, "profile", obs_module_text("Profile"),
  388. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  389. #define add_profile(val) \
  390. obs_property_list_add_string(p, val, val)
  391. add_profile("high");
  392. add_profile("main");
  393. add_profile("baseline");
  394. #undef add_profile
  395. if (!ffmpeg) {
  396. p = obs_properties_add_bool(props, "lookahead",
  397. obs_module_text("NVENC.LookAhead"));
  398. obs_property_set_long_description(p,
  399. obs_module_text("NVENC.LookAhead.ToolTip"));
  400. p = obs_properties_add_bool(props, "psycho_aq",
  401. obs_module_text("NVENC.PsychoVisualTuning"));
  402. obs_property_set_long_description(p,
  403. obs_module_text("NVENC.PsychoVisualTuning.ToolTip"));
  404. }
  405. obs_properties_add_int(props, "gpu", obs_module_text("GPU"), 0, 8, 1);
  406. obs_properties_add_int(props, "bf", obs_module_text("BFrames"),
  407. 0, 4, 1);
  408. return props;
  409. }
  410. obs_properties_t *nvenc_properties(void *unused)
  411. {
  412. UNUSED_PARAMETER(unused);
  413. return nvenc_properties_internal(false);
  414. }
  415. obs_properties_t *nvenc_properties_ffmpeg(void *unused)
  416. {
  417. UNUSED_PARAMETER(unused);
  418. return nvenc_properties_internal(true);
  419. }
  420. static bool nvenc_extra_data(void *data, uint8_t **extra_data, size_t *size)
  421. {
  422. struct nvenc_encoder *enc = data;
  423. *extra_data = enc->header;
  424. *size = enc->header_size;
  425. return true;
  426. }
  427. static bool nvenc_sei_data(void *data, uint8_t **extra_data, size_t *size)
  428. {
  429. struct nvenc_encoder *enc = data;
  430. *extra_data = enc->sei;
  431. *size = enc->sei_size;
  432. return true;
  433. }
  434. struct obs_encoder_info nvenc_encoder_info = {
  435. .id = "ffmpeg_nvenc",
  436. .type = OBS_ENCODER_VIDEO,
  437. .codec = "h264",
  438. .get_name = nvenc_getname,
  439. .create = nvenc_create,
  440. .destroy = nvenc_destroy,
  441. .encode = nvenc_encode,
  442. .get_defaults = nvenc_defaults,
  443. .get_properties = nvenc_properties_ffmpeg,
  444. .get_extra_data = nvenc_extra_data,
  445. .get_sei_data = nvenc_sei_data,
  446. .get_video_info = nvenc_video_info
  447. };