obs-ffmpeg-nvenc.c 16 KB

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