1
0

obs-ffmpeg-vaapi.c 27 KB

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