obs-ffmpeg-vaapi.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 <util/platform.h>
  20. #include <media-io/video-io.h>
  21. #include <obs-module.h>
  22. #include <obs-avc.h>
  23. #ifdef ENABLE_HEVC
  24. #include <obs-hevc.h>
  25. #endif
  26. #include <opts-parser.h>
  27. #include <unistd.h>
  28. #include <libavutil/opt.h>
  29. #include <libavutil/pixdesc.h>
  30. #include <libavutil/hwcontext.h>
  31. #include <libavcodec/avcodec.h>
  32. #include <libavformat/avformat.h>
  33. #include <libavfilter/avfilter.h>
  34. #include <pci/pci.h>
  35. #include "vaapi-utils.h"
  36. #include "obs-ffmpeg-formats.h"
  37. #define do_log(level, format, ...) \
  38. blog(level, "[FFmpeg VAAPI encoder: '%s'] " format, \
  39. obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
  40. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  41. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  42. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  43. struct vaapi_encoder {
  44. obs_encoder_t *encoder;
  45. AVBufferRef *vadevice_ref;
  46. AVBufferRef *vaframes_ref;
  47. const AVCodec *vaapi;
  48. AVCodecContext *context;
  49. AVPacket *packet;
  50. AVFrame *vframe;
  51. DARRAY(uint8_t) buffer;
  52. uint8_t *header;
  53. size_t header_size;
  54. uint8_t *sei;
  55. size_t sei_size;
  56. int height;
  57. bool first_packet;
  58. bool initialized;
  59. };
  60. static const char *h264_vaapi_getname(void *unused)
  61. {
  62. UNUSED_PARAMETER(unused);
  63. return "FFmpeg VAAPI H.264";
  64. }
  65. #ifdef ENABLE_HEVC
  66. static const char *hevc_vaapi_getname(void *unused)
  67. {
  68. UNUSED_PARAMETER(unused);
  69. return "FFmpeg VAAPI HEVC";
  70. }
  71. #endif
  72. static inline bool h264_valid_format(enum video_format format)
  73. {
  74. return format == VIDEO_FORMAT_NV12;
  75. }
  76. #ifdef ENABLE_HEVC
  77. static inline bool hevc_valid_format(enum video_format format)
  78. {
  79. return (format == VIDEO_FORMAT_NV12) || (format == VIDEO_FORMAT_P010);
  80. }
  81. #endif
  82. static void h264_vaapi_video_info(void *data, struct video_scale_info *info)
  83. {
  84. struct vaapi_encoder *enc = data;
  85. enum video_format pref_format;
  86. pref_format = obs_encoder_get_preferred_video_format(enc->encoder);
  87. if (!h264_valid_format(pref_format)) {
  88. pref_format = h264_valid_format(info->format)
  89. ? info->format
  90. : VIDEO_FORMAT_NV12;
  91. }
  92. info->format = pref_format;
  93. }
  94. #ifdef ENABLE_HEVC
  95. static void hevc_vaapi_video_info(void *data, struct video_scale_info *info)
  96. {
  97. struct vaapi_encoder *enc = data;
  98. enum video_format pref_format;
  99. pref_format = obs_encoder_get_preferred_video_format(enc->encoder);
  100. if (!hevc_valid_format(pref_format)) {
  101. pref_format = hevc_valid_format(info->format)
  102. ? info->format
  103. : VIDEO_FORMAT_NV12;
  104. }
  105. info->format = pref_format;
  106. }
  107. #endif
  108. static bool vaapi_init_codec(struct vaapi_encoder *enc, const char *path)
  109. {
  110. int ret;
  111. ret = av_hwdevice_ctx_create(&enc->vadevice_ref, AV_HWDEVICE_TYPE_VAAPI,
  112. path, NULL, 0);
  113. if (ret < 0) {
  114. warn("Failed to create VAAPI device context: %s",
  115. av_err2str(ret));
  116. return false;
  117. }
  118. enc->vaframes_ref = av_hwframe_ctx_alloc(enc->vadevice_ref);
  119. if (!enc->vaframes_ref) {
  120. warn("Failed to alloc HW frames context");
  121. return false;
  122. }
  123. AVHWFramesContext *frames_ctx =
  124. (AVHWFramesContext *)enc->vaframes_ref->data;
  125. frames_ctx->format = AV_PIX_FMT_VAAPI;
  126. frames_ctx->sw_format = enc->context->pix_fmt;
  127. frames_ctx->width = enc->context->width;
  128. frames_ctx->height = enc->context->height;
  129. frames_ctx->initial_pool_size = 20;
  130. ret = av_hwframe_ctx_init(enc->vaframes_ref);
  131. if (ret < 0) {
  132. warn("Failed to init HW frames context: %s", av_err2str(ret));
  133. return false;
  134. }
  135. /* 2. Create software frame and picture */
  136. enc->vframe = av_frame_alloc();
  137. if (!enc->vframe) {
  138. warn("Failed to allocate video frame");
  139. return false;
  140. }
  141. enc->vframe->format = enc->context->pix_fmt;
  142. enc->vframe->width = enc->context->width;
  143. enc->vframe->height = enc->context->height;
  144. enc->vframe->colorspace = enc->context->colorspace;
  145. enc->vframe->color_range = enc->context->color_range;
  146. enc->vframe->chroma_location = enc->context->chroma_sample_location;
  147. ret = av_frame_get_buffer(enc->vframe, base_get_alignment());
  148. if (ret < 0) {
  149. warn("Failed to allocate vframe: %s", av_err2str(ret));
  150. return false;
  151. }
  152. /* 3. set up codec */
  153. enc->context->pix_fmt = AV_PIX_FMT_VAAPI;
  154. enc->context->hw_frames_ctx = av_buffer_ref(enc->vaframes_ref);
  155. ret = avcodec_open2(enc->context, enc->vaapi, NULL);
  156. if (ret < 0) {
  157. warn("Failed to open VAAPI codec: %s", av_err2str(ret));
  158. return false;
  159. }
  160. enc->packet = av_packet_alloc();
  161. enc->initialized = true;
  162. return true;
  163. }
  164. /* "Allowed" options per Rate Control
  165. * See FFMPEG libavcodec/vaapi_encode.c (vaapi_encode_rc_modes)
  166. */
  167. typedef struct {
  168. const char *name;
  169. bool qp;
  170. bool bitrate;
  171. bool maxrate;
  172. } rc_mode_t;
  173. static const rc_mode_t *get_rc_mode(const char *name)
  174. {
  175. /* Set "allowed" options per Rate Control */
  176. static const rc_mode_t RC_MODES[] = {
  177. {.name = "CBR", .qp = false, .bitrate = true, .maxrate = false},
  178. {.name = "CQP", .qp = true, .bitrate = false, .maxrate = false},
  179. {.name = "VBR", .qp = false, .bitrate = true, .maxrate = true},
  180. {0}};
  181. const rc_mode_t *rc_mode = RC_MODES;
  182. while (!!rc_mode->name && strcmp(rc_mode->name, name) != 0)
  183. rc_mode++;
  184. return rc_mode ? rc_mode : RC_MODES;
  185. }
  186. static bool vaapi_update(void *data, obs_data_t *settings, bool hevc)
  187. {
  188. struct vaapi_encoder *enc = data;
  189. const char *device = obs_data_get_string(settings, "vaapi_device");
  190. const char *rate_control =
  191. obs_data_get_string(settings, "rate_control");
  192. const rc_mode_t *rc_mode = get_rc_mode(rate_control);
  193. bool cbr = strcmp(rc_mode->name, "CBR") == 0;
  194. int profile = (int)obs_data_get_int(settings, "profile");
  195. int bf = (int)obs_data_get_int(settings, "bf");
  196. int qp = rc_mode->qp ? (int)obs_data_get_int(settings, "qp") : 0;
  197. av_opt_set_int(enc->context->priv_data, "qp", qp, 0);
  198. int level = (int)obs_data_get_int(settings, "level");
  199. int bitrate = rc_mode->bitrate
  200. ? (int)obs_data_get_int(settings, "bitrate")
  201. : 0;
  202. int maxrate = rc_mode->maxrate
  203. ? (int)obs_data_get_int(settings, "maxrate")
  204. : 0;
  205. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  206. /* For Rate Control which allows maxrate, FFMPEG will give
  207. * an error if maxrate > bitrate. To prevent that set maxrate
  208. * to 0.
  209. * For CBR, maxrate = bitrate
  210. */
  211. if (cbr)
  212. maxrate = bitrate;
  213. else if (rc_mode->maxrate && maxrate && maxrate < bitrate)
  214. maxrate = 0;
  215. video_t *video = obs_encoder_video(enc->encoder);
  216. const struct video_output_info *voi = video_output_get_info(video);
  217. struct video_scale_info info;
  218. info.format = voi->format;
  219. info.colorspace = voi->colorspace;
  220. info.range = voi->range;
  221. #ifdef ENABLE_HEVC
  222. if (hevc) {
  223. if ((profile == FF_PROFILE_HEVC_MAIN) &&
  224. (info.format == VIDEO_FORMAT_P010)) {
  225. warn("Forcing Main10 for P010");
  226. profile = FF_PROFILE_HEVC_MAIN_10;
  227. }
  228. hevc_vaapi_video_info(enc, &info);
  229. } else
  230. #else
  231. UNUSED_PARAMETER(hevc);
  232. #endif
  233. {
  234. h264_vaapi_video_info(enc, &info);
  235. }
  236. enc->context->profile = profile;
  237. enc->context->max_b_frames = bf;
  238. enc->context->level = level;
  239. enc->context->bit_rate = bitrate * 1000;
  240. enc->context->rc_max_rate = maxrate * 1000;
  241. enc->context->width = obs_encoder_get_width(enc->encoder);
  242. enc->context->height = obs_encoder_get_height(enc->encoder);
  243. enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num};
  244. const enum AVPixelFormat pix_fmt =
  245. obs_to_ffmpeg_video_format(info.format);
  246. enc->context->pix_fmt = pix_fmt;
  247. enc->context->color_range = info.range == VIDEO_RANGE_FULL
  248. ? AVCOL_RANGE_JPEG
  249. : AVCOL_RANGE_MPEG;
  250. enum AVColorSpace colorspace = AVCOL_SPC_UNSPECIFIED;
  251. switch (info.colorspace) {
  252. case VIDEO_CS_601:
  253. enc->context->color_primaries = AVCOL_PRI_SMPTE170M;
  254. enc->context->color_trc = AVCOL_TRC_SMPTE170M;
  255. colorspace = AVCOL_SPC_SMPTE170M;
  256. break;
  257. case VIDEO_CS_DEFAULT:
  258. case VIDEO_CS_709:
  259. enc->context->color_primaries = AVCOL_PRI_BT709;
  260. enc->context->color_trc = AVCOL_TRC_BT709;
  261. colorspace = AVCOL_SPC_BT709;
  262. break;
  263. case VIDEO_CS_SRGB:
  264. enc->context->color_primaries = AVCOL_PRI_BT709;
  265. enc->context->color_trc = AVCOL_TRC_IEC61966_2_1;
  266. colorspace = AVCOL_SPC_BT709;
  267. break;
  268. case VIDEO_CS_2100_PQ:
  269. enc->context->color_primaries = AVCOL_PRI_BT2020;
  270. enc->context->color_trc = AVCOL_TRC_SMPTE2084;
  271. colorspace = AVCOL_SPC_BT2020_NCL;
  272. break;
  273. case VIDEO_CS_2100_HLG:
  274. enc->context->color_primaries = AVCOL_PRI_BT2020;
  275. enc->context->color_trc = AVCOL_TRC_ARIB_STD_B67;
  276. colorspace = AVCOL_SPC_BT2020_NCL;
  277. break;
  278. default:
  279. break;
  280. }
  281. enc->context->colorspace = colorspace;
  282. enc->context->chroma_sample_location =
  283. determine_chroma_location(pix_fmt, colorspace);
  284. if (keyint_sec > 0) {
  285. enc->context->gop_size =
  286. keyint_sec * voi->fps_num / voi->fps_den;
  287. } else {
  288. enc->context->gop_size = 120;
  289. }
  290. enc->height = enc->context->height;
  291. const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
  292. struct obs_options opts = obs_parse_options(ffmpeg_opts);
  293. for (size_t i = 0; i < opts.count; i++) {
  294. struct obs_option *opt = &opts.options[i];
  295. av_opt_set(enc->context->priv_data, opt->name, opt->value, 0);
  296. }
  297. obs_free_options(opts);
  298. info("settings:\n"
  299. "\tdevice: %s\n"
  300. "\trate_control: %s\n"
  301. "\tprofile: %d\n"
  302. "\tlevel: %d\n"
  303. "\tqp: %d\n"
  304. "\tbitrate: %d\n"
  305. "\tmaxrate: %d\n"
  306. "\tkeyint: %d\n"
  307. "\twidth: %d\n"
  308. "\theight: %d\n"
  309. "\tb-frames: %d\n"
  310. "\tffmpeg opts: %s\n",
  311. device, rate_control, profile, level, qp, bitrate, maxrate,
  312. enc->context->gop_size, enc->context->width, enc->context->height,
  313. enc->context->max_b_frames, ffmpeg_opts);
  314. return vaapi_init_codec(enc, device);
  315. }
  316. static inline void flush_remaining_packets(struct vaapi_encoder *enc)
  317. {
  318. int r_pkt = 1;
  319. while (r_pkt) {
  320. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  321. if (avcodec_receive_packet(enc->context, enc->packet) < 0)
  322. break;
  323. #else
  324. if (avcodec_encode_video2(enc->context, enc->packet, NULL,
  325. &r_pkt) < 0)
  326. break;
  327. #endif
  328. if (r_pkt)
  329. av_packet_unref(enc->packet);
  330. }
  331. }
  332. static void vaapi_destroy(void *data)
  333. {
  334. struct vaapi_encoder *enc = data;
  335. if (enc->initialized)
  336. flush_remaining_packets(enc);
  337. av_packet_free(&enc->packet);
  338. avcodec_free_context(&enc->context);
  339. av_frame_unref(enc->vframe);
  340. av_frame_free(&enc->vframe);
  341. av_buffer_unref(&enc->vaframes_ref);
  342. av_buffer_unref(&enc->vadevice_ref);
  343. da_free(enc->buffer);
  344. bfree(enc->header);
  345. bfree(enc->sei);
  346. bfree(enc);
  347. }
  348. static void *vaapi_create_internal(obs_data_t *settings, obs_encoder_t *encoder,
  349. bool hevc)
  350. {
  351. struct vaapi_encoder *enc;
  352. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  353. avcodec_register_all();
  354. #endif
  355. enc = bzalloc(sizeof(*enc));
  356. enc->encoder = encoder;
  357. const char *const name = hevc ? "hevc_vaapi" : "h264_vaapi";
  358. enc->vaapi = avcodec_find_encoder_by_name(name);
  359. enc->first_packet = true;
  360. blog(LOG_INFO, "---------------------------------");
  361. if (!enc->vaapi) {
  362. warn("Couldn't find encoder");
  363. goto fail;
  364. }
  365. enc->context = avcodec_alloc_context3(enc->vaapi);
  366. if (!enc->context) {
  367. warn("Failed to create codec context");
  368. goto fail;
  369. }
  370. if (!vaapi_update(enc, settings, hevc))
  371. goto fail;
  372. return enc;
  373. fail:
  374. vaapi_destroy(enc);
  375. return NULL;
  376. }
  377. static void *h264_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder)
  378. {
  379. return vaapi_create_internal(settings, encoder, false);
  380. }
  381. #ifdef ENABLE_HEVC
  382. static void *hevc_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder)
  383. {
  384. return vaapi_create_internal(settings, encoder, true);
  385. }
  386. #endif
  387. static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame,
  388. int height, enum AVPixelFormat format)
  389. {
  390. int h_chroma_shift, v_chroma_shift;
  391. av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift,
  392. &v_chroma_shift);
  393. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  394. if (!frame->data[plane])
  395. continue;
  396. int frame_rowsize = (int)frame->linesize[plane];
  397. int pic_rowsize = pic->linesize[plane];
  398. int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
  399. : pic_rowsize;
  400. int plane_height = height >> (plane ? v_chroma_shift : 0);
  401. for (int y = 0; y < plane_height; y++) {
  402. int pos_frame = y * frame_rowsize;
  403. int pos_pic = y * pic_rowsize;
  404. memcpy(pic->data[plane] + pos_pic,
  405. frame->data[plane] + pos_frame, bytes);
  406. }
  407. }
  408. }
  409. static bool vaapi_encode_internal(void *data, struct encoder_frame *frame,
  410. struct encoder_packet *packet,
  411. bool *received_packet, bool hevc)
  412. {
  413. struct vaapi_encoder *enc = data;
  414. AVFrame *hwframe = NULL;
  415. int got_packet;
  416. int ret;
  417. hwframe = av_frame_alloc();
  418. if (!hwframe) {
  419. warn("vaapi_encode: failed to allocate hw frame");
  420. return false;
  421. }
  422. ret = av_hwframe_get_buffer(enc->vaframes_ref, hwframe, 0);
  423. if (ret < 0) {
  424. warn("vaapi_encode: failed to get buffer for hw frame: %s",
  425. av_err2str(ret));
  426. goto fail;
  427. }
  428. copy_data(enc->vframe, frame, enc->height, enc->context->pix_fmt);
  429. enc->vframe->pts = frame->pts;
  430. hwframe->pts = frame->pts;
  431. hwframe->width = enc->vframe->width;
  432. hwframe->height = enc->vframe->height;
  433. ret = av_hwframe_transfer_data(hwframe, enc->vframe, 0);
  434. if (ret < 0) {
  435. warn("vaapi_encode: failed to upload hw frame: %s",
  436. av_err2str(ret));
  437. goto fail;
  438. }
  439. ret = av_frame_copy_props(hwframe, enc->vframe);
  440. if (ret < 0) {
  441. warn("vaapi_encode: failed to copy props to hw frame: %s",
  442. av_err2str(ret));
  443. goto fail;
  444. }
  445. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  446. ret = avcodec_send_frame(enc->context, hwframe);
  447. if (ret == 0)
  448. ret = avcodec_receive_packet(enc->context, enc->packet);
  449. got_packet = (ret == 0);
  450. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  451. ret = 0;
  452. #else
  453. ret = avcodec_encode_video2(enc->context, enc->packet, hwframe,
  454. &got_packet);
  455. #endif
  456. if (ret < 0) {
  457. warn("vaapi_encode: Error encoding: %s", av_err2str(ret));
  458. goto fail;
  459. }
  460. if (got_packet && enc->packet->size) {
  461. if (enc->first_packet) {
  462. uint8_t *new_packet;
  463. size_t size;
  464. enc->first_packet = false;
  465. #ifdef ENABLE_HEVC
  466. if (hevc) {
  467. obs_extract_hevc_headers(
  468. enc->packet->data, enc->packet->size,
  469. &new_packet, &size, &enc->header,
  470. &enc->header_size, &enc->sei,
  471. &enc->sei_size);
  472. } else
  473. #else
  474. UNUSED_PARAMETER(hevc);
  475. #endif
  476. {
  477. obs_extract_avc_headers(
  478. enc->packet->data, enc->packet->size,
  479. &new_packet, &size, &enc->header,
  480. &enc->header_size, &enc->sei,
  481. &enc->sei_size);
  482. }
  483. da_copy_array(enc->buffer, new_packet, size);
  484. bfree(new_packet);
  485. } else {
  486. da_copy_array(enc->buffer, enc->packet->data,
  487. enc->packet->size);
  488. }
  489. packet->pts = enc->packet->pts;
  490. packet->dts = enc->packet->dts;
  491. packet->data = enc->buffer.array;
  492. packet->size = enc->buffer.num;
  493. packet->type = OBS_ENCODER_VIDEO;
  494. #ifdef ENABLE_HEVC
  495. if (hevc) {
  496. packet->keyframe =
  497. obs_hevc_keyframe(packet->data, packet->size);
  498. } else
  499. #endif
  500. {
  501. packet->keyframe =
  502. obs_avc_keyframe(packet->data, packet->size);
  503. }
  504. *received_packet = true;
  505. } else {
  506. *received_packet = false;
  507. }
  508. av_packet_unref(enc->packet);
  509. av_frame_free(&hwframe);
  510. return true;
  511. fail:
  512. av_frame_free(&hwframe);
  513. return false;
  514. }
  515. static bool h264_vaapi_encode(void *data, struct encoder_frame *frame,
  516. struct encoder_packet *packet,
  517. bool *received_packet)
  518. {
  519. return vaapi_encode_internal(data, frame, packet, received_packet,
  520. false);
  521. }
  522. #ifdef ENABLE_HEVC
  523. static bool hevc_vaapi_encode(void *data, struct encoder_frame *frame,
  524. struct encoder_packet *packet,
  525. bool *received_packet)
  526. {
  527. return vaapi_encode_internal(data, frame, packet, received_packet,
  528. true);
  529. }
  530. #endif
  531. static void set_visible(obs_properties_t *ppts, const char *name, bool visible)
  532. {
  533. obs_property_t *p = obs_properties_get(ppts, name);
  534. obs_property_set_visible(p, visible);
  535. }
  536. static void vaapi_defaults_internal(obs_data_t *settings, bool hevc)
  537. {
  538. #ifdef ENABLE_HEVC
  539. const char *device = hevc ? vaapi_get_hevc_default_device()
  540. : vaapi_get_h264_default_device();
  541. #else
  542. const char *const device = vaapi_get_h264_default_device();
  543. #endif
  544. obs_data_set_default_string(settings, "vaapi_device", device);
  545. #ifdef ENABLE_HEVC
  546. if (hevc) {
  547. obs_data_set_default_int(settings, "profile",
  548. FF_PROFILE_HEVC_MAIN);
  549. } else
  550. #else
  551. UNUSED_PARAMETER(hevc);
  552. #endif
  553. {
  554. obs_data_set_default_int(settings, "profile",
  555. FF_PROFILE_H264_CONSTRAINED_BASELINE);
  556. }
  557. obs_data_set_default_int(settings, "level", 40);
  558. obs_data_set_default_int(settings, "bitrate", 2500);
  559. obs_data_set_default_int(settings, "keyint_sec", 0);
  560. obs_data_set_default_int(settings, "bf", 0);
  561. obs_data_set_default_int(settings, "rendermode", 0);
  562. obs_data_set_default_int(settings, "qp", 20);
  563. obs_data_set_default_int(settings, "maxrate", 0);
  564. int drm_fd = -1;
  565. VADisplay va_dpy = vaapi_open_device(&drm_fd, device, "vaapi_defaults");
  566. if (!va_dpy)
  567. return;
  568. #ifdef ENABLE_HEVC
  569. const VAProfile profile = hevc ? VAProfileHEVCMain
  570. : VAProfileH264ConstrainedBaseline;
  571. #else
  572. const VAProfile profile = VAProfileH264ConstrainedBaseline;
  573. #endif
  574. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CBR, device))
  575. obs_data_set_default_string(settings, "rate_control", "CBR");
  576. else if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_VBR, device))
  577. obs_data_set_default_string(settings, "rate_control", "VBR");
  578. else
  579. obs_data_set_default_string(settings, "rate_control", "CQP");
  580. vaapi_close_device(&drm_fd, va_dpy);
  581. }
  582. static void h264_vaapi_defaults(obs_data_t *settings)
  583. {
  584. vaapi_defaults_internal(settings, false);
  585. }
  586. static void hevc_vaapi_defaults(obs_data_t *settings)
  587. {
  588. vaapi_defaults_internal(settings, true);
  589. }
  590. static bool vaapi_device_modified(obs_properties_t *ppts, obs_property_t *p,
  591. obs_data_t *settings)
  592. {
  593. UNUSED_PARAMETER(p);
  594. const char *device = obs_data_get_string(settings, "vaapi_device");
  595. int drm_fd = -1;
  596. VADisplay va_dpy =
  597. vaapi_open_device(&drm_fd, device, "vaapi_device_modified");
  598. int profile = obs_data_get_int(settings, "profile");
  599. obs_property_t *rc_p = obs_properties_get(ppts, "rate_control");
  600. obs_property_list_clear(rc_p);
  601. if (!va_dpy)
  602. goto fail;
  603. switch (profile) {
  604. case FF_PROFILE_H264_CONSTRAINED_BASELINE:
  605. if (!vaapi_display_h264_supported(va_dpy, device))
  606. goto fail;
  607. profile = VAProfileH264ConstrainedBaseline;
  608. break;
  609. case FF_PROFILE_H264_MAIN:
  610. if (!vaapi_display_h264_supported(va_dpy, device))
  611. goto fail;
  612. profile = VAProfileH264Main;
  613. break;
  614. case FF_PROFILE_H264_HIGH:
  615. if (!vaapi_display_h264_supported(va_dpy, device))
  616. goto fail;
  617. profile = VAProfileH264High;
  618. break;
  619. #ifdef ENABLE_HEVC
  620. case FF_PROFILE_HEVC_MAIN:
  621. if (!vaapi_display_hevc_supported(va_dpy, device))
  622. goto fail;
  623. profile = VAProfileHEVCMain;
  624. break;
  625. case FF_PROFILE_HEVC_MAIN_10:
  626. if (!vaapi_display_hevc_supported(va_dpy, device))
  627. goto fail;
  628. profile = VAProfileHEVCMain10;
  629. break;
  630. #endif
  631. }
  632. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CBR, device))
  633. obs_property_list_add_string(rc_p, "CBR (default)", "CBR");
  634. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_VBR, device))
  635. obs_property_list_add_string(rc_p, "VBR", "VBR");
  636. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CQP, device))
  637. obs_property_list_add_string(rc_p, "CQP", "CQP");
  638. fail:
  639. vaapi_close_device(&drm_fd, va_dpy);
  640. return true;
  641. }
  642. static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
  643. obs_data_t *settings)
  644. {
  645. UNUSED_PARAMETER(p);
  646. const char *rate_control =
  647. obs_data_get_string(settings, "rate_control");
  648. const rc_mode_t *rc_mode = get_rc_mode(rate_control);
  649. /* Set options visibility per Rate Control */
  650. set_visible(ppts, "qp", rc_mode->qp);
  651. set_visible(ppts, "bitrate", rc_mode->bitrate);
  652. set_visible(ppts, "maxrate", rc_mode->maxrate);
  653. return true;
  654. }
  655. static bool get_device_name_from_pci(struct pci_access *pacc, char *pci_slot,
  656. char *buf, int size)
  657. {
  658. struct pci_filter filter;
  659. struct pci_dev *dev;
  660. char *name;
  661. pci_filter_init(pacc, &filter);
  662. if (pci_filter_parse_slot(&filter, pci_slot))
  663. return false;
  664. pci_scan_bus(pacc);
  665. for (dev = pacc->devices; dev; dev = dev->next) {
  666. if (pci_filter_match(&filter, dev)) {
  667. pci_fill_info(dev, PCI_FILL_IDENT);
  668. name = pci_lookup_name(pacc, buf, size,
  669. PCI_LOOKUP_DEVICE,
  670. dev->vendor_id, dev->device_id);
  671. strcpy(buf, name);
  672. return true;
  673. }
  674. }
  675. return false;
  676. }
  677. static obs_properties_t *vaapi_properties_internal(bool hevc)
  678. {
  679. obs_properties_t *props = obs_properties_create();
  680. obs_property_t *list;
  681. list = obs_properties_add_list(props, "vaapi_device",
  682. obs_module_text("VAAPI.Device"),
  683. OBS_COMBO_TYPE_LIST,
  684. OBS_COMBO_FORMAT_STRING);
  685. if (os_file_exists("/dev/dri/by-path")) {
  686. os_dir_t *by_path_dir = os_opendir("/dev/dri/by-path");
  687. struct pci_access *pacc = pci_alloc();
  688. struct os_dirent *file;
  689. char namebuf[1024];
  690. char pci_slot[13];
  691. char *type;
  692. pci_init(pacc);
  693. while ((file = os_readdir(by_path_dir)) != NULL) {
  694. // file_name pattern: pci-<pci_slot::12>-<type::{"card","render"}>
  695. char *file_name = file->d_name;
  696. if (strcmp(file_name, ".") == 0 ||
  697. strcmp(file_name, "..") == 0)
  698. continue;
  699. char path[64] = {0};
  700. // Use the return value of snprintf to prevent truncation warning.
  701. int written = snprintf(path, 64, "/dev/dri/by-path/%s",
  702. file_name);
  703. if (written >= 64)
  704. blog(LOG_DEBUG,
  705. "obs-ffmpeg-vaapi: A format truncation may have occurred."
  706. " This can be ignored since it is quite improbable.");
  707. type = strrchr(file_name, '-');
  708. if (type == NULL)
  709. continue;
  710. else
  711. type++;
  712. if (strcmp(type, "render") == 0) {
  713. strncpy(pci_slot, file_name + 4, 12);
  714. pci_slot[12] = 0;
  715. bool name_found = get_device_name_from_pci(
  716. pacc, pci_slot, namebuf,
  717. sizeof(namebuf));
  718. if (!vaapi_device_h264_supported(path))
  719. continue;
  720. if (!name_found)
  721. obs_property_list_add_string(list, path,
  722. path);
  723. else
  724. obs_property_list_add_string(
  725. list, namebuf, path);
  726. }
  727. }
  728. pci_cleanup(pacc);
  729. os_closedir(by_path_dir);
  730. }
  731. if (obs_property_list_item_count(list) == 0) {
  732. char path[32];
  733. for (int i = 28;; i++) {
  734. snprintf(path, sizeof(path), "/dev/dri/renderD1%d", i);
  735. if (access(path, F_OK) == 0) {
  736. char card[128];
  737. int ret = snprintf(card, sizeof(card),
  738. "Card%d: %s", i - 28, path);
  739. if (ret >= (int)sizeof(card))
  740. blog(LOG_DEBUG,
  741. "obs-ffmpeg-vaapi: A format truncation may have occurred."
  742. " This can be ignored since it is quite improbable.");
  743. if (!vaapi_device_h264_supported(path))
  744. continue;
  745. obs_property_list_add_string(list, card, path);
  746. } else {
  747. break;
  748. }
  749. }
  750. }
  751. obs_property_set_modified_callback(list, vaapi_device_modified);
  752. list = obs_properties_add_list(props, "profile",
  753. obs_module_text("Profile"),
  754. OBS_COMBO_TYPE_LIST,
  755. OBS_COMBO_FORMAT_INT);
  756. if (hevc) {
  757. obs_property_list_add_int(list, "Main", FF_PROFILE_HEVC_MAIN);
  758. obs_property_list_add_int(list, "Main10",
  759. FF_PROFILE_HEVC_MAIN_10);
  760. } else {
  761. obs_property_list_add_int(list,
  762. "Constrained Baseline (default)",
  763. FF_PROFILE_H264_CONSTRAINED_BASELINE);
  764. obs_property_list_add_int(list, "Main", FF_PROFILE_H264_MAIN);
  765. obs_property_list_add_int(list, "High", FF_PROFILE_H264_HIGH);
  766. }
  767. obs_property_set_modified_callback(list, vaapi_device_modified);
  768. list = obs_properties_add_list(props, "level", obs_module_text("Level"),
  769. OBS_COMBO_TYPE_LIST,
  770. OBS_COMBO_FORMAT_INT);
  771. obs_property_list_add_int(list, "Auto", FF_LEVEL_UNKNOWN);
  772. obs_property_list_add_int(list, "3.0", 30);
  773. obs_property_list_add_int(list, "3.1", 31);
  774. obs_property_list_add_int(list, "4.0 (default) (Compatibility mode)",
  775. 40);
  776. obs_property_list_add_int(list, "4.1", 41);
  777. obs_property_list_add_int(list, "4.2", 42);
  778. obs_property_list_add_int(list, "5.0", 50);
  779. obs_property_list_add_int(list, "5.1", 51);
  780. obs_property_list_add_int(list, "5.2", 52);
  781. list = obs_properties_add_list(props, "rate_control",
  782. obs_module_text("RateControl"),
  783. OBS_COMBO_TYPE_LIST,
  784. OBS_COMBO_FORMAT_STRING);
  785. obs_property_set_modified_callback(list, rate_control_modified);
  786. obs_property_t *p;
  787. p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
  788. 0, 300000, 50);
  789. obs_property_int_set_suffix(p, " Kbps");
  790. p = obs_properties_add_int(
  791. props, "maxrate", obs_module_text("MaxBitrate"), 0, 300000, 50);
  792. obs_property_int_set_suffix(p, " Kbps");
  793. obs_properties_add_int(props, "qp", "QP", 0, 51, 1);
  794. p = obs_properties_add_int(props, "keyint_sec",
  795. obs_module_text("KeyframeIntervalSec"), 0,
  796. 20, 1);
  797. obs_property_int_set_suffix(p, " s");
  798. obs_properties_add_text(props, "ffmpeg_opts",
  799. obs_module_text("FFmpegOpts"),
  800. OBS_TEXT_DEFAULT);
  801. return props;
  802. }
  803. static obs_properties_t *h264_vaapi_properties(void *unused)
  804. {
  805. UNUSED_PARAMETER(unused);
  806. return vaapi_properties_internal(false);
  807. }
  808. #ifdef ENABLE_HEVC
  809. static obs_properties_t *hevc_vaapi_properties(void *unused)
  810. {
  811. UNUSED_PARAMETER(unused);
  812. return vaapi_properties_internal(true);
  813. }
  814. #endif
  815. static bool vaapi_extra_data(void *data, uint8_t **extra_data, size_t *size)
  816. {
  817. struct vaapi_encoder *enc = data;
  818. *extra_data = enc->header;
  819. *size = enc->header_size;
  820. return true;
  821. }
  822. static bool vaapi_sei_data(void *data, uint8_t **extra_data, size_t *size)
  823. {
  824. struct vaapi_encoder *enc = data;
  825. *extra_data = enc->sei;
  826. *size = enc->sei_size;
  827. return true;
  828. }
  829. struct obs_encoder_info h264_vaapi_encoder_info = {
  830. .id = "ffmpeg_vaapi",
  831. .type = OBS_ENCODER_VIDEO,
  832. .codec = "h264",
  833. .get_name = h264_vaapi_getname,
  834. .create = h264_vaapi_create,
  835. .destroy = vaapi_destroy,
  836. .encode = h264_vaapi_encode,
  837. .get_defaults = h264_vaapi_defaults,
  838. .get_properties = h264_vaapi_properties,
  839. .get_extra_data = vaapi_extra_data,
  840. .get_sei_data = vaapi_sei_data,
  841. .get_video_info = h264_vaapi_video_info,
  842. };
  843. #ifdef ENABLE_HEVC
  844. struct obs_encoder_info hevc_vaapi_encoder_info = {
  845. .id = "hevc_ffmpeg_vaapi",
  846. .type = OBS_ENCODER_VIDEO,
  847. .codec = "hevc",
  848. .get_name = hevc_vaapi_getname,
  849. .create = hevc_vaapi_create,
  850. .destroy = vaapi_destroy,
  851. .encode = hevc_vaapi_encode,
  852. .get_defaults = hevc_vaapi_defaults,
  853. .get_properties = hevc_vaapi_properties,
  854. .get_extra_data = vaapi_extra_data,
  855. .get_sei_data = vaapi_sei_data,
  856. .get_video_info = hevc_vaapi_video_info,
  857. };
  858. #endif
  859. #endif