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_make_tile_slice(AVCodecContext *avctx,
222 VAAPIEncodePicture *pic)
224 VAAPIEncodeContext *ctx = avctx->priv_data;
225 VAAPIEncodeSlice *slice;
228 for (i = 0; i < ctx->tile_cols; i++) {
229 for (j = 0; j < ctx->tile_rows; j++) {
230 index = j * ctx->tile_cols + i;
231 slice = &pic->slices[index];
232 slice->index = index;
234 pic->slices[index].block_start = ctx->col_bd[i] +
235 ctx->row_bd[j] * ctx->slice_block_cols;
236 pic->slices[index].block_size = ctx->row_height[j] * ctx->col_width[i];
238 av_log(avctx, AV_LOG_DEBUG, "Slice %2d: (%2d, %2d) start at: %4d "
239 "width:%2d height:%2d (%d blocks).\n", index, ctx->col_bd[i],
240 ctx->row_bd[j], slice->block_start, ctx->col_width[i],
241 ctx->row_height[j], slice->block_size);
248 static int vaapi_encode_issue(AVCodecContext *avctx,
249 VAAPIEncodePicture *pic)
251 VAAPIEncodeContext *ctx = avctx->priv_data;
252 VAAPIEncodeSlice *slice;
255 char data[MAX_PARAM_BUFFER_SIZE];
257 av_unused AVFrameSideData *sd;
259 av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
260 "as type %s.\n", pic->display_order, pic->encode_order,
261 picture_type_name[pic->type]);
262 if (pic->nb_refs == 0) {
263 av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
265 av_log(avctx, AV_LOG_DEBUG, "Refers to:");
266 for (i = 0; i < pic->nb_refs; i++) {
267 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
268 pic->refs[i]->display_order, pic->refs[i]->encode_order);
270 av_log(avctx, AV_LOG_DEBUG, ".\n");
273 av_assert0(!pic->encode_issued);
274 for (i = 0; i < pic->nb_refs; i++) {
275 av_assert0(pic->refs[i]);
276 av_assert0(pic->refs[i]->encode_issued);
279 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
281 pic->recon_image = av_frame_alloc();
282 if (!pic->recon_image) {
283 err = AVERROR(ENOMEM);
287 err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
289 err = AVERROR(ENOMEM);
292 pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
293 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
295 pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
296 if (!pic->output_buffer_ref) {
297 err = AVERROR(ENOMEM);
300 pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
301 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
304 if (ctx->codec->picture_params_size > 0) {
305 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
306 if (!pic->codec_picture_params)
308 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
309 ctx->codec->picture_params_size);
311 av_assert0(!ctx->codec_picture_params);
314 pic->nb_param_buffers = 0;
316 if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
317 err = vaapi_encode_make_param_buffer(avctx, pic,
318 VAEncSequenceParameterBufferType,
319 ctx->codec_sequence_params,
320 ctx->codec->sequence_params_size);
325 if (pic->type == PICTURE_TYPE_IDR) {
326 for (i = 0; i < ctx->nb_global_params; i++) {
327 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
328 ctx->global_params_type[i],
329 ctx->global_params[i],
330 ctx->global_params_size[i]);
336 if (ctx->codec->init_picture_params) {
337 err = ctx->codec->init_picture_params(avctx, pic);
339 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
340 "parameters: %d.\n", err);
343 err = vaapi_encode_make_param_buffer(avctx, pic,
344 VAEncPictureParameterBufferType,
345 pic->codec_picture_params,
346 ctx->codec->picture_params_size);
351 if (pic->type == PICTURE_TYPE_IDR) {
352 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
353 ctx->codec->write_sequence_header) {
354 bit_len = 8 * sizeof(data);
355 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
357 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
358 "header: %d.\n", err);
361 err = vaapi_encode_make_packed_header(avctx, pic,
362 ctx->codec->sequence_header_type,
369 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
370 ctx->codec->write_picture_header) {
371 bit_len = 8 * sizeof(data);
372 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
374 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
375 "header: %d.\n", err);
378 err = vaapi_encode_make_packed_header(avctx, pic,
379 ctx->codec->picture_header_type,
385 if (ctx->codec->write_extra_buffer) {
387 size_t len = sizeof(data);
389 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
391 if (err == AVERROR_EOF)
394 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
395 "buffer %d: %d.\n", i, err);
399 err = vaapi_encode_make_param_buffer(avctx, pic, type,
406 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
407 ctx->codec->write_extra_header) {
410 bit_len = 8 * sizeof(data);
411 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
413 if (err == AVERROR_EOF)
416 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
417 "header %d: %d.\n", i, err);
421 err = vaapi_encode_make_packed_header(avctx, pic, type,
428 if (pic->nb_slices == 0)
429 pic->nb_slices = ctx->nb_slices;
430 if (pic->nb_slices > 0) {
431 pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
433 err = AVERROR(ENOMEM);
437 if (ctx->tile_rows && ctx->tile_cols)
438 vaapi_encode_make_tile_slice(avctx, pic);
440 vaapi_encode_make_row_slice(avctx, pic);
443 for (i = 0; i < pic->nb_slices; i++) {
444 slice = &pic->slices[i];
446 if (ctx->codec->slice_params_size > 0) {
447 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
448 if (!slice->codec_slice_params) {
449 err = AVERROR(ENOMEM);
454 if (ctx->codec->init_slice_params) {
455 err = ctx->codec->init_slice_params(avctx, pic, slice);
457 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
458 "parameters: %d.\n", err);
463 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
464 ctx->codec->write_slice_header) {
465 bit_len = 8 * sizeof(data);
466 err = ctx->codec->write_slice_header(avctx, pic, slice,
469 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
470 "header: %d.\n", err);
473 err = vaapi_encode_make_packed_header(avctx, pic,
474 ctx->codec->slice_header_type,
480 if (ctx->codec->init_slice_params) {
481 err = vaapi_encode_make_param_buffer(avctx, pic,
482 VAEncSliceParameterBufferType,
483 slice->codec_slice_params,
484 ctx->codec->slice_params_size);
490 #if VA_CHECK_VERSION(1, 0, 0)
491 sd = av_frame_get_side_data(pic->input_image,
492 AV_FRAME_DATA_REGIONS_OF_INTEREST);
493 if (sd && ctx->roi_allowed) {
494 const AVRegionOfInterest *roi;
496 VAEncMiscParameterBufferROI param_roi;
499 roi = (const AVRegionOfInterest*)sd->data;
500 roi_size = roi->self_size;
501 av_assert0(roi_size && sd->size % roi_size == 0);
502 nb_roi = sd->size / roi_size;
503 if (nb_roi > ctx->roi_max_regions) {
504 if (!ctx->roi_warned) {
505 av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
506 "supported by driver (%d > %d).\n",
507 nb_roi, ctx->roi_max_regions);
510 nb_roi = ctx->roi_max_regions;
513 pic->roi = av_mallocz_array(nb_roi, sizeof(*pic->roi));
515 err = AVERROR(ENOMEM);
518 // For overlapping regions, the first in the array takes priority.
519 for (i = 0; i < nb_roi; i++) {
520 roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
522 av_assert0(roi->qoffset.den != 0);
523 v = roi->qoffset.num * ctx->roi_quant_range / roi->qoffset.den;
524 av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
525 roi->top, roi->left, roi->bottom, roi->right, v);
527 pic->roi[i] = (VAEncROI) {
531 .width = roi->right - roi->left,
532 .height = roi->bottom - roi->top,
534 .roi_value = av_clip_int8(v),
538 param_roi = (VAEncMiscParameterBufferROI) {
540 .max_delta_qp = INT8_MAX,
541 .min_delta_qp = INT8_MIN,
543 .roi_flags.bits.roi_value_is_qp_delta = 1,
546 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
547 VAEncMiscParameterTypeROI,
555 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
557 if (vas != VA_STATUS_SUCCESS) {
558 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
559 "%d (%s).\n", vas, vaErrorStr(vas));
561 goto fail_with_picture;
564 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
565 pic->param_buffers, pic->nb_param_buffers);
566 if (vas != VA_STATUS_SUCCESS) {
567 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
568 "%d (%s).\n", vas, vaErrorStr(vas));
570 goto fail_with_picture;
573 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
574 if (vas != VA_STATUS_SUCCESS) {
575 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
576 "%d (%s).\n", vas, vaErrorStr(vas));
578 // vaRenderPicture() has been called here, so we should not destroy
579 // the parameter buffers unless separate destruction is required.
580 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
581 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
587 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
588 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
589 for (i = 0; i < pic->nb_param_buffers; i++) {
590 vas = vaDestroyBuffer(ctx->hwctx->display,
591 pic->param_buffers[i]);
592 if (vas != VA_STATUS_SUCCESS) {
593 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
594 "param buffer %#x: %d (%s).\n",
595 pic->param_buffers[i], vas, vaErrorStr(vas));
601 pic->encode_issued = 1;
606 vaEndPicture(ctx->hwctx->display, ctx->va_context);
608 for(i = 0; i < pic->nb_param_buffers; i++)
609 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
610 for (i = 0; i < pic->nb_slices; i++) {
612 av_freep(&pic->slices[i].priv_data);
613 av_freep(&pic->slices[i].codec_slice_params);
617 av_freep(&pic->codec_picture_params);
618 av_freep(&pic->param_buffers);
619 av_freep(&pic->slices);
621 av_frame_free(&pic->recon_image);
622 av_buffer_unref(&pic->output_buffer_ref);
623 pic->output_buffer = VA_INVALID_ID;
627 static int vaapi_encode_output(AVCodecContext *avctx,
628 VAAPIEncodePicture *pic, AVPacket *pkt)
630 VAAPIEncodeContext *ctx = avctx->priv_data;
631 VACodedBufferSegment *buf_list, *buf;
637 err = vaapi_encode_wait(avctx, pic);
642 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
644 if (vas != VA_STATUS_SUCCESS) {
645 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
646 "%d (%s).\n", vas, vaErrorStr(vas));
651 for (buf = buf_list; buf; buf = buf->next)
652 total_size += buf->size;
654 err = av_new_packet(pkt, total_size);
660 for (buf = buf_list; buf; buf = buf->next) {
661 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
662 "(status %08x).\n", buf->size, buf->status);
664 memcpy(ptr, buf->buf, buf->size);
668 if (pic->type == PICTURE_TYPE_IDR)
669 pkt->flags |= AV_PKT_FLAG_KEY;
673 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
674 if (vas != VA_STATUS_SUCCESS) {
675 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
676 "%d (%s).\n", vas, vaErrorStr(vas));
681 av_buffer_unref(&pic->output_buffer_ref);
682 pic->output_buffer = VA_INVALID_ID;
684 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
685 pic->display_order, pic->encode_order);
689 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
691 av_buffer_unref(&pic->output_buffer_ref);
692 pic->output_buffer = VA_INVALID_ID;
696 static int vaapi_encode_discard(AVCodecContext *avctx,
697 VAAPIEncodePicture *pic)
699 vaapi_encode_wait(avctx, pic);
701 if (pic->output_buffer_ref) {
702 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
703 "%"PRId64"/%"PRId64".\n",
704 pic->display_order, pic->encode_order);
706 av_buffer_unref(&pic->output_buffer_ref);
707 pic->output_buffer = VA_INVALID_ID;
713 static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
715 VAAPIEncodeContext *ctx = avctx->priv_data;
716 VAAPIEncodePicture *pic;
718 pic = av_mallocz(sizeof(*pic));
722 if (ctx->codec->picture_priv_data_size > 0) {
723 pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
724 if (!pic->priv_data) {
730 pic->input_surface = VA_INVALID_ID;
731 pic->recon_surface = VA_INVALID_ID;
732 pic->output_buffer = VA_INVALID_ID;
737 static int vaapi_encode_free(AVCodecContext *avctx,
738 VAAPIEncodePicture *pic)
742 if (pic->encode_issued)
743 vaapi_encode_discard(avctx, pic);
745 for (i = 0; i < pic->nb_slices; i++) {
747 av_freep(&pic->slices[i].priv_data);
748 av_freep(&pic->slices[i].codec_slice_params);
751 av_freep(&pic->codec_picture_params);
753 av_frame_free(&pic->input_image);
754 av_frame_free(&pic->recon_image);
756 av_freep(&pic->param_buffers);
757 av_freep(&pic->slices);
758 // Output buffer should already be destroyed.
759 av_assert0(pic->output_buffer == VA_INVALID_ID);
761 av_freep(&pic->priv_data);
762 av_freep(&pic->codec_picture_params);
770 static void vaapi_encode_add_ref(AVCodecContext *avctx,
771 VAAPIEncodePicture *pic,
772 VAAPIEncodePicture *target,
773 int is_ref, int in_dpb, int prev)
778 av_assert0(pic != target);
779 av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
780 pic->refs[pic->nb_refs++] = target;
785 av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
786 pic->dpb[pic->nb_dpb_pics++] = target;
791 av_assert0(!pic->prev);
796 target->ref_count[0] += refs;
797 target->ref_count[1] += refs;
800 static void vaapi_encode_remove_refs(AVCodecContext *avctx,
801 VAAPIEncodePicture *pic,
806 if (pic->ref_removed[level])
809 for (i = 0; i < pic->nb_refs; i++) {
810 av_assert0(pic->refs[i]);
811 --pic->refs[i]->ref_count[level];
812 av_assert0(pic->refs[i]->ref_count[level] >= 0);
815 for (i = 0; i < pic->nb_dpb_pics; i++) {
816 av_assert0(pic->dpb[i]);
817 --pic->dpb[i]->ref_count[level];
818 av_assert0(pic->dpb[i]->ref_count[level] >= 0);
821 av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
823 --pic->prev->ref_count[level];
824 av_assert0(pic->prev->ref_count[level] >= 0);
827 pic->ref_removed[level] = 1;
830 static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
831 VAAPIEncodePicture *start,
832 VAAPIEncodePicture *end,
833 VAAPIEncodePicture *prev,
835 VAAPIEncodePicture **last)
837 VAAPIEncodeContext *ctx = avctx->priv_data;
838 VAAPIEncodePicture *pic, *next, *ref;
841 av_assert0(start && end && start != end && start->next != end);
843 // If we are at the maximum depth then encode all pictures as
844 // non-referenced B-pictures. Also do this if there is exactly one
845 // picture left, since there will be nothing to reference it.
846 if (current_depth == ctx->max_b_depth || start->next->next == end) {
847 for (pic = start->next; pic; pic = pic->next) {
850 pic->type = PICTURE_TYPE_B;
851 pic->b_depth = current_depth;
853 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
854 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
855 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
857 for (ref = end->refs[1]; ref; ref = ref->refs[1])
858 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
863 // Split the current list at the midpoint with a referenced
864 // B-picture, then descend into each side separately.
866 for (pic = start->next; pic != end; pic = pic->next)
868 for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
870 pic->type = PICTURE_TYPE_B;
871 pic->b_depth = current_depth;
873 pic->is_reference = 1;
875 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
876 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
877 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
878 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
880 for (ref = end->refs[1]; ref; ref = ref->refs[1])
881 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
884 vaapi_encode_set_b_pictures(avctx, start, pic, pic,
885 current_depth + 1, &next);
889 vaapi_encode_set_b_pictures(avctx, pic, end, next,
890 current_depth + 1, last);
894 static int vaapi_encode_pick_next(AVCodecContext *avctx,
895 VAAPIEncodePicture **pic_out)
897 VAAPIEncodeContext *ctx = avctx->priv_data;
898 VAAPIEncodePicture *pic = NULL, *next, *start;
899 int i, b_counter, closed_gop_end;
901 // If there are any B-frames already queued, the next one to encode
902 // is the earliest not-yet-issued frame for which all references are
904 for (pic = ctx->pic_start; pic; pic = pic->next) {
905 if (pic->encode_issued)
907 if (pic->type != PICTURE_TYPE_B)
909 for (i = 0; i < pic->nb_refs; i++) {
910 if (!pic->refs[i]->encode_issued)
913 if (i == pic->nb_refs)
918 av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
919 "encode next.\n", pic->b_depth);
924 // Find the B-per-Pth available picture to become the next picture
928 closed_gop_end = ctx->closed_gop ||
929 ctx->idr_counter == ctx->gop_per_idr;
930 for (pic = ctx->pic_start; pic; pic = next) {
932 if (pic->encode_issued) {
936 // If the next available picture is force-IDR, encode it to start
937 // a new GOP immediately.
940 if (b_counter == ctx->b_per_p)
942 // If this picture ends a closed GOP or starts a new GOP then it
943 // needs to be in the top layer.
944 if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
946 // If the picture after this one is force-IDR, we need to encode
947 // this one in the top layer.
948 if (next && next->force_idr)
953 // At the end of the stream the last picture must be in the top layer.
954 if (!pic && ctx->end_of_stream) {
957 if (pic->encode_issued)
962 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
963 "need more input for reference pictures.\n");
964 return AVERROR(EAGAIN);
966 if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
967 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
968 "need more input for timestamps.\n");
969 return AVERROR(EAGAIN);
972 if (pic->force_idr) {
973 av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
975 pic->type = PICTURE_TYPE_IDR;
976 ctx->idr_counter = 1;
977 ctx->gop_counter = 1;
979 } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
980 if (ctx->idr_counter == ctx->gop_per_idr) {
981 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
983 pic->type = PICTURE_TYPE_IDR;
984 ctx->idr_counter = 1;
986 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
988 pic->type = PICTURE_TYPE_I;
991 ctx->gop_counter = 1;
994 if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
995 av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
998 av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
1001 pic->type = PICTURE_TYPE_P;
1003 ctx->gop_counter += 1 + b_counter;
1005 pic->is_reference = 1;
1008 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
1009 if (pic->type != PICTURE_TYPE_IDR) {
1010 vaapi_encode_add_ref(avctx, pic, start,
1011 pic->type == PICTURE_TYPE_P,
1013 vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
1016 --ctx->next_prev->ref_count[0];
1018 if (b_counter > 0) {
1019 vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
1022 ctx->next_prev = pic;
1024 ++ctx->next_prev->ref_count[0];
1028 static int vaapi_encode_clear_old(AVCodecContext *avctx)
1030 VAAPIEncodeContext *ctx = avctx->priv_data;
1031 VAAPIEncodePicture *pic, *prev, *next;
1033 av_assert0(ctx->pic_start);
1035 // Remove direct references once each picture is complete.
1036 for (pic = ctx->pic_start; pic; pic = pic->next) {
1037 if (pic->encode_complete && pic->next)
1038 vaapi_encode_remove_refs(avctx, pic, 0);
1041 // Remove indirect references once a picture has no direct references.
1042 for (pic = ctx->pic_start; pic; pic = pic->next) {
1043 if (pic->encode_complete && pic->ref_count[0] == 0)
1044 vaapi_encode_remove_refs(avctx, pic, 1);
1047 // Clear out all complete pictures with no remaining references.
1049 for (pic = ctx->pic_start; pic; pic = next) {
1051 if (pic->encode_complete && pic->ref_count[1] == 0) {
1052 av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
1056 ctx->pic_start = next;
1057 vaapi_encode_free(avctx, pic);
1066 static int vaapi_encode_check_frame(AVCodecContext *avctx,
1067 const AVFrame *frame)
1069 VAAPIEncodeContext *ctx = avctx->priv_data;
1071 if ((frame->crop_top || frame->crop_bottom ||
1072 frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
1073 av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
1074 "frames ignored due to lack of API support.\n");
1075 ctx->crop_warned = 1;
1078 if (!ctx->roi_allowed) {
1079 AVFrameSideData *sd =
1080 av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
1082 if (sd && !ctx->roi_warned) {
1083 av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
1084 "frames ignored due to lack of driver support.\n");
1085 ctx->roi_warned = 1;
1092 static int vaapi_encode_send_frame(AVCodecContext *avctx, AVFrame *frame)
1094 VAAPIEncodeContext *ctx = avctx->priv_data;
1095 VAAPIEncodePicture *pic;
1099 av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
1100 frame->width, frame->height, frame->pts);
1102 err = vaapi_encode_check_frame(avctx, frame);
1106 pic = vaapi_encode_alloc(avctx);
1108 return AVERROR(ENOMEM);
1110 pic->input_image = av_frame_alloc();
1111 if (!pic->input_image) {
1112 err = AVERROR(ENOMEM);
1116 if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
1119 pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
1120 pic->pts = frame->pts;
1122 av_frame_move_ref(pic->input_image, frame);
1124 if (ctx->input_order == 0)
1125 ctx->first_pts = pic->pts;
1126 if (ctx->input_order == ctx->decode_delay)
1127 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
1128 if (ctx->output_delay > 0)
1129 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
1131 pic->display_order = ctx->input_order;
1134 if (ctx->pic_start) {
1135 ctx->pic_end->next = pic;
1138 ctx->pic_start = pic;
1143 ctx->end_of_stream = 1;
1145 // Fix timestamps if we hit end-of-stream before the initial decode
1146 // delay has elapsed.
1147 if (ctx->input_order < ctx->decode_delay)
1148 ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
1154 vaapi_encode_free(avctx, pic);
1158 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
1160 VAAPIEncodeContext *ctx = avctx->priv_data;
1161 VAAPIEncodePicture *pic;
1162 AVFrame *frame = ctx->frame;
1165 err = ff_encode_get_frame(avctx, frame);
1166 if (err < 0 && err != AVERROR_EOF)
1169 if (err == AVERROR_EOF)
1172 err = vaapi_encode_send_frame(avctx, frame);
1176 if (!ctx->pic_start) {
1177 if (ctx->end_of_stream)
1180 return AVERROR(EAGAIN);
1184 err = vaapi_encode_pick_next(avctx, &pic);
1189 pic->encode_order = ctx->encode_order++;
1191 err = vaapi_encode_issue(avctx, pic);
1193 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1197 err = vaapi_encode_output(avctx, pic, pkt);
1199 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1203 if (ctx->output_delay == 0) {
1204 pkt->dts = pkt->pts;
1205 } else if (pic->encode_order < ctx->decode_delay) {
1206 if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1207 pkt->dts = INT64_MIN;
1209 pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1211 pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1212 (3 * ctx->output_delay)];
1214 av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1215 pkt->pts, pkt->dts);
1217 ctx->output_order = pic->encode_order;
1218 vaapi_encode_clear_old(avctx);
1224 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
1225 void *buffer, size_t size)
1227 VAAPIEncodeContext *ctx = avctx->priv_data;
1229 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1231 ctx->global_params_type[ctx->nb_global_params] = type;
1232 ctx->global_params [ctx->nb_global_params] = buffer;
1233 ctx->global_params_size[ctx->nb_global_params] = size;
1235 ++ctx->nb_global_params;
1238 typedef struct VAAPIEncodeRTFormat {
1245 } VAAPIEncodeRTFormat;
1247 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1248 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
1249 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
1250 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
1251 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
1252 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
1253 #if VA_CHECK_VERSION(0, 38, 1)
1254 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1258 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1259 VAEntrypointEncSlice,
1260 VAEntrypointEncPicture,
1261 #if VA_CHECK_VERSION(0, 39, 2)
1262 VAEntrypointEncSliceLP,
1266 #if VA_CHECK_VERSION(0, 39, 2)
1267 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1268 VAEntrypointEncSliceLP,
1273 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1275 VAAPIEncodeContext *ctx = avctx->priv_data;
1276 VAProfile *va_profiles = NULL;
1277 VAEntrypoint *va_entrypoints = NULL;
1279 const VAEntrypoint *usable_entrypoints;
1280 const VAAPIEncodeProfile *profile;
1281 const AVPixFmtDescriptor *desc;
1282 VAConfigAttrib rt_format_attr;
1283 const VAAPIEncodeRTFormat *rt_format;
1284 const char *profile_string, *entrypoint_string;
1285 int i, j, n, depth, err;
1288 if (ctx->low_power) {
1289 #if VA_CHECK_VERSION(0, 39, 2)
1290 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1292 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1293 "supported with this VAAPI version.\n");
1294 return AVERROR(EINVAL);
1297 usable_entrypoints = vaapi_encode_entrypoints_normal;
1300 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1302 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1303 ctx->input_frames->sw_format);
1304 return AVERROR(EINVAL);
1306 depth = desc->comp[0].depth;
1307 for (i = 1; i < desc->nb_components; i++) {
1308 if (desc->comp[i].depth != depth) {
1309 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1311 return AVERROR(EINVAL);
1314 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1317 n = vaMaxNumProfiles(ctx->hwctx->display);
1318 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1320 err = AVERROR(ENOMEM);
1323 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1324 if (vas != VA_STATUS_SUCCESS) {
1325 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1326 vas, vaErrorStr(vas));
1327 err = AVERROR_EXTERNAL;
1331 av_assert0(ctx->codec->profiles);
1332 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1333 FF_PROFILE_UNKNOWN); i++) {
1334 profile = &ctx->codec->profiles[i];
1335 if (depth != profile->depth ||
1336 desc->nb_components != profile->nb_components)
1338 if (desc->nb_components > 1 &&
1339 (desc->log2_chroma_w != profile->log2_chroma_w ||
1340 desc->log2_chroma_h != profile->log2_chroma_h))
1342 if (avctx->profile != profile->av_profile &&
1343 avctx->profile != FF_PROFILE_UNKNOWN)
1346 #if VA_CHECK_VERSION(1, 0, 0)
1347 profile_string = vaProfileStr(profile->va_profile);
1349 profile_string = "(no profile names)";
1352 for (j = 0; j < n; j++) {
1353 if (va_profiles[j] == profile->va_profile)
1357 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1358 "is not supported by driver.\n", profile_string,
1359 profile->va_profile);
1363 ctx->profile = profile;
1366 if (!ctx->profile) {
1367 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1368 err = AVERROR(ENOSYS);
1372 avctx->profile = profile->av_profile;
1373 ctx->va_profile = profile->va_profile;
1374 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1375 profile_string, ctx->va_profile);
1377 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1378 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1379 if (!va_entrypoints) {
1380 err = AVERROR(ENOMEM);
1383 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1384 va_entrypoints, &n);
1385 if (vas != VA_STATUS_SUCCESS) {
1386 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1387 "profile %s (%d): %d (%s).\n", profile_string,
1388 ctx->va_profile, vas, vaErrorStr(vas));
1389 err = AVERROR_EXTERNAL;
1393 for (i = 0; i < n; i++) {
1394 for (j = 0; usable_entrypoints[j]; j++) {
1395 if (va_entrypoints[i] == usable_entrypoints[j])
1398 if (usable_entrypoints[j])
1402 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1403 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1404 err = AVERROR(ENOSYS);
1408 ctx->va_entrypoint = va_entrypoints[i];
1409 #if VA_CHECK_VERSION(1, 0, 0)
1410 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1412 entrypoint_string = "(no entrypoint names)";
1414 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1415 entrypoint_string, ctx->va_entrypoint);
1417 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1418 rt_format = &vaapi_encode_rt_formats[i];
1419 if (rt_format->depth == depth &&
1420 rt_format->nb_components == profile->nb_components &&
1421 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1422 rt_format->log2_chroma_h == profile->log2_chroma_h)
1425 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1426 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1427 "found for profile %s (%d) entrypoint %s (%d).\n",
1428 profile_string, ctx->va_profile,
1429 entrypoint_string, ctx->va_entrypoint);
1430 err = AVERROR(ENOSYS);
1434 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1435 vas = vaGetConfigAttributes(ctx->hwctx->display,
1436 ctx->va_profile, ctx->va_entrypoint,
1437 &rt_format_attr, 1);
1438 if (vas != VA_STATUS_SUCCESS) {
1439 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1440 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1441 err = AVERROR_EXTERNAL;
1445 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1446 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1447 "supported by driver: assuming surface RT format %s "
1448 "is valid.\n", rt_format->name);
1449 } else if (!(rt_format_attr.value & rt_format->value)) {
1450 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1451 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1452 rt_format->name, profile_string, ctx->va_profile,
1453 entrypoint_string, ctx->va_entrypoint);
1454 err = AVERROR(ENOSYS);
1457 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1458 "format %s (%#x).\n", rt_format->name, rt_format->value);
1459 ctx->config_attributes[ctx->nb_config_attributes++] =
1461 .type = VAConfigAttribRTFormat,
1462 .value = rt_format->value,
1468 av_freep(&va_profiles);
1469 av_freep(&va_entrypoints);
1473 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1475 // | Maxrate | HRD/VBV
1477 { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
1478 { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
1479 { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
1480 #if VA_CHECK_VERSION(1, 1, 0)
1481 { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
1483 { RC_MODE_ICQ, "ICQ", 0 },
1485 #if VA_CHECK_VERSION(1, 3, 0)
1486 { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
1487 { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
1489 { RC_MODE_QVBR, "QVBR", 0 },
1490 { RC_MODE_AVBR, "AVBR", 0 },
1494 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1496 VAAPIEncodeContext *ctx = avctx->priv_data;
1497 uint32_t supported_va_rc_modes;
1498 const VAAPIEncodeRCMode *rc_mode;
1499 int64_t rc_bits_per_second;
1500 int rc_target_percentage;
1503 int64_t hrd_buffer_size;
1504 int64_t hrd_initial_buffer_fullness;
1506 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1508 char supported_rc_modes_string[64];
1510 vas = vaGetConfigAttributes(ctx->hwctx->display,
1511 ctx->va_profile, ctx->va_entrypoint,
1513 if (vas != VA_STATUS_SUCCESS) {
1514 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1515 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1516 return AVERROR_EXTERNAL;
1518 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1519 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1520 "supported rate control modes: assuming CQP only.\n");
1521 supported_va_rc_modes = VA_RC_CQP;
1522 strcpy(supported_rc_modes_string, "unknown");
1524 char *str = supported_rc_modes_string;
1525 size_t len = sizeof(supported_rc_modes_string);
1526 int i, first = 1, res;
1528 supported_va_rc_modes = rc_attr.value;
1529 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1530 rc_mode = &vaapi_encode_rc_modes[i];
1531 if (supported_va_rc_modes & rc_mode->va_mode) {
1532 res = snprintf(str, len, "%s%s",
1533 first ? "" : ", ", rc_mode->name);
1546 av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1547 supported_rc_modes_string);
1550 // Rate control mode selection:
1551 // * If the user has set a mode explicitly with the rc_mode option,
1552 // use it and fail if it is not available.
1553 // * If an explicit QP option has been set, use CQP.
1554 // * If the codec is CQ-only, use CQP.
1555 // * If the QSCALE avcodec option is set, use CQP.
1556 // * If bitrate and quality are both set, try QVBR.
1557 // * If quality is set, try ICQ, then CQP.
1558 // * If bitrate and maxrate are set and have the same value, try CBR.
1559 // * If a bitrate is set, try AVBR, then VBR, then CBR.
1560 // * If no bitrate is set, try ICQ, then CQP.
1562 #define TRY_RC_MODE(mode, fail) do { \
1563 rc_mode = &vaapi_encode_rc_modes[mode]; \
1564 if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1566 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1567 "RC mode (supported modes: %s).\n", rc_mode->name, \
1568 supported_rc_modes_string); \
1569 return AVERROR(EINVAL); \
1571 av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1572 "RC mode.\n", rc_mode->name); \
1575 goto rc_mode_found; \
1579 if (ctx->explicit_rc_mode)
1580 TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1582 if (ctx->explicit_qp)
1583 TRY_RC_MODE(RC_MODE_CQP, 1);
1585 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1586 TRY_RC_MODE(RC_MODE_CQP, 1);
1588 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1589 TRY_RC_MODE(RC_MODE_CQP, 1);
1591 if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1592 TRY_RC_MODE(RC_MODE_QVBR, 0);
1594 if (avctx->global_quality > 0) {
1595 TRY_RC_MODE(RC_MODE_ICQ, 0);
1596 TRY_RC_MODE(RC_MODE_CQP, 0);
1599 if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1600 TRY_RC_MODE(RC_MODE_CBR, 0);
1602 if (avctx->bit_rate > 0) {
1603 TRY_RC_MODE(RC_MODE_AVBR, 0);
1604 TRY_RC_MODE(RC_MODE_VBR, 0);
1605 TRY_RC_MODE(RC_MODE_CBR, 0);
1607 TRY_RC_MODE(RC_MODE_ICQ, 0);
1608 TRY_RC_MODE(RC_MODE_CQP, 0);
1611 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1612 "RC mode compatible with selected options "
1613 "(supported modes: %s).\n", supported_rc_modes_string);
1614 return AVERROR(EINVAL);
1617 if (rc_mode->bitrate) {
1618 if (avctx->bit_rate <= 0) {
1619 av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1620 "RC mode.\n", rc_mode->name);
1621 return AVERROR(EINVAL);
1624 if (rc_mode->mode == RC_MODE_AVBR) {
1625 // For maximum confusion AVBR is hacked into the existing API
1626 // by overloading some of the fields with completely different
1629 // Target percentage does not apply in AVBR mode.
1630 rc_bits_per_second = avctx->bit_rate;
1632 // Accuracy tolerance range for meeting the specified target
1633 // bitrate. It's very unclear how this is actually intended
1634 // to work - since we do want to get the specified bitrate,
1635 // set the accuracy to 100% for now.
1636 rc_target_percentage = 100;
1638 // Convergence period in frames. The GOP size reflects the
1639 // user's intended block size for cutting, so reusing that
1640 // as the convergence period seems a reasonable default.
1641 rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1643 } else if (rc_mode->maxrate) {
1644 if (avctx->rc_max_rate > 0) {
1645 if (avctx->rc_max_rate < avctx->bit_rate) {
1646 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1647 "bitrate (%"PRId64") must not be greater than "
1648 "maxrate (%"PRId64").\n", avctx->bit_rate,
1649 avctx->rc_max_rate);
1650 return AVERROR(EINVAL);
1652 rc_bits_per_second = avctx->rc_max_rate;
1653 rc_target_percentage = (avctx->bit_rate * 100) /
1656 // We only have a target bitrate, but this mode requires
1657 // that a maximum rate be supplied as well. Since the
1658 // user does not want this to be a constraint, arbitrarily
1659 // pick a maximum rate of double the target rate.
1660 rc_bits_per_second = 2 * avctx->bit_rate;
1661 rc_target_percentage = 50;
1664 if (avctx->rc_max_rate > avctx->bit_rate) {
1665 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1666 "in %s RC mode.\n", rc_mode->name);
1668 rc_bits_per_second = avctx->bit_rate;
1669 rc_target_percentage = 100;
1672 rc_bits_per_second = 0;
1673 rc_target_percentage = 100;
1676 if (rc_mode->quality) {
1677 if (ctx->explicit_qp) {
1678 rc_quality = ctx->explicit_qp;
1679 } else if (avctx->global_quality > 0) {
1680 rc_quality = avctx->global_quality;
1682 rc_quality = ctx->codec->default_quality;
1683 av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1684 "using default (%d).\n", rc_quality);
1691 if (avctx->rc_buffer_size)
1692 hrd_buffer_size = avctx->rc_buffer_size;
1693 else if (avctx->rc_max_rate > 0)
1694 hrd_buffer_size = avctx->rc_max_rate;
1696 hrd_buffer_size = avctx->bit_rate;
1697 if (avctx->rc_initial_buffer_occupancy) {
1698 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1699 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1700 "must have initial buffer size (%d) <= "
1701 "buffer size (%"PRId64").\n",
1702 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1703 return AVERROR(EINVAL);
1705 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1707 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1710 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1712 if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1713 av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1714 "in %s RC mode.\n", rc_mode->name);
1717 hrd_buffer_size = 0;
1718 hrd_initial_buffer_fullness = 0;
1720 if (rc_mode->mode != RC_MODE_AVBR) {
1721 // Already set (with completely different meaning) for AVBR.
1722 rc_window_size = 1000;
1726 if (rc_bits_per_second > UINT32_MAX ||
1727 hrd_buffer_size > UINT32_MAX ||
1728 hrd_initial_buffer_fullness > UINT32_MAX) {
1729 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1730 "greater are not supported by VAAPI.\n");
1731 return AVERROR(EINVAL);
1734 ctx->rc_mode = rc_mode;
1735 ctx->rc_quality = rc_quality;
1736 ctx->va_rc_mode = rc_mode->va_mode;
1737 ctx->va_bit_rate = rc_bits_per_second;
1739 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1740 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1741 // This driver does not want the RC mode attribute to be set.
1743 ctx->config_attributes[ctx->nb_config_attributes++] =
1745 .type = VAConfigAttribRateControl,
1746 .value = ctx->va_rc_mode,
1750 if (rc_mode->quality)
1751 av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1753 if (rc_mode->va_mode != VA_RC_CQP) {
1754 if (rc_mode->mode == RC_MODE_AVBR) {
1755 av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1756 "converging in %d frames with %d%% accuracy.\n",
1757 rc_bits_per_second, rc_window_size,
1758 rc_target_percentage);
1759 } else if (rc_mode->bitrate) {
1760 av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1761 "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1762 rc_bits_per_second, rc_window_size);
1765 ctx->rc_params = (VAEncMiscParameterRateControl) {
1766 .bits_per_second = rc_bits_per_second,
1767 .target_percentage = rc_target_percentage,
1768 .window_size = rc_window_size,
1770 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1771 .basic_unit_size = 0,
1772 #if VA_CHECK_VERSION(1, 1, 0)
1773 .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1774 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1776 #if VA_CHECK_VERSION(1, 3, 0)
1777 .quality_factor = rc_quality,
1780 vaapi_encode_add_global_param(avctx,
1781 VAEncMiscParameterTypeRateControl,
1783 sizeof(ctx->rc_params));
1787 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1788 "initial fullness %"PRId64" bits.\n",
1789 hrd_buffer_size, hrd_initial_buffer_fullness);
1791 ctx->hrd_params = (VAEncMiscParameterHRD) {
1792 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1793 .buffer_size = hrd_buffer_size,
1795 vaapi_encode_add_global_param(avctx,
1796 VAEncMiscParameterTypeHRD,
1798 sizeof(ctx->hrd_params));
1801 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1802 av_reduce(&fr_num, &fr_den,
1803 avctx->framerate.num, avctx->framerate.den, 65535);
1805 av_reduce(&fr_num, &fr_den,
1806 avctx->time_base.den, avctx->time_base.num, 65535);
1808 av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1809 fr_num, fr_den, (double)fr_num / fr_den);
1811 ctx->fr_params = (VAEncMiscParameterFrameRate) {
1812 .framerate = (unsigned int)fr_den << 16 | fr_num,
1814 #if VA_CHECK_VERSION(0, 40, 0)
1815 vaapi_encode_add_global_param(avctx,
1816 VAEncMiscParameterTypeFrameRate,
1818 sizeof(ctx->fr_params));
1824 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1826 VAAPIEncodeContext *ctx = avctx->priv_data;
1828 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1829 uint32_t ref_l0, ref_l1;
1831 vas = vaGetConfigAttributes(ctx->hwctx->display,
1835 if (vas != VA_STATUS_SUCCESS) {
1836 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1837 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1838 return AVERROR_EXTERNAL;
1841 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1842 ref_l0 = ref_l1 = 0;
1844 ref_l0 = attr.value & 0xffff;
1845 ref_l1 = attr.value >> 16 & 0xffff;
1848 if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1849 avctx->gop_size <= 1) {
1850 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1852 } else if (ref_l0 < 1) {
1853 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1854 "reference frames.\n");
1855 return AVERROR(EINVAL);
1856 } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1857 ref_l1 < 1 || avctx->max_b_frames < 1) {
1858 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1859 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1860 ctx->gop_size = avctx->gop_size;
1861 ctx->p_per_i = INT_MAX;
1864 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1865 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1866 ctx->gop_size = avctx->gop_size;
1867 ctx->p_per_i = INT_MAX;
1868 ctx->b_per_p = avctx->max_b_frames;
1869 if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1870 ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1871 av_log2(ctx->b_per_p) + 1);
1873 ctx->max_b_depth = 1;
1877 if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1878 ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1879 ctx->gop_per_idr = ctx->idr_interval + 1;
1881 ctx->closed_gop = 1;
1882 ctx->gop_per_idr = 1;
1888 static av_cold int vaapi_encode_init_row_slice_structure(AVCodecContext *avctx,
1889 uint32_t slice_structure)
1891 VAAPIEncodeContext *ctx = avctx->priv_data;
1894 // For fixed-size slices currently we only support whole rows, making
1895 // rectangular slices. This could be extended to arbitrary runs of
1896 // blocks, but since slices tend to be a conformance requirement and
1897 // most cases (such as broadcast or bluray) want rectangular slices
1898 // only it would need to be gated behind another option.
1899 if (avctx->slices > ctx->slice_block_rows) {
1900 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1901 "configured number of slices (%d < %d); using "
1902 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1903 req_slices = ctx->slice_block_rows;
1905 req_slices = avctx->slices;
1907 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1908 #if VA_CHECK_VERSION(1, 8, 0)
1909 slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_MULTI_ROWS ||
1911 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1912 ctx->nb_slices = req_slices;
1913 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1914 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1916 for (k = 1;; k *= 2) {
1917 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1920 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1921 ctx->slice_size = k;
1922 #if VA_CHECK_VERSION(1, 0, 0)
1923 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1924 ctx->nb_slices = ctx->slice_block_rows;
1925 ctx->slice_size = 1;
1928 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1929 "slice structure modes (%#x).\n", slice_structure);
1930 return AVERROR(EINVAL);
1936 static av_cold int vaapi_encode_init_tile_slice_structure(AVCodecContext *avctx,
1937 uint32_t slice_structure)
1939 VAAPIEncodeContext *ctx = avctx->priv_data;
1942 if (!(slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS ||
1943 (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS &&
1944 ctx->tile_cols == 1))) {
1945 av_log(avctx, AV_LOG_ERROR, "Supported slice structure (%#x) doesn't work for "
1946 "current tile requirement.\n", slice_structure);
1947 return AVERROR(EINVAL);
1950 if (ctx->tile_rows > ctx->slice_block_rows ||
1951 ctx->tile_cols > ctx->slice_block_cols) {
1952 av_log(avctx, AV_LOG_WARNING, "Not enough block rows/cols (%d x %d) "
1953 "for configured number of tile (%d x %d); ",
1954 ctx->slice_block_rows, ctx->slice_block_cols,
1955 ctx->tile_rows, ctx->tile_cols);
1956 ctx->tile_rows = ctx->tile_rows > ctx->slice_block_rows ?
1957 ctx->slice_block_rows : ctx->tile_rows;
1958 ctx->tile_cols = ctx->tile_cols > ctx->slice_block_cols ?
1959 ctx->slice_block_cols : ctx->tile_cols;
1960 av_log(avctx, AV_LOG_WARNING, "using allowed maximum (%d x %d).\n",
1961 ctx->tile_rows, ctx->tile_cols);
1964 req_tiles = ctx->tile_rows * ctx->tile_cols;
1966 // Tile slice is not allowed to cross the boundary of a tile due to
1967 // the constraints of media-driver. Currently we support one slice
1968 // per tile. This could be extended to multiple slices per tile.
1969 if (avctx->slices != req_tiles)
1970 av_log(avctx, AV_LOG_WARNING, "The number of requested slices "
1971 "mismatches with configured number of tile (%d != %d); "
1972 "using requested tile number for slice.\n",
1973 avctx->slices, req_tiles);
1975 ctx->nb_slices = req_tiles;
1977 // Default in uniform spacing
1979 for (i = 0; i < ctx->tile_cols; i++) {
1980 ctx->col_width[i] = ( i + 1 ) * ctx->slice_block_cols / ctx->tile_cols -
1981 i * ctx->slice_block_cols / ctx->tile_cols;
1982 ctx->col_bd[i + 1] = ctx->col_bd[i] + ctx->col_width[i];
1985 for (i = 0; i < ctx->tile_rows; i++) {
1986 ctx->row_height[i] = ( i + 1 ) * ctx->slice_block_rows / ctx->tile_rows -
1987 i * ctx->slice_block_rows / ctx->tile_rows;
1988 ctx->row_bd[i + 1] = ctx->row_bd[i] + ctx->row_height[i];
1991 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d x %d tile.\n",
1992 ctx->tile_rows, ctx->tile_cols);
1997 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1999 VAAPIEncodeContext *ctx = avctx->priv_data;
2000 VAConfigAttrib attr[3] = { { VAConfigAttribEncMaxSlices },
2001 { VAConfigAttribEncSliceStructure },
2002 #if VA_CHECK_VERSION(1, 1, 0)
2003 { VAConfigAttribEncTileSupport },
2007 uint32_t max_slices, slice_structure;
2010 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
2011 if (avctx->slices > 0) {
2012 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
2013 "but this codec does not support controlling slices.\n");
2018 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
2019 ctx->slice_block_height;
2020 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
2021 ctx->slice_block_width;
2023 if (avctx->slices <= 1 && !ctx->tile_rows && !ctx->tile_cols) {
2025 ctx->slice_size = ctx->slice_block_rows;
2029 vas = vaGetConfigAttributes(ctx->hwctx->display,
2032 attr, FF_ARRAY_ELEMS(attr));
2033 if (vas != VA_STATUS_SUCCESS) {
2034 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
2035 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
2036 return AVERROR_EXTERNAL;
2038 max_slices = attr[0].value;
2039 slice_structure = attr[1].value;
2040 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
2041 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
2042 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
2043 "pictures as multiple slices.\n.");
2044 return AVERROR(EINVAL);
2047 if (ctx->tile_rows && ctx->tile_cols) {
2048 #if VA_CHECK_VERSION(1, 1, 0)
2049 uint32_t tile_support = attr[2].value;
2050 if (tile_support == VA_ATTRIB_NOT_SUPPORTED) {
2051 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
2052 "pictures as multiple tiles.\n.");
2053 return AVERROR(EINVAL);
2056 av_log(avctx, AV_LOG_ERROR, "Tile encoding option is "
2057 "not supported with this VAAPI version.\n");
2058 return AVERROR(EINVAL);
2062 if (ctx->tile_rows && ctx->tile_cols)
2063 ret = vaapi_encode_init_tile_slice_structure(avctx, slice_structure);
2065 ret = vaapi_encode_init_row_slice_structure(avctx, slice_structure);
2069 if (ctx->nb_slices > avctx->slices) {
2070 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
2071 "%d (from %d) due to driver constraints on slice "
2072 "structure.\n", ctx->nb_slices, avctx->slices);
2074 if (ctx->nb_slices > max_slices) {
2075 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
2076 "encoding with %d slices (max %"PRIu32").\n",
2077 ctx->nb_slices, max_slices);
2078 return AVERROR(EINVAL);
2081 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices.\n",
2086 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
2088 VAAPIEncodeContext *ctx = avctx->priv_data;
2090 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
2092 vas = vaGetConfigAttributes(ctx->hwctx->display,
2096 if (vas != VA_STATUS_SUCCESS) {
2097 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
2098 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
2099 return AVERROR_EXTERNAL;
2102 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2103 if (ctx->desired_packed_headers) {
2104 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
2105 "packed headers (wanted %#x).\n",
2106 ctx->desired_packed_headers);
2108 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
2109 "packed headers (none wanted).\n");
2111 ctx->va_packed_headers = 0;
2113 if (ctx->desired_packed_headers & ~attr.value) {
2114 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
2115 "wanted packed headers (wanted %#x, found %#x).\n",
2116 ctx->desired_packed_headers, attr.value);
2118 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
2119 "available (wanted %#x, found %#x).\n",
2120 ctx->desired_packed_headers, attr.value);
2122 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
2125 if (ctx->va_packed_headers) {
2126 ctx->config_attributes[ctx->nb_config_attributes++] =
2128 .type = VAConfigAttribEncPackedHeaders,
2129 .value = ctx->va_packed_headers,
2133 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
2134 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
2135 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
2136 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
2137 "sequence headers, but a global header is requested.\n");
2138 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
2139 "this may result in a stream which is not usable for some "
2140 "purposes (e.g. not muxable to some containers).\n");
2146 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
2148 #if VA_CHECK_VERSION(0, 36, 0)
2149 VAAPIEncodeContext *ctx = avctx->priv_data;
2151 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
2152 int quality = avctx->compression_level;
2154 vas = vaGetConfigAttributes(ctx->hwctx->display,
2158 if (vas != VA_STATUS_SUCCESS) {
2159 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
2160 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2161 return AVERROR_EXTERNAL;
2164 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2166 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
2167 "supported: will use default quality level.\n");
2170 if (quality > attr.value) {
2171 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
2172 "valid range is 0-%d, using %d.\n",
2173 attr.value, attr.value);
2174 quality = attr.value;
2177 ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
2178 .quality_level = quality,
2180 vaapi_encode_add_global_param(avctx,
2181 VAEncMiscParameterTypeQualityLevel,
2182 &ctx->quality_params,
2183 sizeof(ctx->quality_params));
2186 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
2187 "not supported with this VAAPI version.\n");
2193 static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
2195 #if VA_CHECK_VERSION(1, 0, 0)
2196 VAAPIEncodeContext *ctx = avctx->priv_data;
2198 VAConfigAttrib attr = { VAConfigAttribEncROI };
2200 vas = vaGetConfigAttributes(ctx->hwctx->display,
2204 if (vas != VA_STATUS_SUCCESS) {
2205 av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
2206 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2207 return AVERROR_EXTERNAL;
2210 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2211 ctx->roi_allowed = 0;
2213 VAConfigAttribValEncROI roi = {
2214 .value = attr.value,
2217 ctx->roi_max_regions = roi.bits.num_roi_regions;
2218 ctx->roi_allowed = ctx->roi_max_regions > 0 &&
2219 (ctx->va_rc_mode == VA_RC_CQP ||
2220 roi.bits.roi_rc_qp_delta_support);
2226 static void vaapi_encode_free_output_buffer(void *opaque,
2229 AVCodecContext *avctx = opaque;
2230 VAAPIEncodeContext *ctx = avctx->priv_data;
2231 VABufferID buffer_id;
2233 buffer_id = (VABufferID)(uintptr_t)data;
2235 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2237 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
2240 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
2243 AVCodecContext *avctx = opaque;
2244 VAAPIEncodeContext *ctx = avctx->priv_data;
2245 VABufferID buffer_id;
2249 // The output buffer size is fixed, so it needs to be large enough
2250 // to hold the largest possible compressed frame. We assume here
2251 // that the uncompressed frame plus some header data is an upper
2253 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
2254 VAEncCodedBufferType,
2255 3 * ctx->surface_width * ctx->surface_height +
2256 (1 << 16), 1, 0, &buffer_id);
2257 if (vas != VA_STATUS_SUCCESS) {
2258 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
2259 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
2263 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
2265 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
2267 &vaapi_encode_free_output_buffer,
2268 avctx, AV_BUFFER_FLAG_READONLY);
2270 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2277 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
2279 VAAPIEncodeContext *ctx = avctx->priv_data;
2280 AVVAAPIHWConfig *hwconfig = NULL;
2281 AVHWFramesConstraints *constraints = NULL;
2282 enum AVPixelFormat recon_format;
2285 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
2287 err = AVERROR(ENOMEM);
2290 hwconfig->config_id = ctx->va_config;
2292 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
2295 err = AVERROR(ENOMEM);
2299 // Probably we can use the input surface format as the surface format
2300 // of the reconstructed frames. If not, we just pick the first (only?)
2301 // format in the valid list and hope that it all works.
2302 recon_format = AV_PIX_FMT_NONE;
2303 if (constraints->valid_sw_formats) {
2304 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
2305 if (ctx->input_frames->sw_format ==
2306 constraints->valid_sw_formats[i]) {
2307 recon_format = ctx->input_frames->sw_format;
2311 if (recon_format == AV_PIX_FMT_NONE) {
2312 // No match. Just use the first in the supported list and
2313 // hope for the best.
2314 recon_format = constraints->valid_sw_formats[0];
2317 // No idea what to use; copy input format.
2318 recon_format = ctx->input_frames->sw_format;
2320 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
2321 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
2323 if (ctx->surface_width < constraints->min_width ||
2324 ctx->surface_height < constraints->min_height ||
2325 ctx->surface_width > constraints->max_width ||
2326 ctx->surface_height > constraints->max_height) {
2327 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2328 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2329 ctx->surface_width, ctx->surface_height,
2330 constraints->min_width, constraints->max_width,
2331 constraints->min_height, constraints->max_height);
2332 err = AVERROR(EINVAL);
2336 av_freep(&hwconfig);
2337 av_hwframe_constraints_free(&constraints);
2339 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2340 if (!ctx->recon_frames_ref) {
2341 err = AVERROR(ENOMEM);
2344 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2346 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
2347 ctx->recon_frames->sw_format = recon_format;
2348 ctx->recon_frames->width = ctx->surface_width;
2349 ctx->recon_frames->height = ctx->surface_height;
2351 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2353 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2354 "frame context: %d.\n", err);
2360 av_freep(&hwconfig);
2361 av_hwframe_constraints_free(&constraints);
2365 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2367 VAAPIEncodeContext *ctx = avctx->priv_data;
2368 AVVAAPIFramesContext *recon_hwctx = NULL;
2372 ctx->frame = av_frame_alloc();
2374 return AVERROR(ENOMEM);
2377 if (!avctx->hw_frames_ctx) {
2378 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2379 "required to associate the encoding device.\n");
2380 return AVERROR(EINVAL);
2383 ctx->va_config = VA_INVALID_ID;
2384 ctx->va_context = VA_INVALID_ID;
2386 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2387 if (!ctx->input_frames_ref) {
2388 err = AVERROR(ENOMEM);
2391 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2393 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2394 if (!ctx->device_ref) {
2395 err = AVERROR(ENOMEM);
2398 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2399 ctx->hwctx = ctx->device->hwctx;
2401 err = vaapi_encode_profile_entrypoint(avctx);
2405 err = vaapi_encode_init_rate_control(avctx);
2409 err = vaapi_encode_init_gop_structure(avctx);
2413 err = vaapi_encode_init_slice_structure(avctx);
2417 err = vaapi_encode_init_packed_headers(avctx);
2421 err = vaapi_encode_init_roi(avctx);
2425 if (avctx->compression_level >= 0) {
2426 err = vaapi_encode_init_quality(avctx);
2431 vas = vaCreateConfig(ctx->hwctx->display,
2432 ctx->va_profile, ctx->va_entrypoint,
2433 ctx->config_attributes, ctx->nb_config_attributes,
2435 if (vas != VA_STATUS_SUCCESS) {
2436 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2437 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2442 err = vaapi_encode_create_recon_frames(avctx);
2446 recon_hwctx = ctx->recon_frames->hwctx;
2447 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2448 ctx->surface_width, ctx->surface_height,
2450 recon_hwctx->surface_ids,
2451 recon_hwctx->nb_surfaces,
2453 if (vas != VA_STATUS_SUCCESS) {
2454 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2455 "context: %d (%s).\n", vas, vaErrorStr(vas));
2460 ctx->output_buffer_pool =
2461 av_buffer_pool_init2(sizeof(VABufferID), avctx,
2462 &vaapi_encode_alloc_output_buffer, NULL);
2463 if (!ctx->output_buffer_pool) {
2464 err = AVERROR(ENOMEM);
2468 if (ctx->codec->configure) {
2469 err = ctx->codec->configure(avctx);
2474 ctx->output_delay = ctx->b_per_p;
2475 ctx->decode_delay = ctx->max_b_depth;
2477 if (ctx->codec->sequence_params_size > 0) {
2478 ctx->codec_sequence_params =
2479 av_mallocz(ctx->codec->sequence_params_size);
2480 if (!ctx->codec_sequence_params) {
2481 err = AVERROR(ENOMEM);
2485 if (ctx->codec->picture_params_size > 0) {
2486 ctx->codec_picture_params =
2487 av_mallocz(ctx->codec->picture_params_size);
2488 if (!ctx->codec_picture_params) {
2489 err = AVERROR(ENOMEM);
2494 if (ctx->codec->init_sequence_params) {
2495 err = ctx->codec->init_sequence_params(avctx);
2497 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2498 "failed: %d.\n", err);
2503 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2504 ctx->codec->write_sequence_header &&
2505 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2506 char data[MAX_PARAM_BUFFER_SIZE];
2507 size_t bit_len = 8 * sizeof(data);
2509 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2511 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2512 "for extradata: %d.\n", err);
2515 avctx->extradata_size = (bit_len + 7) / 8;
2516 avctx->extradata = av_mallocz(avctx->extradata_size +
2517 AV_INPUT_BUFFER_PADDING_SIZE);
2518 if (!avctx->extradata) {
2519 err = AVERROR(ENOMEM);
2522 memcpy(avctx->extradata, data, avctx->extradata_size);
2532 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2534 VAAPIEncodeContext *ctx = avctx->priv_data;
2535 VAAPIEncodePicture *pic, *next;
2537 for (pic = ctx->pic_start; pic; pic = next) {
2539 vaapi_encode_free(avctx, pic);
2542 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2544 if (ctx->va_context != VA_INVALID_ID) {
2545 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2546 ctx->va_context = VA_INVALID_ID;
2549 if (ctx->va_config != VA_INVALID_ID) {
2550 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2551 ctx->va_config = VA_INVALID_ID;
2554 av_frame_free(&ctx->frame);
2556 av_freep(&ctx->codec_sequence_params);
2557 av_freep(&ctx->codec_picture_params);
2559 av_buffer_unref(&ctx->recon_frames_ref);
2560 av_buffer_unref(&ctx->input_frames_ref);
2561 av_buffer_unref(&ctx->device_ref);