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_make_row_slice(AVCodecContext *avctx,
167 VAAPIEncodePicture *pic)
169 VAAPIEncodeContext *ctx = avctx->priv_data;
170 VAAPIEncodeSlice *slice;
173 for (i = 0; i < pic->nb_slices; i++)
174 pic->slices[i].row_size = ctx->slice_size;
176 rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
178 // Place rounding error at top and bottom of frame.
179 av_assert0(rounding < pic->nb_slices);
180 // Some Intel drivers contain a bug where the encoder will fail
181 // if the last slice is smaller than the one before it. Since
182 // that's straightforward to avoid here, just do so.
184 for (i = 0; i < rounding; i++)
185 ++pic->slices[i].row_size;
187 for (i = 0; i < (rounding + 1) / 2; i++)
188 ++pic->slices[pic->nb_slices - i - 1].row_size;
189 for (i = 0; i < rounding / 2; i++)
190 ++pic->slices[i].row_size;
192 } else if (rounding < 0) {
193 // Remove rounding error from last slice only.
194 av_assert0(rounding < ctx->slice_size);
195 pic->slices[pic->nb_slices - 1].row_size += rounding;
198 for (i = 0; i < pic->nb_slices; i++) {
199 slice = &pic->slices[i];
202 slice->row_start = 0;
203 slice->block_start = 0;
205 const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
206 slice->row_start = prev->row_start + prev->row_size;
207 slice->block_start = prev->block_start + prev->block_size;
209 slice->block_size = slice->row_size * ctx->slice_block_cols;
211 av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
212 "%d-%d (%d blocks).\n", i, slice->row_start,
213 slice->row_start + slice->row_size - 1, slice->row_size,
214 slice->block_start, slice->block_start + slice->block_size - 1,
221 static int vaapi_encode_issue(AVCodecContext *avctx,
222 VAAPIEncodePicture *pic)
224 VAAPIEncodeContext *ctx = avctx->priv_data;
225 VAAPIEncodeSlice *slice;
228 char data[MAX_PARAM_BUFFER_SIZE];
230 av_unused AVFrameSideData *sd;
232 av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
233 "as type %s.\n", pic->display_order, pic->encode_order,
234 picture_type_name[pic->type]);
235 if (pic->nb_refs == 0) {
236 av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
238 av_log(avctx, AV_LOG_DEBUG, "Refers to:");
239 for (i = 0; i < pic->nb_refs; i++) {
240 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
241 pic->refs[i]->display_order, pic->refs[i]->encode_order);
243 av_log(avctx, AV_LOG_DEBUG, ".\n");
246 av_assert0(!pic->encode_issued);
247 for (i = 0; i < pic->nb_refs; i++) {
248 av_assert0(pic->refs[i]);
249 av_assert0(pic->refs[i]->encode_issued);
252 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
254 pic->recon_image = av_frame_alloc();
255 if (!pic->recon_image) {
256 err = AVERROR(ENOMEM);
260 err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
262 err = AVERROR(ENOMEM);
265 pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
266 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
268 pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
269 if (!pic->output_buffer_ref) {
270 err = AVERROR(ENOMEM);
273 pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
274 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
277 if (ctx->codec->picture_params_size > 0) {
278 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
279 if (!pic->codec_picture_params)
281 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
282 ctx->codec->picture_params_size);
284 av_assert0(!ctx->codec_picture_params);
287 pic->nb_param_buffers = 0;
289 if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
290 err = vaapi_encode_make_param_buffer(avctx, pic,
291 VAEncSequenceParameterBufferType,
292 ctx->codec_sequence_params,
293 ctx->codec->sequence_params_size);
298 if (pic->type == PICTURE_TYPE_IDR) {
299 for (i = 0; i < ctx->nb_global_params; i++) {
300 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
301 ctx->global_params_type[i],
302 ctx->global_params[i],
303 ctx->global_params_size[i]);
309 if (ctx->codec->init_picture_params) {
310 err = ctx->codec->init_picture_params(avctx, pic);
312 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
313 "parameters: %d.\n", err);
316 err = vaapi_encode_make_param_buffer(avctx, pic,
317 VAEncPictureParameterBufferType,
318 pic->codec_picture_params,
319 ctx->codec->picture_params_size);
324 if (pic->type == PICTURE_TYPE_IDR) {
325 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
326 ctx->codec->write_sequence_header) {
327 bit_len = 8 * sizeof(data);
328 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
330 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
331 "header: %d.\n", err);
334 err = vaapi_encode_make_packed_header(avctx, pic,
335 ctx->codec->sequence_header_type,
342 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
343 ctx->codec->write_picture_header) {
344 bit_len = 8 * sizeof(data);
345 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
347 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
348 "header: %d.\n", err);
351 err = vaapi_encode_make_packed_header(avctx, pic,
352 ctx->codec->picture_header_type,
358 if (ctx->codec->write_extra_buffer) {
360 size_t len = sizeof(data);
362 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
364 if (err == AVERROR_EOF)
367 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
368 "buffer %d: %d.\n", i, err);
372 err = vaapi_encode_make_param_buffer(avctx, pic, type,
379 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
380 ctx->codec->write_extra_header) {
383 bit_len = 8 * sizeof(data);
384 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
386 if (err == AVERROR_EOF)
389 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
390 "header %d: %d.\n", i, err);
394 err = vaapi_encode_make_packed_header(avctx, pic, type,
401 if (pic->nb_slices == 0)
402 pic->nb_slices = ctx->nb_slices;
403 if (pic->nb_slices > 0) {
404 pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
406 err = AVERROR(ENOMEM);
410 vaapi_encode_make_row_slice(avctx, pic);
413 for (i = 0; i < pic->nb_slices; i++) {
414 slice = &pic->slices[i];
416 if (ctx->codec->slice_params_size > 0) {
417 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
418 if (!slice->codec_slice_params) {
419 err = AVERROR(ENOMEM);
424 if (ctx->codec->init_slice_params) {
425 err = ctx->codec->init_slice_params(avctx, pic, slice);
427 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
428 "parameters: %d.\n", err);
433 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
434 ctx->codec->write_slice_header) {
435 bit_len = 8 * sizeof(data);
436 err = ctx->codec->write_slice_header(avctx, pic, slice,
439 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
440 "header: %d.\n", err);
443 err = vaapi_encode_make_packed_header(avctx, pic,
444 ctx->codec->slice_header_type,
450 if (ctx->codec->init_slice_params) {
451 err = vaapi_encode_make_param_buffer(avctx, pic,
452 VAEncSliceParameterBufferType,
453 slice->codec_slice_params,
454 ctx->codec->slice_params_size);
460 #if VA_CHECK_VERSION(1, 0, 0)
461 sd = av_frame_get_side_data(pic->input_image,
462 AV_FRAME_DATA_REGIONS_OF_INTEREST);
463 if (sd && ctx->roi_allowed) {
464 const AVRegionOfInterest *roi;
466 VAEncMiscParameterBufferROI param_roi;
469 roi = (const AVRegionOfInterest*)sd->data;
470 roi_size = roi->self_size;
471 av_assert0(roi_size && sd->size % roi_size == 0);
472 nb_roi = sd->size / roi_size;
473 if (nb_roi > ctx->roi_max_regions) {
474 if (!ctx->roi_warned) {
475 av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
476 "supported by driver (%d > %d).\n",
477 nb_roi, ctx->roi_max_regions);
480 nb_roi = ctx->roi_max_regions;
483 pic->roi = av_mallocz_array(nb_roi, sizeof(*pic->roi));
485 err = AVERROR(ENOMEM);
488 // For overlapping regions, the first in the array takes priority.
489 for (i = 0; i < nb_roi; i++) {
490 roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
492 av_assert0(roi->qoffset.den != 0);
493 v = roi->qoffset.num * ctx->roi_quant_range / roi->qoffset.den;
494 av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
495 roi->top, roi->left, roi->bottom, roi->right, v);
497 pic->roi[i] = (VAEncROI) {
501 .width = roi->right - roi->left,
502 .height = roi->bottom - roi->top,
504 .roi_value = av_clip_int8(v),
508 param_roi = (VAEncMiscParameterBufferROI) {
510 .max_delta_qp = INT8_MAX,
511 .min_delta_qp = INT8_MIN,
513 .roi_flags.bits.roi_value_is_qp_delta = 1,
516 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
517 VAEncMiscParameterTypeROI,
525 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
527 if (vas != VA_STATUS_SUCCESS) {
528 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
529 "%d (%s).\n", vas, vaErrorStr(vas));
531 goto fail_with_picture;
534 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
535 pic->param_buffers, pic->nb_param_buffers);
536 if (vas != VA_STATUS_SUCCESS) {
537 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
538 "%d (%s).\n", vas, vaErrorStr(vas));
540 goto fail_with_picture;
543 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
544 if (vas != VA_STATUS_SUCCESS) {
545 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
546 "%d (%s).\n", vas, vaErrorStr(vas));
548 // vaRenderPicture() has been called here, so we should not destroy
549 // the parameter buffers unless separate destruction is required.
550 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
551 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
557 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
558 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
559 for (i = 0; i < pic->nb_param_buffers; i++) {
560 vas = vaDestroyBuffer(ctx->hwctx->display,
561 pic->param_buffers[i]);
562 if (vas != VA_STATUS_SUCCESS) {
563 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
564 "param buffer %#x: %d (%s).\n",
565 pic->param_buffers[i], vas, vaErrorStr(vas));
571 pic->encode_issued = 1;
576 vaEndPicture(ctx->hwctx->display, ctx->va_context);
578 for(i = 0; i < pic->nb_param_buffers; i++)
579 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
580 for (i = 0; i < pic->nb_slices; i++) {
582 av_freep(&pic->slices[i].priv_data);
583 av_freep(&pic->slices[i].codec_slice_params);
587 av_freep(&pic->codec_picture_params);
588 av_freep(&pic->param_buffers);
589 av_freep(&pic->slices);
591 av_frame_free(&pic->recon_image);
592 av_buffer_unref(&pic->output_buffer_ref);
593 pic->output_buffer = VA_INVALID_ID;
597 static int vaapi_encode_output(AVCodecContext *avctx,
598 VAAPIEncodePicture *pic, AVPacket *pkt)
600 VAAPIEncodeContext *ctx = avctx->priv_data;
601 VACodedBufferSegment *buf_list, *buf;
607 err = vaapi_encode_wait(avctx, pic);
612 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
614 if (vas != VA_STATUS_SUCCESS) {
615 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
616 "%d (%s).\n", vas, vaErrorStr(vas));
621 for (buf = buf_list; buf; buf = buf->next)
622 total_size += buf->size;
624 err = av_new_packet(pkt, total_size);
630 for (buf = buf_list; buf; buf = buf->next) {
631 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
632 "(status %08x).\n", buf->size, buf->status);
634 memcpy(ptr, buf->buf, buf->size);
638 if (pic->type == PICTURE_TYPE_IDR)
639 pkt->flags |= AV_PKT_FLAG_KEY;
643 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
644 if (vas != VA_STATUS_SUCCESS) {
645 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
646 "%d (%s).\n", vas, vaErrorStr(vas));
651 av_buffer_unref(&pic->output_buffer_ref);
652 pic->output_buffer = VA_INVALID_ID;
654 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
655 pic->display_order, pic->encode_order);
659 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
661 av_buffer_unref(&pic->output_buffer_ref);
662 pic->output_buffer = VA_INVALID_ID;
666 static int vaapi_encode_discard(AVCodecContext *avctx,
667 VAAPIEncodePicture *pic)
669 vaapi_encode_wait(avctx, pic);
671 if (pic->output_buffer_ref) {
672 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
673 "%"PRId64"/%"PRId64".\n",
674 pic->display_order, pic->encode_order);
676 av_buffer_unref(&pic->output_buffer_ref);
677 pic->output_buffer = VA_INVALID_ID;
683 static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
685 VAAPIEncodeContext *ctx = avctx->priv_data;
686 VAAPIEncodePicture *pic;
688 pic = av_mallocz(sizeof(*pic));
692 if (ctx->codec->picture_priv_data_size > 0) {
693 pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
694 if (!pic->priv_data) {
700 pic->input_surface = VA_INVALID_ID;
701 pic->recon_surface = VA_INVALID_ID;
702 pic->output_buffer = VA_INVALID_ID;
707 static int vaapi_encode_free(AVCodecContext *avctx,
708 VAAPIEncodePicture *pic)
712 if (pic->encode_issued)
713 vaapi_encode_discard(avctx, pic);
715 for (i = 0; i < pic->nb_slices; i++) {
717 av_freep(&pic->slices[i].priv_data);
718 av_freep(&pic->slices[i].codec_slice_params);
721 av_freep(&pic->codec_picture_params);
723 av_frame_free(&pic->input_image);
724 av_frame_free(&pic->recon_image);
726 av_freep(&pic->param_buffers);
727 av_freep(&pic->slices);
728 // Output buffer should already be destroyed.
729 av_assert0(pic->output_buffer == VA_INVALID_ID);
731 av_freep(&pic->priv_data);
732 av_freep(&pic->codec_picture_params);
740 static void vaapi_encode_add_ref(AVCodecContext *avctx,
741 VAAPIEncodePicture *pic,
742 VAAPIEncodePicture *target,
743 int is_ref, int in_dpb, int prev)
748 av_assert0(pic != target);
749 av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
750 pic->refs[pic->nb_refs++] = target;
755 av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
756 pic->dpb[pic->nb_dpb_pics++] = target;
761 av_assert0(!pic->prev);
766 target->ref_count[0] += refs;
767 target->ref_count[1] += refs;
770 static void vaapi_encode_remove_refs(AVCodecContext *avctx,
771 VAAPIEncodePicture *pic,
776 if (pic->ref_removed[level])
779 for (i = 0; i < pic->nb_refs; i++) {
780 av_assert0(pic->refs[i]);
781 --pic->refs[i]->ref_count[level];
782 av_assert0(pic->refs[i]->ref_count[level] >= 0);
785 for (i = 0; i < pic->nb_dpb_pics; i++) {
786 av_assert0(pic->dpb[i]);
787 --pic->dpb[i]->ref_count[level];
788 av_assert0(pic->dpb[i]->ref_count[level] >= 0);
791 av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
793 --pic->prev->ref_count[level];
794 av_assert0(pic->prev->ref_count[level] >= 0);
797 pic->ref_removed[level] = 1;
800 static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
801 VAAPIEncodePicture *start,
802 VAAPIEncodePicture *end,
803 VAAPIEncodePicture *prev,
805 VAAPIEncodePicture **last)
807 VAAPIEncodeContext *ctx = avctx->priv_data;
808 VAAPIEncodePicture *pic, *next, *ref;
811 av_assert0(start && end && start != end && start->next != end);
813 // If we are at the maximum depth then encode all pictures as
814 // non-referenced B-pictures. Also do this if there is exactly one
815 // picture left, since there will be nothing to reference it.
816 if (current_depth == ctx->max_b_depth || start->next->next == end) {
817 for (pic = start->next; pic; pic = pic->next) {
820 pic->type = PICTURE_TYPE_B;
821 pic->b_depth = current_depth;
823 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
824 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
825 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
827 for (ref = end->refs[1]; ref; ref = ref->refs[1])
828 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
833 // Split the current list at the midpoint with a referenced
834 // B-picture, then descend into each side separately.
836 for (pic = start->next; pic != end; pic = pic->next)
838 for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
840 pic->type = PICTURE_TYPE_B;
841 pic->b_depth = current_depth;
843 pic->is_reference = 1;
845 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
846 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
847 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
848 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
850 for (ref = end->refs[1]; ref; ref = ref->refs[1])
851 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
854 vaapi_encode_set_b_pictures(avctx, start, pic, pic,
855 current_depth + 1, &next);
859 vaapi_encode_set_b_pictures(avctx, pic, end, next,
860 current_depth + 1, last);
864 static int vaapi_encode_pick_next(AVCodecContext *avctx,
865 VAAPIEncodePicture **pic_out)
867 VAAPIEncodeContext *ctx = avctx->priv_data;
868 VAAPIEncodePicture *pic = NULL, *next, *start;
869 int i, b_counter, closed_gop_end;
871 // If there are any B-frames already queued, the next one to encode
872 // is the earliest not-yet-issued frame for which all references are
874 for (pic = ctx->pic_start; pic; pic = pic->next) {
875 if (pic->encode_issued)
877 if (pic->type != PICTURE_TYPE_B)
879 for (i = 0; i < pic->nb_refs; i++) {
880 if (!pic->refs[i]->encode_issued)
883 if (i == pic->nb_refs)
888 av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
889 "encode next.\n", pic->b_depth);
894 // Find the B-per-Pth available picture to become the next picture
898 closed_gop_end = ctx->closed_gop ||
899 ctx->idr_counter == ctx->gop_per_idr;
900 for (pic = ctx->pic_start; pic; pic = next) {
902 if (pic->encode_issued) {
906 // If the next available picture is force-IDR, encode it to start
907 // a new GOP immediately.
910 if (b_counter == ctx->b_per_p)
912 // If this picture ends a closed GOP or starts a new GOP then it
913 // needs to be in the top layer.
914 if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
916 // If the picture after this one is force-IDR, we need to encode
917 // this one in the top layer.
918 if (next && next->force_idr)
923 // At the end of the stream the last picture must be in the top layer.
924 if (!pic && ctx->end_of_stream) {
927 if (pic->encode_issued)
932 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
933 "need more input for reference pictures.\n");
934 return AVERROR(EAGAIN);
936 if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
937 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
938 "need more input for timestamps.\n");
939 return AVERROR(EAGAIN);
942 if (pic->force_idr) {
943 av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
945 pic->type = PICTURE_TYPE_IDR;
946 ctx->idr_counter = 1;
947 ctx->gop_counter = 1;
949 } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
950 if (ctx->idr_counter == ctx->gop_per_idr) {
951 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
953 pic->type = PICTURE_TYPE_IDR;
954 ctx->idr_counter = 1;
956 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
958 pic->type = PICTURE_TYPE_I;
961 ctx->gop_counter = 1;
964 if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
965 av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
968 av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
971 pic->type = PICTURE_TYPE_P;
973 ctx->gop_counter += 1 + b_counter;
975 pic->is_reference = 1;
978 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
979 if (pic->type != PICTURE_TYPE_IDR) {
980 vaapi_encode_add_ref(avctx, pic, start,
981 pic->type == PICTURE_TYPE_P,
983 vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
986 --ctx->next_prev->ref_count[0];
989 vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
992 ctx->next_prev = pic;
994 ++ctx->next_prev->ref_count[0];
998 static int vaapi_encode_clear_old(AVCodecContext *avctx)
1000 VAAPIEncodeContext *ctx = avctx->priv_data;
1001 VAAPIEncodePicture *pic, *prev, *next;
1003 av_assert0(ctx->pic_start);
1005 // Remove direct references once each picture is complete.
1006 for (pic = ctx->pic_start; pic; pic = pic->next) {
1007 if (pic->encode_complete && pic->next)
1008 vaapi_encode_remove_refs(avctx, pic, 0);
1011 // Remove indirect references once a picture has no direct references.
1012 for (pic = ctx->pic_start; pic; pic = pic->next) {
1013 if (pic->encode_complete && pic->ref_count[0] == 0)
1014 vaapi_encode_remove_refs(avctx, pic, 1);
1017 // Clear out all complete pictures with no remaining references.
1019 for (pic = ctx->pic_start; pic; pic = next) {
1021 if (pic->encode_complete && pic->ref_count[1] == 0) {
1022 av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
1026 ctx->pic_start = next;
1027 vaapi_encode_free(avctx, pic);
1036 static int vaapi_encode_check_frame(AVCodecContext *avctx,
1037 const AVFrame *frame)
1039 VAAPIEncodeContext *ctx = avctx->priv_data;
1041 if ((frame->crop_top || frame->crop_bottom ||
1042 frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
1043 av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
1044 "frames ignored due to lack of API support.\n");
1045 ctx->crop_warned = 1;
1048 if (!ctx->roi_allowed) {
1049 AVFrameSideData *sd =
1050 av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
1052 if (sd && !ctx->roi_warned) {
1053 av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
1054 "frames ignored due to lack of driver support.\n");
1055 ctx->roi_warned = 1;
1062 static int vaapi_encode_send_frame(AVCodecContext *avctx, AVFrame *frame)
1064 VAAPIEncodeContext *ctx = avctx->priv_data;
1065 VAAPIEncodePicture *pic;
1069 av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
1070 frame->width, frame->height, frame->pts);
1072 err = vaapi_encode_check_frame(avctx, frame);
1076 pic = vaapi_encode_alloc(avctx);
1078 return AVERROR(ENOMEM);
1080 pic->input_image = av_frame_alloc();
1081 if (!pic->input_image) {
1082 err = AVERROR(ENOMEM);
1086 if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
1089 pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
1090 pic->pts = frame->pts;
1092 av_frame_move_ref(pic->input_image, frame);
1094 if (ctx->input_order == 0)
1095 ctx->first_pts = pic->pts;
1096 if (ctx->input_order == ctx->decode_delay)
1097 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
1098 if (ctx->output_delay > 0)
1099 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
1101 pic->display_order = ctx->input_order;
1104 if (ctx->pic_start) {
1105 ctx->pic_end->next = pic;
1108 ctx->pic_start = pic;
1113 ctx->end_of_stream = 1;
1115 // Fix timestamps if we hit end-of-stream before the initial decode
1116 // delay has elapsed.
1117 if (ctx->input_order < ctx->decode_delay)
1118 ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
1124 vaapi_encode_free(avctx, pic);
1128 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
1130 VAAPIEncodeContext *ctx = avctx->priv_data;
1131 VAAPIEncodePicture *pic;
1132 AVFrame *frame = ctx->frame;
1135 err = ff_encode_get_frame(avctx, frame);
1136 if (err < 0 && err != AVERROR_EOF)
1139 if (err == AVERROR_EOF)
1142 err = vaapi_encode_send_frame(avctx, frame);
1146 if (!ctx->pic_start) {
1147 if (ctx->end_of_stream)
1150 return AVERROR(EAGAIN);
1154 err = vaapi_encode_pick_next(avctx, &pic);
1159 pic->encode_order = ctx->encode_order++;
1161 err = vaapi_encode_issue(avctx, pic);
1163 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1167 err = vaapi_encode_output(avctx, pic, pkt);
1169 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1173 if (ctx->output_delay == 0) {
1174 pkt->dts = pkt->pts;
1175 } else if (pic->encode_order < ctx->decode_delay) {
1176 if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1177 pkt->dts = INT64_MIN;
1179 pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1181 pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1182 (3 * ctx->output_delay)];
1184 av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1185 pkt->pts, pkt->dts);
1187 ctx->output_order = pic->encode_order;
1188 vaapi_encode_clear_old(avctx);
1194 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
1195 void *buffer, size_t size)
1197 VAAPIEncodeContext *ctx = avctx->priv_data;
1199 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1201 ctx->global_params_type[ctx->nb_global_params] = type;
1202 ctx->global_params [ctx->nb_global_params] = buffer;
1203 ctx->global_params_size[ctx->nb_global_params] = size;
1205 ++ctx->nb_global_params;
1208 typedef struct VAAPIEncodeRTFormat {
1215 } VAAPIEncodeRTFormat;
1217 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1218 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
1219 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
1220 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
1221 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
1222 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
1223 #if VA_CHECK_VERSION(0, 38, 1)
1224 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1228 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1229 VAEntrypointEncSlice,
1230 VAEntrypointEncPicture,
1231 #if VA_CHECK_VERSION(0, 39, 2)
1232 VAEntrypointEncSliceLP,
1236 #if VA_CHECK_VERSION(0, 39, 2)
1237 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1238 VAEntrypointEncSliceLP,
1243 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1245 VAAPIEncodeContext *ctx = avctx->priv_data;
1246 VAProfile *va_profiles = NULL;
1247 VAEntrypoint *va_entrypoints = NULL;
1249 const VAEntrypoint *usable_entrypoints;
1250 const VAAPIEncodeProfile *profile;
1251 const AVPixFmtDescriptor *desc;
1252 VAConfigAttrib rt_format_attr;
1253 const VAAPIEncodeRTFormat *rt_format;
1254 const char *profile_string, *entrypoint_string;
1255 int i, j, n, depth, err;
1258 if (ctx->low_power) {
1259 #if VA_CHECK_VERSION(0, 39, 2)
1260 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1262 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1263 "supported with this VAAPI version.\n");
1264 return AVERROR(EINVAL);
1267 usable_entrypoints = vaapi_encode_entrypoints_normal;
1270 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1272 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1273 ctx->input_frames->sw_format);
1274 return AVERROR(EINVAL);
1276 depth = desc->comp[0].depth;
1277 for (i = 1; i < desc->nb_components; i++) {
1278 if (desc->comp[i].depth != depth) {
1279 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1281 return AVERROR(EINVAL);
1284 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1287 n = vaMaxNumProfiles(ctx->hwctx->display);
1288 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1290 err = AVERROR(ENOMEM);
1293 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1294 if (vas != VA_STATUS_SUCCESS) {
1295 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1296 vas, vaErrorStr(vas));
1297 err = AVERROR_EXTERNAL;
1301 av_assert0(ctx->codec->profiles);
1302 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1303 FF_PROFILE_UNKNOWN); i++) {
1304 profile = &ctx->codec->profiles[i];
1305 if (depth != profile->depth ||
1306 desc->nb_components != profile->nb_components)
1308 if (desc->nb_components > 1 &&
1309 (desc->log2_chroma_w != profile->log2_chroma_w ||
1310 desc->log2_chroma_h != profile->log2_chroma_h))
1312 if (avctx->profile != profile->av_profile &&
1313 avctx->profile != FF_PROFILE_UNKNOWN)
1316 #if VA_CHECK_VERSION(1, 0, 0)
1317 profile_string = vaProfileStr(profile->va_profile);
1319 profile_string = "(no profile names)";
1322 for (j = 0; j < n; j++) {
1323 if (va_profiles[j] == profile->va_profile)
1327 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1328 "is not supported by driver.\n", profile_string,
1329 profile->va_profile);
1333 ctx->profile = profile;
1336 if (!ctx->profile) {
1337 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1338 err = AVERROR(ENOSYS);
1342 avctx->profile = profile->av_profile;
1343 ctx->va_profile = profile->va_profile;
1344 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1345 profile_string, ctx->va_profile);
1347 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1348 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1349 if (!va_entrypoints) {
1350 err = AVERROR(ENOMEM);
1353 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1354 va_entrypoints, &n);
1355 if (vas != VA_STATUS_SUCCESS) {
1356 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1357 "profile %s (%d): %d (%s).\n", profile_string,
1358 ctx->va_profile, vas, vaErrorStr(vas));
1359 err = AVERROR_EXTERNAL;
1363 for (i = 0; i < n; i++) {
1364 for (j = 0; usable_entrypoints[j]; j++) {
1365 if (va_entrypoints[i] == usable_entrypoints[j])
1368 if (usable_entrypoints[j])
1372 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1373 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1374 err = AVERROR(ENOSYS);
1378 ctx->va_entrypoint = va_entrypoints[i];
1379 #if VA_CHECK_VERSION(1, 0, 0)
1380 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1382 entrypoint_string = "(no entrypoint names)";
1384 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1385 entrypoint_string, ctx->va_entrypoint);
1387 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1388 rt_format = &vaapi_encode_rt_formats[i];
1389 if (rt_format->depth == depth &&
1390 rt_format->nb_components == profile->nb_components &&
1391 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1392 rt_format->log2_chroma_h == profile->log2_chroma_h)
1395 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1396 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1397 "found for profile %s (%d) entrypoint %s (%d).\n",
1398 profile_string, ctx->va_profile,
1399 entrypoint_string, ctx->va_entrypoint);
1400 err = AVERROR(ENOSYS);
1404 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1405 vas = vaGetConfigAttributes(ctx->hwctx->display,
1406 ctx->va_profile, ctx->va_entrypoint,
1407 &rt_format_attr, 1);
1408 if (vas != VA_STATUS_SUCCESS) {
1409 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1410 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1411 err = AVERROR_EXTERNAL;
1415 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1416 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1417 "supported by driver: assuming surface RT format %s "
1418 "is valid.\n", rt_format->name);
1419 } else if (!(rt_format_attr.value & rt_format->value)) {
1420 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1421 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1422 rt_format->name, profile_string, ctx->va_profile,
1423 entrypoint_string, ctx->va_entrypoint);
1424 err = AVERROR(ENOSYS);
1427 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1428 "format %s (%#x).\n", rt_format->name, rt_format->value);
1429 ctx->config_attributes[ctx->nb_config_attributes++] =
1431 .type = VAConfigAttribRTFormat,
1432 .value = rt_format->value,
1438 av_freep(&va_profiles);
1439 av_freep(&va_entrypoints);
1443 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1445 // | Maxrate | HRD/VBV
1447 { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
1448 { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
1449 { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
1450 #if VA_CHECK_VERSION(1, 1, 0)
1451 { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
1453 { RC_MODE_ICQ, "ICQ", 0 },
1455 #if VA_CHECK_VERSION(1, 3, 0)
1456 { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
1457 { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
1459 { RC_MODE_QVBR, "QVBR", 0 },
1460 { RC_MODE_AVBR, "AVBR", 0 },
1464 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1466 VAAPIEncodeContext *ctx = avctx->priv_data;
1467 uint32_t supported_va_rc_modes;
1468 const VAAPIEncodeRCMode *rc_mode;
1469 int64_t rc_bits_per_second;
1470 int rc_target_percentage;
1473 int64_t hrd_buffer_size;
1474 int64_t hrd_initial_buffer_fullness;
1476 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1478 char supported_rc_modes_string[64];
1480 vas = vaGetConfigAttributes(ctx->hwctx->display,
1481 ctx->va_profile, ctx->va_entrypoint,
1483 if (vas != VA_STATUS_SUCCESS) {
1484 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1485 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1486 return AVERROR_EXTERNAL;
1488 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1489 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1490 "supported rate control modes: assuming CQP only.\n");
1491 supported_va_rc_modes = VA_RC_CQP;
1492 strcpy(supported_rc_modes_string, "unknown");
1494 char *str = supported_rc_modes_string;
1495 size_t len = sizeof(supported_rc_modes_string);
1496 int i, first = 1, res;
1498 supported_va_rc_modes = rc_attr.value;
1499 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1500 rc_mode = &vaapi_encode_rc_modes[i];
1501 if (supported_va_rc_modes & rc_mode->va_mode) {
1502 res = snprintf(str, len, "%s%s",
1503 first ? "" : ", ", rc_mode->name);
1516 av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1517 supported_rc_modes_string);
1520 // Rate control mode selection:
1521 // * If the user has set a mode explicitly with the rc_mode option,
1522 // use it and fail if it is not available.
1523 // * If an explicit QP option has been set, use CQP.
1524 // * If the codec is CQ-only, use CQP.
1525 // * If the QSCALE avcodec option is set, use CQP.
1526 // * If bitrate and quality are both set, try QVBR.
1527 // * If quality is set, try ICQ, then CQP.
1528 // * If bitrate and maxrate are set and have the same value, try CBR.
1529 // * If a bitrate is set, try AVBR, then VBR, then CBR.
1530 // * If no bitrate is set, try ICQ, then CQP.
1532 #define TRY_RC_MODE(mode, fail) do { \
1533 rc_mode = &vaapi_encode_rc_modes[mode]; \
1534 if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1536 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1537 "RC mode (supported modes: %s).\n", rc_mode->name, \
1538 supported_rc_modes_string); \
1539 return AVERROR(EINVAL); \
1541 av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1542 "RC mode.\n", rc_mode->name); \
1545 goto rc_mode_found; \
1549 if (ctx->explicit_rc_mode)
1550 TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1552 if (ctx->explicit_qp)
1553 TRY_RC_MODE(RC_MODE_CQP, 1);
1555 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1556 TRY_RC_MODE(RC_MODE_CQP, 1);
1558 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1559 TRY_RC_MODE(RC_MODE_CQP, 1);
1561 if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1562 TRY_RC_MODE(RC_MODE_QVBR, 0);
1564 if (avctx->global_quality > 0) {
1565 TRY_RC_MODE(RC_MODE_ICQ, 0);
1566 TRY_RC_MODE(RC_MODE_CQP, 0);
1569 if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1570 TRY_RC_MODE(RC_MODE_CBR, 0);
1572 if (avctx->bit_rate > 0) {
1573 TRY_RC_MODE(RC_MODE_AVBR, 0);
1574 TRY_RC_MODE(RC_MODE_VBR, 0);
1575 TRY_RC_MODE(RC_MODE_CBR, 0);
1577 TRY_RC_MODE(RC_MODE_ICQ, 0);
1578 TRY_RC_MODE(RC_MODE_CQP, 0);
1581 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1582 "RC mode compatible with selected options "
1583 "(supported modes: %s).\n", supported_rc_modes_string);
1584 return AVERROR(EINVAL);
1587 if (rc_mode->bitrate) {
1588 if (avctx->bit_rate <= 0) {
1589 av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1590 "RC mode.\n", rc_mode->name);
1591 return AVERROR(EINVAL);
1594 if (rc_mode->mode == RC_MODE_AVBR) {
1595 // For maximum confusion AVBR is hacked into the existing API
1596 // by overloading some of the fields with completely different
1599 // Target percentage does not apply in AVBR mode.
1600 rc_bits_per_second = avctx->bit_rate;
1602 // Accuracy tolerance range for meeting the specified target
1603 // bitrate. It's very unclear how this is actually intended
1604 // to work - since we do want to get the specified bitrate,
1605 // set the accuracy to 100% for now.
1606 rc_target_percentage = 100;
1608 // Convergence period in frames. The GOP size reflects the
1609 // user's intended block size for cutting, so reusing that
1610 // as the convergence period seems a reasonable default.
1611 rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1613 } else if (rc_mode->maxrate) {
1614 if (avctx->rc_max_rate > 0) {
1615 if (avctx->rc_max_rate < avctx->bit_rate) {
1616 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1617 "bitrate (%"PRId64") must not be greater than "
1618 "maxrate (%"PRId64").\n", avctx->bit_rate,
1619 avctx->rc_max_rate);
1620 return AVERROR(EINVAL);
1622 rc_bits_per_second = avctx->rc_max_rate;
1623 rc_target_percentage = (avctx->bit_rate * 100) /
1626 // We only have a target bitrate, but this mode requires
1627 // that a maximum rate be supplied as well. Since the
1628 // user does not want this to be a constraint, arbitrarily
1629 // pick a maximum rate of double the target rate.
1630 rc_bits_per_second = 2 * avctx->bit_rate;
1631 rc_target_percentage = 50;
1634 if (avctx->rc_max_rate > avctx->bit_rate) {
1635 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1636 "in %s RC mode.\n", rc_mode->name);
1638 rc_bits_per_second = avctx->bit_rate;
1639 rc_target_percentage = 100;
1642 rc_bits_per_second = 0;
1643 rc_target_percentage = 100;
1646 if (rc_mode->quality) {
1647 if (ctx->explicit_qp) {
1648 rc_quality = ctx->explicit_qp;
1649 } else if (avctx->global_quality > 0) {
1650 rc_quality = avctx->global_quality;
1652 rc_quality = ctx->codec->default_quality;
1653 av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1654 "using default (%d).\n", rc_quality);
1661 if (avctx->rc_buffer_size)
1662 hrd_buffer_size = avctx->rc_buffer_size;
1663 else if (avctx->rc_max_rate > 0)
1664 hrd_buffer_size = avctx->rc_max_rate;
1666 hrd_buffer_size = avctx->bit_rate;
1667 if (avctx->rc_initial_buffer_occupancy) {
1668 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1669 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1670 "must have initial buffer size (%d) <= "
1671 "buffer size (%"PRId64").\n",
1672 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1673 return AVERROR(EINVAL);
1675 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1677 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1680 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1682 if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1683 av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1684 "in %s RC mode.\n", rc_mode->name);
1687 hrd_buffer_size = 0;
1688 hrd_initial_buffer_fullness = 0;
1690 if (rc_mode->mode != RC_MODE_AVBR) {
1691 // Already set (with completely different meaning) for AVBR.
1692 rc_window_size = 1000;
1696 if (rc_bits_per_second > UINT32_MAX ||
1697 hrd_buffer_size > UINT32_MAX ||
1698 hrd_initial_buffer_fullness > UINT32_MAX) {
1699 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1700 "greater are not supported by VAAPI.\n");
1701 return AVERROR(EINVAL);
1704 ctx->rc_mode = rc_mode;
1705 ctx->rc_quality = rc_quality;
1706 ctx->va_rc_mode = rc_mode->va_mode;
1707 ctx->va_bit_rate = rc_bits_per_second;
1709 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1710 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1711 // This driver does not want the RC mode attribute to be set.
1713 ctx->config_attributes[ctx->nb_config_attributes++] =
1715 .type = VAConfigAttribRateControl,
1716 .value = ctx->va_rc_mode,
1720 if (rc_mode->quality)
1721 av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1723 if (rc_mode->va_mode != VA_RC_CQP) {
1724 if (rc_mode->mode == RC_MODE_AVBR) {
1725 av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1726 "converging in %d frames with %d%% accuracy.\n",
1727 rc_bits_per_second, rc_window_size,
1728 rc_target_percentage);
1729 } else if (rc_mode->bitrate) {
1730 av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1731 "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1732 rc_bits_per_second, rc_window_size);
1735 ctx->rc_params = (VAEncMiscParameterRateControl) {
1736 .bits_per_second = rc_bits_per_second,
1737 .target_percentage = rc_target_percentage,
1738 .window_size = rc_window_size,
1740 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1741 .basic_unit_size = 0,
1742 #if VA_CHECK_VERSION(1, 1, 0)
1743 .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1744 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1746 #if VA_CHECK_VERSION(1, 3, 0)
1747 .quality_factor = rc_quality,
1750 vaapi_encode_add_global_param(avctx,
1751 VAEncMiscParameterTypeRateControl,
1753 sizeof(ctx->rc_params));
1757 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1758 "initial fullness %"PRId64" bits.\n",
1759 hrd_buffer_size, hrd_initial_buffer_fullness);
1761 ctx->hrd_params = (VAEncMiscParameterHRD) {
1762 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1763 .buffer_size = hrd_buffer_size,
1765 vaapi_encode_add_global_param(avctx,
1766 VAEncMiscParameterTypeHRD,
1768 sizeof(ctx->hrd_params));
1771 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1772 av_reduce(&fr_num, &fr_den,
1773 avctx->framerate.num, avctx->framerate.den, 65535);
1775 av_reduce(&fr_num, &fr_den,
1776 avctx->time_base.den, avctx->time_base.num, 65535);
1778 av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1779 fr_num, fr_den, (double)fr_num / fr_den);
1781 ctx->fr_params = (VAEncMiscParameterFrameRate) {
1782 .framerate = (unsigned int)fr_den << 16 | fr_num,
1784 #if VA_CHECK_VERSION(0, 40, 0)
1785 vaapi_encode_add_global_param(avctx,
1786 VAEncMiscParameterTypeFrameRate,
1788 sizeof(ctx->fr_params));
1794 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1796 VAAPIEncodeContext *ctx = avctx->priv_data;
1798 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1799 uint32_t ref_l0, ref_l1;
1801 vas = vaGetConfigAttributes(ctx->hwctx->display,
1805 if (vas != VA_STATUS_SUCCESS) {
1806 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1807 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1808 return AVERROR_EXTERNAL;
1811 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1812 ref_l0 = ref_l1 = 0;
1814 ref_l0 = attr.value & 0xffff;
1815 ref_l1 = attr.value >> 16 & 0xffff;
1818 if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1819 avctx->gop_size <= 1) {
1820 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1822 } else if (ref_l0 < 1) {
1823 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1824 "reference frames.\n");
1825 return AVERROR(EINVAL);
1826 } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1827 ref_l1 < 1 || avctx->max_b_frames < 1) {
1828 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1829 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1830 ctx->gop_size = avctx->gop_size;
1831 ctx->p_per_i = INT_MAX;
1834 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1835 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1836 ctx->gop_size = avctx->gop_size;
1837 ctx->p_per_i = INT_MAX;
1838 ctx->b_per_p = avctx->max_b_frames;
1839 if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1840 ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1841 av_log2(ctx->b_per_p) + 1);
1843 ctx->max_b_depth = 1;
1847 if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1848 ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1849 ctx->gop_per_idr = ctx->idr_interval + 1;
1851 ctx->closed_gop = 1;
1852 ctx->gop_per_idr = 1;
1858 static av_cold int vaapi_encode_init_row_slice_structure(AVCodecContext *avctx,
1859 uint32_t slice_structure)
1861 VAAPIEncodeContext *ctx = avctx->priv_data;
1864 // For fixed-size slices currently we only support whole rows, making
1865 // rectangular slices. This could be extended to arbitrary runs of
1866 // blocks, but since slices tend to be a conformance requirement and
1867 // most cases (such as broadcast or bluray) want rectangular slices
1868 // only it would need to be gated behind another option.
1869 if (avctx->slices > ctx->slice_block_rows) {
1870 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1871 "configured number of slices (%d < %d); using "
1872 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1873 req_slices = ctx->slice_block_rows;
1875 req_slices = avctx->slices;
1877 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1878 #if VA_CHECK_VERSION(1, 8, 0)
1879 slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_MULTI_ROWS ||
1881 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1882 ctx->nb_slices = req_slices;
1883 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1884 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1886 for (k = 1;; k *= 2) {
1887 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1890 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1891 ctx->slice_size = k;
1892 #if VA_CHECK_VERSION(1, 0, 0)
1893 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1894 ctx->nb_slices = ctx->slice_block_rows;
1895 ctx->slice_size = 1;
1898 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1899 "slice structure modes (%#x).\n", slice_structure);
1900 return AVERROR(EINVAL);
1906 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1908 VAAPIEncodeContext *ctx = avctx->priv_data;
1909 VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1910 { VAConfigAttribEncSliceStructure } };
1912 uint32_t max_slices, slice_structure;
1915 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1916 if (avctx->slices > 0) {
1917 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1918 "but this codec does not support controlling slices.\n");
1923 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1924 ctx->slice_block_height;
1925 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
1926 ctx->slice_block_width;
1928 if (avctx->slices <= 1) {
1930 ctx->slice_size = ctx->slice_block_rows;
1934 vas = vaGetConfigAttributes(ctx->hwctx->display,
1937 attr, FF_ARRAY_ELEMS(attr));
1938 if (vas != VA_STATUS_SUCCESS) {
1939 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1940 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1941 return AVERROR_EXTERNAL;
1943 max_slices = attr[0].value;
1944 slice_structure = attr[1].value;
1945 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1946 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1947 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1948 "pictures as multiple slices.\n.");
1949 return AVERROR(EINVAL);
1952 ret = vaapi_encode_init_row_slice_structure(avctx, slice_structure);
1956 if (ctx->nb_slices > avctx->slices) {
1957 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1958 "%d (from %d) due to driver constraints on slice "
1959 "structure.\n", ctx->nb_slices, avctx->slices);
1961 if (ctx->nb_slices > max_slices) {
1962 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1963 "encoding with %d slices (max %"PRIu32").\n",
1964 ctx->nb_slices, max_slices);
1965 return AVERROR(EINVAL);
1968 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1969 "(default size %d block rows).\n",
1970 ctx->nb_slices, ctx->slice_size);
1974 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1976 VAAPIEncodeContext *ctx = avctx->priv_data;
1978 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1980 vas = vaGetConfigAttributes(ctx->hwctx->display,
1984 if (vas != VA_STATUS_SUCCESS) {
1985 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1986 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1987 return AVERROR_EXTERNAL;
1990 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1991 if (ctx->desired_packed_headers) {
1992 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1993 "packed headers (wanted %#x).\n",
1994 ctx->desired_packed_headers);
1996 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1997 "packed headers (none wanted).\n");
1999 ctx->va_packed_headers = 0;
2001 if (ctx->desired_packed_headers & ~attr.value) {
2002 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
2003 "wanted packed headers (wanted %#x, found %#x).\n",
2004 ctx->desired_packed_headers, attr.value);
2006 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
2007 "available (wanted %#x, found %#x).\n",
2008 ctx->desired_packed_headers, attr.value);
2010 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
2013 if (ctx->va_packed_headers) {
2014 ctx->config_attributes[ctx->nb_config_attributes++] =
2016 .type = VAConfigAttribEncPackedHeaders,
2017 .value = ctx->va_packed_headers,
2021 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
2022 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
2023 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
2024 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
2025 "sequence headers, but a global header is requested.\n");
2026 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
2027 "this may result in a stream which is not usable for some "
2028 "purposes (e.g. not muxable to some containers).\n");
2034 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
2036 #if VA_CHECK_VERSION(0, 36, 0)
2037 VAAPIEncodeContext *ctx = avctx->priv_data;
2039 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
2040 int quality = avctx->compression_level;
2042 vas = vaGetConfigAttributes(ctx->hwctx->display,
2046 if (vas != VA_STATUS_SUCCESS) {
2047 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
2048 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2049 return AVERROR_EXTERNAL;
2052 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2054 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
2055 "supported: will use default quality level.\n");
2058 if (quality > attr.value) {
2059 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
2060 "valid range is 0-%d, using %d.\n",
2061 attr.value, attr.value);
2062 quality = attr.value;
2065 ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
2066 .quality_level = quality,
2068 vaapi_encode_add_global_param(avctx,
2069 VAEncMiscParameterTypeQualityLevel,
2070 &ctx->quality_params,
2071 sizeof(ctx->quality_params));
2074 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
2075 "not supported with this VAAPI version.\n");
2081 static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
2083 #if VA_CHECK_VERSION(1, 0, 0)
2084 VAAPIEncodeContext *ctx = avctx->priv_data;
2086 VAConfigAttrib attr = { VAConfigAttribEncROI };
2088 vas = vaGetConfigAttributes(ctx->hwctx->display,
2092 if (vas != VA_STATUS_SUCCESS) {
2093 av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
2094 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2095 return AVERROR_EXTERNAL;
2098 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2099 ctx->roi_allowed = 0;
2101 VAConfigAttribValEncROI roi = {
2102 .value = attr.value,
2105 ctx->roi_max_regions = roi.bits.num_roi_regions;
2106 ctx->roi_allowed = ctx->roi_max_regions > 0 &&
2107 (ctx->va_rc_mode == VA_RC_CQP ||
2108 roi.bits.roi_rc_qp_delta_support);
2114 static void vaapi_encode_free_output_buffer(void *opaque,
2117 AVCodecContext *avctx = opaque;
2118 VAAPIEncodeContext *ctx = avctx->priv_data;
2119 VABufferID buffer_id;
2121 buffer_id = (VABufferID)(uintptr_t)data;
2123 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2125 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
2128 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
2131 AVCodecContext *avctx = opaque;
2132 VAAPIEncodeContext *ctx = avctx->priv_data;
2133 VABufferID buffer_id;
2137 // The output buffer size is fixed, so it needs to be large enough
2138 // to hold the largest possible compressed frame. We assume here
2139 // that the uncompressed frame plus some header data is an upper
2141 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
2142 VAEncCodedBufferType,
2143 3 * ctx->surface_width * ctx->surface_height +
2144 (1 << 16), 1, 0, &buffer_id);
2145 if (vas != VA_STATUS_SUCCESS) {
2146 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
2147 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
2151 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
2153 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
2155 &vaapi_encode_free_output_buffer,
2156 avctx, AV_BUFFER_FLAG_READONLY);
2158 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2165 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
2167 VAAPIEncodeContext *ctx = avctx->priv_data;
2168 AVVAAPIHWConfig *hwconfig = NULL;
2169 AVHWFramesConstraints *constraints = NULL;
2170 enum AVPixelFormat recon_format;
2173 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
2175 err = AVERROR(ENOMEM);
2178 hwconfig->config_id = ctx->va_config;
2180 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
2183 err = AVERROR(ENOMEM);
2187 // Probably we can use the input surface format as the surface format
2188 // of the reconstructed frames. If not, we just pick the first (only?)
2189 // format in the valid list and hope that it all works.
2190 recon_format = AV_PIX_FMT_NONE;
2191 if (constraints->valid_sw_formats) {
2192 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
2193 if (ctx->input_frames->sw_format ==
2194 constraints->valid_sw_formats[i]) {
2195 recon_format = ctx->input_frames->sw_format;
2199 if (recon_format == AV_PIX_FMT_NONE) {
2200 // No match. Just use the first in the supported list and
2201 // hope for the best.
2202 recon_format = constraints->valid_sw_formats[0];
2205 // No idea what to use; copy input format.
2206 recon_format = ctx->input_frames->sw_format;
2208 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
2209 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
2211 if (ctx->surface_width < constraints->min_width ||
2212 ctx->surface_height < constraints->min_height ||
2213 ctx->surface_width > constraints->max_width ||
2214 ctx->surface_height > constraints->max_height) {
2215 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2216 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2217 ctx->surface_width, ctx->surface_height,
2218 constraints->min_width, constraints->max_width,
2219 constraints->min_height, constraints->max_height);
2220 err = AVERROR(EINVAL);
2224 av_freep(&hwconfig);
2225 av_hwframe_constraints_free(&constraints);
2227 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2228 if (!ctx->recon_frames_ref) {
2229 err = AVERROR(ENOMEM);
2232 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2234 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
2235 ctx->recon_frames->sw_format = recon_format;
2236 ctx->recon_frames->width = ctx->surface_width;
2237 ctx->recon_frames->height = ctx->surface_height;
2239 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2241 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2242 "frame context: %d.\n", err);
2248 av_freep(&hwconfig);
2249 av_hwframe_constraints_free(&constraints);
2253 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2255 VAAPIEncodeContext *ctx = avctx->priv_data;
2256 AVVAAPIFramesContext *recon_hwctx = NULL;
2260 ctx->frame = av_frame_alloc();
2262 return AVERROR(ENOMEM);
2265 if (!avctx->hw_frames_ctx) {
2266 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2267 "required to associate the encoding device.\n");
2268 return AVERROR(EINVAL);
2271 ctx->va_config = VA_INVALID_ID;
2272 ctx->va_context = VA_INVALID_ID;
2274 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2275 if (!ctx->input_frames_ref) {
2276 err = AVERROR(ENOMEM);
2279 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2281 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2282 if (!ctx->device_ref) {
2283 err = AVERROR(ENOMEM);
2286 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2287 ctx->hwctx = ctx->device->hwctx;
2289 err = vaapi_encode_profile_entrypoint(avctx);
2293 err = vaapi_encode_init_rate_control(avctx);
2297 err = vaapi_encode_init_gop_structure(avctx);
2301 err = vaapi_encode_init_slice_structure(avctx);
2305 err = vaapi_encode_init_packed_headers(avctx);
2309 err = vaapi_encode_init_roi(avctx);
2313 if (avctx->compression_level >= 0) {
2314 err = vaapi_encode_init_quality(avctx);
2319 vas = vaCreateConfig(ctx->hwctx->display,
2320 ctx->va_profile, ctx->va_entrypoint,
2321 ctx->config_attributes, ctx->nb_config_attributes,
2323 if (vas != VA_STATUS_SUCCESS) {
2324 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2325 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2330 err = vaapi_encode_create_recon_frames(avctx);
2334 recon_hwctx = ctx->recon_frames->hwctx;
2335 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2336 ctx->surface_width, ctx->surface_height,
2338 recon_hwctx->surface_ids,
2339 recon_hwctx->nb_surfaces,
2341 if (vas != VA_STATUS_SUCCESS) {
2342 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2343 "context: %d (%s).\n", vas, vaErrorStr(vas));
2348 ctx->output_buffer_pool =
2349 av_buffer_pool_init2(sizeof(VABufferID), avctx,
2350 &vaapi_encode_alloc_output_buffer, NULL);
2351 if (!ctx->output_buffer_pool) {
2352 err = AVERROR(ENOMEM);
2356 if (ctx->codec->configure) {
2357 err = ctx->codec->configure(avctx);
2362 ctx->output_delay = ctx->b_per_p;
2363 ctx->decode_delay = ctx->max_b_depth;
2365 if (ctx->codec->sequence_params_size > 0) {
2366 ctx->codec_sequence_params =
2367 av_mallocz(ctx->codec->sequence_params_size);
2368 if (!ctx->codec_sequence_params) {
2369 err = AVERROR(ENOMEM);
2373 if (ctx->codec->picture_params_size > 0) {
2374 ctx->codec_picture_params =
2375 av_mallocz(ctx->codec->picture_params_size);
2376 if (!ctx->codec_picture_params) {
2377 err = AVERROR(ENOMEM);
2382 if (ctx->codec->init_sequence_params) {
2383 err = ctx->codec->init_sequence_params(avctx);
2385 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2386 "failed: %d.\n", err);
2391 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2392 ctx->codec->write_sequence_header &&
2393 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2394 char data[MAX_PARAM_BUFFER_SIZE];
2395 size_t bit_len = 8 * sizeof(data);
2397 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2399 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2400 "for extradata: %d.\n", err);
2403 avctx->extradata_size = (bit_len + 7) / 8;
2404 avctx->extradata = av_mallocz(avctx->extradata_size +
2405 AV_INPUT_BUFFER_PADDING_SIZE);
2406 if (!avctx->extradata) {
2407 err = AVERROR(ENOMEM);
2410 memcpy(avctx->extradata, data, avctx->extradata_size);
2420 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2422 VAAPIEncodeContext *ctx = avctx->priv_data;
2423 VAAPIEncodePicture *pic, *next;
2425 for (pic = ctx->pic_start; pic; pic = next) {
2427 vaapi_encode_free(avctx, pic);
2430 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2432 if (ctx->va_context != VA_INVALID_ID) {
2433 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2434 ctx->va_context = VA_INVALID_ID;
2437 if (ctx->va_config != VA_INVALID_ID) {
2438 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2439 ctx->va_config = VA_INVALID_ID;
2442 av_frame_free(&ctx->frame);
2444 av_freep(&ctx->codec_sequence_params);
2445 av_freep(&ctx->codec_picture_params);
2447 av_buffer_unref(&ctx->recon_frames_ref);
2448 av_buffer_unref(&ctx->input_frames_ref);
2449 av_buffer_unref(&ctx->device_ref);