2 * This file is part of FFmpeg.
4 * FFmpeg 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.
9 * FFmpeg 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.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with FFmpeg; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/avassert.h"
23 #include "libavutil/common.h"
24 #include "libavutil/log.h"
25 #include "libavutil/pixdesc.h"
27 #include "vaapi_encode.h"
31 const AVCodecHWConfigInternal *ff_vaapi_encode_hw_configs[] = {
32 HW_CONFIG_ENCODER_FRAMES(VAAPI, VAAPI),
36 static const char * const picture_type_name[] = { "IDR", "I", "P", "B" };
38 static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
39 VAAPIEncodePicture *pic,
40 int type, char *data, size_t bit_len)
42 VAAPIEncodeContext *ctx = avctx->priv_data;
44 VABufferID param_buffer, data_buffer;
46 VAEncPackedHeaderParameterBuffer params = {
48 .bit_length = bit_len,
49 .has_emulation_bytes = 1,
52 tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 2);
54 return AVERROR(ENOMEM);
55 pic->param_buffers = tmp;
57 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
58 VAEncPackedHeaderParameterBufferType,
59 sizeof(params), 1, ¶ms, ¶m_buffer);
60 if (vas != VA_STATUS_SUCCESS) {
61 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
62 "for packed header (type %d): %d (%s).\n",
63 type, vas, vaErrorStr(vas));
66 pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
68 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
69 VAEncPackedHeaderDataBufferType,
70 (bit_len + 7) / 8, 1, data, &data_buffer);
71 if (vas != VA_STATUS_SUCCESS) {
72 av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
73 "for packed header (type %d): %d (%s).\n",
74 type, vas, vaErrorStr(vas));
77 pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
79 av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
80 "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
84 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
85 VAAPIEncodePicture *pic,
86 int type, char *data, size_t len)
88 VAAPIEncodeContext *ctx = avctx->priv_data;
93 tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 1);
95 return AVERROR(ENOMEM);
96 pic->param_buffers = tmp;
98 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
99 type, len, 1, data, &buffer);
100 if (vas != VA_STATUS_SUCCESS) {
101 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
102 "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
105 pic->param_buffers[pic->nb_param_buffers++] = buffer;
107 av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
112 static int vaapi_encode_make_misc_param_buffer(AVCodecContext *avctx,
113 VAAPIEncodePicture *pic,
115 const void *data, size_t len)
117 // Construct the buffer on the stack - 1KB is much larger than any
118 // current misc parameter buffer type (the largest is EncQuality at
120 uint8_t buffer[1024];
121 VAEncMiscParameterBuffer header = {
124 size_t buffer_size = sizeof(header) + len;
125 av_assert0(buffer_size <= sizeof(buffer));
127 memcpy(buffer, &header, sizeof(header));
128 memcpy(buffer + sizeof(header), data, len);
130 return vaapi_encode_make_param_buffer(avctx, pic,
131 VAEncMiscParameterBufferType,
132 buffer, buffer_size);
135 static int vaapi_encode_wait(AVCodecContext *avctx,
136 VAAPIEncodePicture *pic)
138 VAAPIEncodeContext *ctx = avctx->priv_data;
141 av_assert0(pic->encode_issued);
143 if (pic->encode_complete) {
144 // Already waited for this picture.
148 av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
149 "(input surface %#x).\n", pic->display_order,
150 pic->encode_order, pic->input_surface);
152 vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
153 if (vas != VA_STATUS_SUCCESS) {
154 av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
155 "%d (%s).\n", vas, vaErrorStr(vas));
159 // Input is definitely finished with now.
160 av_frame_free(&pic->input_image);
162 pic->encode_complete = 1;
166 static int vaapi_encode_issue(AVCodecContext *avctx,
167 VAAPIEncodePicture *pic)
169 VAAPIEncodeContext *ctx = avctx->priv_data;
170 VAAPIEncodeSlice *slice;
173 char data[MAX_PARAM_BUFFER_SIZE];
175 av_unused AVFrameSideData *sd;
177 av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
178 "as type %s.\n", pic->display_order, pic->encode_order,
179 picture_type_name[pic->type]);
180 if (pic->nb_refs == 0) {
181 av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
183 av_log(avctx, AV_LOG_DEBUG, "Refers to:");
184 for (i = 0; i < pic->nb_refs; i++) {
185 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
186 pic->refs[i]->display_order, pic->refs[i]->encode_order);
188 av_log(avctx, AV_LOG_DEBUG, ".\n");
191 av_assert0(!pic->encode_issued);
192 for (i = 0; i < pic->nb_refs; i++) {
193 av_assert0(pic->refs[i]);
194 av_assert0(pic->refs[i]->encode_issued);
197 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
199 pic->recon_image = av_frame_alloc();
200 if (!pic->recon_image) {
201 err = AVERROR(ENOMEM);
205 err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
207 err = AVERROR(ENOMEM);
210 pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
211 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
213 pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
214 if (!pic->output_buffer_ref) {
215 err = AVERROR(ENOMEM);
218 pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
219 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
222 if (ctx->codec->picture_params_size > 0) {
223 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
224 if (!pic->codec_picture_params)
226 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
227 ctx->codec->picture_params_size);
229 av_assert0(!ctx->codec_picture_params);
232 pic->nb_param_buffers = 0;
234 if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
235 err = vaapi_encode_make_param_buffer(avctx, pic,
236 VAEncSequenceParameterBufferType,
237 ctx->codec_sequence_params,
238 ctx->codec->sequence_params_size);
243 if (pic->type == PICTURE_TYPE_IDR) {
244 for (i = 0; i < ctx->nb_global_params; i++) {
245 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
246 ctx->global_params_type[i],
247 ctx->global_params[i],
248 ctx->global_params_size[i]);
254 if (ctx->codec->init_picture_params) {
255 err = ctx->codec->init_picture_params(avctx, pic);
257 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
258 "parameters: %d.\n", err);
261 err = vaapi_encode_make_param_buffer(avctx, pic,
262 VAEncPictureParameterBufferType,
263 pic->codec_picture_params,
264 ctx->codec->picture_params_size);
269 if (pic->type == PICTURE_TYPE_IDR) {
270 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
271 ctx->codec->write_sequence_header) {
272 bit_len = 8 * sizeof(data);
273 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
275 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
276 "header: %d.\n", err);
279 err = vaapi_encode_make_packed_header(avctx, pic,
280 ctx->codec->sequence_header_type,
287 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
288 ctx->codec->write_picture_header) {
289 bit_len = 8 * sizeof(data);
290 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
292 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
293 "header: %d.\n", err);
296 err = vaapi_encode_make_packed_header(avctx, pic,
297 ctx->codec->picture_header_type,
303 if (ctx->codec->write_extra_buffer) {
305 size_t len = sizeof(data);
307 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
309 if (err == AVERROR_EOF)
312 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
313 "buffer %d: %d.\n", i, err);
317 err = vaapi_encode_make_param_buffer(avctx, pic, type,
324 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
325 ctx->codec->write_extra_header) {
328 bit_len = 8 * sizeof(data);
329 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
331 if (err == AVERROR_EOF)
334 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
335 "header %d: %d.\n", i, err);
339 err = vaapi_encode_make_packed_header(avctx, pic, type,
346 if (pic->nb_slices == 0)
347 pic->nb_slices = ctx->nb_slices;
348 if (pic->nb_slices > 0) {
351 pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
353 err = AVERROR(ENOMEM);
357 for (i = 0; i < pic->nb_slices; i++)
358 pic->slices[i].row_size = ctx->slice_size;
360 rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
362 // Place rounding error at top and bottom of frame.
363 av_assert0(rounding < pic->nb_slices);
364 // Some Intel drivers contain a bug where the encoder will fail
365 // if the last slice is smaller than the one before it. Since
366 // that's straightforward to avoid here, just do so.
368 for (i = 0; i < rounding; i++)
369 ++pic->slices[i].row_size;
371 for (i = 0; i < (rounding + 1) / 2; i++)
372 ++pic->slices[pic->nb_slices - i - 1].row_size;
373 for (i = 0; i < rounding / 2; i++)
374 ++pic->slices[i].row_size;
376 } else if (rounding < 0) {
377 // Remove rounding error from last slice only.
378 av_assert0(rounding < ctx->slice_size);
379 pic->slices[pic->nb_slices - 1].row_size += rounding;
382 for (i = 0; i < pic->nb_slices; i++) {
383 slice = &pic->slices[i];
386 slice->row_start = 0;
387 slice->block_start = 0;
389 const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
390 slice->row_start = prev->row_start + prev->row_size;
391 slice->block_start = prev->block_start + prev->block_size;
393 slice->block_size = slice->row_size * ctx->slice_block_cols;
395 av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
396 "%d-%d (%d blocks).\n", i, slice->row_start,
397 slice->row_start + slice->row_size - 1, slice->row_size,
398 slice->block_start, slice->block_start + slice->block_size - 1,
401 if (ctx->codec->slice_params_size > 0) {
402 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
403 if (!slice->codec_slice_params) {
404 err = AVERROR(ENOMEM);
409 if (ctx->codec->init_slice_params) {
410 err = ctx->codec->init_slice_params(avctx, pic, slice);
412 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
413 "parameters: %d.\n", err);
418 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
419 ctx->codec->write_slice_header) {
420 bit_len = 8 * sizeof(data);
421 err = ctx->codec->write_slice_header(avctx, pic, slice,
424 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
425 "header: %d.\n", err);
428 err = vaapi_encode_make_packed_header(avctx, pic,
429 ctx->codec->slice_header_type,
435 if (ctx->codec->init_slice_params) {
436 err = vaapi_encode_make_param_buffer(avctx, pic,
437 VAEncSliceParameterBufferType,
438 slice->codec_slice_params,
439 ctx->codec->slice_params_size);
445 #if VA_CHECK_VERSION(1, 0, 0)
446 sd = av_frame_get_side_data(pic->input_image,
447 AV_FRAME_DATA_REGIONS_OF_INTEREST);
448 if (sd && ctx->roi_allowed) {
449 const AVRegionOfInterest *roi;
451 VAEncMiscParameterBufferROI param_roi;
454 roi = (const AVRegionOfInterest*)sd->data;
455 roi_size = roi->self_size;
456 av_assert0(roi_size && sd->size % roi_size == 0);
457 nb_roi = sd->size / roi_size;
458 if (nb_roi > ctx->roi_max_regions) {
459 if (!ctx->roi_warned) {
460 av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
461 "supported by driver (%d > %d).\n",
462 nb_roi, ctx->roi_max_regions);
465 nb_roi = ctx->roi_max_regions;
468 pic->roi = av_mallocz_array(nb_roi, sizeof(*pic->roi));
470 err = AVERROR(ENOMEM);
473 // For overlapping regions, the first in the array takes priority.
474 for (i = 0; i < nb_roi; i++) {
475 roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
477 av_assert0(roi->qoffset.den != 0);
478 v = roi->qoffset.num * ctx->roi_quant_range / roi->qoffset.den;
479 av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
480 roi->top, roi->left, roi->bottom, roi->right, v);
482 pic->roi[i] = (VAEncROI) {
486 .width = roi->right - roi->left,
487 .height = roi->bottom - roi->top,
489 .roi_value = av_clip_int8(v),
493 param_roi = (VAEncMiscParameterBufferROI) {
495 .max_delta_qp = INT8_MAX,
496 .min_delta_qp = INT8_MIN,
498 .roi_flags.bits.roi_value_is_qp_delta = 1,
501 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
502 VAEncMiscParameterTypeROI,
510 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
512 if (vas != VA_STATUS_SUCCESS) {
513 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
514 "%d (%s).\n", vas, vaErrorStr(vas));
516 goto fail_with_picture;
519 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
520 pic->param_buffers, pic->nb_param_buffers);
521 if (vas != VA_STATUS_SUCCESS) {
522 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
523 "%d (%s).\n", vas, vaErrorStr(vas));
525 goto fail_with_picture;
528 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
529 if (vas != VA_STATUS_SUCCESS) {
530 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
531 "%d (%s).\n", vas, vaErrorStr(vas));
533 // vaRenderPicture() has been called here, so we should not destroy
534 // the parameter buffers unless separate destruction is required.
535 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
536 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
542 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
543 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
544 for (i = 0; i < pic->nb_param_buffers; i++) {
545 vas = vaDestroyBuffer(ctx->hwctx->display,
546 pic->param_buffers[i]);
547 if (vas != VA_STATUS_SUCCESS) {
548 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
549 "param buffer %#x: %d (%s).\n",
550 pic->param_buffers[i], vas, vaErrorStr(vas));
556 pic->encode_issued = 1;
561 vaEndPicture(ctx->hwctx->display, ctx->va_context);
563 for(i = 0; i < pic->nb_param_buffers; i++)
564 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
565 for (i = 0; i < pic->nb_slices; i++) {
567 av_freep(&pic->slices[i].priv_data);
568 av_freep(&pic->slices[i].codec_slice_params);
572 av_freep(&pic->codec_picture_params);
573 av_freep(&pic->param_buffers);
574 av_freep(&pic->slices);
576 av_frame_free(&pic->recon_image);
577 av_buffer_unref(&pic->output_buffer_ref);
578 pic->output_buffer = VA_INVALID_ID;
582 static int vaapi_encode_output(AVCodecContext *avctx,
583 VAAPIEncodePicture *pic, AVPacket *pkt)
585 VAAPIEncodeContext *ctx = avctx->priv_data;
586 VACodedBufferSegment *buf_list, *buf;
592 err = vaapi_encode_wait(avctx, pic);
597 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
599 if (vas != VA_STATUS_SUCCESS) {
600 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
601 "%d (%s).\n", vas, vaErrorStr(vas));
606 for (buf = buf_list; buf; buf = buf->next)
607 total_size += buf->size;
609 err = av_new_packet(pkt, total_size);
615 for (buf = buf_list; buf; buf = buf->next) {
616 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
617 "(status %08x).\n", buf->size, buf->status);
619 memcpy(ptr, buf->buf, buf->size);
623 if (pic->type == PICTURE_TYPE_IDR)
624 pkt->flags |= AV_PKT_FLAG_KEY;
628 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
629 if (vas != VA_STATUS_SUCCESS) {
630 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
631 "%d (%s).\n", vas, vaErrorStr(vas));
636 av_buffer_unref(&pic->output_buffer_ref);
637 pic->output_buffer = VA_INVALID_ID;
639 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
640 pic->display_order, pic->encode_order);
644 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
646 av_buffer_unref(&pic->output_buffer_ref);
647 pic->output_buffer = VA_INVALID_ID;
651 static int vaapi_encode_discard(AVCodecContext *avctx,
652 VAAPIEncodePicture *pic)
654 vaapi_encode_wait(avctx, pic);
656 if (pic->output_buffer_ref) {
657 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
658 "%"PRId64"/%"PRId64".\n",
659 pic->display_order, pic->encode_order);
661 av_buffer_unref(&pic->output_buffer_ref);
662 pic->output_buffer = VA_INVALID_ID;
668 static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
670 VAAPIEncodeContext *ctx = avctx->priv_data;
671 VAAPIEncodePicture *pic;
673 pic = av_mallocz(sizeof(*pic));
677 if (ctx->codec->picture_priv_data_size > 0) {
678 pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
679 if (!pic->priv_data) {
685 pic->input_surface = VA_INVALID_ID;
686 pic->recon_surface = VA_INVALID_ID;
687 pic->output_buffer = VA_INVALID_ID;
692 static int vaapi_encode_free(AVCodecContext *avctx,
693 VAAPIEncodePicture *pic)
697 if (pic->encode_issued)
698 vaapi_encode_discard(avctx, pic);
700 for (i = 0; i < pic->nb_slices; i++) {
702 av_freep(&pic->slices[i].priv_data);
703 av_freep(&pic->slices[i].codec_slice_params);
706 av_freep(&pic->codec_picture_params);
708 av_frame_free(&pic->input_image);
709 av_frame_free(&pic->recon_image);
711 av_freep(&pic->param_buffers);
712 av_freep(&pic->slices);
713 // Output buffer should already be destroyed.
714 av_assert0(pic->output_buffer == VA_INVALID_ID);
716 av_freep(&pic->priv_data);
717 av_freep(&pic->codec_picture_params);
725 static void vaapi_encode_add_ref(AVCodecContext *avctx,
726 VAAPIEncodePicture *pic,
727 VAAPIEncodePicture *target,
728 int is_ref, int in_dpb, int prev)
733 av_assert0(pic != target);
734 av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
735 pic->refs[pic->nb_refs++] = target;
740 av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
741 pic->dpb[pic->nb_dpb_pics++] = target;
746 av_assert0(!pic->prev);
751 target->ref_count[0] += refs;
752 target->ref_count[1] += refs;
755 static void vaapi_encode_remove_refs(AVCodecContext *avctx,
756 VAAPIEncodePicture *pic,
761 if (pic->ref_removed[level])
764 for (i = 0; i < pic->nb_refs; i++) {
765 av_assert0(pic->refs[i]);
766 --pic->refs[i]->ref_count[level];
767 av_assert0(pic->refs[i]->ref_count[level] >= 0);
770 for (i = 0; i < pic->nb_dpb_pics; i++) {
771 av_assert0(pic->dpb[i]);
772 --pic->dpb[i]->ref_count[level];
773 av_assert0(pic->dpb[i]->ref_count[level] >= 0);
776 av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
778 --pic->prev->ref_count[level];
779 av_assert0(pic->prev->ref_count[level] >= 0);
782 pic->ref_removed[level] = 1;
785 static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
786 VAAPIEncodePicture *start,
787 VAAPIEncodePicture *end,
788 VAAPIEncodePicture *prev,
790 VAAPIEncodePicture **last)
792 VAAPIEncodeContext *ctx = avctx->priv_data;
793 VAAPIEncodePicture *pic, *next, *ref;
796 av_assert0(start && end && start != end && start->next != end);
798 // If we are at the maximum depth then encode all pictures as
799 // non-referenced B-pictures. Also do this if there is exactly one
800 // picture left, since there will be nothing to reference it.
801 if (current_depth == ctx->max_b_depth || start->next->next == end) {
802 for (pic = start->next; pic; pic = pic->next) {
805 pic->type = PICTURE_TYPE_B;
806 pic->b_depth = current_depth;
808 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
809 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
810 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
812 for (ref = end->refs[1]; ref; ref = ref->refs[1])
813 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
818 // Split the current list at the midpoint with a referenced
819 // B-picture, then descend into each side separately.
821 for (pic = start->next; pic != end; pic = pic->next)
823 for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
825 pic->type = PICTURE_TYPE_B;
826 pic->b_depth = current_depth;
828 pic->is_reference = 1;
830 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
831 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
832 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
833 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
835 for (ref = end->refs[1]; ref; ref = ref->refs[1])
836 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
839 vaapi_encode_set_b_pictures(avctx, start, pic, pic,
840 current_depth + 1, &next);
844 vaapi_encode_set_b_pictures(avctx, pic, end, next,
845 current_depth + 1, last);
849 static int vaapi_encode_pick_next(AVCodecContext *avctx,
850 VAAPIEncodePicture **pic_out)
852 VAAPIEncodeContext *ctx = avctx->priv_data;
853 VAAPIEncodePicture *pic = NULL, *next, *start;
854 int i, b_counter, closed_gop_end;
856 // If there are any B-frames already queued, the next one to encode
857 // is the earliest not-yet-issued frame for which all references are
859 for (pic = ctx->pic_start; pic; pic = pic->next) {
860 if (pic->encode_issued)
862 if (pic->type != PICTURE_TYPE_B)
864 for (i = 0; i < pic->nb_refs; i++) {
865 if (!pic->refs[i]->encode_issued)
868 if (i == pic->nb_refs)
873 av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
874 "encode next.\n", pic->b_depth);
879 // Find the B-per-Pth available picture to become the next picture
883 closed_gop_end = ctx->closed_gop ||
884 ctx->idr_counter == ctx->gop_per_idr;
885 for (pic = ctx->pic_start; pic; pic = next) {
887 if (pic->encode_issued) {
891 // If the next available picture is force-IDR, encode it to start
892 // a new GOP immediately.
895 if (b_counter == ctx->b_per_p)
897 // If this picture ends a closed GOP or starts a new GOP then it
898 // needs to be in the top layer.
899 if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
901 // If the picture after this one is force-IDR, we need to encode
902 // this one in the top layer.
903 if (next && next->force_idr)
908 // At the end of the stream the last picture must be in the top layer.
909 if (!pic && ctx->end_of_stream) {
912 if (pic->encode_issued)
917 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
918 "need more input for reference pictures.\n");
919 return AVERROR(EAGAIN);
921 if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
922 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
923 "need more input for timestamps.\n");
924 return AVERROR(EAGAIN);
927 if (pic->force_idr) {
928 av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
930 pic->type = PICTURE_TYPE_IDR;
931 ctx->idr_counter = 1;
932 ctx->gop_counter = 1;
934 } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
935 if (ctx->idr_counter == ctx->gop_per_idr) {
936 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
938 pic->type = PICTURE_TYPE_IDR;
939 ctx->idr_counter = 1;
941 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
943 pic->type = PICTURE_TYPE_I;
946 ctx->gop_counter = 1;
949 if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
950 av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
953 av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
956 pic->type = PICTURE_TYPE_P;
958 ctx->gop_counter += 1 + b_counter;
960 pic->is_reference = 1;
963 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
964 if (pic->type != PICTURE_TYPE_IDR) {
965 vaapi_encode_add_ref(avctx, pic, start,
966 pic->type == PICTURE_TYPE_P,
968 vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
971 --ctx->next_prev->ref_count[0];
974 vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
977 ctx->next_prev = pic;
979 ++ctx->next_prev->ref_count[0];
983 static int vaapi_encode_clear_old(AVCodecContext *avctx)
985 VAAPIEncodeContext *ctx = avctx->priv_data;
986 VAAPIEncodePicture *pic, *prev, *next;
988 av_assert0(ctx->pic_start);
990 // Remove direct references once each picture is complete.
991 for (pic = ctx->pic_start; pic; pic = pic->next) {
992 if (pic->encode_complete && pic->next)
993 vaapi_encode_remove_refs(avctx, pic, 0);
996 // Remove indirect references once a picture has no direct references.
997 for (pic = ctx->pic_start; pic; pic = pic->next) {
998 if (pic->encode_complete && pic->ref_count[0] == 0)
999 vaapi_encode_remove_refs(avctx, pic, 1);
1002 // Clear out all complete pictures with no remaining references.
1004 for (pic = ctx->pic_start; pic; pic = next) {
1006 if (pic->encode_complete && pic->ref_count[1] == 0) {
1007 av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
1011 ctx->pic_start = next;
1012 vaapi_encode_free(avctx, pic);
1021 static int vaapi_encode_check_frame(AVCodecContext *avctx,
1022 const AVFrame *frame)
1024 VAAPIEncodeContext *ctx = avctx->priv_data;
1026 if ((frame->crop_top || frame->crop_bottom ||
1027 frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
1028 av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
1029 "frames ignored due to lack of API support.\n");
1030 ctx->crop_warned = 1;
1033 if (!ctx->roi_allowed) {
1034 AVFrameSideData *sd =
1035 av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
1037 if (sd && !ctx->roi_warned) {
1038 av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
1039 "frames ignored due to lack of driver support.\n");
1040 ctx->roi_warned = 1;
1047 static int vaapi_encode_send_frame(AVCodecContext *avctx, AVFrame *frame)
1049 VAAPIEncodeContext *ctx = avctx->priv_data;
1050 VAAPIEncodePicture *pic;
1054 av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
1055 frame->width, frame->height, frame->pts);
1057 err = vaapi_encode_check_frame(avctx, frame);
1061 pic = vaapi_encode_alloc(avctx);
1063 return AVERROR(ENOMEM);
1065 pic->input_image = av_frame_alloc();
1066 if (!pic->input_image) {
1067 err = AVERROR(ENOMEM);
1071 if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
1074 pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
1075 pic->pts = frame->pts;
1077 av_frame_move_ref(pic->input_image, frame);
1079 if (ctx->input_order == 0)
1080 ctx->first_pts = pic->pts;
1081 if (ctx->input_order == ctx->decode_delay)
1082 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
1083 if (ctx->output_delay > 0)
1084 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
1086 pic->display_order = ctx->input_order;
1089 if (ctx->pic_start) {
1090 ctx->pic_end->next = pic;
1093 ctx->pic_start = pic;
1098 ctx->end_of_stream = 1;
1100 // Fix timestamps if we hit end-of-stream before the initial decode
1101 // delay has elapsed.
1102 if (ctx->input_order < ctx->decode_delay)
1103 ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
1109 vaapi_encode_free(avctx, pic);
1113 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
1115 VAAPIEncodeContext *ctx = avctx->priv_data;
1116 VAAPIEncodePicture *pic;
1117 AVFrame *frame = ctx->frame;
1120 err = ff_encode_get_frame(avctx, frame);
1121 if (err < 0 && err != AVERROR_EOF)
1124 if (err == AVERROR_EOF)
1127 err = vaapi_encode_send_frame(avctx, frame);
1131 if (!ctx->pic_start) {
1132 if (ctx->end_of_stream)
1135 return AVERROR(EAGAIN);
1139 err = vaapi_encode_pick_next(avctx, &pic);
1144 pic->encode_order = ctx->encode_order++;
1146 err = vaapi_encode_issue(avctx, pic);
1148 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1152 err = vaapi_encode_output(avctx, pic, pkt);
1154 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1158 if (ctx->output_delay == 0) {
1159 pkt->dts = pkt->pts;
1160 } else if (pic->encode_order < ctx->decode_delay) {
1161 if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1162 pkt->dts = INT64_MIN;
1164 pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1166 pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1167 (3 * ctx->output_delay)];
1169 av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1170 pkt->pts, pkt->dts);
1172 ctx->output_order = pic->encode_order;
1173 vaapi_encode_clear_old(avctx);
1179 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
1180 void *buffer, size_t size)
1182 VAAPIEncodeContext *ctx = avctx->priv_data;
1184 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1186 ctx->global_params_type[ctx->nb_global_params] = type;
1187 ctx->global_params [ctx->nb_global_params] = buffer;
1188 ctx->global_params_size[ctx->nb_global_params] = size;
1190 ++ctx->nb_global_params;
1193 typedef struct VAAPIEncodeRTFormat {
1200 } VAAPIEncodeRTFormat;
1202 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1203 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
1204 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
1205 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
1206 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
1207 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
1208 #if VA_CHECK_VERSION(0, 38, 1)
1209 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1213 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1214 VAEntrypointEncSlice,
1215 VAEntrypointEncPicture,
1216 #if VA_CHECK_VERSION(0, 39, 2)
1217 VAEntrypointEncSliceLP,
1221 #if VA_CHECK_VERSION(0, 39, 2)
1222 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1223 VAEntrypointEncSliceLP,
1228 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1230 VAAPIEncodeContext *ctx = avctx->priv_data;
1231 VAProfile *va_profiles = NULL;
1232 VAEntrypoint *va_entrypoints = NULL;
1234 const VAEntrypoint *usable_entrypoints;
1235 const VAAPIEncodeProfile *profile;
1236 const AVPixFmtDescriptor *desc;
1237 VAConfigAttrib rt_format_attr;
1238 const VAAPIEncodeRTFormat *rt_format;
1239 const char *profile_string, *entrypoint_string;
1240 int i, j, n, depth, err;
1243 if (ctx->low_power) {
1244 #if VA_CHECK_VERSION(0, 39, 2)
1245 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1247 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1248 "supported with this VAAPI version.\n");
1249 return AVERROR(EINVAL);
1252 usable_entrypoints = vaapi_encode_entrypoints_normal;
1255 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1257 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1258 ctx->input_frames->sw_format);
1259 return AVERROR(EINVAL);
1261 depth = desc->comp[0].depth;
1262 for (i = 1; i < desc->nb_components; i++) {
1263 if (desc->comp[i].depth != depth) {
1264 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1266 return AVERROR(EINVAL);
1269 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1272 n = vaMaxNumProfiles(ctx->hwctx->display);
1273 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1275 err = AVERROR(ENOMEM);
1278 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1279 if (vas != VA_STATUS_SUCCESS) {
1280 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1281 vas, vaErrorStr(vas));
1282 err = AVERROR_EXTERNAL;
1286 av_assert0(ctx->codec->profiles);
1287 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1288 FF_PROFILE_UNKNOWN); i++) {
1289 profile = &ctx->codec->profiles[i];
1290 if (depth != profile->depth ||
1291 desc->nb_components != profile->nb_components)
1293 if (desc->nb_components > 1 &&
1294 (desc->log2_chroma_w != profile->log2_chroma_w ||
1295 desc->log2_chroma_h != profile->log2_chroma_h))
1297 if (avctx->profile != profile->av_profile &&
1298 avctx->profile != FF_PROFILE_UNKNOWN)
1301 #if VA_CHECK_VERSION(1, 0, 0)
1302 profile_string = vaProfileStr(profile->va_profile);
1304 profile_string = "(no profile names)";
1307 for (j = 0; j < n; j++) {
1308 if (va_profiles[j] == profile->va_profile)
1312 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1313 "is not supported by driver.\n", profile_string,
1314 profile->va_profile);
1318 ctx->profile = profile;
1321 if (!ctx->profile) {
1322 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1323 err = AVERROR(ENOSYS);
1327 avctx->profile = profile->av_profile;
1328 ctx->va_profile = profile->va_profile;
1329 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1330 profile_string, ctx->va_profile);
1332 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1333 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1334 if (!va_entrypoints) {
1335 err = AVERROR(ENOMEM);
1338 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1339 va_entrypoints, &n);
1340 if (vas != VA_STATUS_SUCCESS) {
1341 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1342 "profile %s (%d): %d (%s).\n", profile_string,
1343 ctx->va_profile, vas, vaErrorStr(vas));
1344 err = AVERROR_EXTERNAL;
1348 for (i = 0; i < n; i++) {
1349 for (j = 0; usable_entrypoints[j]; j++) {
1350 if (va_entrypoints[i] == usable_entrypoints[j])
1353 if (usable_entrypoints[j])
1357 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1358 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1359 err = AVERROR(ENOSYS);
1363 ctx->va_entrypoint = va_entrypoints[i];
1364 #if VA_CHECK_VERSION(1, 0, 0)
1365 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1367 entrypoint_string = "(no entrypoint names)";
1369 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1370 entrypoint_string, ctx->va_entrypoint);
1372 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1373 rt_format = &vaapi_encode_rt_formats[i];
1374 if (rt_format->depth == depth &&
1375 rt_format->nb_components == profile->nb_components &&
1376 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1377 rt_format->log2_chroma_h == profile->log2_chroma_h)
1380 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1381 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1382 "found for profile %s (%d) entrypoint %s (%d).\n",
1383 profile_string, ctx->va_profile,
1384 entrypoint_string, ctx->va_entrypoint);
1385 err = AVERROR(ENOSYS);
1389 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1390 vas = vaGetConfigAttributes(ctx->hwctx->display,
1391 ctx->va_profile, ctx->va_entrypoint,
1392 &rt_format_attr, 1);
1393 if (vas != VA_STATUS_SUCCESS) {
1394 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1395 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1396 err = AVERROR_EXTERNAL;
1400 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1401 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1402 "supported by driver: assuming surface RT format %s "
1403 "is valid.\n", rt_format->name);
1404 } else if (!(rt_format_attr.value & rt_format->value)) {
1405 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1406 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1407 rt_format->name, profile_string, ctx->va_profile,
1408 entrypoint_string, ctx->va_entrypoint);
1409 err = AVERROR(ENOSYS);
1412 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1413 "format %s (%#x).\n", rt_format->name, rt_format->value);
1414 ctx->config_attributes[ctx->nb_config_attributes++] =
1416 .type = VAConfigAttribRTFormat,
1417 .value = rt_format->value,
1423 av_freep(&va_profiles);
1424 av_freep(&va_entrypoints);
1428 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1430 // | Maxrate | HRD/VBV
1432 { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
1433 { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
1434 { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
1435 #if VA_CHECK_VERSION(1, 1, 0)
1436 { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
1438 { RC_MODE_ICQ, "ICQ", 0 },
1440 #if VA_CHECK_VERSION(1, 3, 0)
1441 { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
1442 { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
1444 { RC_MODE_QVBR, "QVBR", 0 },
1445 { RC_MODE_AVBR, "AVBR", 0 },
1449 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1451 VAAPIEncodeContext *ctx = avctx->priv_data;
1452 uint32_t supported_va_rc_modes;
1453 const VAAPIEncodeRCMode *rc_mode;
1454 int64_t rc_bits_per_second;
1455 int rc_target_percentage;
1458 int64_t hrd_buffer_size;
1459 int64_t hrd_initial_buffer_fullness;
1461 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1463 char supported_rc_modes_string[64];
1465 vas = vaGetConfigAttributes(ctx->hwctx->display,
1466 ctx->va_profile, ctx->va_entrypoint,
1468 if (vas != VA_STATUS_SUCCESS) {
1469 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1470 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1471 return AVERROR_EXTERNAL;
1473 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1474 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1475 "supported rate control modes: assuming CQP only.\n");
1476 supported_va_rc_modes = VA_RC_CQP;
1477 strcpy(supported_rc_modes_string, "unknown");
1479 char *str = supported_rc_modes_string;
1480 size_t len = sizeof(supported_rc_modes_string);
1481 int i, first = 1, res;
1483 supported_va_rc_modes = rc_attr.value;
1484 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1485 rc_mode = &vaapi_encode_rc_modes[i];
1486 if (supported_va_rc_modes & rc_mode->va_mode) {
1487 res = snprintf(str, len, "%s%s",
1488 first ? "" : ", ", rc_mode->name);
1501 av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1502 supported_rc_modes_string);
1505 // Rate control mode selection:
1506 // * If the user has set a mode explicitly with the rc_mode option,
1507 // use it and fail if it is not available.
1508 // * If an explicit QP option has been set, use CQP.
1509 // * If the codec is CQ-only, use CQP.
1510 // * If the QSCALE avcodec option is set, use CQP.
1511 // * If bitrate and quality are both set, try QVBR.
1512 // * If quality is set, try ICQ, then CQP.
1513 // * If bitrate and maxrate are set and have the same value, try CBR.
1514 // * If a bitrate is set, try AVBR, then VBR, then CBR.
1515 // * If no bitrate is set, try ICQ, then CQP.
1517 #define TRY_RC_MODE(mode, fail) do { \
1518 rc_mode = &vaapi_encode_rc_modes[mode]; \
1519 if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1521 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1522 "RC mode (supported modes: %s).\n", rc_mode->name, \
1523 supported_rc_modes_string); \
1524 return AVERROR(EINVAL); \
1526 av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1527 "RC mode.\n", rc_mode->name); \
1530 goto rc_mode_found; \
1534 if (ctx->explicit_rc_mode)
1535 TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1537 if (ctx->explicit_qp)
1538 TRY_RC_MODE(RC_MODE_CQP, 1);
1540 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1541 TRY_RC_MODE(RC_MODE_CQP, 1);
1543 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1544 TRY_RC_MODE(RC_MODE_CQP, 1);
1546 if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1547 TRY_RC_MODE(RC_MODE_QVBR, 0);
1549 if (avctx->global_quality > 0) {
1550 TRY_RC_MODE(RC_MODE_ICQ, 0);
1551 TRY_RC_MODE(RC_MODE_CQP, 0);
1554 if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1555 TRY_RC_MODE(RC_MODE_CBR, 0);
1557 if (avctx->bit_rate > 0) {
1558 TRY_RC_MODE(RC_MODE_AVBR, 0);
1559 TRY_RC_MODE(RC_MODE_VBR, 0);
1560 TRY_RC_MODE(RC_MODE_CBR, 0);
1562 TRY_RC_MODE(RC_MODE_ICQ, 0);
1563 TRY_RC_MODE(RC_MODE_CQP, 0);
1566 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1567 "RC mode compatible with selected options "
1568 "(supported modes: %s).\n", supported_rc_modes_string);
1569 return AVERROR(EINVAL);
1572 if (rc_mode->bitrate) {
1573 if (avctx->bit_rate <= 0) {
1574 av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1575 "RC mode.\n", rc_mode->name);
1576 return AVERROR(EINVAL);
1579 if (rc_mode->mode == RC_MODE_AVBR) {
1580 // For maximum confusion AVBR is hacked into the existing API
1581 // by overloading some of the fields with completely different
1584 // Target percentage does not apply in AVBR mode.
1585 rc_bits_per_second = avctx->bit_rate;
1587 // Accuracy tolerance range for meeting the specified target
1588 // bitrate. It's very unclear how this is actually intended
1589 // to work - since we do want to get the specified bitrate,
1590 // set the accuracy to 100% for now.
1591 rc_target_percentage = 100;
1593 // Convergence period in frames. The GOP size reflects the
1594 // user's intended block size for cutting, so reusing that
1595 // as the convergence period seems a reasonable default.
1596 rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1598 } else if (rc_mode->maxrate) {
1599 if (avctx->rc_max_rate > 0) {
1600 if (avctx->rc_max_rate < avctx->bit_rate) {
1601 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1602 "bitrate (%"PRId64") must not be greater than "
1603 "maxrate (%"PRId64").\n", avctx->bit_rate,
1604 avctx->rc_max_rate);
1605 return AVERROR(EINVAL);
1607 rc_bits_per_second = avctx->rc_max_rate;
1608 rc_target_percentage = (avctx->bit_rate * 100) /
1611 // We only have a target bitrate, but this mode requires
1612 // that a maximum rate be supplied as well. Since the
1613 // user does not want this to be a constraint, arbitrarily
1614 // pick a maximum rate of double the target rate.
1615 rc_bits_per_second = 2 * avctx->bit_rate;
1616 rc_target_percentage = 50;
1619 if (avctx->rc_max_rate > avctx->bit_rate) {
1620 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1621 "in %s RC mode.\n", rc_mode->name);
1623 rc_bits_per_second = avctx->bit_rate;
1624 rc_target_percentage = 100;
1627 rc_bits_per_second = 0;
1628 rc_target_percentage = 100;
1631 if (rc_mode->quality) {
1632 if (ctx->explicit_qp) {
1633 rc_quality = ctx->explicit_qp;
1634 } else if (avctx->global_quality > 0) {
1635 rc_quality = avctx->global_quality;
1637 rc_quality = ctx->codec->default_quality;
1638 av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1639 "using default (%d).\n", rc_quality);
1646 if (avctx->rc_buffer_size)
1647 hrd_buffer_size = avctx->rc_buffer_size;
1648 else if (avctx->rc_max_rate > 0)
1649 hrd_buffer_size = avctx->rc_max_rate;
1651 hrd_buffer_size = avctx->bit_rate;
1652 if (avctx->rc_initial_buffer_occupancy) {
1653 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1654 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1655 "must have initial buffer size (%d) <= "
1656 "buffer size (%"PRId64").\n",
1657 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1658 return AVERROR(EINVAL);
1660 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1662 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1665 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1667 if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1668 av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1669 "in %s RC mode.\n", rc_mode->name);
1672 hrd_buffer_size = 0;
1673 hrd_initial_buffer_fullness = 0;
1675 if (rc_mode->mode != RC_MODE_AVBR) {
1676 // Already set (with completely different meaning) for AVBR.
1677 rc_window_size = 1000;
1681 if (rc_bits_per_second > UINT32_MAX ||
1682 hrd_buffer_size > UINT32_MAX ||
1683 hrd_initial_buffer_fullness > UINT32_MAX) {
1684 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1685 "greater are not supported by VAAPI.\n");
1686 return AVERROR(EINVAL);
1689 ctx->rc_mode = rc_mode;
1690 ctx->rc_quality = rc_quality;
1691 ctx->va_rc_mode = rc_mode->va_mode;
1692 ctx->va_bit_rate = rc_bits_per_second;
1694 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1695 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1696 // This driver does not want the RC mode attribute to be set.
1698 ctx->config_attributes[ctx->nb_config_attributes++] =
1700 .type = VAConfigAttribRateControl,
1701 .value = ctx->va_rc_mode,
1705 if (rc_mode->quality)
1706 av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1708 if (rc_mode->va_mode != VA_RC_CQP) {
1709 if (rc_mode->mode == RC_MODE_AVBR) {
1710 av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1711 "converging in %d frames with %d%% accuracy.\n",
1712 rc_bits_per_second, rc_window_size,
1713 rc_target_percentage);
1714 } else if (rc_mode->bitrate) {
1715 av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1716 "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1717 rc_bits_per_second, rc_window_size);
1720 ctx->rc_params = (VAEncMiscParameterRateControl) {
1721 .bits_per_second = rc_bits_per_second,
1722 .target_percentage = rc_target_percentage,
1723 .window_size = rc_window_size,
1725 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1726 .basic_unit_size = 0,
1727 #if VA_CHECK_VERSION(1, 1, 0)
1728 .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1729 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1731 #if VA_CHECK_VERSION(1, 3, 0)
1732 .quality_factor = rc_quality,
1735 vaapi_encode_add_global_param(avctx,
1736 VAEncMiscParameterTypeRateControl,
1738 sizeof(ctx->rc_params));
1742 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1743 "initial fullness %"PRId64" bits.\n",
1744 hrd_buffer_size, hrd_initial_buffer_fullness);
1746 ctx->hrd_params = (VAEncMiscParameterHRD) {
1747 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1748 .buffer_size = hrd_buffer_size,
1750 vaapi_encode_add_global_param(avctx,
1751 VAEncMiscParameterTypeHRD,
1753 sizeof(ctx->hrd_params));
1756 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1757 av_reduce(&fr_num, &fr_den,
1758 avctx->framerate.num, avctx->framerate.den, 65535);
1760 av_reduce(&fr_num, &fr_den,
1761 avctx->time_base.den, avctx->time_base.num, 65535);
1763 av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1764 fr_num, fr_den, (double)fr_num / fr_den);
1766 ctx->fr_params = (VAEncMiscParameterFrameRate) {
1767 .framerate = (unsigned int)fr_den << 16 | fr_num,
1769 #if VA_CHECK_VERSION(0, 40, 0)
1770 vaapi_encode_add_global_param(avctx,
1771 VAEncMiscParameterTypeFrameRate,
1773 sizeof(ctx->fr_params));
1779 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1781 VAAPIEncodeContext *ctx = avctx->priv_data;
1783 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1784 uint32_t ref_l0, ref_l1;
1786 vas = vaGetConfigAttributes(ctx->hwctx->display,
1790 if (vas != VA_STATUS_SUCCESS) {
1791 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1792 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1793 return AVERROR_EXTERNAL;
1796 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1797 ref_l0 = ref_l1 = 0;
1799 ref_l0 = attr.value & 0xffff;
1800 ref_l1 = attr.value >> 16 & 0xffff;
1803 if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1804 avctx->gop_size <= 1) {
1805 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1807 } else if (ref_l0 < 1) {
1808 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1809 "reference frames.\n");
1810 return AVERROR(EINVAL);
1811 } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1812 ref_l1 < 1 || avctx->max_b_frames < 1) {
1813 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1814 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1815 ctx->gop_size = avctx->gop_size;
1816 ctx->p_per_i = INT_MAX;
1819 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1820 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1821 ctx->gop_size = avctx->gop_size;
1822 ctx->p_per_i = INT_MAX;
1823 ctx->b_per_p = avctx->max_b_frames;
1824 if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1825 ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1826 av_log2(ctx->b_per_p) + 1);
1828 ctx->max_b_depth = 1;
1832 if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1833 ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1834 ctx->gop_per_idr = ctx->idr_interval + 1;
1836 ctx->closed_gop = 1;
1837 ctx->gop_per_idr = 1;
1843 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1845 VAAPIEncodeContext *ctx = avctx->priv_data;
1846 VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1847 { VAConfigAttribEncSliceStructure } };
1849 uint32_t max_slices, slice_structure;
1852 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1853 if (avctx->slices > 0) {
1854 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1855 "but this codec does not support controlling slices.\n");
1860 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1861 ctx->slice_block_height;
1862 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
1863 ctx->slice_block_width;
1865 if (avctx->slices <= 1) {
1867 ctx->slice_size = ctx->slice_block_rows;
1871 vas = vaGetConfigAttributes(ctx->hwctx->display,
1874 attr, FF_ARRAY_ELEMS(attr));
1875 if (vas != VA_STATUS_SUCCESS) {
1876 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1877 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1878 return AVERROR_EXTERNAL;
1880 max_slices = attr[0].value;
1881 slice_structure = attr[1].value;
1882 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1883 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1884 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1885 "pictures as multiple slices.\n.");
1886 return AVERROR(EINVAL);
1889 // For fixed-size slices currently we only support whole rows, making
1890 // rectangular slices. This could be extended to arbitrary runs of
1891 // blocks, but since slices tend to be a conformance requirement and
1892 // most cases (such as broadcast or bluray) want rectangular slices
1893 // only it would need to be gated behind another option.
1894 if (avctx->slices > ctx->slice_block_rows) {
1895 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1896 "configured number of slices (%d < %d); using "
1897 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1898 req_slices = ctx->slice_block_rows;
1900 req_slices = avctx->slices;
1902 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1903 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1904 ctx->nb_slices = req_slices;
1905 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1906 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1908 for (k = 1;; k *= 2) {
1909 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1912 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1913 ctx->slice_size = k;
1914 #if VA_CHECK_VERSION(1, 0, 0)
1915 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1916 ctx->nb_slices = ctx->slice_block_rows;
1917 ctx->slice_size = 1;
1920 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1921 "slice structure modes (%#x).\n", slice_structure);
1922 return AVERROR(EINVAL);
1925 if (ctx->nb_slices > avctx->slices) {
1926 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1927 "%d (from %d) due to driver constraints on slice "
1928 "structure.\n", ctx->nb_slices, avctx->slices);
1930 if (ctx->nb_slices > max_slices) {
1931 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1932 "encoding with %d slices (max %"PRIu32").\n",
1933 ctx->nb_slices, max_slices);
1934 return AVERROR(EINVAL);
1937 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1938 "(default size %d block rows).\n",
1939 ctx->nb_slices, ctx->slice_size);
1943 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1945 VAAPIEncodeContext *ctx = avctx->priv_data;
1947 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1949 vas = vaGetConfigAttributes(ctx->hwctx->display,
1953 if (vas != VA_STATUS_SUCCESS) {
1954 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1955 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1956 return AVERROR_EXTERNAL;
1959 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1960 if (ctx->desired_packed_headers) {
1961 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1962 "packed headers (wanted %#x).\n",
1963 ctx->desired_packed_headers);
1965 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1966 "packed headers (none wanted).\n");
1968 ctx->va_packed_headers = 0;
1970 if (ctx->desired_packed_headers & ~attr.value) {
1971 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1972 "wanted packed headers (wanted %#x, found %#x).\n",
1973 ctx->desired_packed_headers, attr.value);
1975 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1976 "available (wanted %#x, found %#x).\n",
1977 ctx->desired_packed_headers, attr.value);
1979 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1982 if (ctx->va_packed_headers) {
1983 ctx->config_attributes[ctx->nb_config_attributes++] =
1985 .type = VAConfigAttribEncPackedHeaders,
1986 .value = ctx->va_packed_headers,
1990 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1991 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1992 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1993 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1994 "sequence headers, but a global header is requested.\n");
1995 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1996 "this may result in a stream which is not usable for some "
1997 "purposes (e.g. not muxable to some containers).\n");
2003 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
2005 #if VA_CHECK_VERSION(0, 36, 0)
2006 VAAPIEncodeContext *ctx = avctx->priv_data;
2008 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
2009 int quality = avctx->compression_level;
2011 vas = vaGetConfigAttributes(ctx->hwctx->display,
2015 if (vas != VA_STATUS_SUCCESS) {
2016 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
2017 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2018 return AVERROR_EXTERNAL;
2021 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2023 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
2024 "supported: will use default quality level.\n");
2027 if (quality > attr.value) {
2028 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
2029 "valid range is 0-%d, using %d.\n",
2030 attr.value, attr.value);
2031 quality = attr.value;
2034 ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
2035 .quality_level = quality,
2037 vaapi_encode_add_global_param(avctx,
2038 VAEncMiscParameterTypeQualityLevel,
2039 &ctx->quality_params,
2040 sizeof(ctx->quality_params));
2043 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
2044 "not supported with this VAAPI version.\n");
2050 static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
2052 #if VA_CHECK_VERSION(1, 0, 0)
2053 VAAPIEncodeContext *ctx = avctx->priv_data;
2055 VAConfigAttrib attr = { VAConfigAttribEncROI };
2057 vas = vaGetConfigAttributes(ctx->hwctx->display,
2061 if (vas != VA_STATUS_SUCCESS) {
2062 av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
2063 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2064 return AVERROR_EXTERNAL;
2067 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2068 ctx->roi_allowed = 0;
2070 VAConfigAttribValEncROI roi = {
2071 .value = attr.value,
2074 ctx->roi_max_regions = roi.bits.num_roi_regions;
2075 ctx->roi_allowed = ctx->roi_max_regions > 0 &&
2076 (ctx->va_rc_mode == VA_RC_CQP ||
2077 roi.bits.roi_rc_qp_delta_support);
2083 static void vaapi_encode_free_output_buffer(void *opaque,
2086 AVCodecContext *avctx = opaque;
2087 VAAPIEncodeContext *ctx = avctx->priv_data;
2088 VABufferID buffer_id;
2090 buffer_id = (VABufferID)(uintptr_t)data;
2092 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2094 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
2097 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
2100 AVCodecContext *avctx = opaque;
2101 VAAPIEncodeContext *ctx = avctx->priv_data;
2102 VABufferID buffer_id;
2106 // The output buffer size is fixed, so it needs to be large enough
2107 // to hold the largest possible compressed frame. We assume here
2108 // that the uncompressed frame plus some header data is an upper
2110 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
2111 VAEncCodedBufferType,
2112 3 * ctx->surface_width * ctx->surface_height +
2113 (1 << 16), 1, 0, &buffer_id);
2114 if (vas != VA_STATUS_SUCCESS) {
2115 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
2116 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
2120 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
2122 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
2124 &vaapi_encode_free_output_buffer,
2125 avctx, AV_BUFFER_FLAG_READONLY);
2127 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2134 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
2136 VAAPIEncodeContext *ctx = avctx->priv_data;
2137 AVVAAPIHWConfig *hwconfig = NULL;
2138 AVHWFramesConstraints *constraints = NULL;
2139 enum AVPixelFormat recon_format;
2142 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
2144 err = AVERROR(ENOMEM);
2147 hwconfig->config_id = ctx->va_config;
2149 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
2152 err = AVERROR(ENOMEM);
2156 // Probably we can use the input surface format as the surface format
2157 // of the reconstructed frames. If not, we just pick the first (only?)
2158 // format in the valid list and hope that it all works.
2159 recon_format = AV_PIX_FMT_NONE;
2160 if (constraints->valid_sw_formats) {
2161 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
2162 if (ctx->input_frames->sw_format ==
2163 constraints->valid_sw_formats[i]) {
2164 recon_format = ctx->input_frames->sw_format;
2168 if (recon_format == AV_PIX_FMT_NONE) {
2169 // No match. Just use the first in the supported list and
2170 // hope for the best.
2171 recon_format = constraints->valid_sw_formats[0];
2174 // No idea what to use; copy input format.
2175 recon_format = ctx->input_frames->sw_format;
2177 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
2178 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
2180 if (ctx->surface_width < constraints->min_width ||
2181 ctx->surface_height < constraints->min_height ||
2182 ctx->surface_width > constraints->max_width ||
2183 ctx->surface_height > constraints->max_height) {
2184 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2185 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2186 ctx->surface_width, ctx->surface_height,
2187 constraints->min_width, constraints->max_width,
2188 constraints->min_height, constraints->max_height);
2189 err = AVERROR(EINVAL);
2193 av_freep(&hwconfig);
2194 av_hwframe_constraints_free(&constraints);
2196 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2197 if (!ctx->recon_frames_ref) {
2198 err = AVERROR(ENOMEM);
2201 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2203 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
2204 ctx->recon_frames->sw_format = recon_format;
2205 ctx->recon_frames->width = ctx->surface_width;
2206 ctx->recon_frames->height = ctx->surface_height;
2208 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2210 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2211 "frame context: %d.\n", err);
2217 av_freep(&hwconfig);
2218 av_hwframe_constraints_free(&constraints);
2222 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2224 VAAPIEncodeContext *ctx = avctx->priv_data;
2225 AVVAAPIFramesContext *recon_hwctx = NULL;
2229 ctx->frame = av_frame_alloc();
2231 return AVERROR(ENOMEM);
2234 if (!avctx->hw_frames_ctx) {
2235 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2236 "required to associate the encoding device.\n");
2237 return AVERROR(EINVAL);
2240 ctx->va_config = VA_INVALID_ID;
2241 ctx->va_context = VA_INVALID_ID;
2243 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2244 if (!ctx->input_frames_ref) {
2245 err = AVERROR(ENOMEM);
2248 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2250 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2251 if (!ctx->device_ref) {
2252 err = AVERROR(ENOMEM);
2255 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2256 ctx->hwctx = ctx->device->hwctx;
2258 err = vaapi_encode_profile_entrypoint(avctx);
2262 err = vaapi_encode_init_rate_control(avctx);
2266 err = vaapi_encode_init_gop_structure(avctx);
2270 err = vaapi_encode_init_slice_structure(avctx);
2274 err = vaapi_encode_init_packed_headers(avctx);
2278 err = vaapi_encode_init_roi(avctx);
2282 if (avctx->compression_level >= 0) {
2283 err = vaapi_encode_init_quality(avctx);
2288 vas = vaCreateConfig(ctx->hwctx->display,
2289 ctx->va_profile, ctx->va_entrypoint,
2290 ctx->config_attributes, ctx->nb_config_attributes,
2292 if (vas != VA_STATUS_SUCCESS) {
2293 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2294 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2299 err = vaapi_encode_create_recon_frames(avctx);
2303 recon_hwctx = ctx->recon_frames->hwctx;
2304 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2305 ctx->surface_width, ctx->surface_height,
2307 recon_hwctx->surface_ids,
2308 recon_hwctx->nb_surfaces,
2310 if (vas != VA_STATUS_SUCCESS) {
2311 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2312 "context: %d (%s).\n", vas, vaErrorStr(vas));
2317 ctx->output_buffer_pool =
2318 av_buffer_pool_init2(sizeof(VABufferID), avctx,
2319 &vaapi_encode_alloc_output_buffer, NULL);
2320 if (!ctx->output_buffer_pool) {
2321 err = AVERROR(ENOMEM);
2325 if (ctx->codec->configure) {
2326 err = ctx->codec->configure(avctx);
2331 ctx->output_delay = ctx->b_per_p;
2332 ctx->decode_delay = ctx->max_b_depth;
2334 if (ctx->codec->sequence_params_size > 0) {
2335 ctx->codec_sequence_params =
2336 av_mallocz(ctx->codec->sequence_params_size);
2337 if (!ctx->codec_sequence_params) {
2338 err = AVERROR(ENOMEM);
2342 if (ctx->codec->picture_params_size > 0) {
2343 ctx->codec_picture_params =
2344 av_mallocz(ctx->codec->picture_params_size);
2345 if (!ctx->codec_picture_params) {
2346 err = AVERROR(ENOMEM);
2351 if (ctx->codec->init_sequence_params) {
2352 err = ctx->codec->init_sequence_params(avctx);
2354 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2355 "failed: %d.\n", err);
2360 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2361 ctx->codec->write_sequence_header &&
2362 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2363 char data[MAX_PARAM_BUFFER_SIZE];
2364 size_t bit_len = 8 * sizeof(data);
2366 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2368 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2369 "for extradata: %d.\n", err);
2372 avctx->extradata_size = (bit_len + 7) / 8;
2373 avctx->extradata = av_mallocz(avctx->extradata_size +
2374 AV_INPUT_BUFFER_PADDING_SIZE);
2375 if (!avctx->extradata) {
2376 err = AVERROR(ENOMEM);
2379 memcpy(avctx->extradata, data, avctx->extradata_size);
2389 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2391 VAAPIEncodeContext *ctx = avctx->priv_data;
2392 VAAPIEncodePicture *pic, *next;
2394 for (pic = ctx->pic_start; pic; pic = next) {
2396 vaapi_encode_free(avctx, pic);
2399 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2401 if (ctx->va_context != VA_INVALID_ID) {
2402 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2403 ctx->va_context = VA_INVALID_ID;
2406 if (ctx->va_config != VA_INVALID_ID) {
2407 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2408 ctx->va_config = VA_INVALID_ID;
2411 av_frame_free(&ctx->frame);
2413 av_freep(&ctx->codec_sequence_params);
2414 av_freep(&ctx->codec_picture_params);
2416 av_buffer_unref(&ctx->recon_frames_ref);
2417 av_buffer_unref(&ctx->input_frames_ref);
2418 av_buffer_unref(&ctx->device_ref);