You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1239 lines
39KB

  1. /*
  2. * This file is part of Libav.
  3. *
  4. * Libav is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * Libav is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with Libav; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include <inttypes.h>
  19. #include <string.h>
  20. #include "libavutil/avassert.h"
  21. #include "libavutil/common.h"
  22. #include "libavutil/log.h"
  23. #include "libavutil/pixdesc.h"
  24. #include "vaapi_encode.h"
  25. #include "avcodec.h"
  26. static const char *picture_type_name[] = { "IDR", "I", "P", "B" };
  27. static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
  28. VAAPIEncodePicture *pic,
  29. int type, char *data, size_t bit_len)
  30. {
  31. VAAPIEncodeContext *ctx = avctx->priv_data;
  32. VAStatus vas;
  33. VABufferID param_buffer, data_buffer;
  34. VAEncPackedHeaderParameterBuffer params = {
  35. .type = type,
  36. .bit_length = bit_len,
  37. .has_emulation_bytes = 1,
  38. };
  39. av_assert0(pic->nb_param_buffers + 2 <= MAX_PARAM_BUFFERS);
  40. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  41. VAEncPackedHeaderParameterBufferType,
  42. sizeof(params), 1, &params, &param_buffer);
  43. if (vas != VA_STATUS_SUCCESS) {
  44. av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
  45. "for packed header (type %d): %d (%s).\n",
  46. type, vas, vaErrorStr(vas));
  47. return AVERROR(EIO);
  48. }
  49. pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
  50. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  51. VAEncPackedHeaderDataBufferType,
  52. (bit_len + 7) / 8, 1, data, &data_buffer);
  53. if (vas != VA_STATUS_SUCCESS) {
  54. av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
  55. "for packed header (type %d): %d (%s).\n",
  56. type, vas, vaErrorStr(vas));
  57. return AVERROR(EIO);
  58. }
  59. pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
  60. av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
  61. "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
  62. return 0;
  63. }
  64. static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
  65. VAAPIEncodePicture *pic,
  66. int type, char *data, size_t len)
  67. {
  68. VAAPIEncodeContext *ctx = avctx->priv_data;
  69. VAStatus vas;
  70. VABufferID buffer;
  71. av_assert0(pic->nb_param_buffers + 1 <= MAX_PARAM_BUFFERS);
  72. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  73. type, len, 1, data, &buffer);
  74. if (vas != VA_STATUS_SUCCESS) {
  75. av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
  76. "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
  77. return AVERROR(EIO);
  78. }
  79. pic->param_buffers[pic->nb_param_buffers++] = buffer;
  80. av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
  81. type, buffer);
  82. return 0;
  83. }
  84. static int vaapi_encode_wait(AVCodecContext *avctx,
  85. VAAPIEncodePicture *pic)
  86. {
  87. VAAPIEncodeContext *ctx = avctx->priv_data;
  88. VAStatus vas;
  89. av_assert0(pic->encode_issued);
  90. if (pic->encode_complete) {
  91. // Already waited for this picture.
  92. return 0;
  93. }
  94. av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
  95. "(recon surface %#x).\n", pic->display_order,
  96. pic->encode_order, pic->recon_surface);
  97. vas = vaSyncSurface(ctx->hwctx->display, pic->recon_surface);
  98. if (vas != VA_STATUS_SUCCESS) {
  99. av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
  100. "%d (%s).\n", vas, vaErrorStr(vas));
  101. return AVERROR(EIO);
  102. }
  103. // Input is definitely finished with now.
  104. av_frame_free(&pic->input_image);
  105. pic->encode_complete = 1;
  106. return 0;
  107. }
  108. static int vaapi_encode_issue(AVCodecContext *avctx,
  109. VAAPIEncodePicture *pic)
  110. {
  111. VAAPIEncodeContext *ctx = avctx->priv_data;
  112. VAAPIEncodeSlice *slice;
  113. VAStatus vas;
  114. int err, i;
  115. char data[MAX_PARAM_BUFFER_SIZE];
  116. size_t bit_len;
  117. av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
  118. "as type %s.\n", pic->display_order, pic->encode_order,
  119. picture_type_name[pic->type]);
  120. if (pic->nb_refs == 0) {
  121. av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
  122. } else {
  123. av_log(avctx, AV_LOG_DEBUG, "Refers to:");
  124. for (i = 0; i < pic->nb_refs; i++) {
  125. av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
  126. pic->refs[i]->display_order, pic->refs[i]->encode_order);
  127. }
  128. av_log(avctx, AV_LOG_DEBUG, ".\n");
  129. }
  130. av_assert0(pic->input_available && !pic->encode_issued);
  131. for (i = 0; i < pic->nb_refs; i++) {
  132. av_assert0(pic->refs[i]);
  133. // If we are serialised then the references must have already
  134. // completed. If not, they must have been issued but need not
  135. // have completed yet.
  136. if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
  137. av_assert0(pic->refs[i]->encode_complete);
  138. else
  139. av_assert0(pic->refs[i]->encode_issued);
  140. }
  141. av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
  142. pic->recon_image = av_frame_alloc();
  143. if (!pic->recon_image) {
  144. err = AVERROR(ENOMEM);
  145. goto fail;
  146. }
  147. err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
  148. if (err < 0) {
  149. err = AVERROR(ENOMEM);
  150. goto fail;
  151. }
  152. pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
  153. av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
  154. vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
  155. VAEncCodedBufferType,
  156. MAX_OUTPUT_BUFFER_SIZE, 1, 0,
  157. &pic->output_buffer);
  158. if (vas != VA_STATUS_SUCCESS) {
  159. av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
  160. "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
  161. err = AVERROR(ENOMEM);
  162. goto fail;
  163. }
  164. av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
  165. pic->output_buffer);
  166. if (ctx->codec->picture_params_size > 0) {
  167. pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
  168. if (!pic->codec_picture_params)
  169. goto fail;
  170. memcpy(pic->codec_picture_params, ctx->codec_picture_params,
  171. ctx->codec->picture_params_size);
  172. } else {
  173. av_assert0(!ctx->codec_picture_params);
  174. }
  175. pic->nb_param_buffers = 0;
  176. if (pic->encode_order == 0) {
  177. // Global parameter buffers are set on the first picture only.
  178. for (i = 0; i < ctx->nb_global_params; i++) {
  179. err = vaapi_encode_make_param_buffer(avctx, pic,
  180. VAEncMiscParameterBufferType,
  181. (char*)ctx->global_params[i],
  182. ctx->global_params_size[i]);
  183. if (err < 0)
  184. goto fail;
  185. }
  186. }
  187. if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
  188. err = vaapi_encode_make_param_buffer(avctx, pic,
  189. VAEncSequenceParameterBufferType,
  190. ctx->codec_sequence_params,
  191. ctx->codec->sequence_params_size);
  192. if (err < 0)
  193. goto fail;
  194. }
  195. if (ctx->codec->init_picture_params) {
  196. err = ctx->codec->init_picture_params(avctx, pic);
  197. if (err < 0) {
  198. av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
  199. "parameters: %d.\n", err);
  200. goto fail;
  201. }
  202. err = vaapi_encode_make_param_buffer(avctx, pic,
  203. VAEncPictureParameterBufferType,
  204. pic->codec_picture_params,
  205. ctx->codec->picture_params_size);
  206. if (err < 0)
  207. goto fail;
  208. }
  209. if (pic->type == PICTURE_TYPE_IDR) {
  210. if (ctx->codec->write_sequence_header) {
  211. bit_len = 8 * sizeof(data);
  212. err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
  213. if (err < 0) {
  214. av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
  215. "header: %d.\n", err);
  216. goto fail;
  217. }
  218. err = vaapi_encode_make_packed_header(avctx, pic,
  219. ctx->codec->sequence_header_type,
  220. data, bit_len);
  221. if (err < 0)
  222. goto fail;
  223. }
  224. }
  225. if (ctx->codec->write_picture_header) {
  226. bit_len = 8 * sizeof(data);
  227. err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
  228. if (err < 0) {
  229. av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
  230. "header: %d.\n", err);
  231. goto fail;
  232. }
  233. err = vaapi_encode_make_packed_header(avctx, pic,
  234. ctx->codec->picture_header_type,
  235. data, bit_len);
  236. if (err < 0)
  237. goto fail;
  238. }
  239. if (ctx->codec->write_extra_buffer) {
  240. for (i = 0;; i++) {
  241. size_t len = sizeof(data);
  242. int type;
  243. err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
  244. data, &len);
  245. if (err == AVERROR_EOF)
  246. break;
  247. if (err < 0) {
  248. av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
  249. "buffer %d: %d.\n", i, err);
  250. goto fail;
  251. }
  252. err = vaapi_encode_make_param_buffer(avctx, pic, type,
  253. data, len);
  254. if (err < 0)
  255. goto fail;
  256. }
  257. }
  258. av_assert0(pic->nb_slices <= MAX_PICTURE_SLICES);
  259. for (i = 0; i < pic->nb_slices; i++) {
  260. slice = av_mallocz(sizeof(*slice));
  261. if (!slice) {
  262. err = AVERROR(ENOMEM);
  263. goto fail;
  264. }
  265. pic->slices[i] = slice;
  266. if (ctx->codec->slice_params_size > 0) {
  267. slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
  268. if (!slice->codec_slice_params) {
  269. err = AVERROR(ENOMEM);
  270. goto fail;
  271. }
  272. }
  273. if (ctx->codec->init_slice_params) {
  274. err = ctx->codec->init_slice_params(avctx, pic, slice);
  275. if (err < 0) {
  276. av_log(avctx, AV_LOG_ERROR, "Failed to initalise slice "
  277. "parameters: %d.\n", err);
  278. goto fail;
  279. }
  280. }
  281. if (ctx->codec->write_slice_header) {
  282. bit_len = 8 * sizeof(data);
  283. err = ctx->codec->write_slice_header(avctx, pic, slice,
  284. data, &bit_len);
  285. if (err < 0) {
  286. av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
  287. "header: %d.\n", err);
  288. goto fail;
  289. }
  290. err = vaapi_encode_make_packed_header(avctx, pic,
  291. ctx->codec->slice_header_type,
  292. data, bit_len);
  293. if (err < 0)
  294. goto fail;
  295. }
  296. if (ctx->codec->init_slice_params) {
  297. err = vaapi_encode_make_param_buffer(avctx, pic,
  298. VAEncSliceParameterBufferType,
  299. slice->codec_slice_params,
  300. ctx->codec->slice_params_size);
  301. if (err < 0)
  302. goto fail;
  303. }
  304. }
  305. vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
  306. pic->input_surface);
  307. if (vas != VA_STATUS_SUCCESS) {
  308. av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
  309. "%d (%s).\n", vas, vaErrorStr(vas));
  310. err = AVERROR(EIO);
  311. goto fail_with_picture;
  312. }
  313. vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
  314. pic->param_buffers, pic->nb_param_buffers);
  315. if (vas != VA_STATUS_SUCCESS) {
  316. av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
  317. "%d (%s).\n", vas, vaErrorStr(vas));
  318. err = AVERROR(EIO);
  319. goto fail_with_picture;
  320. }
  321. vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
  322. if (vas != VA_STATUS_SUCCESS) {
  323. av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
  324. "%d (%s).\n", vas, vaErrorStr(vas));
  325. err = AVERROR(EIO);
  326. goto fail_at_end;
  327. }
  328. pic->encode_issued = 1;
  329. if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
  330. return vaapi_encode_wait(avctx, pic);
  331. else
  332. return 0;
  333. fail_with_picture:
  334. vaEndPicture(ctx->hwctx->display, ctx->va_context);
  335. fail:
  336. for(i = 0; i < pic->nb_param_buffers; i++)
  337. vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
  338. fail_at_end:
  339. av_freep(&pic->codec_picture_params);
  340. av_frame_free(&pic->recon_image);
  341. return err;
  342. }
  343. static int vaapi_encode_output(AVCodecContext *avctx,
  344. VAAPIEncodePicture *pic, AVPacket *pkt)
  345. {
  346. VAAPIEncodeContext *ctx = avctx->priv_data;
  347. VACodedBufferSegment *buf_list, *buf;
  348. VAStatus vas;
  349. int err;
  350. err = vaapi_encode_wait(avctx, pic);
  351. if (err < 0)
  352. return err;
  353. buf_list = NULL;
  354. vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
  355. (void**)&buf_list);
  356. if (vas != VA_STATUS_SUCCESS) {
  357. av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
  358. "%d (%s).\n", vas, vaErrorStr(vas));
  359. err = AVERROR(EIO);
  360. goto fail;
  361. }
  362. for (buf = buf_list; buf; buf = buf->next) {
  363. av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
  364. "(status %08x).\n", buf->size, buf->status);
  365. err = av_new_packet(pkt, buf->size);
  366. if (err < 0)
  367. goto fail;
  368. memcpy(pkt->data, buf->buf, buf->size);
  369. }
  370. if (pic->type == PICTURE_TYPE_IDR)
  371. pkt->flags |= AV_PKT_FLAG_KEY;
  372. pkt->pts = pic->pts;
  373. vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  374. if (vas != VA_STATUS_SUCCESS) {
  375. av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
  376. "%d (%s).\n", vas, vaErrorStr(vas));
  377. err = AVERROR(EIO);
  378. goto fail;
  379. }
  380. vaDestroyBuffer(ctx->hwctx->display, pic->output_buffer);
  381. pic->output_buffer = VA_INVALID_ID;
  382. av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
  383. pic->display_order, pic->encode_order);
  384. return 0;
  385. fail:
  386. if (pic->output_buffer != VA_INVALID_ID) {
  387. vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
  388. vaDestroyBuffer(ctx->hwctx->display, pic->output_buffer);
  389. pic->output_buffer = VA_INVALID_ID;
  390. }
  391. return err;
  392. }
  393. static int vaapi_encode_discard(AVCodecContext *avctx,
  394. VAAPIEncodePicture *pic)
  395. {
  396. VAAPIEncodeContext *ctx = avctx->priv_data;
  397. vaapi_encode_wait(avctx, pic);
  398. if (pic->output_buffer != VA_INVALID_ID) {
  399. av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
  400. "%"PRId64"/%"PRId64".\n",
  401. pic->display_order, pic->encode_order);
  402. vaDestroyBuffer(ctx->hwctx->display, pic->output_buffer);
  403. pic->output_buffer = VA_INVALID_ID;
  404. }
  405. return 0;
  406. }
  407. static VAAPIEncodePicture *vaapi_encode_alloc(void)
  408. {
  409. VAAPIEncodePicture *pic;
  410. pic = av_mallocz(sizeof(*pic));
  411. if (!pic)
  412. return NULL;
  413. pic->input_surface = VA_INVALID_ID;
  414. pic->recon_surface = VA_INVALID_ID;
  415. pic->output_buffer = VA_INVALID_ID;
  416. return pic;
  417. }
  418. static int vaapi_encode_free(AVCodecContext *avctx,
  419. VAAPIEncodePicture *pic)
  420. {
  421. int i;
  422. if (pic->encode_issued)
  423. vaapi_encode_discard(avctx, pic);
  424. for (i = 0; i < pic->nb_slices; i++) {
  425. av_freep(&pic->slices[i]->priv_data);
  426. av_freep(&pic->slices[i]->codec_slice_params);
  427. av_freep(&pic->slices[i]);
  428. }
  429. av_freep(&pic->codec_picture_params);
  430. av_frame_free(&pic->input_image);
  431. av_frame_free(&pic->recon_image);
  432. // Output buffer should already be destroyed.
  433. av_assert0(pic->output_buffer == VA_INVALID_ID);
  434. av_freep(&pic->priv_data);
  435. av_freep(&pic->codec_picture_params);
  436. av_free(pic);
  437. return 0;
  438. }
  439. static int vaapi_encode_step(AVCodecContext *avctx,
  440. VAAPIEncodePicture *target)
  441. {
  442. VAAPIEncodeContext *ctx = avctx->priv_data;
  443. VAAPIEncodePicture *pic;
  444. int i, err;
  445. if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
  446. ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
  447. // These two modes are equivalent, except that we wait for
  448. // immediate completion on each operation if serialised.
  449. if (!target) {
  450. // No target, nothing to do yet.
  451. return 0;
  452. }
  453. if (target->encode_complete) {
  454. // Already done.
  455. return 0;
  456. }
  457. pic = target;
  458. for (i = 0; i < pic->nb_refs; i++) {
  459. if (!pic->refs[i]->encode_complete) {
  460. err = vaapi_encode_step(avctx, pic->refs[i]);
  461. if (err < 0)
  462. return err;
  463. }
  464. }
  465. err = vaapi_encode_issue(avctx, pic);
  466. if (err < 0)
  467. return err;
  468. } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
  469. int activity;
  470. do {
  471. activity = 0;
  472. for (pic = ctx->pic_start; pic; pic = pic->next) {
  473. if (!pic->input_available || pic->encode_issued)
  474. continue;
  475. for (i = 0; i < pic->nb_refs; i++) {
  476. if (!pic->refs[i]->encode_issued)
  477. break;
  478. }
  479. if (i < pic->nb_refs)
  480. continue;
  481. err = vaapi_encode_issue(avctx, pic);
  482. if (err < 0)
  483. return err;
  484. activity = 1;
  485. }
  486. } while(activity);
  487. if (target) {
  488. av_assert0(target->encode_issued && "broken dependencies?");
  489. }
  490. } else {
  491. av_assert0(0);
  492. }
  493. return 0;
  494. }
  495. static int vaapi_encode_get_next(AVCodecContext *avctx,
  496. VAAPIEncodePicture **pic_out)
  497. {
  498. VAAPIEncodeContext *ctx = avctx->priv_data;
  499. VAAPIEncodePicture *start, *end, *pic;
  500. int i;
  501. for (pic = ctx->pic_start; pic; pic = pic->next) {
  502. if (pic->next)
  503. av_assert0(pic->display_order + 1 == pic->next->display_order);
  504. if (pic->display_order == ctx->input_order) {
  505. *pic_out = pic;
  506. return 0;
  507. }
  508. }
  509. if (ctx->input_order == 0) {
  510. // First frame is always an IDR frame.
  511. av_assert0(!ctx->pic_start && !ctx->pic_end);
  512. pic = vaapi_encode_alloc();
  513. if (!pic)
  514. return AVERROR(ENOMEM);
  515. pic->type = PICTURE_TYPE_IDR;
  516. pic->display_order = 0;
  517. pic->encode_order = 0;
  518. ctx->pic_start = ctx->pic_end = pic;
  519. *pic_out = pic;
  520. return 0;
  521. }
  522. pic = vaapi_encode_alloc();
  523. if (!pic)
  524. return AVERROR(ENOMEM);
  525. if (ctx->p_per_i == 0 || ctx->p_counter == ctx->p_per_i) {
  526. if (ctx->i_per_idr == 0 || ctx->i_counter == ctx->i_per_idr) {
  527. pic->type = PICTURE_TYPE_IDR;
  528. ctx->i_counter = 0;
  529. } else {
  530. pic->type = PICTURE_TYPE_I;
  531. ++ctx->i_counter;
  532. }
  533. ctx->p_counter = 0;
  534. } else {
  535. pic->type = PICTURE_TYPE_P;
  536. pic->refs[0] = ctx->pic_end;
  537. pic->nb_refs = 1;
  538. ++ctx->p_counter;
  539. }
  540. start = end = pic;
  541. if (pic->type != PICTURE_TYPE_IDR) {
  542. // If that was not an IDR frame, add B-frames display-before and
  543. // encode-after it.
  544. for (i = 0; i < ctx->b_per_p; i++) {
  545. pic = vaapi_encode_alloc();
  546. if (!pic)
  547. goto fail;
  548. pic->type = PICTURE_TYPE_B;
  549. pic->refs[0] = ctx->pic_end;
  550. pic->refs[1] = end;
  551. pic->nb_refs = 2;
  552. pic->next = start;
  553. pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
  554. pic->encode_order = pic->display_order + 1;
  555. start = pic;
  556. }
  557. }
  558. for (i = 0, pic = start; pic; i++, pic = pic->next) {
  559. pic->display_order = ctx->input_order + i;
  560. if (end->type == PICTURE_TYPE_IDR)
  561. pic->encode_order = ctx->input_order + i;
  562. else if (pic == end)
  563. pic->encode_order = ctx->input_order;
  564. else
  565. pic->encode_order = ctx->input_order + i + 1;
  566. }
  567. av_assert0(ctx->pic_end);
  568. ctx->pic_end->next = start;
  569. ctx->pic_end = end;
  570. *pic_out = start;
  571. av_log(avctx, AV_LOG_DEBUG, "Pictures:");
  572. for (pic = ctx->pic_start; pic; pic = pic->next) {
  573. av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
  574. picture_type_name[pic->type],
  575. pic->display_order, pic->encode_order);
  576. }
  577. av_log(avctx, AV_LOG_DEBUG, "\n");
  578. return 0;
  579. fail:
  580. while (start) {
  581. pic = start->next;
  582. vaapi_encode_free(avctx, start);
  583. start = pic;
  584. }
  585. return AVERROR(ENOMEM);
  586. }
  587. static int vaapi_encode_mangle_end(AVCodecContext *avctx)
  588. {
  589. VAAPIEncodeContext *ctx = avctx->priv_data;
  590. VAAPIEncodePicture *pic, *last_pic, *next;
  591. // Find the last picture we actually have input for.
  592. for (pic = ctx->pic_start; pic; pic = pic->next) {
  593. if (!pic->input_available)
  594. break;
  595. last_pic = pic;
  596. }
  597. if (pic) {
  598. av_assert0(last_pic);
  599. if (last_pic->type == PICTURE_TYPE_B) {
  600. // Some fixing up is required. Change the type of this
  601. // picture to P, then modify preceding B references which
  602. // point beyond it to point at it instead.
  603. last_pic->type = PICTURE_TYPE_P;
  604. last_pic->encode_order = last_pic->refs[1]->encode_order;
  605. for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
  606. if (pic->type == PICTURE_TYPE_B &&
  607. pic->refs[1] == last_pic->refs[1])
  608. pic->refs[1] = last_pic;
  609. }
  610. last_pic->nb_refs = 1;
  611. last_pic->refs[1] = NULL;
  612. } else {
  613. // We can use the current structure (no references point
  614. // beyond the end), but there are unused pics to discard.
  615. }
  616. // Discard all following pics, they will never be used.
  617. for (pic = last_pic->next; pic; pic = next) {
  618. next = pic->next;
  619. vaapi_encode_free(avctx, pic);
  620. }
  621. last_pic->next = NULL;
  622. ctx->pic_end = last_pic;
  623. } else {
  624. // Input is available for all pictures, so we don't need to
  625. // mangle anything.
  626. }
  627. av_log(avctx, AV_LOG_DEBUG, "Pictures at end of stream:");
  628. for (pic = ctx->pic_start; pic; pic = pic->next) {
  629. av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
  630. picture_type_name[pic->type],
  631. pic->display_order, pic->encode_order);
  632. }
  633. av_log(avctx, AV_LOG_DEBUG, "\n");
  634. return 0;
  635. }
  636. static int vaapi_encode_clear_old(AVCodecContext *avctx)
  637. {
  638. VAAPIEncodeContext *ctx = avctx->priv_data;
  639. VAAPIEncodePicture *pic, *old;
  640. int i;
  641. while (ctx->pic_start != ctx->pic_end) {
  642. old = ctx->pic_start;
  643. if (old->encode_order > ctx->output_order)
  644. break;
  645. for (pic = old->next; pic; pic = pic->next) {
  646. if (pic->encode_complete)
  647. continue;
  648. for (i = 0; i < pic->nb_refs; i++) {
  649. if (pic->refs[i] == old) {
  650. // We still need this picture because it's referred to
  651. // directly by a later one, so it and all following
  652. // pictures have to stay.
  653. return 0;
  654. }
  655. }
  656. }
  657. pic = ctx->pic_start;
  658. ctx->pic_start = pic->next;
  659. vaapi_encode_free(avctx, pic);
  660. }
  661. return 0;
  662. }
  663. int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
  664. const AVFrame *input_image, int *got_packet)
  665. {
  666. VAAPIEncodeContext *ctx = avctx->priv_data;
  667. VAAPIEncodePicture *pic;
  668. int err;
  669. if (input_image) {
  670. av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
  671. input_image->width, input_image->height, input_image->pts);
  672. err = vaapi_encode_get_next(avctx, &pic);
  673. if (err) {
  674. av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
  675. return err;
  676. }
  677. pic->input_image = av_frame_alloc();
  678. if (!pic->input_image) {
  679. err = AVERROR(ENOMEM);
  680. goto fail;
  681. }
  682. err = av_frame_ref(pic->input_image, input_image);
  683. if (err < 0)
  684. goto fail;
  685. pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
  686. pic->pts = input_image->pts;
  687. if (ctx->input_order == 0)
  688. ctx->first_pts = pic->pts;
  689. if (ctx->input_order == ctx->decode_delay)
  690. ctx->dts_pts_diff = pic->pts - ctx->first_pts;
  691. if (ctx->output_delay > 0)
  692. ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
  693. pic->input_available = 1;
  694. } else {
  695. if (!ctx->end_of_stream) {
  696. err = vaapi_encode_mangle_end(avctx);
  697. if (err < 0)
  698. goto fail;
  699. ctx->end_of_stream = 1;
  700. }
  701. }
  702. ++ctx->input_order;
  703. ++ctx->output_order;
  704. av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
  705. for (pic = ctx->pic_start; pic; pic = pic->next)
  706. if (pic->encode_order == ctx->output_order)
  707. break;
  708. // pic can be null here if we don't have a specific target in this
  709. // iteration. We might still issue encodes if things can be overlapped,
  710. // even though we don't intend to output anything.
  711. err = vaapi_encode_step(avctx, pic);
  712. if (err < 0) {
  713. av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
  714. goto fail;
  715. }
  716. if (!pic) {
  717. *got_packet = 0;
  718. } else {
  719. err = vaapi_encode_output(avctx, pic, pkt);
  720. if (err < 0) {
  721. av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
  722. goto fail;
  723. }
  724. if (ctx->output_delay == 0) {
  725. pkt->dts = pkt->pts;
  726. } else if (ctx->output_order < ctx->decode_delay) {
  727. if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
  728. pkt->dts = INT64_MIN;
  729. else
  730. pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
  731. } else {
  732. pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
  733. (3 * ctx->output_delay)];
  734. }
  735. *got_packet = 1;
  736. }
  737. err = vaapi_encode_clear_old(avctx);
  738. if (err < 0) {
  739. av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
  740. goto fail;
  741. }
  742. return 0;
  743. fail:
  744. // Unclear what to clean up on failure. There are probably some things we
  745. // could do usefully clean up here, but for now just leave them for uninit()
  746. // to do instead.
  747. return err;
  748. }
  749. static av_cold int vaapi_encode_check_config(AVCodecContext *avctx)
  750. {
  751. VAAPIEncodeContext *ctx = avctx->priv_data;
  752. VAStatus vas;
  753. int i, n, err;
  754. VAProfile *profiles = NULL;
  755. VAEntrypoint *entrypoints = NULL;
  756. VAConfigAttrib attr[] = {
  757. { VAConfigAttribRateControl },
  758. { VAConfigAttribEncMaxRefFrames },
  759. };
  760. n = vaMaxNumProfiles(ctx->hwctx->display);
  761. profiles = av_malloc_array(n, sizeof(VAProfile));
  762. if (!profiles) {
  763. err = AVERROR(ENOMEM);
  764. goto fail;
  765. }
  766. vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);
  767. if (vas != VA_STATUS_SUCCESS) {
  768. av_log(ctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
  769. vas, vaErrorStr(vas));
  770. err = AVERROR(ENOSYS);
  771. goto fail;
  772. }
  773. for (i = 0; i < n; i++) {
  774. if (profiles[i] == ctx->va_profile)
  775. break;
  776. }
  777. if (i >= n) {
  778. av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",
  779. ctx->va_profile);
  780. err = AVERROR(ENOSYS);
  781. goto fail;
  782. }
  783. n = vaMaxNumEntrypoints(ctx->hwctx->display);
  784. entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
  785. if (!entrypoints) {
  786. err = AVERROR(ENOMEM);
  787. goto fail;
  788. }
  789. vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
  790. entrypoints, &n);
  791. if (vas != VA_STATUS_SUCCESS) {
  792. av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "
  793. "profile %u: %d (%s).\n", ctx->va_profile,
  794. vas, vaErrorStr(vas));
  795. err = AVERROR(ENOSYS);
  796. goto fail;
  797. }
  798. for (i = 0; i < n; i++) {
  799. if (entrypoints[i] == ctx->va_entrypoint)
  800. break;
  801. }
  802. if (i >= n) {
  803. av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "
  804. "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);
  805. err = AVERROR(ENOSYS);
  806. goto fail;
  807. }
  808. vas = vaGetConfigAttributes(ctx->hwctx->display,
  809. ctx->va_profile, ctx->va_entrypoint,
  810. attr, FF_ARRAY_ELEMS(attr));
  811. if (vas != VA_STATUS_SUCCESS) {
  812. av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "
  813. "attributes: %d (%s).\n", vas, vaErrorStr(vas));
  814. return AVERROR(EINVAL);
  815. }
  816. for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {
  817. if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {
  818. // Unfortunately we have to treat this as "don't know" and hope
  819. // for the best, because the Intel MJPEG encoder returns this
  820. // for all the interesting attributes.
  821. continue;
  822. }
  823. switch (attr[i].type) {
  824. case VAConfigAttribRateControl:
  825. if (!(ctx->va_rc_mode & attr[i].value)) {
  826. av_log(avctx, AV_LOG_ERROR, "Rate control mode is not "
  827. "supported: %x\n", attr[i].value);
  828. err = AVERROR(EINVAL);
  829. goto fail;
  830. }
  831. break;
  832. case VAConfigAttribEncMaxRefFrames:
  833. {
  834. unsigned int ref_l0 = attr[i].value & 0xffff;
  835. unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;
  836. if (avctx->gop_size > 1 && ref_l0 < 1) {
  837. av_log(avctx, AV_LOG_ERROR, "P frames are not "
  838. "supported (%x).\n", attr[i].value);
  839. err = AVERROR(EINVAL);
  840. goto fail;
  841. }
  842. if (avctx->max_b_frames > 0 && ref_l1 < 1) {
  843. av_log(avctx, AV_LOG_ERROR, "B frames are not "
  844. "supported (%x).\n", attr[i].value);
  845. err = AVERROR(EINVAL);
  846. goto fail;
  847. }
  848. }
  849. break;
  850. }
  851. }
  852. err = 0;
  853. fail:
  854. av_freep(&profiles);
  855. av_freep(&entrypoints);
  856. return err;
  857. }
  858. av_cold int ff_vaapi_encode_init(AVCodecContext *avctx,
  859. const VAAPIEncodeType *type)
  860. {
  861. VAAPIEncodeContext *ctx = avctx->priv_data;
  862. AVVAAPIFramesContext *recon_hwctx = NULL;
  863. AVVAAPIHWConfig *hwconfig = NULL;
  864. AVHWFramesConstraints *constraints = NULL;
  865. enum AVPixelFormat recon_format;
  866. VAStatus vas;
  867. int err, i;
  868. if (!avctx->hw_frames_ctx) {
  869. av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
  870. "required to associate the encoding device.\n");
  871. return AVERROR(EINVAL);
  872. }
  873. ctx->codec = type;
  874. ctx->codec_options = ctx->codec_options_data;
  875. ctx->va_config = VA_INVALID_ID;
  876. ctx->va_context = VA_INVALID_ID;
  877. ctx->priv_data = av_mallocz(type->priv_data_size);
  878. if (!ctx->priv_data) {
  879. err = AVERROR(ENOMEM);
  880. goto fail;
  881. }
  882. ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
  883. if (!ctx->input_frames_ref) {
  884. err = AVERROR(ENOMEM);
  885. goto fail;
  886. }
  887. ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
  888. ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
  889. if (!ctx->device_ref) {
  890. err = AVERROR(ENOMEM);
  891. goto fail;
  892. }
  893. ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
  894. ctx->hwctx = ctx->device->hwctx;
  895. err = ctx->codec->init(avctx);
  896. if (err < 0)
  897. goto fail;
  898. err = vaapi_encode_check_config(avctx);
  899. if (err < 0)
  900. goto fail;
  901. vas = vaCreateConfig(ctx->hwctx->display,
  902. ctx->va_profile, ctx->va_entrypoint,
  903. ctx->config_attributes, ctx->nb_config_attributes,
  904. &ctx->va_config);
  905. if (vas != VA_STATUS_SUCCESS) {
  906. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  907. "configuration: %d (%s).\n", vas, vaErrorStr(vas));
  908. err = AVERROR(EIO);
  909. goto fail;
  910. }
  911. hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
  912. if (!hwconfig) {
  913. err = AVERROR(ENOMEM);
  914. goto fail;
  915. }
  916. hwconfig->config_id = ctx->va_config;
  917. constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
  918. hwconfig);
  919. if (!constraints) {
  920. err = AVERROR(ENOMEM);
  921. goto fail;
  922. }
  923. // Probably we can use the input surface format as the surface format
  924. // of the reconstructed frames. If not, we just pick the first (only?)
  925. // format in the valid list and hope that it all works.
  926. recon_format = AV_PIX_FMT_NONE;
  927. if (constraints->valid_sw_formats) {
  928. for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
  929. if (ctx->input_frames->sw_format ==
  930. constraints->valid_sw_formats[i]) {
  931. recon_format = ctx->input_frames->sw_format;
  932. break;
  933. }
  934. }
  935. if (recon_format == AV_PIX_FMT_NONE)
  936. recon_format = constraints->valid_sw_formats[i];
  937. } else {
  938. // No idea what to use; copy input format.
  939. recon_format = ctx->input_frames->sw_format;
  940. }
  941. av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
  942. "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
  943. if (ctx->aligned_width < constraints->min_width ||
  944. ctx->aligned_height < constraints->min_height ||
  945. ctx->aligned_width > constraints->max_width ||
  946. ctx->aligned_height > constraints->max_height) {
  947. av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
  948. "size %dx%d (constraints: width %d-%d height %d-%d).\n",
  949. ctx->aligned_width, ctx->aligned_height,
  950. constraints->min_width, constraints->max_width,
  951. constraints->min_height, constraints->max_height);
  952. err = AVERROR(EINVAL);
  953. goto fail;
  954. }
  955. av_freep(&hwconfig);
  956. av_hwframe_constraints_free(&constraints);
  957. ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
  958. if (!ctx->recon_frames_ref) {
  959. err = AVERROR(ENOMEM);
  960. goto fail;
  961. }
  962. ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
  963. ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
  964. ctx->recon_frames->sw_format = recon_format;
  965. ctx->recon_frames->width = ctx->aligned_width;
  966. ctx->recon_frames->height = ctx->aligned_height;
  967. ctx->recon_frames->initial_pool_size = ctx->nb_recon_frames;
  968. err = av_hwframe_ctx_init(ctx->recon_frames_ref);
  969. if (err < 0) {
  970. av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
  971. "frame context: %d.\n", err);
  972. goto fail;
  973. }
  974. recon_hwctx = ctx->recon_frames->hwctx;
  975. vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
  976. ctx->aligned_width, ctx->aligned_height,
  977. VA_PROGRESSIVE,
  978. recon_hwctx->surface_ids,
  979. recon_hwctx->nb_surfaces,
  980. &ctx->va_context);
  981. if (vas != VA_STATUS_SUCCESS) {
  982. av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
  983. "context: %d (%s).\n", vas, vaErrorStr(vas));
  984. err = AVERROR(EIO);
  985. goto fail;
  986. }
  987. ctx->input_order = 0;
  988. ctx->output_delay = avctx->max_b_frames;
  989. ctx->decode_delay = 1;
  990. ctx->output_order = - ctx->output_delay - 1;
  991. if (ctx->codec->sequence_params_size > 0) {
  992. ctx->codec_sequence_params =
  993. av_mallocz(ctx->codec->sequence_params_size);
  994. if (!ctx->codec_sequence_params) {
  995. err = AVERROR(ENOMEM);
  996. goto fail;
  997. }
  998. }
  999. if (ctx->codec->picture_params_size > 0) {
  1000. ctx->codec_picture_params =
  1001. av_mallocz(ctx->codec->picture_params_size);
  1002. if (!ctx->codec_picture_params) {
  1003. err = AVERROR(ENOMEM);
  1004. goto fail;
  1005. }
  1006. }
  1007. if (ctx->codec->init_sequence_params) {
  1008. err = ctx->codec->init_sequence_params(avctx);
  1009. if (err < 0) {
  1010. av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
  1011. "failed: %d.\n", err);
  1012. goto fail;
  1013. }
  1014. }
  1015. // All I are IDR for now.
  1016. ctx->i_per_idr = 0;
  1017. ctx->p_per_i = ((avctx->gop_size + avctx->max_b_frames) /
  1018. (avctx->max_b_frames + 1));
  1019. ctx->b_per_p = avctx->max_b_frames;
  1020. // This should be configurable somehow. (Needs testing on a machine
  1021. // where it actually overlaps properly, though.)
  1022. ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
  1023. return 0;
  1024. fail:
  1025. av_freep(&hwconfig);
  1026. av_hwframe_constraints_free(&constraints);
  1027. ff_vaapi_encode_close(avctx);
  1028. return err;
  1029. }
  1030. av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
  1031. {
  1032. VAAPIEncodeContext *ctx = avctx->priv_data;
  1033. VAAPIEncodePicture *pic, *next;
  1034. for (pic = ctx->pic_start; pic; pic = next) {
  1035. next = pic->next;
  1036. vaapi_encode_free(avctx, pic);
  1037. }
  1038. if (ctx->va_context != VA_INVALID_ID) {
  1039. vaDestroyContext(ctx->hwctx->display, ctx->va_context);
  1040. ctx->va_context = VA_INVALID_ID;
  1041. }
  1042. if (ctx->va_config != VA_INVALID_ID) {
  1043. vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
  1044. ctx->va_config = VA_INVALID_ID;
  1045. }
  1046. if (ctx->codec->close)
  1047. ctx->codec->close(avctx);
  1048. av_freep(&ctx->codec_sequence_params);
  1049. av_freep(&ctx->codec_picture_params);
  1050. av_buffer_unref(&ctx->recon_frames_ref);
  1051. av_buffer_unref(&ctx->input_frames_ref);
  1052. av_buffer_unref(&ctx->device_ref);
  1053. av_freep(&ctx->priv_data);
  1054. return 0;
  1055. }