obs-ffmpeg-vaapi.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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. switch (enc->codec) {
  462. case CODEC_HEVC:
  463. #ifdef ENABLE_HEVC
  464. obs_extract_hevc_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. break;
  470. #else
  471. warn("vaapi_encode: HEVC codec is not supported");
  472. goto fail;
  473. #endif
  474. case CODEC_H264:
  475. obs_extract_avc_headers(
  476. enc->packet->data, enc->packet->size,
  477. &new_packet, &size, &enc->header,
  478. &enc->header_size, &enc->sei,
  479. &enc->sei_size);
  480. break;
  481. case CODEC_AV1:
  482. obs_extract_av1_headers(enc->packet->data,
  483. enc->packet->size,
  484. &new_packet, &size,
  485. &enc->header,
  486. &enc->header_size);
  487. break;
  488. }
  489. da_copy_array(enc->buffer, new_packet, size);
  490. bfree(new_packet);
  491. } else {
  492. da_copy_array(enc->buffer, enc->packet->data,
  493. enc->packet->size);
  494. }
  495. packet->pts = enc->packet->pts;
  496. packet->dts = enc->packet->dts;
  497. packet->data = enc->buffer.array;
  498. packet->size = enc->buffer.num;
  499. packet->type = OBS_ENCODER_VIDEO;
  500. #ifdef ENABLE_HEVC
  501. if (enc->codec == CODEC_HEVC) {
  502. packet->keyframe =
  503. obs_hevc_keyframe(packet->data, packet->size);
  504. } else
  505. #endif
  506. if (enc->codec == CODEC_H264) {
  507. packet->keyframe =
  508. obs_avc_keyframe(packet->data, packet->size);
  509. } else if (enc->codec == CODEC_AV1) {
  510. packet->keyframe =
  511. obs_av1_keyframe(packet->data, packet->size);
  512. }
  513. *received_packet = true;
  514. } else {
  515. *received_packet = false;
  516. }
  517. av_packet_unref(enc->packet);
  518. av_frame_free(&hwframe);
  519. return true;
  520. fail:
  521. av_frame_free(&hwframe);
  522. return false;
  523. }
  524. static void set_visible(obs_properties_t *ppts, const char *name, bool visible)
  525. {
  526. obs_property_t *p = obs_properties_get(ppts, name);
  527. obs_property_set_visible(p, visible);
  528. }
  529. static inline VAProfile vaapi_profile(enum codec_type codec)
  530. {
  531. if (codec == CODEC_H264) {
  532. return VAProfileH264ConstrainedBaseline;
  533. } else if (codec == CODEC_AV1) {
  534. return VAProfileAV1Profile0;
  535. #if ENABLE_HEVC
  536. } else if (codec == CODEC_HEVC) {
  537. return VAProfileHEVCMain;
  538. #endif
  539. }
  540. return VAProfileNone;
  541. }
  542. static inline const char *vaapi_default_device(enum codec_type codec)
  543. {
  544. if (codec == CODEC_H264) {
  545. return vaapi_get_h264_default_device();
  546. } else if (codec == CODEC_AV1) {
  547. return vaapi_get_av1_default_device();
  548. #if ENABLE_HEVC
  549. } else if (codec == CODEC_HEVC) {
  550. return vaapi_get_hevc_default_device();
  551. #endif
  552. }
  553. return NULL;
  554. }
  555. static void vaapi_defaults_internal(obs_data_t *settings, enum codec_type codec)
  556. {
  557. const char *const device = vaapi_default_device(codec);
  558. obs_data_set_default_string(settings, "vaapi_device", device);
  559. #ifdef ENABLE_HEVC
  560. if (codec == CODEC_HEVC)
  561. obs_data_set_default_int(settings, "profile",
  562. FF_PROFILE_HEVC_MAIN);
  563. else
  564. #endif
  565. if (codec == CODEC_H264)
  566. obs_data_set_default_int(settings, "profile",
  567. FF_PROFILE_H264_HIGH);
  568. else if (codec == CODEC_AV1)
  569. obs_data_set_default_int(settings, "profile",
  570. FF_PROFILE_AV1_MAIN);
  571. obs_data_set_default_int(settings, "level", FF_LEVEL_UNKNOWN);
  572. obs_data_set_default_int(settings, "bitrate", 2500);
  573. obs_data_set_default_int(settings, "keyint_sec", 0);
  574. obs_data_set_default_int(settings, "bf", 0);
  575. obs_data_set_default_int(settings, "qp", 20);
  576. obs_data_set_default_int(settings, "maxrate", 0);
  577. int drm_fd = -1;
  578. VADisplay va_dpy = vaapi_open_device(&drm_fd, device, "vaapi_defaults");
  579. if (!va_dpy)
  580. return;
  581. const VAProfile profile = vaapi_profile(codec);
  582. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CBR, device))
  583. obs_data_set_default_string(settings, "rate_control", "CBR");
  584. else if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_VBR, device))
  585. obs_data_set_default_string(settings, "rate_control", "VBR");
  586. else
  587. obs_data_set_default_string(settings, "rate_control", "CQP");
  588. vaapi_close_device(&drm_fd, va_dpy);
  589. }
  590. static void h264_vaapi_defaults(obs_data_t *settings)
  591. {
  592. vaapi_defaults_internal(settings, CODEC_H264);
  593. }
  594. static void av1_vaapi_defaults(obs_data_t *settings)
  595. {
  596. vaapi_defaults_internal(settings, CODEC_AV1);
  597. }
  598. static void hevc_vaapi_defaults(obs_data_t *settings)
  599. {
  600. vaapi_defaults_internal(settings, CODEC_HEVC);
  601. }
  602. static bool vaapi_device_modified(obs_properties_t *ppts, obs_property_t *p,
  603. obs_data_t *settings)
  604. {
  605. UNUSED_PARAMETER(p);
  606. const char *device = obs_data_get_string(settings, "vaapi_device");
  607. int drm_fd = -1;
  608. VADisplay va_dpy =
  609. vaapi_open_device(&drm_fd, device, "vaapi_device_modified");
  610. int profile = obs_data_get_int(settings, "profile");
  611. obs_property_t *rc_p = obs_properties_get(ppts, "rate_control");
  612. obs_property_list_clear(rc_p);
  613. if (!va_dpy)
  614. goto fail;
  615. switch (profile) {
  616. case FF_PROFILE_H264_CONSTRAINED_BASELINE:
  617. if (!vaapi_display_h264_supported(va_dpy, device))
  618. goto fail;
  619. profile = VAProfileH264ConstrainedBaseline;
  620. break;
  621. case FF_PROFILE_H264_MAIN:
  622. if (!vaapi_display_h264_supported(va_dpy, device))
  623. goto fail;
  624. profile = VAProfileH264Main;
  625. break;
  626. case FF_PROFILE_H264_HIGH:
  627. if (!vaapi_display_h264_supported(va_dpy, device))
  628. goto fail;
  629. profile = VAProfileH264High;
  630. break;
  631. case FF_PROFILE_AV1_MAIN:
  632. if (!vaapi_display_av1_supported(va_dpy, device))
  633. goto fail;
  634. profile = VAProfileAV1Profile0;
  635. break;
  636. #ifdef ENABLE_HEVC
  637. case FF_PROFILE_HEVC_MAIN:
  638. if (!vaapi_display_hevc_supported(va_dpy, device))
  639. goto fail;
  640. profile = VAProfileHEVCMain;
  641. break;
  642. case FF_PROFILE_HEVC_MAIN_10:
  643. if (!vaapi_display_hevc_supported(va_dpy, device))
  644. goto fail;
  645. profile = VAProfileHEVCMain10;
  646. break;
  647. #endif
  648. }
  649. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CBR, device))
  650. obs_property_list_add_string(rc_p, "CBR", "CBR");
  651. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_VBR, device))
  652. obs_property_list_add_string(rc_p, "VBR", "VBR");
  653. if (vaapi_device_rc_supported(profile, va_dpy, VA_RC_CQP, device))
  654. obs_property_list_add_string(rc_p, "CQP", "CQP");
  655. set_visible(ppts, "bf", vaapi_device_bframe_supported(profile, va_dpy));
  656. fail:
  657. vaapi_close_device(&drm_fd, va_dpy);
  658. return true;
  659. }
  660. static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
  661. obs_data_t *settings)
  662. {
  663. UNUSED_PARAMETER(p);
  664. const char *rate_control =
  665. obs_data_get_string(settings, "rate_control");
  666. const rc_mode_t *rc_mode = get_rc_mode(rate_control);
  667. /* Set options visibility per Rate Control */
  668. set_visible(ppts, "qp", rc_mode->qp);
  669. set_visible(ppts, "bitrate", rc_mode->bitrate);
  670. set_visible(ppts, "maxrate", rc_mode->maxrate);
  671. return true;
  672. }
  673. static bool get_device_name_from_pci(struct pci_access *pacc, char *pci_slot,
  674. char *buf, int size)
  675. {
  676. struct pci_filter filter;
  677. struct pci_dev *dev;
  678. char *name;
  679. pci_filter_init(pacc, &filter);
  680. if (pci_filter_parse_slot(&filter, pci_slot))
  681. return false;
  682. pci_scan_bus(pacc);
  683. for (dev = pacc->devices; dev; dev = dev->next) {
  684. if (pci_filter_match(&filter, dev)) {
  685. pci_fill_info(dev, PCI_FILL_IDENT);
  686. name = pci_lookup_name(pacc, buf, size,
  687. PCI_LOOKUP_DEVICE,
  688. dev->vendor_id, dev->device_id);
  689. strcpy(buf, name);
  690. return true;
  691. }
  692. }
  693. return false;
  694. }
  695. static obs_properties_t *vaapi_properties_internal(enum codec_type codec)
  696. {
  697. obs_properties_t *props = obs_properties_create();
  698. obs_property_t *list;
  699. list = obs_properties_add_list(props, "vaapi_device",
  700. obs_module_text("VAAPI.Device"),
  701. OBS_COMBO_TYPE_LIST,
  702. OBS_COMBO_FORMAT_STRING);
  703. if (os_file_exists("/dev/dri/by-path")) {
  704. os_dir_t *by_path_dir = os_opendir("/dev/dri/by-path");
  705. struct pci_access *pacc = pci_alloc();
  706. struct os_dirent *file;
  707. char namebuf[1024];
  708. char pci_slot[13];
  709. char *type;
  710. pci_init(pacc);
  711. while ((file = os_readdir(by_path_dir)) != NULL) {
  712. // file_name pattern: pci-<pci_slot::12>-<type::{"card","render"}>
  713. char *file_name = file->d_name;
  714. if (strcmp(file_name, ".") == 0 ||
  715. strcmp(file_name, "..") == 0)
  716. continue;
  717. char path[64] = {0};
  718. // Use the return value of snprintf to prevent truncation warning.
  719. int written = snprintf(path, 64, "/dev/dri/by-path/%s",
  720. file_name);
  721. if (written >= 64)
  722. blog(LOG_DEBUG,
  723. "obs-ffmpeg-vaapi: A format truncation may have occurred."
  724. " This can be ignored since it is quite improbable.");
  725. type = strrchr(file_name, '-');
  726. if (type == NULL)
  727. continue;
  728. else
  729. type++;
  730. if (strcmp(type, "render") == 0) {
  731. strncpy(pci_slot, file_name + 4, 12);
  732. pci_slot[12] = 0;
  733. bool name_found = get_device_name_from_pci(
  734. pacc, pci_slot, namebuf,
  735. sizeof(namebuf));
  736. if (!vaapi_device_h264_supported(path))
  737. continue;
  738. if (!name_found)
  739. obs_property_list_add_string(list, path,
  740. path);
  741. else
  742. obs_property_list_add_string(
  743. list, namebuf, path);
  744. }
  745. }
  746. pci_cleanup(pacc);
  747. os_closedir(by_path_dir);
  748. }
  749. if (obs_property_list_item_count(list) == 0) {
  750. char path[32];
  751. for (int i = 28;; i++) {
  752. snprintf(path, sizeof(path), "/dev/dri/renderD1%d", i);
  753. if (access(path, F_OK) == 0) {
  754. char card[128];
  755. int ret = snprintf(card, sizeof(card),
  756. "Card%d: %s", i - 28, path);
  757. if (ret >= (int)sizeof(card))
  758. blog(LOG_DEBUG,
  759. "obs-ffmpeg-vaapi: A format truncation may have occurred."
  760. " This can be ignored since it is quite improbable.");
  761. if (!vaapi_device_h264_supported(path))
  762. continue;
  763. obs_property_list_add_string(list, card, path);
  764. } else {
  765. break;
  766. }
  767. }
  768. }
  769. obs_property_set_modified_callback(list, vaapi_device_modified);
  770. list = obs_properties_add_list(props, "profile",
  771. obs_module_text("Profile"),
  772. OBS_COMBO_TYPE_LIST,
  773. OBS_COMBO_FORMAT_INT);
  774. if (codec == CODEC_HEVC) {
  775. obs_property_list_add_int(list, "Main", FF_PROFILE_HEVC_MAIN);
  776. obs_property_list_add_int(list, "Main10",
  777. FF_PROFILE_HEVC_MAIN_10);
  778. } else if (codec == CODEC_H264) {
  779. obs_property_list_add_int(list, "Constrained Baseline",
  780. FF_PROFILE_H264_CONSTRAINED_BASELINE);
  781. obs_property_list_add_int(list, "Main", FF_PROFILE_H264_MAIN);
  782. obs_property_list_add_int(list, "High", FF_PROFILE_H264_HIGH);
  783. } else if (codec == CODEC_AV1) {
  784. obs_property_list_add_int(list, "Main", FF_PROFILE_AV1_MAIN);
  785. }
  786. obs_property_set_modified_callback(list, vaapi_device_modified);
  787. list = obs_properties_add_list(props, "level", obs_module_text("Level"),
  788. OBS_COMBO_TYPE_LIST,
  789. OBS_COMBO_FORMAT_INT);
  790. obs_property_list_add_int(list, "Auto", FF_LEVEL_UNKNOWN);
  791. if (codec == CODEC_H264) {
  792. obs_property_list_add_int(list, "3.0", 30);
  793. obs_property_list_add_int(list, "3.1", 31);
  794. obs_property_list_add_int(list, "4.0", 40);
  795. obs_property_list_add_int(list, "4.1", 41);
  796. obs_property_list_add_int(list, "4.2", 42);
  797. obs_property_list_add_int(list, "5.0", 50);
  798. obs_property_list_add_int(list, "5.1", 51);
  799. obs_property_list_add_int(list, "5.2", 52);
  800. } else if (codec == CODEC_HEVC) {
  801. obs_property_list_add_int(list, "3.0", 90);
  802. obs_property_list_add_int(list, "3.1", 93);
  803. obs_property_list_add_int(list, "4.0", 120);
  804. obs_property_list_add_int(list, "4.1", 123);
  805. obs_property_list_add_int(list, "5.0", 150);
  806. obs_property_list_add_int(list, "5.1", 153);
  807. obs_property_list_add_int(list, "5.2", 156);
  808. } else if (codec == CODEC_AV1) {
  809. obs_property_list_add_int(list, "3.0", 4);
  810. obs_property_list_add_int(list, "3.1", 5);
  811. obs_property_list_add_int(list, "4.0", 8);
  812. obs_property_list_add_int(list, "4.1", 9);
  813. obs_property_list_add_int(list, "5.0", 12);
  814. obs_property_list_add_int(list, "5.1", 13);
  815. obs_property_list_add_int(list, "5.2", 14);
  816. obs_property_list_add_int(list, "5.3", 15);
  817. }
  818. list = obs_properties_add_list(props, "rate_control",
  819. obs_module_text("RateControl"),
  820. OBS_COMBO_TYPE_LIST,
  821. OBS_COMBO_FORMAT_STRING);
  822. obs_property_set_modified_callback(list, rate_control_modified);
  823. obs_property_t *p;
  824. p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
  825. 0, 300000, 50);
  826. obs_property_int_set_suffix(p, " Kbps");
  827. p = obs_properties_add_int(
  828. props, "maxrate", obs_module_text("MaxBitrate"), 0, 300000, 50);
  829. obs_property_int_set_suffix(p, " Kbps");
  830. obs_properties_add_int(props, "qp", "QP", 0, 51, 1);
  831. p = obs_properties_add_int(props, "keyint_sec",
  832. obs_module_text("KeyframeIntervalSec"), 0,
  833. 20, 1);
  834. obs_property_int_set_suffix(p, " s");
  835. obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4,
  836. 1);
  837. obs_properties_add_text(props, "ffmpeg_opts",
  838. obs_module_text("FFmpegOpts"),
  839. OBS_TEXT_DEFAULT);
  840. return props;
  841. }
  842. static obs_properties_t *h264_vaapi_properties(void *unused)
  843. {
  844. UNUSED_PARAMETER(unused);
  845. return vaapi_properties_internal(CODEC_H264);
  846. }
  847. static obs_properties_t *av1_vaapi_properties(void *unused)
  848. {
  849. UNUSED_PARAMETER(unused);
  850. return vaapi_properties_internal(CODEC_AV1);
  851. }
  852. #ifdef ENABLE_HEVC
  853. static obs_properties_t *hevc_vaapi_properties(void *unused)
  854. {
  855. UNUSED_PARAMETER(unused);
  856. return vaapi_properties_internal(CODEC_HEVC);
  857. }
  858. #endif
  859. static bool vaapi_extra_data(void *data, uint8_t **extra_data, size_t *size)
  860. {
  861. struct vaapi_encoder *enc = data;
  862. *extra_data = enc->header;
  863. *size = enc->header_size;
  864. return true;
  865. }
  866. static bool vaapi_sei_data(void *data, uint8_t **extra_data, size_t *size)
  867. {
  868. struct vaapi_encoder *enc = data;
  869. *extra_data = enc->sei;
  870. *size = enc->sei_size;
  871. return true;
  872. }
  873. struct obs_encoder_info h264_vaapi_encoder_info = {
  874. .id = "ffmpeg_vaapi",
  875. .type = OBS_ENCODER_VIDEO,
  876. .codec = "h264",
  877. .get_name = h264_vaapi_getname,
  878. .create = h264_vaapi_create,
  879. .destroy = vaapi_destroy,
  880. .encode = vaapi_encode,
  881. .get_defaults = h264_vaapi_defaults,
  882. .get_properties = h264_vaapi_properties,
  883. .get_extra_data = vaapi_extra_data,
  884. .get_sei_data = vaapi_sei_data,
  885. .get_video_info = vaapi_video_info,
  886. };
  887. struct obs_encoder_info av1_vaapi_encoder_info = {
  888. .id = "av1_ffmpeg_vaapi",
  889. .type = OBS_ENCODER_VIDEO,
  890. .codec = "av1",
  891. .get_name = av1_vaapi_getname,
  892. .create = av1_vaapi_create,
  893. .destroy = vaapi_destroy,
  894. .encode = vaapi_encode,
  895. .get_defaults = av1_vaapi_defaults,
  896. .get_properties = av1_vaapi_properties,
  897. .get_extra_data = vaapi_extra_data,
  898. .get_sei_data = vaapi_sei_data,
  899. .get_video_info = vaapi_video_info,
  900. };
  901. #ifdef ENABLE_HEVC
  902. struct obs_encoder_info hevc_vaapi_encoder_info = {
  903. .id = "hevc_ffmpeg_vaapi",
  904. .type = OBS_ENCODER_VIDEO,
  905. .codec = "hevc",
  906. .get_name = hevc_vaapi_getname,
  907. .create = hevc_vaapi_create,
  908. .destroy = vaapi_destroy,
  909. .encode = vaapi_encode,
  910. .get_defaults = hevc_vaapi_defaults,
  911. .get_properties = hevc_vaapi_properties,
  912. .get_extra_data = vaapi_extra_data,
  913. .get_sei_data = vaapi_sei_data,
  914. .get_video_info = vaapi_video_info,
  915. };
  916. #endif