obs-ffmpeg-nvenc.c 14 KB

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