1
0

obs-ffmpeg-vaapi.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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. #include <obs-av1.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. enum codec_type {
  44. CODEC_H264,
  45. CODEC_HEVC,
  46. CODEC_AV1,
  47. };
  48. struct vaapi_encoder {
  49. obs_encoder_t *encoder;
  50. enum codec_type codec;
  51. AVBufferRef *vadevice_ref;
  52. AVBufferRef *vaframes_ref;
  53. const AVCodec *vaapi;
  54. AVCodecContext *context;
  55. AVPacket *packet;
  56. AVFrame *vframe;
  57. DARRAY(uint8_t) buffer;
  58. uint8_t *header;
  59. size_t header_size;
  60. uint8_t *sei;
  61. size_t sei_size;
  62. int height;
  63. bool first_packet;
  64. bool initialized;
  65. };
  66. static const char *h264_vaapi_getname(void *unused)
  67. {
  68. UNUSED_PARAMETER(unused);
  69. return "FFmpeg VAAPI H.264";
  70. }
  71. static const char *av1_vaapi_getname(void *unused)
  72. {
  73. UNUSED_PARAMETER(unused);
  74. return "FFmpeg VAAPI AV1";
  75. }
  76. #ifdef ENABLE_HEVC
  77. static const char *hevc_vaapi_getname(void *unused)
  78. {
  79. UNUSED_PARAMETER(unused);
  80. return "FFmpeg VAAPI HEVC";
  81. }
  82. #endif
  83. static inline bool vaapi_valid_format(struct vaapi_encoder *enc,
  84. enum video_format format)
  85. {
  86. if (enc->codec == CODEC_H264) {
  87. return format == VIDEO_FORMAT_NV12;
  88. } else if (enc->codec == CODEC_HEVC || enc->codec == CODEC_AV1) {
  89. return (format == VIDEO_FORMAT_NV12) ||
  90. (format == VIDEO_FORMAT_P010);
  91. } else {
  92. return false;
  93. }
  94. }
  95. static void 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 (!vaapi_valid_format(enc, pref_format)) {
  101. pref_format = vaapi_valid_format(enc, info->format)
  102. ? info->format
  103. : VIDEO_FORMAT_NV12;
  104. }
  105. info->format = pref_format;
  106. }
  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)
  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. enc->context->global_quality = enc->codec == CODEC_AV1 ? qp * 5 : qp;
  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 (enc->codec == CODEC_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. }
  228. #endif
  229. vaapi_video_info(enc, &info);
  230. enc->context->profile = profile;
  231. enc->context->max_b_frames = bf;
  232. enc->context->level = level;
  233. enc->context->bit_rate = bitrate * 1000;
  234. enc->context->rc_max_rate = maxrate * 1000;
  235. enc->context->rc_initial_buffer_occupancy =
  236. (maxrate ? maxrate : bitrate) * 1000;
  237. enc->context->width = obs_encoder_get_width(enc->encoder);
  238. enc->context->height = obs_encoder_get_height(enc->encoder);
  239. enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num};
  240. const enum AVPixelFormat pix_fmt =
  241. obs_to_ffmpeg_video_format(info.format);
  242. enc->context->pix_fmt = pix_fmt;
  243. enc->context->color_range = info.range == VIDEO_RANGE_FULL
  244. ? AVCOL_RANGE_JPEG
  245. : AVCOL_RANGE_MPEG;
  246. enum AVColorSpace colorspace = AVCOL_SPC_UNSPECIFIED;
  247. switch (info.colorspace) {
  248. case VIDEO_CS_601:
  249. enc->context->color_primaries = AVCOL_PRI_SMPTE170M;
  250. enc->context->color_trc = AVCOL_TRC_SMPTE170M;
  251. colorspace = AVCOL_SPC_SMPTE170M;
  252. break;
  253. case VIDEO_CS_DEFAULT:
  254. case VIDEO_CS_709:
  255. enc->context->color_primaries = AVCOL_PRI_BT709;
  256. enc->context->color_trc = AVCOL_TRC_BT709;
  257. colorspace = AVCOL_SPC_BT709;
  258. break;
  259. case VIDEO_CS_SRGB:
  260. enc->context->color_primaries = AVCOL_PRI_BT709;
  261. enc->context->color_trc = AVCOL_TRC_IEC61966_2_1;
  262. colorspace = AVCOL_SPC_BT709;
  263. break;
  264. case VIDEO_CS_2100_PQ:
  265. enc->context->color_primaries = AVCOL_PRI_BT2020;
  266. enc->context->color_trc = AVCOL_TRC_SMPTE2084;
  267. colorspace = AVCOL_SPC_BT2020_NCL;
  268. break;
  269. case VIDEO_CS_2100_HLG:
  270. enc->context->color_primaries = AVCOL_PRI_BT2020;
  271. enc->context->color_trc = AVCOL_TRC_ARIB_STD_B67;
  272. colorspace = AVCOL_SPC_BT2020_NCL;
  273. break;
  274. default:
  275. break;
  276. }
  277. enc->context->colorspace = colorspace;
  278. enc->context->chroma_sample_location =
  279. determine_chroma_location(pix_fmt, colorspace);
  280. if (keyint_sec > 0) {
  281. enc->context->gop_size =
  282. keyint_sec * voi->fps_num / voi->fps_den;
  283. } else {
  284. enc->context->gop_size = 120;
  285. }
  286. enc->height = enc->context->height;
  287. const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts");
  288. struct obs_options opts = obs_parse_options(ffmpeg_opts);
  289. for (size_t i = 0; i < opts.count; i++) {
  290. struct obs_option *opt = &opts.options[i];
  291. av_opt_set(enc->context->priv_data, opt->name, opt->value, 0);
  292. }
  293. obs_free_options(opts);
  294. info("settings:\n"
  295. "\tdevice: %s\n"
  296. "\trate_control: %s\n"
  297. "\tprofile: %d\n"
  298. "\tlevel: %d\n"
  299. "\tqp: %d\n"
  300. "\tbitrate: %d\n"
  301. "\tmaxrate: %d\n"
  302. "\tkeyint: %d\n"
  303. "\twidth: %d\n"
  304. "\theight: %d\n"
  305. "\tb-frames: %d\n"
  306. "\tffmpeg opts: %s\n",
  307. device, rate_control, profile, level, qp, bitrate, maxrate,
  308. enc->context->gop_size, enc->context->width, enc->context->height,
  309. enc->context->max_b_frames, ffmpeg_opts);
  310. return vaapi_init_codec(enc, device);
  311. }
  312. static inline void flush_remaining_packets(struct vaapi_encoder *enc)
  313. {
  314. int r_pkt = 1;
  315. while (r_pkt) {
  316. if (avcodec_receive_packet(enc->context, enc->packet) < 0)
  317. break;
  318. if (r_pkt)
  319. av_packet_unref(enc->packet);
  320. }
  321. }
  322. static void vaapi_destroy(void *data)
  323. {
  324. struct vaapi_encoder *enc = data;
  325. if (enc->initialized)
  326. flush_remaining_packets(enc);
  327. av_packet_free(&enc->packet);
  328. avcodec_free_context(&enc->context);
  329. av_frame_unref(enc->vframe);
  330. av_frame_free(&enc->vframe);
  331. av_buffer_unref(&enc->vaframes_ref);
  332. av_buffer_unref(&enc->vadevice_ref);
  333. da_free(enc->buffer);
  334. bfree(enc->header);
  335. bfree(enc->sei);
  336. bfree(enc);
  337. }
  338. static inline const char *vaapi_encoder_name(enum codec_type codec)
  339. {
  340. if (codec == CODEC_H264) {
  341. return "h264_vaapi";
  342. } else if (codec == CODEC_HEVC) {
  343. return "hevc_vaapi";
  344. } else if (codec == CODEC_AV1) {
  345. return "av1_vaapi";
  346. }
  347. return NULL;
  348. }
  349. static void *vaapi_create_internal(obs_data_t *settings, obs_encoder_t *encoder,
  350. enum codec_type codec)
  351. {
  352. struct vaapi_encoder *enc;
  353. enc = bzalloc(sizeof(*enc));
  354. enc->encoder = encoder;
  355. enc->codec = codec;
  356. enc->vaapi = avcodec_find_encoder_by_name(vaapi_encoder_name(codec));
  357. enc->first_packet = true;
  358. blog(LOG_INFO, "---------------------------------");
  359. if (!enc->vaapi) {
  360. warn("Couldn't find encoder");
  361. goto fail;
  362. }
  363. enc->context = avcodec_alloc_context3(enc->vaapi);
  364. if (!enc->context) {
  365. warn("Failed to create codec context");
  366. goto fail;
  367. }
  368. if (!vaapi_update(enc, settings))
  369. goto fail;
  370. return enc;
  371. fail:
  372. vaapi_destroy(enc);
  373. return NULL;
  374. }
  375. static void *h264_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder)
  376. {
  377. return vaapi_create_internal(settings, encoder, CODEC_H264);
  378. }
  379. static void *av1_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder)
  380. {
  381. return vaapi_create_internal(settings, encoder, CODEC_AV1);
  382. }
  383. #ifdef ENABLE_HEVC
  384. static void *hevc_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder)
  385. {
  386. return vaapi_create_internal(settings, encoder, CODEC_HEVC);
  387. }
  388. #endif
  389. static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame,
  390. int height, enum AVPixelFormat format)
  391. {
  392. int h_chroma_shift, v_chroma_shift;
  393. av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift,
  394. &v_chroma_shift);
  395. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  396. if (!frame->data[plane])
  397. continue;
  398. int frame_rowsize = (int)frame->linesize[plane];
  399. int pic_rowsize = pic->linesize[plane];
  400. int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
  401. : pic_rowsize;
  402. int plane_height = height >> (plane ? v_chroma_shift : 0);
  403. for (int y = 0; y < plane_height; y++) {
  404. int pos_frame = y * frame_rowsize;
  405. int pos_pic = y * pic_rowsize;
  406. memcpy(pic->data[plane] + pos_pic,
  407. frame->data[plane] + pos_frame, bytes);
  408. }
  409. }
  410. }
  411. static bool vaapi_encode(void *data, struct encoder_frame *frame,
  412. struct encoder_packet *packet, bool *received_packet)
  413. {
  414. struct vaapi_encoder *enc = data;
  415. AVFrame *hwframe = NULL;
  416. int got_packet;
  417. int ret;
  418. hwframe = av_frame_alloc();
  419. if (!hwframe) {
  420. warn("vaapi_encode: failed to allocate hw frame");
  421. return false;
  422. }
  423. ret = av_hwframe_get_buffer(enc->vaframes_ref, hwframe, 0);
  424. if (ret < 0) {
  425. warn("vaapi_encode: failed to get buffer for hw frame: %s",
  426. av_err2str(ret));
  427. goto fail;
  428. }
  429. copy_data(enc->vframe, frame, enc->height, enc->context->pix_fmt);
  430. enc->vframe->pts = frame->pts;
  431. hwframe->pts = frame->pts;
  432. hwframe->width = enc->vframe->width;
  433. hwframe->height = enc->vframe->height;
  434. ret = av_hwframe_transfer_data(hwframe, enc->vframe, 0);
  435. if (ret < 0) {
  436. warn("vaapi_encode: failed to upload hw frame: %s",
  437. av_err2str(ret));
  438. goto fail;
  439. }
  440. ret = av_frame_copy_props(hwframe, enc->vframe);
  441. if (ret < 0) {
  442. warn("vaapi_encode: failed to copy props to hw frame: %s",
  443. av_err2str(ret));
  444. goto fail;
  445. }
  446. ret = avcodec_send_frame(enc->context, hwframe);
  447. if (ret == 0 || ret == AVERROR(EAGAIN))
  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. if (ret < 0) {
  453. warn("vaapi_encode: Error encoding: %s", av_err2str(ret));
  454. goto fail;
  455. }
  456. if (got_packet && enc->packet->size) {
  457. if (enc->first_packet) {
  458. uint8_t *new_packet;
  459. size_t size;
  460. enc->first_packet = false;
  461. #ifdef ENABLE_HEVC
  462. if (enc->codec == CODEC_HEVC) {
  463. obs_extract_hevc_headers(
  464. enc->packet->data, enc->packet->size,
  465. &new_packet, &size, &enc->header,
  466. &enc->header_size, &enc->sei,
  467. &enc->sei_size);
  468. } else
  469. #endif
  470. if (enc->codec == CODEC_H264) {
  471. obs_extract_avc_headers(
  472. enc->packet->data, enc->packet->size,
  473. &new_packet, &size, &enc->header,
  474. &enc->header_size, &enc->sei,
  475. &enc->sei_size);
  476. } else if (enc->codec == CODEC_AV1) {
  477. obs_extract_av1_headers(enc->packet->data,
  478. enc->packet->size,
  479. &new_packet, &size,
  480. &enc->header,
  481. &enc->header_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 (enc->codec == CODEC_HEVC) {
  496. packet->keyframe =
  497. obs_hevc_keyframe(packet->data, packet->size);
  498. } else
  499. #endif
  500. if (enc->codec == CODEC_H264) {
  501. packet->keyframe =
  502. obs_avc_keyframe(packet->data, packet->size);
  503. } else if (enc->codec == CODEC_AV1) {
  504. packet->keyframe =
  505. obs_av1_keyframe(packet->data, packet->size);
  506. }
  507. *received_packet = true;
  508. } else {
  509. *received_packet = false;
  510. }
  511. av_packet_unref(enc->packet);
  512. av_frame_free(&hwframe);
  513. return true;
  514. fail:
  515. av_frame_free(&hwframe);
  516. return false;
  517. }
  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 inline VAProfile vaapi_profile(enum codec_type codec)
  524. {
  525. if (codec == CODEC_H264) {
  526. return VAProfileH264ConstrainedBaseline;
  527. } else if (codec == CODEC_AV1) {
  528. return VAProfileAV1Profile0;
  529. #if ENABLE_HEVC
  530. } else if (codec == CODEC_HEVC) {
  531. return VAProfileHEVCMain;
  532. #endif
  533. }
  534. return VAProfileNone;
  535. }
  536. static inline const char *vaapi_default_device(enum codec_type codec)
  537. {
  538. if (codec == CODEC_H264) {
  539. return vaapi_get_h264_default_device();
  540. } else if (codec == CODEC_AV1) {
  541. return vaapi_get_av1_default_device();
  542. #if ENABLE_HEVC
  543. } else if (codec == CODEC_HEVC) {
  544. return vaapi_get_hevc_default_device();
  545. #endif
  546. }
  547. return NULL;
  548. }
  549. static void vaapi_defaults_internal(obs_data_t *settings, enum codec_type codec)
  550. {
  551. const char *const device = vaapi_default_device(codec);
  552. obs_data_set_default_string(settings, "vaapi_device", device);
  553. #ifdef ENABLE_HEVC
  554. if (codec == CODEC_HEVC)
  555. obs_data_set_default_int(settings, "profile",
  556. FF_PROFILE_HEVC_MAIN);
  557. else
  558. #endif
  559. if (codec == CODEC_H264)
  560. obs_data_set_default_int(settings, "profile",
  561. FF_PROFILE_H264_HIGH);
  562. else if (codec == CODEC_AV1)
  563. obs_data_set_default_int(settings, "profile",
  564. FF_PROFILE_AV1_MAIN);
  565. obs_data_set_default_int(settings, "level", FF_LEVEL_UNKNOWN);
  566. obs_data_set_default_int(settings, "bitrate", 2500);
  567. obs_data_set_default_int(settings, "keyint_sec", 0);
  568. obs_data_set_default_int(settings, "bf", 0);
  569. obs_data_set_default_int(settings, "qp", 20);
  570. obs_data_set_default_int(settings, "maxrate", 0);
  571. int drm_fd = -1;
  572. VADisplay va_dpy = vaapi_open_device(&drm_fd, device, "vaapi_defaults");
  573. if (!va_dpy)
  574. return;
  575. const VAProfile profile = vaapi_profile(codec);
  576. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CBR, device))
  577. obs_data_set_default_string(settings, "rate_control", "CBR");
  578. else if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_VBR, device))
  579. obs_data_set_default_string(settings, "rate_control", "VBR");
  580. else
  581. obs_data_set_default_string(settings, "rate_control", "CQP");
  582. vaapi_close_device(&drm_fd, va_dpy);
  583. }
  584. static void h264_vaapi_defaults(obs_data_t *settings)
  585. {
  586. vaapi_defaults_internal(settings, CODEC_H264);
  587. }
  588. static void av1_vaapi_defaults(obs_data_t *settings)
  589. {
  590. vaapi_defaults_internal(settings, CODEC_AV1);
  591. }
  592. static void hevc_vaapi_defaults(obs_data_t *settings)
  593. {
  594. vaapi_defaults_internal(settings, CODEC_HEVC);
  595. }
  596. static bool vaapi_device_modified(obs_properties_t *ppts, obs_property_t *p,
  597. obs_data_t *settings)
  598. {
  599. UNUSED_PARAMETER(p);
  600. const char *device = obs_data_get_string(settings, "vaapi_device");
  601. int drm_fd = -1;
  602. VADisplay va_dpy =
  603. vaapi_open_device(&drm_fd, device, "vaapi_device_modified");
  604. int profile = obs_data_get_int(settings, "profile");
  605. obs_property_t *rc_p = obs_properties_get(ppts, "rate_control");
  606. obs_property_list_clear(rc_p);
  607. if (!va_dpy)
  608. goto fail;
  609. switch (profile) {
  610. case FF_PROFILE_H264_CONSTRAINED_BASELINE:
  611. if (!vaapi_display_h264_supported(va_dpy, device))
  612. goto fail;
  613. profile = VAProfileH264ConstrainedBaseline;
  614. break;
  615. case FF_PROFILE_H264_MAIN:
  616. if (!vaapi_display_h264_supported(va_dpy, device))
  617. goto fail;
  618. profile = VAProfileH264Main;
  619. break;
  620. case FF_PROFILE_H264_HIGH:
  621. if (!vaapi_display_h264_supported(va_dpy, device))
  622. goto fail;
  623. profile = VAProfileH264High;
  624. break;
  625. case FF_PROFILE_AV1_MAIN:
  626. if (!vaapi_display_av1_supported(va_dpy, device))
  627. goto fail;
  628. profile = VAProfileAV1Profile0;
  629. break;
  630. #ifdef ENABLE_HEVC
  631. case FF_PROFILE_HEVC_MAIN:
  632. if (!vaapi_display_hevc_supported(va_dpy, device))
  633. goto fail;
  634. profile = VAProfileHEVCMain;
  635. break;
  636. case FF_PROFILE_HEVC_MAIN_10:
  637. if (!vaapi_display_hevc_supported(va_dpy, device))
  638. goto fail;
  639. profile = VAProfileHEVCMain10;
  640. break;
  641. #endif
  642. }
  643. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CBR, device))
  644. obs_property_list_add_string(rc_p, "CBR", "CBR");
  645. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_VBR, device))
  646. obs_property_list_add_string(rc_p, "VBR", "VBR");
  647. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CQP, device))
  648. obs_property_list_add_string(rc_p, "CQP", "CQP");
  649. set_visible(ppts, "bf", vaapi_device_bframe_supported(profile, va_dpy));
  650. fail:
  651. vaapi_close_device(&drm_fd, va_dpy);
  652. return true;
  653. }
  654. static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
  655. obs_data_t *settings)
  656. {
  657. UNUSED_PARAMETER(p);
  658. const char *rate_control =
  659. obs_data_get_string(settings, "rate_control");
  660. const rc_mode_t *rc_mode = get_rc_mode(rate_control);
  661. /* Set options visibility per Rate Control */
  662. set_visible(ppts, "qp", rc_mode->qp);
  663. set_visible(ppts, "bitrate", rc_mode->bitrate);
  664. set_visible(ppts, "maxrate", rc_mode->maxrate);
  665. return true;
  666. }
  667. static bool get_device_name_from_pci(struct pci_access *pacc, char *pci_slot,
  668. char *buf, int size)
  669. {
  670. struct pci_filter filter;
  671. struct pci_dev *dev;
  672. char *name;
  673. pci_filter_init(pacc, &filter);
  674. if (pci_filter_parse_slot(&filter, pci_slot))
  675. return false;
  676. pci_scan_bus(pacc);
  677. for (dev = pacc->devices; dev; dev = dev->next) {
  678. if (pci_filter_match(&filter, dev)) {
  679. pci_fill_info(dev, PCI_FILL_IDENT);
  680. name = pci_lookup_name(pacc, buf, size,
  681. PCI_LOOKUP_DEVICE,
  682. dev->vendor_id, dev->device_id);
  683. strcpy(buf, name);
  684. return true;
  685. }
  686. }
  687. return false;
  688. }
  689. static obs_properties_t *vaapi_properties_internal(enum codec_type codec)
  690. {
  691. obs_properties_t *props = obs_properties_create();
  692. obs_property_t *list;
  693. list = obs_properties_add_list(props, "vaapi_device",
  694. obs_module_text("VAAPI.Device"),
  695. OBS_COMBO_TYPE_LIST,
  696. OBS_COMBO_FORMAT_STRING);
  697. if (os_file_exists("/dev/dri/by-path")) {
  698. os_dir_t *by_path_dir = os_opendir("/dev/dri/by-path");
  699. struct pci_access *pacc = pci_alloc();
  700. struct os_dirent *file;
  701. char namebuf[1024];
  702. char pci_slot[13];
  703. char *type;
  704. pci_init(pacc);
  705. while ((file = os_readdir(by_path_dir)) != NULL) {
  706. // file_name pattern: pci-<pci_slot::12>-<type::{"card","render"}>
  707. char *file_name = file->d_name;
  708. if (strcmp(file_name, ".") == 0 ||
  709. strcmp(file_name, "..") == 0)
  710. continue;
  711. char path[64] = {0};
  712. // Use the return value of snprintf to prevent truncation warning.
  713. int written = snprintf(path, 64, "/dev/dri/by-path/%s",
  714. file_name);
  715. if (written >= 64)
  716. blog(LOG_DEBUG,
  717. "obs-ffmpeg-vaapi: A format truncation may have occurred."
  718. " This can be ignored since it is quite improbable.");
  719. type = strrchr(file_name, '-');
  720. if (type == NULL)
  721. continue;
  722. else
  723. type++;
  724. if (strcmp(type, "render") == 0) {
  725. strncpy(pci_slot, file_name + 4, 12);
  726. pci_slot[12] = 0;
  727. bool name_found = get_device_name_from_pci(
  728. pacc, pci_slot, namebuf,
  729. sizeof(namebuf));
  730. if (!vaapi_device_h264_supported(path))
  731. continue;
  732. if (!name_found)
  733. obs_property_list_add_string(list, path,
  734. path);
  735. else
  736. obs_property_list_add_string(
  737. list, namebuf, path);
  738. }
  739. }
  740. pci_cleanup(pacc);
  741. os_closedir(by_path_dir);
  742. }
  743. if (obs_property_list_item_count(list) == 0) {
  744. char path[32];
  745. for (int i = 28;; i++) {
  746. snprintf(path, sizeof(path), "/dev/dri/renderD1%d", i);
  747. if (access(path, F_OK) == 0) {
  748. char card[128];
  749. int ret = snprintf(card, sizeof(card),
  750. "Card%d: %s", i - 28, path);
  751. if (ret >= (int)sizeof(card))
  752. blog(LOG_DEBUG,
  753. "obs-ffmpeg-vaapi: A format truncation may have occurred."
  754. " This can be ignored since it is quite improbable.");
  755. if (!vaapi_device_h264_supported(path))
  756. continue;
  757. obs_property_list_add_string(list, card, path);
  758. } else {
  759. break;
  760. }
  761. }
  762. }
  763. obs_property_set_modified_callback(list, vaapi_device_modified);
  764. list = obs_properties_add_list(props, "profile",
  765. obs_module_text("Profile"),
  766. OBS_COMBO_TYPE_LIST,
  767. OBS_COMBO_FORMAT_INT);
  768. if (codec == CODEC_HEVC) {
  769. obs_property_list_add_int(list, "Main", FF_PROFILE_HEVC_MAIN);
  770. obs_property_list_add_int(list, "Main10",
  771. FF_PROFILE_HEVC_MAIN_10);
  772. } else if (codec == CODEC_H264) {
  773. obs_property_list_add_int(list, "Constrained Baseline",
  774. FF_PROFILE_H264_CONSTRAINED_BASELINE);
  775. obs_property_list_add_int(list, "Main", FF_PROFILE_H264_MAIN);
  776. obs_property_list_add_int(list, "High", FF_PROFILE_H264_HIGH);
  777. } else if (codec == CODEC_AV1) {
  778. obs_property_list_add_int(list, "Main", FF_PROFILE_AV1_MAIN);
  779. }
  780. obs_property_set_modified_callback(list, vaapi_device_modified);
  781. list = obs_properties_add_list(props, "level", obs_module_text("Level"),
  782. OBS_COMBO_TYPE_LIST,
  783. OBS_COMBO_FORMAT_INT);
  784. obs_property_list_add_int(list, "Auto", FF_LEVEL_UNKNOWN);
  785. if (codec == CODEC_H264) {
  786. obs_property_list_add_int(list, "3.0", 30);
  787. obs_property_list_add_int(list, "3.1", 31);
  788. obs_property_list_add_int(list, "4.0", 40);
  789. obs_property_list_add_int(list, "4.1", 41);
  790. obs_property_list_add_int(list, "4.2", 42);
  791. obs_property_list_add_int(list, "5.0", 50);
  792. obs_property_list_add_int(list, "5.1", 51);
  793. obs_property_list_add_int(list, "5.2", 52);
  794. } else if (codec == CODEC_HEVC) {
  795. obs_property_list_add_int(list, "3.0", 90);
  796. obs_property_list_add_int(list, "3.1", 93);
  797. obs_property_list_add_int(list, "4.0", 120);
  798. obs_property_list_add_int(list, "4.1", 123);
  799. obs_property_list_add_int(list, "5.0", 150);
  800. obs_property_list_add_int(list, "5.1", 153);
  801. obs_property_list_add_int(list, "5.2", 156);
  802. } else if (codec == CODEC_AV1) {
  803. obs_property_list_add_int(list, "3.0", 4);
  804. obs_property_list_add_int(list, "3.1", 5);
  805. obs_property_list_add_int(list, "4.0", 8);
  806. obs_property_list_add_int(list, "4.1", 9);
  807. obs_property_list_add_int(list, "5.0", 12);
  808. obs_property_list_add_int(list, "5.1", 13);
  809. obs_property_list_add_int(list, "5.2", 14);
  810. obs_property_list_add_int(list, "5.3", 15);
  811. }
  812. list = obs_properties_add_list(props, "rate_control",
  813. obs_module_text("RateControl"),
  814. OBS_COMBO_TYPE_LIST,
  815. OBS_COMBO_FORMAT_STRING);
  816. obs_property_set_modified_callback(list, rate_control_modified);
  817. obs_property_t *p;
  818. p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
  819. 0, 300000, 50);
  820. obs_property_int_set_suffix(p, " Kbps");
  821. p = obs_properties_add_int(
  822. props, "maxrate", obs_module_text("MaxBitrate"), 0, 300000, 50);
  823. obs_property_int_set_suffix(p, " Kbps");
  824. obs_properties_add_int(props, "qp", "QP", 0, 51, 1);
  825. p = obs_properties_add_int(props, "keyint_sec",
  826. obs_module_text("KeyframeIntervalSec"), 0,
  827. 20, 1);
  828. obs_property_int_set_suffix(p, " s");
  829. obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4,
  830. 1);
  831. obs_properties_add_text(props, "ffmpeg_opts",
  832. obs_module_text("FFmpegOpts"),
  833. OBS_TEXT_DEFAULT);
  834. return props;
  835. }
  836. static obs_properties_t *h264_vaapi_properties(void *unused)
  837. {
  838. UNUSED_PARAMETER(unused);
  839. return vaapi_properties_internal(CODEC_H264);
  840. }
  841. static obs_properties_t *av1_vaapi_properties(void *unused)
  842. {
  843. UNUSED_PARAMETER(unused);
  844. return vaapi_properties_internal(CODEC_AV1);
  845. }
  846. #ifdef ENABLE_HEVC
  847. static obs_properties_t *hevc_vaapi_properties(void *unused)
  848. {
  849. UNUSED_PARAMETER(unused);
  850. return vaapi_properties_internal(CODEC_HEVC);
  851. }
  852. #endif
  853. static bool vaapi_extra_data(void *data, uint8_t **extra_data, size_t *size)
  854. {
  855. struct vaapi_encoder *enc = data;
  856. *extra_data = enc->header;
  857. *size = enc->header_size;
  858. return true;
  859. }
  860. static bool vaapi_sei_data(void *data, uint8_t **extra_data, size_t *size)
  861. {
  862. struct vaapi_encoder *enc = data;
  863. *extra_data = enc->sei;
  864. *size = enc->sei_size;
  865. return true;
  866. }
  867. struct obs_encoder_info h264_vaapi_encoder_info = {
  868. .id = "ffmpeg_vaapi",
  869. .type = OBS_ENCODER_VIDEO,
  870. .codec = "h264",
  871. .get_name = h264_vaapi_getname,
  872. .create = h264_vaapi_create,
  873. .destroy = vaapi_destroy,
  874. .encode = vaapi_encode,
  875. .get_defaults = h264_vaapi_defaults,
  876. .get_properties = h264_vaapi_properties,
  877. .get_extra_data = vaapi_extra_data,
  878. .get_sei_data = vaapi_sei_data,
  879. .get_video_info = vaapi_video_info,
  880. };
  881. struct obs_encoder_info av1_vaapi_encoder_info = {
  882. .id = "av1_ffmpeg_vaapi",
  883. .type = OBS_ENCODER_VIDEO,
  884. .codec = "av1",
  885. .get_name = av1_vaapi_getname,
  886. .create = av1_vaapi_create,
  887. .destroy = vaapi_destroy,
  888. .encode = vaapi_encode,
  889. .get_defaults = av1_vaapi_defaults,
  890. .get_properties = av1_vaapi_properties,
  891. .get_extra_data = vaapi_extra_data,
  892. .get_sei_data = vaapi_sei_data,
  893. .get_video_info = vaapi_video_info,
  894. };
  895. #ifdef ENABLE_HEVC
  896. struct obs_encoder_info hevc_vaapi_encoder_info = {
  897. .id = "hevc_ffmpeg_vaapi",
  898. .type = OBS_ENCODER_VIDEO,
  899. .codec = "hevc",
  900. .get_name = hevc_vaapi_getname,
  901. .create = hevc_vaapi_create,
  902. .destroy = vaapi_destroy,
  903. .encode = vaapi_encode,
  904. .get_defaults = hevc_vaapi_defaults,
  905. .get_properties = hevc_vaapi_properties,
  906. .get_extra_data = vaapi_extra_data,
  907. .get_sei_data = vaapi_sei_data,
  908. .get_video_info = vaapi_video_info,
  909. };
  910. #endif