obs-ffmpeg-nvenc.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 <libavformat/avformat.h>
  22. #include "obs-ffmpeg-formats.h"
  23. #define do_log(level, format, ...) \
  24. blog(level, "[NVENC encoder: '%s'] " format, \
  25. obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
  26. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  27. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  28. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  29. struct nvenc_encoder {
  30. obs_encoder_t *encoder;
  31. AVCodec *nvenc;
  32. AVCodecContext *context;
  33. AVPicture dst_picture;
  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. };
  43. static const char *nvenc_getname(void *unused)
  44. {
  45. UNUSED_PARAMETER(unused);
  46. return "NVENC H.264";
  47. }
  48. static inline bool valid_format(enum video_format format)
  49. {
  50. return format == VIDEO_FORMAT_I420 ||
  51. 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) ?
  61. info->format : 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 = avpicture_alloc(&enc->dst_picture, enc->context->pix_fmt,
  84. enc->context->width, enc->context->height);
  85. if (ret < 0) {
  86. warn("Failed to allocate dst_picture: %s", av_err2str(ret));
  87. return false;
  88. }
  89. *((AVPicture*)enc->vframe) = enc->dst_picture;
  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. const char *level = obs_data_get_string(settings, "level");
  108. bool twopass = obs_data_get_bool(settings, "2pass");
  109. int gpu = (int)obs_data_get_int(settings, "gpu");
  110. bool cbr_override = obs_data_get_bool(settings, "cbr");
  111. int bf = (int)obs_data_get_int(settings, "bf");
  112. video_t *video = obs_encoder_video(enc->encoder);
  113. const struct video_output_info *voi = video_output_get_info(video);
  114. struct video_scale_info info;
  115. /* XXX: "cbr" setting has been deprecated */
  116. if (cbr_override) {
  117. warn("\"cbr\" setting has been deprecated for all encoders! "
  118. "Please set \"rate_control\" to \"CBR\" instead. "
  119. "Forcing CBR mode. "
  120. "(Note to all: this is why you shouldn't use strings for "
  121. "common settings)");
  122. rc = "CBR";
  123. }
  124. info.format = voi->format;
  125. info.colorspace = voi->colorspace;
  126. info.range = voi->range;
  127. nvenc_video_info(enc, &info);
  128. av_opt_set_int(enc->context->priv_data, "cbr", false, 0);
  129. av_opt_set(enc->context->priv_data, "profile", profile, 0);
  130. av_opt_set(enc->context->priv_data, "preset", preset, 0);
  131. if (astrcmpi(rc, "cqp") == 0) {
  132. bitrate = 0;
  133. enc->context->global_quality = cqp;
  134. } else if (astrcmpi(rc, "lossless") == 0) {
  135. bitrate = 0;
  136. cqp = 0;
  137. bool hp = (astrcmpi(preset, "hp") == 0 ||
  138. astrcmpi(preset, "llhp") == 0);
  139. av_opt_set(enc->context->priv_data, "preset",
  140. hp ? "losslesshp" : "lossless", 0);
  141. } else if (astrcmpi(rc, "vbr") != 0) { /* CBR by default */
  142. av_opt_set_int(enc->context->priv_data, "cbr", true, 0);
  143. enc->context->rc_max_rate = bitrate * 1000;
  144. enc->context->rc_min_rate = bitrate * 1000;
  145. cqp = 0;
  146. }
  147. av_opt_set(enc->context->priv_data, "level", level, 0);
  148. av_opt_set_int(enc->context->priv_data, "2pass", twopass, 0);
  149. av_opt_set_int(enc->context->priv_data, "gpu", gpu, 0);
  150. enc->context->bit_rate = bitrate * 1000;
  151. enc->context->rc_buffer_size = bitrate * 1000;
  152. enc->context->width = obs_encoder_get_width(enc->encoder);
  153. enc->context->height = obs_encoder_get_height(enc->encoder);
  154. enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num};
  155. enc->context->pix_fmt = obs_to_ffmpeg_video_format(info.format);
  156. enc->context->colorspace = info.colorspace == VIDEO_CS_709 ?
  157. AVCOL_SPC_BT709 : AVCOL_SPC_BT470BG;
  158. enc->context->color_range = info.range == VIDEO_RANGE_FULL ?
  159. AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  160. enc->context->max_b_frames = bf;
  161. if (keyint_sec)
  162. enc->context->gop_size = keyint_sec * voi->fps_num /
  163. voi->fps_den;
  164. else
  165. enc->context->gop_size = 250;
  166. enc->height = enc->context->height;
  167. info("settings:\n"
  168. "\trate_control: %s\n"
  169. "\tbitrate: %d\n"
  170. "\tcqp: %d\n"
  171. "\tkeyint: %d\n"
  172. "\tpreset: %s\n"
  173. "\tprofile: %s\n"
  174. "\tlevel: %s\n"
  175. "\twidth: %d\n"
  176. "\theight: %d\n"
  177. "\t2-pass: %s\n"
  178. "\tGPU: %d\n",
  179. rc, bitrate, cqp, enc->context->gop_size,
  180. preset, profile, level,
  181. enc->context->width, enc->context->height,
  182. twopass ? "true" : "false",
  183. gpu);
  184. return nvenc_init_codec(enc);
  185. }
  186. static void nvenc_destroy(void *data)
  187. {
  188. struct nvenc_encoder *enc = data;
  189. AVPacket pkt = {0};
  190. int r_pkt = 1;
  191. while (r_pkt) {
  192. if (avcodec_encode_video2(enc->context, &pkt, NULL, &r_pkt) < 0)
  193. break;
  194. if (r_pkt)
  195. av_free_packet(&pkt);
  196. }
  197. avcodec_close(enc->context);
  198. av_frame_free(&enc->vframe);
  199. avpicture_free(&enc->dst_picture);
  200. da_free(enc->buffer);
  201. bfree(enc->header);
  202. bfree(enc->sei);
  203. bfree(enc);
  204. }
  205. static void *nvenc_create(obs_data_t *settings, obs_encoder_t *encoder)
  206. {
  207. struct nvenc_encoder *enc;
  208. avcodec_register_all();
  209. enc = bzalloc(sizeof(*enc));
  210. enc->encoder = encoder;
  211. enc->nvenc = avcodec_find_encoder_by_name("nvenc_h264");
  212. enc->first_packet = true;
  213. blog(LOG_INFO, "---------------------------------");
  214. if (!enc->nvenc) {
  215. warn("Couldn't find encoder");
  216. goto fail;
  217. }
  218. enc->context = avcodec_alloc_context3(enc->nvenc);
  219. if (!enc->context) {
  220. warn("Failed to create codec context");
  221. goto fail;
  222. }
  223. if (!nvenc_update(enc, settings))
  224. goto fail;
  225. return enc;
  226. fail:
  227. nvenc_destroy(enc);
  228. return NULL;
  229. }
  230. static inline void copy_data(AVPicture *pic, const struct encoder_frame *frame,
  231. int height)
  232. {
  233. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  234. if (!frame->data[plane])
  235. continue;
  236. int frame_rowsize = (int)frame->linesize[plane];
  237. int pic_rowsize = pic->linesize[plane];
  238. int bytes = frame_rowsize < pic_rowsize ?
  239. frame_rowsize : pic_rowsize;
  240. int plane_height = plane == 0 ? height : height/2;
  241. for (int y = 0; y < plane_height; y++) {
  242. int pos_frame = y * frame_rowsize;
  243. int pos_pic = y * pic_rowsize;
  244. memcpy(pic->data[plane] + pos_pic,
  245. frame->data[plane] + pos_frame,
  246. bytes);
  247. }
  248. }
  249. }
  250. static bool nvenc_encode(void *data, struct encoder_frame *frame,
  251. struct encoder_packet *packet, bool *received_packet)
  252. {
  253. struct nvenc_encoder *enc = data;
  254. AVPacket av_pkt = {0};
  255. int got_packet;
  256. int ret;
  257. av_init_packet(&av_pkt);
  258. copy_data(&enc->dst_picture, frame, enc->height);
  259. enc->vframe->pts = frame->pts;
  260. ret = avcodec_encode_video2(enc->context, &av_pkt, enc->vframe,
  261. &got_packet);
  262. if (ret < 0) {
  263. warn("nvenc_encode: Error encoding: %s", av_err2str(ret));
  264. return false;
  265. }
  266. if (got_packet && av_pkt.size) {
  267. if (enc->first_packet) {
  268. uint8_t *new_packet;
  269. size_t size;
  270. enc->first_packet = false;
  271. obs_extract_avc_headers(av_pkt.data, av_pkt.size,
  272. &new_packet, &size,
  273. &enc->header, &enc->header_size,
  274. &enc->sei, &enc->sei_size);
  275. da_copy_array(enc->buffer, new_packet, size);
  276. bfree(new_packet);
  277. } else {
  278. da_copy_array(enc->buffer, av_pkt.data, av_pkt.size);
  279. }
  280. packet->pts = av_pkt.pts;
  281. packet->dts = av_pkt.dts;
  282. packet->data = enc->buffer.array;
  283. packet->size = enc->buffer.num;
  284. packet->type = OBS_ENCODER_VIDEO;
  285. packet->keyframe = obs_avc_keyframe(packet->data, packet->size);
  286. *received_packet = true;
  287. } else {
  288. *received_packet = false;
  289. }
  290. av_free_packet(&av_pkt);
  291. return true;
  292. }
  293. static void nvenc_defaults(obs_data_t *settings)
  294. {
  295. obs_data_set_default_int(settings, "bitrate", 2500);
  296. obs_data_set_default_int(settings, "keyint_sec", 0);
  297. obs_data_set_default_int(settings, "cqp", 23);
  298. obs_data_set_default_string(settings, "rate_control", "CBR");
  299. obs_data_set_default_string(settings, "preset", "default");
  300. obs_data_set_default_string(settings, "profile", "main");
  301. obs_data_set_default_string(settings, "level", "auto");
  302. obs_data_set_default_bool(settings, "2pass", true);
  303. obs_data_set_default_int(settings, "gpu", 0);
  304. obs_data_set_default_int(settings, "bf", 2);
  305. }
  306. static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
  307. obs_data_t *settings)
  308. {
  309. const char *rc = obs_data_get_string(settings, "rate_control");
  310. bool cqp = astrcmpi(rc, "CQP") == 0;
  311. bool lossless = astrcmpi(rc, "lossless") == 0;
  312. size_t count;
  313. p = obs_properties_get(ppts, "bitrate");
  314. obs_property_set_visible(p, !cqp && !lossless);
  315. p = obs_properties_get(ppts, "cqp");
  316. obs_property_set_visible(p, cqp);
  317. p = obs_properties_get(ppts, "preset");
  318. count = obs_property_list_item_count(p);
  319. for (size_t i = 0; i < count; i++) {
  320. bool compatible = (i == 0 || i == 2);
  321. obs_property_list_item_disable(p, i, lossless && !compatible);
  322. }
  323. return true;
  324. }
  325. static obs_properties_t *nvenc_properties(void *unused)
  326. {
  327. UNUSED_PARAMETER(unused);
  328. obs_properties_t *props = obs_properties_create();
  329. obs_property_t *p;
  330. p = obs_properties_add_list(props, "rate_control",
  331. obs_module_text("RateControl"),
  332. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  333. obs_property_list_add_string(p, "CBR", "CBR");
  334. obs_property_list_add_string(p, "VBR", "VBR");
  335. obs_property_list_add_string(p, "CQP", "CQP");
  336. obs_property_list_add_string(p, obs_module_text("Lossless"),
  337. "lossless");
  338. obs_property_set_modified_callback(p, rate_control_modified);
  339. obs_properties_add_int(props, "bitrate",
  340. obs_module_text("Bitrate"), 50, 300000, 50);
  341. obs_properties_add_int(props, "cqp", "CQP", 0, 50, 1);
  342. obs_properties_add_int(props, "keyint_sec",
  343. obs_module_text("KeyframeIntervalSec"), 0, 10, 1);
  344. p = obs_properties_add_list(props, "preset", obs_module_text("Preset"),
  345. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  346. #define add_preset(val) \
  347. obs_property_list_add_string(p, obs_module_text("NVENC.Preset." val), \
  348. val)
  349. add_preset("default");
  350. add_preset("hq");
  351. add_preset("hp");
  352. add_preset("bd");
  353. add_preset("ll");
  354. add_preset("llhq");
  355. add_preset("llhp");
  356. #undef add_preset
  357. p = obs_properties_add_list(props, "profile", obs_module_text("Profile"),
  358. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  359. #define add_profile(val) \
  360. obs_property_list_add_string(p, val, val)
  361. add_profile("high");
  362. add_profile("main");
  363. add_profile("baseline");
  364. add_profile("high444p");
  365. p = obs_properties_add_list(props, "level",
  366. obs_module_text("NVENC.Level"), OBS_COMBO_TYPE_LIST,
  367. OBS_COMBO_FORMAT_STRING);
  368. add_profile("auto");
  369. add_profile("1" );
  370. add_profile("1.0" );
  371. add_profile("1b" );
  372. add_profile("1.0b");
  373. add_profile("1.1" );
  374. add_profile("1.2" );
  375. add_profile("1.3" );
  376. add_profile("2" );
  377. add_profile("2.0" );
  378. add_profile("2.1" );
  379. add_profile("2.2" );
  380. add_profile("3" );
  381. add_profile("3.0" );
  382. add_profile("3.1" );
  383. add_profile("3.2" );
  384. add_profile("4" );
  385. add_profile("4.0" );
  386. add_profile("4.1" );
  387. add_profile("4.2" );
  388. add_profile("5" );
  389. add_profile("5.0" );
  390. add_profile("5.1" );
  391. #undef add_profile
  392. obs_properties_add_bool(props, "2pass",
  393. obs_module_text("NVENC.Use2Pass"));
  394. obs_properties_add_int(props, "gpu", obs_module_text("GPU"), 0, 8, 1);
  395. obs_properties_add_int(props, "bf", obs_module_text("BFrames"),
  396. 0, 4, 1);
  397. return props;
  398. }
  399. static bool nvenc_extra_data(void *data, uint8_t **extra_data, size_t *size)
  400. {
  401. struct nvenc_encoder *enc = data;
  402. *extra_data = enc->header;
  403. *size = enc->header_size;
  404. return true;
  405. }
  406. static bool nvenc_sei_data(void *data, uint8_t **extra_data, size_t *size)
  407. {
  408. struct nvenc_encoder *enc = data;
  409. *extra_data = enc->sei;
  410. *size = enc->sei_size;
  411. return true;
  412. }
  413. struct obs_encoder_info nvenc_encoder_info = {
  414. .id = "ffmpeg_nvenc",
  415. .type = OBS_ENCODER_VIDEO,
  416. .codec = "h264",
  417. .get_name = nvenc_getname,
  418. .create = nvenc_create,
  419. .destroy = nvenc_destroy,
  420. .encode = nvenc_encode,
  421. .get_defaults = nvenc_defaults,
  422. .get_properties = nvenc_properties,
  423. .get_extra_data = nvenc_extra_data,
  424. .get_sei_data = nvenc_sei_data,
  425. .get_video_info = nvenc_video_info
  426. };