obs-ffmpeg-nvenc.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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/base.h>
  16. #include <media-io/video-io.h>
  17. #include <obs-module.h>
  18. #include <obs-avc.h>
  19. #include <libavutil/opt.h>
  20. #include <libavformat/avformat.h>
  21. #include "obs-ffmpeg-formats.h"
  22. #define do_log(level, format, ...) \
  23. blog(level, "[NVENC encoder: '%s'] " format, \
  24. obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
  25. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  26. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  27. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  28. struct nvenc_encoder {
  29. obs_encoder_t *encoder;
  30. AVCodec *nvenc;
  31. AVCodecContext *context;
  32. AVPicture dst_picture;
  33. AVFrame *vframe;
  34. DARRAY(uint8_t) buffer;
  35. uint8_t *header;
  36. size_t header_size;
  37. uint8_t *sei;
  38. size_t sei_size;
  39. int height;
  40. bool first_packet;
  41. };
  42. static const char *nvenc_getname(void *unused)
  43. {
  44. UNUSED_PARAMETER(unused);
  45. return "NVENC H.264";
  46. }
  47. static inline bool valid_format(enum video_format format)
  48. {
  49. return format == VIDEO_FORMAT_I420 ||
  50. format == VIDEO_FORMAT_NV12 ||
  51. format == VIDEO_FORMAT_I444;
  52. }
  53. static void nvenc_video_info(void *data, struct video_scale_info *info)
  54. {
  55. struct nvenc_encoder *enc = data;
  56. enum video_format pref_format;
  57. pref_format = obs_encoder_get_preferred_video_format(enc->encoder);
  58. if (!valid_format(pref_format)) {
  59. pref_format = valid_format(info->format) ?
  60. info->format : VIDEO_FORMAT_NV12;
  61. }
  62. info->format = pref_format;
  63. }
  64. static bool nvenc_init_codec(struct nvenc_encoder *enc)
  65. {
  66. int ret;
  67. ret = avcodec_open2(enc->context, enc->nvenc, NULL);
  68. if (ret < 0) {
  69. warn("Failed to open NVENC codec: %s", av_err2str(ret));
  70. return false;
  71. }
  72. enc->vframe = av_frame_alloc();
  73. if (!enc->vframe) {
  74. warn("Failed to allocate video frame");
  75. return false;
  76. }
  77. enc->vframe->format = enc->context->pix_fmt;
  78. enc->vframe->width = enc->context->width;
  79. enc->vframe->height = enc->context->height;
  80. enc->vframe->colorspace = enc->context->colorspace;
  81. enc->vframe->color_range = enc->context->color_range;
  82. ret = avpicture_alloc(&enc->dst_picture, enc->context->pix_fmt,
  83. enc->context->width, enc->context->height);
  84. if (ret < 0) {
  85. warn("Failed to allocate dst_picture: %s", av_err2str(ret));
  86. return false;
  87. }
  88. *((AVPicture*)enc->vframe) = enc->dst_picture;
  89. return true;
  90. }
  91. static bool nvenc_update(void *data, obs_data_t *settings)
  92. {
  93. struct nvenc_encoder *enc = data;
  94. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  95. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  96. const char *preset = obs_data_get_string(settings, "preset");
  97. const char *profile = obs_data_get_string(settings, "profile");
  98. const char *level = obs_data_get_string(settings, "level");
  99. bool cbr = obs_data_get_bool(settings, "cbr");
  100. bool twopass = obs_data_get_bool(settings, "2pass");
  101. int gpu = (int)obs_data_get_int(settings, "gpu");
  102. video_t *video = obs_encoder_video(enc->encoder);
  103. const struct video_output_info *voi = video_output_get_info(video);
  104. struct video_scale_info info;
  105. info.format = voi->format;
  106. info.colorspace = voi->colorspace;
  107. info.range = voi->range;
  108. nvenc_video_info(enc, &info);
  109. av_opt_set(enc->context->priv_data, "preset", preset, 0);
  110. av_opt_set(enc->context->priv_data, "profile", profile, 0);
  111. av_opt_set(enc->context->priv_data, "level", level, 0);
  112. av_opt_set_int(enc->context->priv_data, "cbr", cbr, 0);
  113. av_opt_set_int(enc->context->priv_data, "2pass", twopass, 0);
  114. av_opt_set_int(enc->context->priv_data, "gpu", gpu, 0);
  115. enc->context->bit_rate = bitrate * 1000;
  116. enc->context->width = obs_encoder_get_width(enc->encoder);
  117. enc->context->height = obs_encoder_get_height(enc->encoder);
  118. enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num};
  119. enc->context->pix_fmt = obs_to_ffmpeg_video_format(info.format);
  120. enc->context->colorspace = info.colorspace == VIDEO_CS_709 ?
  121. AVCOL_SPC_BT709 : AVCOL_SPC_BT470BG;
  122. enc->context->color_range = info.range == VIDEO_RANGE_FULL ?
  123. AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
  124. if (keyint_sec)
  125. enc->context->gop_size = keyint_sec * voi->fps_num /
  126. voi->fps_den;
  127. else
  128. enc->context->gop_size = 250;
  129. enc->height = enc->context->height;
  130. info("settings:\n"
  131. "\tbitrate: %d\n"
  132. "\tkeyint: %d\n"
  133. "\tpreset: %s\n"
  134. "\tprofile: %s\n"
  135. "\tlevel: %s\n"
  136. "\twidth: %d\n"
  137. "\theight: %d\n"
  138. "\tcbr: %s\n"
  139. "\t2-pass: %s\n"
  140. "\tGPU: %d\n",
  141. bitrate, enc->context->gop_size,
  142. preset, profile, level,
  143. enc->context->width, enc->context->height,
  144. cbr ? "true" : "false",
  145. twopass ? "true" : "false",
  146. gpu);
  147. return nvenc_init_codec(enc);
  148. }
  149. static void nvenc_destroy(void *data)
  150. {
  151. struct nvenc_encoder *enc = data;
  152. avcodec_close(enc->context);
  153. av_frame_free(&enc->vframe);
  154. avpicture_free(&enc->dst_picture);
  155. da_free(enc->buffer);
  156. bfree(enc->header);
  157. bfree(enc->sei);
  158. bfree(enc);
  159. }
  160. static void *nvenc_create(obs_data_t *settings, obs_encoder_t *encoder)
  161. {
  162. struct nvenc_encoder *enc;
  163. video_t *video = obs_encoder_video(encoder);
  164. avcodec_register_all();
  165. enc = bzalloc(sizeof(*enc));
  166. enc->encoder = encoder;
  167. enc->nvenc = avcodec_find_encoder_by_name("nvenc_h264");
  168. enc->first_packet = true;
  169. blog(LOG_INFO, "---------------------------------");
  170. if (!enc->nvenc) {
  171. warn("Couldn't find encoder");
  172. goto fail;
  173. }
  174. enc->context = avcodec_alloc_context3(enc->nvenc);
  175. if (!enc->context) {
  176. warn("Failed to create codec context");
  177. goto fail;
  178. }
  179. if (!nvenc_update(enc, settings))
  180. goto fail;
  181. return enc;
  182. fail:
  183. nvenc_destroy(enc);
  184. return NULL;
  185. }
  186. static inline void copy_data(AVPicture *pic, const struct encoder_frame *frame,
  187. int height)
  188. {
  189. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  190. if (!frame->data[plane])
  191. continue;
  192. int frame_rowsize = (int)frame->linesize[plane];
  193. int pic_rowsize = pic->linesize[plane];
  194. int bytes = frame_rowsize < pic_rowsize ?
  195. frame_rowsize : pic_rowsize;
  196. int plane_height = plane == 0 ? height : height/2;
  197. for (int y = 0; y < plane_height; y++) {
  198. int pos_frame = y * frame_rowsize;
  199. int pos_pic = y * pic_rowsize;
  200. memcpy(pic->data[plane] + pos_pic,
  201. frame->data[plane] + pos_frame,
  202. bytes);
  203. }
  204. }
  205. }
  206. static bool nvenc_encode(void *data, struct encoder_frame *frame,
  207. struct encoder_packet *packet, bool *received_packet)
  208. {
  209. struct nvenc_encoder *enc = data;
  210. AVPacket av_pkt = {0};
  211. int got_packet;
  212. int ret;
  213. av_init_packet(&av_pkt);
  214. copy_data(&enc->dst_picture, frame, enc->height);
  215. enc->vframe->pts = frame->pts;
  216. ret = avcodec_encode_video2(enc->context, &av_pkt, enc->vframe,
  217. &got_packet);
  218. if (ret < 0) {
  219. warn("nvenc_encode: Error encoding: %s", av_err2str(ret));
  220. return false;
  221. }
  222. if (got_packet && av_pkt.size) {
  223. if (enc->first_packet) {
  224. uint8_t *new_packet;
  225. size_t size;
  226. enc->first_packet = false;
  227. obs_extract_avc_headers(av_pkt.data, av_pkt.size,
  228. &new_packet, &size,
  229. &enc->header, &enc->header_size,
  230. &enc->sei, &enc->sei_size);
  231. da_copy_array(enc->buffer, new_packet, size);
  232. bfree(new_packet);
  233. } else {
  234. da_copy_array(enc->buffer, av_pkt.data, av_pkt.size);
  235. }
  236. packet->pts = av_pkt.pts;
  237. packet->dts = av_pkt.dts;
  238. packet->data = enc->buffer.array;
  239. packet->size = enc->buffer.num;
  240. packet->type = OBS_ENCODER_VIDEO;
  241. packet->keyframe = obs_avc_keyframe(packet->data, packet->size);
  242. *received_packet = true;
  243. } else {
  244. *received_packet = false;
  245. }
  246. av_free_packet(&av_pkt);
  247. return true;
  248. }
  249. static void nvenc_defaults(obs_data_t *settings)
  250. {
  251. obs_data_set_default_int(settings, "bitrate", 2500);
  252. obs_data_set_default_int(settings, "keyint_sec", 0);
  253. obs_data_set_default_string(settings, "preset", "default");
  254. obs_data_set_default_string(settings, "profile", "main");
  255. obs_data_set_default_string(settings, "level", "auto");
  256. obs_data_set_default_bool(settings, "cbr", false);
  257. obs_data_set_default_bool(settings, "2pass", true);
  258. obs_data_set_default_int(settings, "gpu", 0);
  259. }
  260. static obs_properties_t *nvenc_properties(void *unused)
  261. {
  262. UNUSED_PARAMETER(unused);
  263. obs_properties_t *props = obs_properties_create();
  264. obs_property_t *p;
  265. obs_properties_add_int(props, "bitrate",
  266. obs_module_text("Bitrate"), 50, 90000, 50);
  267. obs_properties_add_int(props, "keyint_sec",
  268. obs_module_text("KeyframeIntervalSec"), 0, 10, 1);
  269. p = obs_properties_add_list(props, "preset", obs_module_text("Preset"),
  270. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  271. #define add_preset(val) \
  272. obs_property_list_add_string(p, obs_module_text("NVENC.Preset." val), \
  273. val)
  274. add_preset("default");
  275. add_preset("hq");
  276. add_preset("hp");
  277. add_preset("bd");
  278. add_preset("ll");
  279. add_preset("llhq");
  280. add_preset("llhp");
  281. #undef add_preset
  282. p = obs_properties_add_list(props, "profile", obs_module_text("Profile"),
  283. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  284. #define add_profile(val) \
  285. obs_property_list_add_string(p, val, val)
  286. add_profile("high");
  287. add_profile("main");
  288. add_profile("baseline");
  289. add_profile("high444p");
  290. p = obs_properties_add_list(props, "level",
  291. obs_module_text("NVENC.Level"), OBS_COMBO_TYPE_LIST,
  292. OBS_COMBO_FORMAT_STRING);
  293. add_profile("auto");
  294. add_profile("1" );
  295. add_profile("1.0" );
  296. add_profile("1b" );
  297. add_profile("1.0b");
  298. add_profile("1.1" );
  299. add_profile("1.2" );
  300. add_profile("1.3" );
  301. add_profile("2" );
  302. add_profile("2.0" );
  303. add_profile("2.1" );
  304. add_profile("2.2" );
  305. add_profile("3" );
  306. add_profile("3.0" );
  307. add_profile("3.1" );
  308. add_profile("3.2" );
  309. add_profile("4" );
  310. add_profile("4.0" );
  311. add_profile("4.1" );
  312. add_profile("4.2" );
  313. add_profile("5" );
  314. add_profile("5.0" );
  315. add_profile("5.1" );
  316. #undef add_profile
  317. obs_properties_add_bool(props, "2pass",
  318. obs_module_text("NVENC.Use2Pass"));
  319. obs_properties_add_bool(props, "cbr", obs_module_text("UseCBR"));
  320. obs_properties_add_int(props, "gpu", obs_module_text("GPU"), 0, 8, 1);
  321. return props;
  322. }
  323. static bool nvenc_extra_data(void *data, uint8_t **extra_data, size_t *size)
  324. {
  325. struct nvenc_encoder *enc = data;
  326. *extra_data = enc->header;
  327. *size = enc->header_size;
  328. return true;
  329. }
  330. static bool nvenc_sei_data(void *data, uint8_t **extra_data, size_t *size)
  331. {
  332. struct nvenc_encoder *enc = data;
  333. *extra_data = enc->sei;
  334. *size = enc->sei_size;
  335. return true;
  336. }
  337. struct obs_encoder_info nvenc_encoder_info = {
  338. .id = "ffmpeg_nvenc",
  339. .type = OBS_ENCODER_VIDEO,
  340. .codec = "h264",
  341. .get_name = nvenc_getname,
  342. .create = nvenc_create,
  343. .destroy = nvenc_destroy,
  344. .encode = nvenc_encode,
  345. .get_defaults = nvenc_defaults,
  346. .get_properties = nvenc_properties,
  347. .get_extra_data = nvenc_extra_data,
  348. .get_sei_data = nvenc_sei_data,
  349. .get_video_info = nvenc_video_info
  350. };