obs-ffmpeg-vaapi.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /******************************************************************************
  2. Copyright (C) 2016 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <libavutil/avutil.h>
  15. #if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(55, 27, 100)
  16. #include <util/darray.h>
  17. #include <util/dstr.h>
  18. #include <util/base.h>
  19. #include <media-io/video-io.h>
  20. #include <obs-module.h>
  21. #include <obs-avc.h>
  22. #include <unistd.h>
  23. #include <libavutil/opt.h>
  24. #include <libavutil/pixdesc.h>
  25. #include <libavutil/hwcontext.h>
  26. #include <libavcodec/avcodec.h>
  27. #include <libavformat/avformat.h>
  28. #include <libavfilter/avfilter.h>
  29. #include "obs-ffmpeg-formats.h"
  30. #define do_log(level, format, ...) \
  31. blog(level, "[FFMPEG VAAPI encoder: '%s'] " format, \
  32. obs_encoder_get_name(enc->encoder), ##__VA_ARGS__)
  33. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  34. #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__)
  35. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  36. struct vaapi_encoder {
  37. obs_encoder_t *encoder;
  38. AVBufferRef *vadevice_ref;
  39. AVBufferRef *vaframes_ref;
  40. AVCodec *vaapi;
  41. AVCodecContext *context;
  42. AVFrame *vframe;
  43. DARRAY(uint8_t) buffer;
  44. uint8_t *header;
  45. size_t header_size;
  46. uint8_t *sei;
  47. size_t sei_size;
  48. int height;
  49. bool first_packet;
  50. bool initialized;
  51. };
  52. static const char *vaapi_getname(void *unused)
  53. {
  54. UNUSED_PARAMETER(unused);
  55. return "FFMPEG VAAPI";
  56. }
  57. static inline bool valid_format(enum video_format format)
  58. {
  59. return format == VIDEO_FORMAT_NV12;
  60. }
  61. static void vaapi_video_info(void *data, struct video_scale_info *info)
  62. {
  63. struct vaapi_encoder *enc = data;
  64. enum video_format pref_format;
  65. pref_format = obs_encoder_get_preferred_video_format(enc->encoder);
  66. if (!valid_format(pref_format)) {
  67. pref_format = valid_format(info->format) ? info->format
  68. : VIDEO_FORMAT_NV12;
  69. }
  70. info->format = pref_format;
  71. }
  72. static bool vaapi_init_codec(struct vaapi_encoder *enc, const char *path)
  73. {
  74. int ret;
  75. ret = av_hwdevice_ctx_create(&enc->vadevice_ref, AV_HWDEVICE_TYPE_VAAPI,
  76. path, NULL, 0);
  77. if (ret < 0) {
  78. warn("Failed to create VAAPI device context: %s",
  79. av_err2str(ret));
  80. return false;
  81. }
  82. enc->vaframes_ref = av_hwframe_ctx_alloc(enc->vadevice_ref);
  83. if (!enc->vaframes_ref) {
  84. warn("Failed to alloc HW frames context");
  85. return false;
  86. }
  87. AVHWFramesContext *frames_ctx =
  88. (AVHWFramesContext *)enc->vaframes_ref->data;
  89. frames_ctx->format = AV_PIX_FMT_VAAPI;
  90. frames_ctx->sw_format = AV_PIX_FMT_NV12;
  91. frames_ctx->width = enc->context->width;
  92. frames_ctx->height = enc->context->height;
  93. frames_ctx->initial_pool_size = 20;
  94. ret = av_hwframe_ctx_init(enc->vaframes_ref);
  95. if (ret < 0) {
  96. warn("Failed to init HW frames context: %s", av_err2str(ret));
  97. return false;
  98. }
  99. /* 2. Create software frame and picture */
  100. enc->vframe = av_frame_alloc();
  101. if (!enc->vframe) {
  102. warn("Failed to allocate video frame");
  103. return false;
  104. }
  105. enc->vframe->format = enc->context->pix_fmt;
  106. enc->vframe->width = enc->context->width;
  107. enc->vframe->height = enc->context->height;
  108. enc->vframe->colorspace = enc->context->colorspace;
  109. enc->vframe->color_range = enc->context->color_range;
  110. ret = av_frame_get_buffer(enc->vframe, base_get_alignment());
  111. if (ret < 0) {
  112. warn("Failed to allocate vframe: %s", av_err2str(ret));
  113. return false;
  114. }
  115. /* 3. set up codec */
  116. enc->context->pix_fmt = AV_PIX_FMT_VAAPI;
  117. enc->context->hw_frames_ctx = av_buffer_ref(enc->vaframes_ref);
  118. ret = avcodec_open2(enc->context, enc->vaapi, NULL);
  119. if (ret < 0) {
  120. warn("Failed to open VAAPI codec: %s", av_err2str(ret));
  121. return false;
  122. }
  123. enc->initialized = true;
  124. return true;
  125. }
  126. /* "Allowed" options per Rate Control
  127. * See FFMPEG libavcodec/vaapi_encode.c (vaapi_encode_rc_modes)
  128. */
  129. typedef struct {
  130. const char *name;
  131. bool qp;
  132. bool bitrate;
  133. bool maxrate;
  134. } rc_mode_t;
  135. static const rc_mode_t *get_rc_mode(const char *name)
  136. {
  137. /* Set "allowed" options per Rate Control */
  138. static const rc_mode_t RC_MODES[] = {
  139. {.name = "CBR", .qp = false, .bitrate = true, .maxrate = false},
  140. {.name = "CQP", .qp = true, .bitrate = false, .maxrate = false},
  141. {.name = "VBR", .qp = false, .bitrate = true, .maxrate = true},
  142. NULL};
  143. const rc_mode_t *rc_mode = RC_MODES;
  144. while (!!rc_mode && strcmp(rc_mode->name, name) != 0)
  145. rc_mode++;
  146. return rc_mode ? rc_mode : RC_MODES;
  147. }
  148. static bool vaapi_update(void *data, obs_data_t *settings)
  149. {
  150. struct vaapi_encoder *enc = data;
  151. const char *device = obs_data_get_string(settings, "vaapi_device");
  152. const char *rate_control =
  153. obs_data_get_string(settings, "rate_control");
  154. const rc_mode_t *rc_mode = get_rc_mode(rate_control);
  155. bool cbr = strcmp(rc_mode->name, "CBR") == 0;
  156. int profile = (int)obs_data_get_int(settings, "profile");
  157. int bf = (int)obs_data_get_int(settings, "bf");
  158. int qp = rc_mode->qp ? (int)obs_data_get_int(settings, "qp") : 0;
  159. av_opt_set_int(enc->context->priv_data, "qp", qp, 0);
  160. int level = (int)obs_data_get_int(settings, "level");
  161. int bitrate = rc_mode->bitrate
  162. ? (int)obs_data_get_int(settings, "bitrate")
  163. : 0;
  164. int maxrate = rc_mode->maxrate
  165. ? (int)obs_data_get_int(settings, "maxrate")
  166. : 0;
  167. int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec");
  168. /* For Rate Control which allows maxrate, FFMPEG will give
  169. * an error if maxrate > bitrate. To prevent that set maxrate
  170. * to 0.
  171. * For CBR, maxrate = bitrate
  172. */
  173. if (cbr)
  174. maxrate = bitrate;
  175. else if (rc_mode->maxrate && maxrate && maxrate < bitrate)
  176. maxrate = 0;
  177. video_t *video = obs_encoder_video(enc->encoder);
  178. const struct video_output_info *voi = video_output_get_info(video);
  179. struct video_scale_info info;
  180. info.format = voi->format;
  181. info.colorspace = voi->colorspace;
  182. info.range = voi->range;
  183. vaapi_video_info(enc, &info);
  184. enc->context->profile = profile;
  185. enc->context->max_b_frames = bf;
  186. enc->context->level = level;
  187. enc->context->bit_rate = bitrate * 1000;
  188. enc->context->rc_max_rate = maxrate * 1000;
  189. enc->context->width = obs_encoder_get_width(enc->encoder);
  190. enc->context->height = obs_encoder_get_height(enc->encoder);
  191. enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num};
  192. enc->context->pix_fmt = obs_to_ffmpeg_video_format(info.format);
  193. enc->context->colorspace = info.colorspace == VIDEO_CS_709
  194. ? AVCOL_SPC_BT709
  195. : AVCOL_SPC_BT470BG;
  196. enc->context->color_range = info.range == VIDEO_RANGE_FULL
  197. ? AVCOL_RANGE_JPEG
  198. : AVCOL_RANGE_MPEG;
  199. if (keyint_sec > 0) {
  200. enc->context->gop_size =
  201. keyint_sec * voi->fps_num / voi->fps_den;
  202. } else {
  203. enc->context->gop_size = 120;
  204. }
  205. enc->height = enc->context->height;
  206. info("settings:\n"
  207. "\tdevice: %s\n"
  208. "\trate_control: %s\n"
  209. "\tprofile: %d\n"
  210. "\tlevel: %d\n"
  211. "\tqp: %d\n"
  212. "\tbitrate: %d\n"
  213. "\tmaxrate: %d\n"
  214. "\tkeyint: %d\n"
  215. "\twidth: %d\n"
  216. "\theight: %d\n"
  217. "\tb-frames: %d\n",
  218. device, rate_control, profile, level, qp, bitrate, maxrate,
  219. enc->context->gop_size, enc->context->width, enc->context->height,
  220. enc->context->max_b_frames);
  221. return vaapi_init_codec(enc, device);
  222. }
  223. static void vaapi_destroy(void *data)
  224. {
  225. struct vaapi_encoder *enc = data;
  226. if (enc->initialized) {
  227. AVPacket pkt = {0};
  228. int r_pkt = 1;
  229. while (r_pkt) {
  230. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  231. if (avcodec_receive_packet(enc->context, &pkt) < 0)
  232. break;
  233. #else
  234. if (avcodec_encode_video2(enc->context, &pkt, NULL,
  235. &r_pkt) < 0)
  236. break;
  237. #endif
  238. if (r_pkt)
  239. av_packet_unref(&pkt);
  240. }
  241. }
  242. avcodec_close(enc->context);
  243. av_frame_unref(enc->vframe);
  244. av_frame_free(&enc->vframe);
  245. av_buffer_unref(&enc->vaframes_ref);
  246. av_buffer_unref(&enc->vadevice_ref);
  247. da_free(enc->buffer);
  248. bfree(enc->header);
  249. bfree(enc->sei);
  250. bfree(enc);
  251. }
  252. static void *vaapi_create(obs_data_t *settings, obs_encoder_t *encoder)
  253. {
  254. struct vaapi_encoder *enc;
  255. #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(58, 9, 100)
  256. avcodec_register_all();
  257. #endif
  258. enc = bzalloc(sizeof(*enc));
  259. enc->encoder = encoder;
  260. int vaapi_codec = (int)obs_data_get_int(settings, "vaapi_codec");
  261. if (vaapi_codec == AV_CODEC_ID_H264) {
  262. enc->vaapi = avcodec_find_encoder_by_name("h264_vaapi");
  263. }
  264. enc->first_packet = true;
  265. blog(LOG_INFO, "---------------------------------");
  266. if (!enc->vaapi) {
  267. warn("Couldn't find encoder");
  268. goto fail;
  269. }
  270. enc->context = avcodec_alloc_context3(enc->vaapi);
  271. if (!enc->context) {
  272. warn("Failed to create codec context");
  273. goto fail;
  274. }
  275. if (!vaapi_update(enc, settings))
  276. goto fail;
  277. return enc;
  278. fail:
  279. vaapi_destroy(enc);
  280. return NULL;
  281. }
  282. static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame,
  283. int height, enum AVPixelFormat format)
  284. {
  285. int h_chroma_shift, v_chroma_shift;
  286. av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift,
  287. &v_chroma_shift);
  288. for (int plane = 0; plane < MAX_AV_PLANES; plane++) {
  289. if (!frame->data[plane])
  290. continue;
  291. int frame_rowsize = (int)frame->linesize[plane];
  292. int pic_rowsize = pic->linesize[plane];
  293. int bytes = frame_rowsize < pic_rowsize ? frame_rowsize
  294. : pic_rowsize;
  295. int plane_height = height >> (plane ? v_chroma_shift : 0);
  296. for (int y = 0; y < plane_height; y++) {
  297. int pos_frame = y * frame_rowsize;
  298. int pos_pic = y * pic_rowsize;
  299. memcpy(pic->data[plane] + pos_pic,
  300. frame->data[plane] + pos_frame, bytes);
  301. }
  302. }
  303. }
  304. static bool vaapi_encode(void *data, struct encoder_frame *frame,
  305. struct encoder_packet *packet, bool *received_packet)
  306. {
  307. struct vaapi_encoder *enc = data;
  308. AVFrame *hwframe = NULL;
  309. AVPacket av_pkt;
  310. int got_packet;
  311. int ret;
  312. hwframe = av_frame_alloc();
  313. if (!hwframe) {
  314. warn("vaapi_encode: failed to allocate hw frame");
  315. return false;
  316. }
  317. ret = av_hwframe_get_buffer(enc->vaframes_ref, hwframe, 0);
  318. if (ret < 0) {
  319. warn("vaapi_encode: failed to get buffer for hw frame: %s",
  320. av_err2str(ret));
  321. goto fail;
  322. }
  323. copy_data(enc->vframe, frame, enc->height, enc->context->pix_fmt);
  324. enc->vframe->pts = frame->pts;
  325. hwframe->pts = frame->pts;
  326. hwframe->width = enc->vframe->width;
  327. hwframe->height = enc->vframe->height;
  328. ret = av_hwframe_transfer_data(hwframe, enc->vframe, 0);
  329. if (ret < 0) {
  330. warn("vaapi_encode: failed to upload hw frame: %s",
  331. av_err2str(ret));
  332. goto fail;
  333. }
  334. ret = av_frame_copy_props(hwframe, enc->vframe);
  335. if (ret < 0) {
  336. warn("vaapi_encode: failed to copy props to hw frame: %s",
  337. av_err2str(ret));
  338. goto fail;
  339. }
  340. av_init_packet(&av_pkt);
  341. #if LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(57, 40, 101)
  342. ret = avcodec_send_frame(enc->context, hwframe);
  343. if (ret == 0)
  344. ret = avcodec_receive_packet(enc->context, &av_pkt);
  345. got_packet = (ret == 0);
  346. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  347. ret = 0;
  348. #else
  349. ret = avcodec_encode_video2(enc->context, &av_pkt, hwframe,
  350. &got_packet);
  351. #endif
  352. if (ret < 0) {
  353. warn("vaapi_encode: Error encoding: %s", av_err2str(ret));
  354. goto fail;
  355. }
  356. if (got_packet && av_pkt.size) {
  357. if (enc->first_packet) {
  358. uint8_t *new_packet;
  359. size_t size;
  360. enc->first_packet = false;
  361. obs_extract_avc_headers(av_pkt.data, av_pkt.size,
  362. &new_packet, &size,
  363. &enc->header, &enc->header_size,
  364. &enc->sei, &enc->sei_size);
  365. da_copy_array(enc->buffer, new_packet, size);
  366. bfree(new_packet);
  367. } else {
  368. da_copy_array(enc->buffer, av_pkt.data, av_pkt.size);
  369. }
  370. packet->pts = av_pkt.pts;
  371. packet->dts = av_pkt.dts;
  372. packet->data = enc->buffer.array;
  373. packet->size = enc->buffer.num;
  374. packet->type = OBS_ENCODER_VIDEO;
  375. packet->keyframe = obs_avc_keyframe(packet->data, packet->size);
  376. *received_packet = true;
  377. } else {
  378. *received_packet = false;
  379. }
  380. av_packet_unref(&av_pkt);
  381. av_frame_free(&hwframe);
  382. return true;
  383. fail:
  384. av_frame_free(&hwframe);
  385. return false;
  386. }
  387. static void set_visible(obs_properties_t *ppts, const char *name, bool visible)
  388. {
  389. obs_property_t *p = obs_properties_get(ppts, name);
  390. obs_property_set_visible(p, visible);
  391. }
  392. static void vaapi_defaults(obs_data_t *settings)
  393. {
  394. obs_data_set_default_string(settings, "vaapi_device",
  395. "/dev/dri/renderD128");
  396. obs_data_set_default_int(settings, "vaapi_codec", AV_CODEC_ID_H264);
  397. obs_data_set_default_int(settings, "profile",
  398. FF_PROFILE_H264_CONSTRAINED_BASELINE);
  399. obs_data_set_default_int(settings, "level", 40);
  400. obs_data_set_default_int(settings, "bitrate", 2500);
  401. obs_data_set_default_int(settings, "keyint_sec", 0);
  402. obs_data_set_default_int(settings, "bf", 0);
  403. obs_data_set_default_int(settings, "rendermode", 0);
  404. obs_data_set_default_string(settings, "rate_control", "CBR");
  405. obs_data_set_default_int(settings, "qp", 20);
  406. obs_data_set_default_int(settings, "maxrate", 0);
  407. }
  408. static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p,
  409. obs_data_t *settings)
  410. {
  411. UNUSED_PARAMETER(p);
  412. const char *rate_control =
  413. obs_data_get_string(settings, "rate_control");
  414. const rc_mode_t *rc_mode = get_rc_mode(rate_control);
  415. /* Set options visibility per Rate Control */
  416. set_visible(ppts, "qp", rc_mode->qp);
  417. set_visible(ppts, "bitrate", rc_mode->bitrate);
  418. set_visible(ppts, "maxrate", rc_mode->maxrate);
  419. return true;
  420. }
  421. static obs_properties_t *vaapi_properties(void *unused)
  422. {
  423. UNUSED_PARAMETER(unused);
  424. obs_properties_t *props = obs_properties_create();
  425. obs_property_t *list;
  426. list = obs_properties_add_list(props, "vaapi_device", "VAAPI Device",
  427. OBS_COMBO_TYPE_LIST,
  428. OBS_COMBO_FORMAT_STRING);
  429. char path[32] = "/dev/dri/renderD1";
  430. for (int i = 28;; i++) {
  431. sprintf(path, "/dev/dri/renderD1%d", i);
  432. if (access(path, F_OK) == 0) {
  433. char card[128] = "Card: ";
  434. sprintf(card, "Card%d: %s", i - 28, path);
  435. obs_property_list_add_string(list, card, path);
  436. } else {
  437. break;
  438. }
  439. }
  440. list = obs_properties_add_list(props, "vaapi_codec", "VAAPI Codec",
  441. OBS_COMBO_TYPE_LIST,
  442. OBS_COMBO_FORMAT_INT);
  443. obs_property_list_add_int(list, "H.264 (default)", AV_CODEC_ID_H264);
  444. list = obs_properties_add_list(props, "level", "Level",
  445. OBS_COMBO_TYPE_LIST,
  446. OBS_COMBO_FORMAT_INT);
  447. obs_property_list_add_int(list, "480p30 (3.0)", 30);
  448. obs_property_list_add_int(list, "720p30/480p60 (3.1)", 31);
  449. obs_property_list_add_int(list, "Compatibility mode (4.0 default)",
  450. 40);
  451. obs_property_list_add_int(list, "720p60/1080p30 (4.1)", 41);
  452. obs_property_list_add_int(list, "1080p60 (4.2)", 42);
  453. list = obs_properties_add_list(props, "rate_control",
  454. obs_module_text("RateControl"),
  455. OBS_COMBO_TYPE_LIST,
  456. OBS_COMBO_FORMAT_STRING);
  457. obs_property_list_add_string(list, "CBR (default)", "CBR");
  458. obs_property_list_add_string(list, "CQP", "CQP");
  459. obs_property_list_add_string(list, "VBR", "VBR");
  460. obs_property_set_modified_callback(list, rate_control_modified);
  461. obs_property_t *p;
  462. p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"),
  463. 0, 300000, 50);
  464. obs_property_int_set_suffix(p, " Kbps");
  465. p = obs_properties_add_int(
  466. props, "maxrate", obs_module_text("MaxBitrate"), 0, 300000, 50);
  467. obs_property_int_set_suffix(p, " Kbps");
  468. obs_properties_add_int(props, "qp", "QP", 0, 51, 1);
  469. obs_properties_add_int(props, "keyint_sec",
  470. obs_module_text("KeyframeIntervalSec"), 0, 20,
  471. 1);
  472. return props;
  473. }
  474. static bool vaapi_extra_data(void *data, uint8_t **extra_data, size_t *size)
  475. {
  476. struct vaapi_encoder *enc = data;
  477. *extra_data = enc->header;
  478. *size = enc->header_size;
  479. return true;
  480. }
  481. static bool vaapi_sei_data(void *data, uint8_t **extra_data, size_t *size)
  482. {
  483. struct vaapi_encoder *enc = data;
  484. *extra_data = enc->sei;
  485. *size = enc->sei_size;
  486. return true;
  487. }
  488. struct obs_encoder_info vaapi_encoder_info = {
  489. .id = "ffmpeg_vaapi",
  490. .type = OBS_ENCODER_VIDEO,
  491. .codec = "h264",
  492. .get_name = vaapi_getname,
  493. .create = vaapi_create,
  494. .destroy = vaapi_destroy,
  495. .encode = vaapi_encode,
  496. .get_defaults = vaapi_defaults,
  497. .get_properties = vaapi_properties,
  498. .get_extra_data = vaapi_extra_data,
  499. .get_sei_data = vaapi_sei_data,
  500. .get_video_info = vaapi_video_info,
  501. };
  502. #endif