1
0

obs-ffmpeg-vaapi.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 <libavutil/avutil.h>
  15. #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(55, 27, 100)
  16. #include <util/darray.h>
  17. #include <util/dstr.h>
  18. #include <util/base.h>
  19. #include <media-io/video-io.h>
  20. #include <obs-module.h>
  21. #include <obs-avc.h>
  22. #include <unistd.h>
  23. #include <libavutil/opt.h>
  24. #include <libavutil/pixdesc.h>
  25. #include <libavutil/hwcontext.h>
  26. #include <libavcodec/avcodec.h>
  27. #include <libavformat/avformat.h>
  28. #include <libavfilter/avfilter.h>
  29. #include "obs-ffmpeg-formats.h"
  30. #define do_log(level, format, ...) \
  31. blog(level, "[FFMPEG VAAPI encoder: '%s'] " format, \
  32. obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
  33. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  34. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  35. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  36. struct vaapi_encoder {
  37. obs_encoder_t *encoder;
  38. AVBufferRef *vadevice_ref;
  39. AVBufferRef *vaframes_ref;
  40. AVCodec * vaapi;
  41. AVCodecContext *context;
  42. AVFrame *vframe;
  43. DARRAY(uint8_t) buffer;
  44. uint8_t *header;
  45. size_t header_size;
  46. uint8_t *sei;
  47. size_t sei_size;
  48. int height;
  49. bool first_packet;
  50. bool initialized;
  51. };
  52. static const char *vaapi_getname(void *unused)
  53. {
  54. UNUSED_PARAMETER(unused);
  55. return "FFMPEG VAAPI";
  56. }
  57. static inline bool valid_format(enum video_format format)
  58. {
  59. return format == VIDEO_FORMAT_NV12;
  60. }
  61. static void vaapi_video_info(void *data, struct video_scale_info *info)
  62. {
  63. struct vaapi_encoder *enc = data;
  64. enum video_format pref_format;
  65. pref_format = obs_encoder_get_preferred_video_format(enc->encoder);
  66. if (!valid_format(pref_format)) {
  67. pref_format = valid_format(info->format) ? info->format
  68. : VIDEO_FORMAT_NV12;
  69. }
  70. info->format = pref_format;
  71. }
  72. static bool vaapi_init_codec(struct vaapi_encoder *enc, const char *path)
  73. {
  74. int ret;
  75. ret = av_hwdevice_ctx_create(&enc->vadevice_ref, AV_HWDEVICE_TYPE_VAAPI,
  76. path, NULL, 0);
  77. if (ret < 0) {
  78. warn("Failed to create VAAPI device context: %s",
  79. av_err2str(ret));
  80. return false;
  81. }
  82. enc->vaframes_ref = av_hwframe_ctx_alloc(enc->vadevice_ref);
  83. if (!enc->vaframes_ref) {
  84. warn("Failed to alloc HW frames context");
  85. return false;
  86. }
  87. AVHWFramesContext *frames_ctx =
  88. (AVHWFramesContext *)enc->vaframes_ref->data;
  89. frames_ctx->format = AV_PIX_FMT_VAAPI;
  90. frames_ctx->sw_format = AV_PIX_FMT_NV12;
  91. frames_ctx->width = enc->context->width;
  92. frames_ctx->height = enc->context->height;
  93. frames_ctx->initial_pool_size = 20;
  94. ret = av_hwframe_ctx_init(enc->vaframes_ref);
  95. if (ret < 0) {
  96. warn("Failed to init HW frames context: %s", av_err2str(ret));
  97. return false;
  98. }
  99. /* 2. Create software frame and picture */
  100. enc->vframe = av_frame_alloc();
  101. if (!enc->vframe) {
  102. warn("Failed to allocate video frame");
  103. return false;
  104. }
  105. enc->vframe->format = enc->context->pix_fmt;
  106. enc->vframe->width = enc->context->width;
  107. enc->vframe->height = enc->context->height;
  108. enc->vframe->colorspace = enc->context->colorspace;
  109. enc->vframe->color_range = enc->context->color_range;
  110. ret = av_frame_get_buffer(enc->vframe, base_get_alignment());
  111. if (ret < 0) {
  112. warn("Failed to allocate vframe: %s", av_err2str(ret));
  113. return false;
  114. }
  115. /* 3. set up codec */
  116. enc->context->pix_fmt = AV_PIX_FMT_VAAPI;
  117. enc->context->hw_frames_ctx = av_buffer_ref(enc->vaframes_ref);
  118. ret = avcodec_open2(enc->context, enc->vaapi, NULL);
  119. if (ret < 0) {
  120. warn("Failed to open VAAPI codec: %s", av_err2str(ret));
  121. return false;
  122. }
  123. enc->initialized = true;
  124. return true;
  125. }
  126. static bool vaapi_update(void *data, obs_data_t *settings)
  127. {
  128. struct vaapi_encoder *enc = data;
  129. const char *device = obs_data_get_string(settings, "vaapi_device");
  130. int profile = (int)obs_data_get_int(settings, "profile");
  131. int bf = (int)obs_data_get_int(settings, "bf");
  132. int level = (int)obs_data_get_int(settings, "level");
  133. int bitrate = (int)obs_data_get_int(settings, "bitrate");
  134. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  135. int qp = (int)obs_data_get_int(settings, "qp");
  136. int quality = (int)obs_data_get_int(settings, "quality");
  137. av_opt_set_int(enc->context->priv_data, "qp", qp, 0);
  138. av_opt_set_int(enc->context->priv_data, "quality", quality, 0);
  139. video_t * video = obs_encoder_video(enc->encoder);
  140. const struct video_output_info *voi = video_output_get_info(video);
  141. struct video_scale_info info;
  142. info.format = voi->format;
  143. info.colorspace = voi->colorspace;
  144. info.range = voi->range;
  145. vaapi_video_info(enc, &info);
  146. enc->context->profile = profile;
  147. enc->context->max_b_frames = bf;
  148. enc->context->level = level;
  149. enc->context->bit_rate = 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
  156. : AVCOL_SPC_BT470BG;
  157. enc->context->color_range = info.range == VIDEO_RANGE_FULL
  158. ? AVCOL_RANGE_JPEG
  159. : AVCOL_RANGE_MPEG;
  160. if (keyint_sec > 0) {
  161. enc->context->gop_size =
  162. keyint_sec * voi->fps_num / voi->fps_den;
  163. } else {
  164. enc->context->gop_size = 120;
  165. }
  166. enc->height = enc->context->height;
  167. info("settings:\n"
  168. "\tdevice: %s\n"
  169. "\tqp: %d\n"
  170. "\tquality: %d\n"
  171. "\tprofile: %d\n"
  172. "\tlevel: %d\n"
  173. "\tbitrate: %d\n"
  174. "\tkeyint: %d\n"
  175. "\twidth: %d\n"
  176. "\theight: %d\n"
  177. "\tb-frames: %d\n",
  178. device, qp, quality, profile, level, bitrate,
  179. enc->context->gop_size, enc->context->width,
  180. enc->context->height, enc->context->max_b_frames);
  181. return vaapi_init_codec(enc, device);
  182. }
  183. static void vaapi_destroy(void *data)
  184. {
  185. struct vaapi_encoder *enc = data;
  186. if (enc->initialized) {
  187. AVPacket pkt = {0};
  188. int r_pkt = 1;
  189. while (r_pkt) {
  190. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  191. if (avcodec_receive_packet(enc->context, &pkt) < 0)
  192. break;
  193. #else
  194. if (avcodec_encode_video2(enc->context, &pkt, NULL,
  195. &r_pkt) < 0)
  196. break;
  197. #endif
  198. if (r_pkt)
  199. av_packet_unref(&pkt);
  200. }
  201. }
  202. avcodec_close(enc->context);
  203. av_frame_unref(enc->vframe);
  204. av_frame_free(&enc->vframe);
  205. av_buffer_unref(&enc->vaframes_ref);
  206. av_buffer_unref(&enc->vadevice_ref);
  207. da_free(enc->buffer);
  208. bfree(enc->header);
  209. bfree(enc->sei);
  210. bfree(enc);
  211. }
  212. static void *vaapi_create(obs_data_t *settings, obs_encoder_t *encoder)
  213. {
  214. struct vaapi_encoder *enc;
  215. avcodec_register_all();
  216. enc = bzalloc(sizeof(*enc));
  217. enc->encoder = encoder;
  218. int vaapi_codec = (int)obs_data_get_int(settings, "vaapi_codec");
  219. if (vaapi_codec == AV_CODEC_ID_H264) {
  220. enc->vaapi = avcodec_find_encoder_by_name("h264_vaapi");
  221. }
  222. enc->first_packet = true;
  223. blog(LOG_INFO, "---------------------------------");
  224. if (!enc->vaapi) {
  225. warn("Couldn't find encoder");
  226. goto fail;
  227. }
  228. enc->context = avcodec_alloc_context3(enc->vaapi);
  229. if (!enc->context) {
  230. warn("Failed to create codec context");
  231. goto fail;
  232. }
  233. if (!vaapi_update(enc, settings))
  234. goto fail;
  235. return enc;
  236. fail:
  237. vaapi_destroy(enc);
  238. return NULL;
  239. }
  240. static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame,
  241. int height, enum AVPixelFormat format)
  242. {
  243. int h_chroma_shift, v_chroma_shift;
  244. av_pix_fmt_get_chroma_sub_sample(
  245. format, &h_chroma_shift, &v_chroma_shift);
  246. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  247. if (!frame->data[plane])
  248. continue;
  249. int frame_rowsize = (int)frame->linesize[plane];
  250. int pic_rowsize = pic->linesize[plane];
  251. int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
  252. : pic_rowsize;
  253. int plane_height = height >> (plane ? v_chroma_shift : 0);
  254. for (int y = 0; y < plane_height; y++) {
  255. int pos_frame = y * frame_rowsize;
  256. int pos_pic = y * pic_rowsize;
  257. memcpy(pic->data[plane] + pos_pic,
  258. frame->data[plane] + pos_frame, bytes);
  259. }
  260. }
  261. }
  262. static bool vaapi_encode(void *data, struct encoder_frame *frame,
  263. struct encoder_packet *packet, bool *received_packet)
  264. {
  265. struct vaapi_encoder *enc = data;
  266. AVFrame * hwframe = NULL;
  267. AVPacket av_pkt;
  268. int got_packet;
  269. int ret;
  270. hwframe = av_frame_alloc();
  271. if (!hwframe) {
  272. warn("vaapi_encode: failed to allocate hw frame");
  273. return false;
  274. }
  275. ret = av_hwframe_get_buffer(enc->vaframes_ref, hwframe, 0);
  276. if (ret < 0) {
  277. warn("vaapi_encode: failed to get buffer for hw frame: %s",
  278. av_err2str(ret));
  279. goto fail;
  280. }
  281. copy_data(enc->vframe, frame, enc->height, enc->context->pix_fmt);
  282. enc->vframe->pts = frame->pts;
  283. hwframe->pts = frame->pts;
  284. hwframe->width = enc->vframe->width;
  285. hwframe->height = enc->vframe->height;
  286. ret = av_hwframe_transfer_data(hwframe, enc->vframe, 0);
  287. if (ret < 0) {
  288. warn("vaapi_encode: failed to upload hw frame: %s",
  289. av_err2str(ret));
  290. goto fail;
  291. }
  292. ret = av_frame_copy_props(hwframe, enc->vframe);
  293. if (ret < 0) {
  294. warn("vaapi_encode: failed to copy props to hw frame: %s",
  295. av_err2str(ret));
  296. goto fail;
  297. }
  298. av_init_packet(&av_pkt);
  299. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  300. ret = avcodec_send_frame(enc->context, hwframe);
  301. if (ret == 0)
  302. ret = avcodec_receive_packet(enc->context, &av_pkt);
  303. got_packet = (ret == 0);
  304. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  305. ret = 0;
  306. #else
  307. ret = avcodec_encode_video2(
  308. enc->context, &av_pkt, hwframe, &got_packet);
  309. #endif
  310. if (ret < 0) {
  311. warn("vaapi_encode: Error encoding: %s", av_err2str(ret));
  312. goto fail;
  313. }
  314. if (got_packet && av_pkt.size) {
  315. if (enc->first_packet) {
  316. uint8_t *new_packet;
  317. size_t size;
  318. enc->first_packet = false;
  319. obs_extract_avc_headers(av_pkt.data, av_pkt.size,
  320. &new_packet, &size, &enc->header,
  321. &enc->header_size, &enc->sei,
  322. &enc->sei_size);
  323. da_copy_array(enc->buffer, new_packet, size);
  324. bfree(new_packet);
  325. } else {
  326. da_copy_array(enc->buffer, av_pkt.data, av_pkt.size);
  327. }
  328. packet->pts = av_pkt.pts;
  329. packet->dts = av_pkt.dts;
  330. packet->data = enc->buffer.array;
  331. packet->size = enc->buffer.num;
  332. packet->type = OBS_ENCODER_VIDEO;
  333. packet->keyframe = obs_avc_keyframe(packet->data, packet->size);
  334. *received_packet = true;
  335. } else {
  336. *received_packet = false;
  337. }
  338. av_packet_unref(&av_pkt);
  339. av_frame_free(&hwframe);
  340. return true;
  341. fail:
  342. av_frame_free(&hwframe);
  343. return false;
  344. }
  345. static void set_visible(obs_properties_t *ppts, const char *name, bool visible)
  346. {
  347. obs_property_t *p = obs_properties_get(ppts, name);
  348. obs_property_set_visible(p, visible);
  349. }
  350. static void vaapi_defaults(obs_data_t *settings)
  351. {
  352. obs_data_set_default_string(
  353. settings, "vaapi_device", "/dev/dri/renderD128");
  354. obs_data_set_default_int(settings, "vaapi_codec", AV_CODEC_ID_H264);
  355. obs_data_set_default_int(settings, "profile",
  356. FF_PROFILE_H264_CONSTRAINED_BASELINE);
  357. obs_data_set_default_int(settings, "level", 40);
  358. obs_data_set_default_int(settings, "bitrate", 2500);
  359. obs_data_set_default_int(settings, "keyint_sec", 0);
  360. obs_data_set_default_int(settings, "bf", 0);
  361. obs_data_set_default_int(settings, "qp", 20);
  362. obs_data_set_default_int(settings, "quality", 0);
  363. obs_data_set_default_int(settings, "rendermode", 0);
  364. }
  365. static obs_properties_t *vaapi_properties(void *unused)
  366. {
  367. UNUSED_PARAMETER(unused);
  368. obs_properties_t *props = obs_properties_create();
  369. obs_property_t * list;
  370. list = obs_properties_add_list(props, "vaapi_device", "VAAPI Device",
  371. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  372. char path[32] = "/dev/dri/renderD1";
  373. for (int i = 28;; i++) {
  374. sprintf(path, "/dev/dri/renderD1%d", i);
  375. if (access(path, F_OK) == 0) {
  376. char card[128] = "Card: ";
  377. sprintf(card, "Card%d: %s", i - 28, path);
  378. obs_property_list_add_string(list, card, path);
  379. } else {
  380. break;
  381. }
  382. }
  383. list = obs_properties_add_list(props, "vaapi_codec", "VAAPI Codec",
  384. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  385. obs_property_list_add_int(list, "H.264 (default)", AV_CODEC_ID_H264);
  386. list = obs_properties_add_list(props, "level", "Level",
  387. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  388. obs_property_list_add_int(list, "480p30 (3.0)", 30);
  389. obs_property_list_add_int(list, "720p30/480p60 (3.1)", 31);
  390. obs_property_list_add_int(
  391. list, "Compatibility mode (4.0 default)", 40);
  392. obs_property_list_add_int(list, "720p60/1080p30 (4.1)", 41);
  393. obs_property_list_add_int(list, "1080p60 (4.2)", 42);
  394. obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 0,
  395. 300000, 50);
  396. obs_properties_add_int(props, "keyint_sec",
  397. obs_module_text("Keyframe Interval (seconds)"), 0, 20,
  398. 1);
  399. return props;
  400. }
  401. static bool vaapi_extra_data(void *data, uint8_t **extra_data, size_t *size)
  402. {
  403. struct vaapi_encoder *enc = data;
  404. *extra_data = enc->header;
  405. *size = enc->header_size;
  406. return true;
  407. }
  408. static bool vaapi_sei_data(void *data, uint8_t **extra_data, size_t *size)
  409. {
  410. struct vaapi_encoder *enc = data;
  411. *extra_data = enc->sei;
  412. *size = enc->sei_size;
  413. return true;
  414. }
  415. struct obs_encoder_info vaapi_encoder_info = {
  416. .id = "ffmpeg_vaapi",
  417. .type = OBS_ENCODER_VIDEO,
  418. .codec = "h264",
  419. .get_name = vaapi_getname,
  420. .create = vaapi_create,
  421. .destroy = vaapi_destroy,
  422. .encode = vaapi_encode,
  423. .get_defaults = vaapi_defaults,
  424. .get_properties = vaapi_properties,
  425. .get_extra_data = vaapi_extra_data,
  426. .get_sei_data = vaapi_sei_data,
  427. .get_video_info = vaapi_video_info
  428. };
  429. #endif