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"
30 static const char * const picture_type_name[] = { "IDR", "I", "P", "B" };
32 static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
33 VAAPIEncodePicture *pic,
34 int type, char *data, size_t bit_len)
36 VAAPIEncodeContext *ctx = avctx->priv_data;
38 VABufferID param_buffer, data_buffer;
40 VAEncPackedHeaderParameterBuffer params = {
42 .bit_length = bit_len,
43 .has_emulation_bytes = 1,
46 tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 2);
48 return AVERROR(ENOMEM);
49 pic->param_buffers = tmp;
51 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
52 VAEncPackedHeaderParameterBufferType,
53 sizeof(params), 1, ¶ms, ¶m_buffer);
54 if (vas != VA_STATUS_SUCCESS) {
55 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
56 "for packed header (type %d): %d (%s).\n",
57 type, vas, vaErrorStr(vas));
60 pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
62 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
63 VAEncPackedHeaderDataBufferType,
64 (bit_len + 7) / 8, 1, data, &data_buffer);
65 if (vas != VA_STATUS_SUCCESS) {
66 av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
67 "for packed header (type %d): %d (%s).\n",
68 type, vas, vaErrorStr(vas));
71 pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
73 av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
74 "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
78 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
79 VAAPIEncodePicture *pic,
80 int type, char *data, size_t len)
82 VAAPIEncodeContext *ctx = avctx->priv_data;
87 tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 1);
89 return AVERROR(ENOMEM);
90 pic->param_buffers = tmp;
92 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
93 type, len, 1, data, &buffer);
94 if (vas != VA_STATUS_SUCCESS) {
95 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
96 "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
99 pic->param_buffers[pic->nb_param_buffers++] = buffer;
101 av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
106 static int vaapi_encode_make_misc_param_buffer(AVCodecContext *avctx,
107 VAAPIEncodePicture *pic,
109 const void *data, size_t len)
111 // Construct the buffer on the stack - 1KB is much larger than any
112 // current misc parameter buffer type (the largest is EncQuality at
114 uint8_t buffer[1024];
115 VAEncMiscParameterBuffer header = {
118 size_t buffer_size = sizeof(header) + len;
119 av_assert0(buffer_size <= sizeof(buffer));
121 memcpy(buffer, &header, sizeof(header));
122 memcpy(buffer + sizeof(header), data, len);
124 return vaapi_encode_make_param_buffer(avctx, pic,
125 VAEncMiscParameterBufferType,
126 buffer, buffer_size);
129 static int vaapi_encode_wait(AVCodecContext *avctx,
130 VAAPIEncodePicture *pic)
132 VAAPIEncodeContext *ctx = avctx->priv_data;
135 av_assert0(pic->encode_issued);
137 if (pic->encode_complete) {
138 // Already waited for this picture.
142 av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
143 "(input surface %#x).\n", pic->display_order,
144 pic->encode_order, pic->input_surface);
146 vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
147 if (vas != VA_STATUS_SUCCESS) {
148 av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
149 "%d (%s).\n", vas, vaErrorStr(vas));
153 // Input is definitely finished with now.
154 av_frame_free(&pic->input_image);
156 pic->encode_complete = 1;
160 static int vaapi_encode_issue(AVCodecContext *avctx,
161 VAAPIEncodePicture *pic)
163 VAAPIEncodeContext *ctx = avctx->priv_data;
164 VAAPIEncodeSlice *slice;
167 char data[MAX_PARAM_BUFFER_SIZE];
169 av_unused AVFrameSideData *sd;
171 av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
172 "as type %s.\n", pic->display_order, pic->encode_order,
173 picture_type_name[pic->type]);
174 if (pic->nb_refs == 0) {
175 av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
177 av_log(avctx, AV_LOG_DEBUG, "Refers to:");
178 for (i = 0; i < pic->nb_refs; i++) {
179 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
180 pic->refs[i]->display_order, pic->refs[i]->encode_order);
182 av_log(avctx, AV_LOG_DEBUG, ".\n");
185 av_assert0(!pic->encode_issued);
186 for (i = 0; i < pic->nb_refs; i++) {
187 av_assert0(pic->refs[i]);
188 av_assert0(pic->refs[i]->encode_issued);
191 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
193 pic->recon_image = av_frame_alloc();
194 if (!pic->recon_image) {
195 err = AVERROR(ENOMEM);
199 err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
201 err = AVERROR(ENOMEM);
204 pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
205 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
207 pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
208 if (!pic->output_buffer_ref) {
209 err = AVERROR(ENOMEM);
212 pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
213 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
216 if (ctx->codec->picture_params_size > 0) {
217 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
218 if (!pic->codec_picture_params)
220 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
221 ctx->codec->picture_params_size);
223 av_assert0(!ctx->codec_picture_params);
226 pic->nb_param_buffers = 0;
228 if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
229 err = vaapi_encode_make_param_buffer(avctx, pic,
230 VAEncSequenceParameterBufferType,
231 ctx->codec_sequence_params,
232 ctx->codec->sequence_params_size);
237 if (pic->type == PICTURE_TYPE_IDR) {
238 for (i = 0; i < ctx->nb_global_params; i++) {
239 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
240 ctx->global_params_type[i],
241 ctx->global_params[i],
242 ctx->global_params_size[i]);
248 if (ctx->codec->init_picture_params) {
249 err = ctx->codec->init_picture_params(avctx, pic);
251 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
252 "parameters: %d.\n", err);
255 err = vaapi_encode_make_param_buffer(avctx, pic,
256 VAEncPictureParameterBufferType,
257 pic->codec_picture_params,
258 ctx->codec->picture_params_size);
263 if (pic->type == PICTURE_TYPE_IDR) {
264 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
265 ctx->codec->write_sequence_header) {
266 bit_len = 8 * sizeof(data);
267 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
269 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
270 "header: %d.\n", err);
273 err = vaapi_encode_make_packed_header(avctx, pic,
274 ctx->codec->sequence_header_type,
281 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
282 ctx->codec->write_picture_header) {
283 bit_len = 8 * sizeof(data);
284 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
286 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
287 "header: %d.\n", err);
290 err = vaapi_encode_make_packed_header(avctx, pic,
291 ctx->codec->picture_header_type,
297 if (ctx->codec->write_extra_buffer) {
299 size_t len = sizeof(data);
301 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
303 if (err == AVERROR_EOF)
306 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
307 "buffer %d: %d.\n", i, err);
311 err = vaapi_encode_make_param_buffer(avctx, pic, type,
318 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
319 ctx->codec->write_extra_header) {
322 bit_len = 8 * sizeof(data);
323 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
325 if (err == AVERROR_EOF)
328 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
329 "header %d: %d.\n", i, err);
333 err = vaapi_encode_make_packed_header(avctx, pic, type,
340 if (pic->nb_slices == 0)
341 pic->nb_slices = ctx->nb_slices;
342 if (pic->nb_slices > 0) {
345 pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
347 err = AVERROR(ENOMEM);
351 for (i = 0; i < pic->nb_slices; i++)
352 pic->slices[i].row_size = ctx->slice_size;
354 rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
356 // Place rounding error at top and bottom of frame.
357 av_assert0(rounding < pic->nb_slices);
358 // Some Intel drivers contain a bug where the encoder will fail
359 // if the last slice is smaller than the one before it. Since
360 // that's straightforward to avoid here, just do so.
362 for (i = 0; i < rounding; i++)
363 ++pic->slices[i].row_size;
365 for (i = 0; i < (rounding + 1) / 2; i++)
366 ++pic->slices[pic->nb_slices - i - 1].row_size;
367 for (i = 0; i < rounding / 2; i++)
368 ++pic->slices[i].row_size;
370 } else if (rounding < 0) {
371 // Remove rounding error from last slice only.
372 av_assert0(rounding < ctx->slice_size);
373 pic->slices[pic->nb_slices - 1].row_size += rounding;
376 for (i = 0; i < pic->nb_slices; i++) {
377 slice = &pic->slices[i];
380 slice->row_start = 0;
381 slice->block_start = 0;
383 const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
384 slice->row_start = prev->row_start + prev->row_size;
385 slice->block_start = prev->block_start + prev->block_size;
387 slice->block_size = slice->row_size * ctx->slice_block_cols;
389 av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
390 "%d-%d (%d blocks).\n", i, slice->row_start,
391 slice->row_start + slice->row_size - 1, slice->row_size,
392 slice->block_start, slice->block_start + slice->block_size - 1,
395 if (ctx->codec->slice_params_size > 0) {
396 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
397 if (!slice->codec_slice_params) {
398 err = AVERROR(ENOMEM);
403 if (ctx->codec->init_slice_params) {
404 err = ctx->codec->init_slice_params(avctx, pic, slice);
406 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
407 "parameters: %d.\n", err);
412 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
413 ctx->codec->write_slice_header) {
414 bit_len = 8 * sizeof(data);
415 err = ctx->codec->write_slice_header(avctx, pic, slice,
418 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
419 "header: %d.\n", err);
422 err = vaapi_encode_make_packed_header(avctx, pic,
423 ctx->codec->slice_header_type,
429 if (ctx->codec->init_slice_params) {
430 err = vaapi_encode_make_param_buffer(avctx, pic,
431 VAEncSliceParameterBufferType,
432 slice->codec_slice_params,
433 ctx->codec->slice_params_size);
439 #if VA_CHECK_VERSION(1, 0, 0)
440 sd = av_frame_get_side_data(pic->input_image,
441 AV_FRAME_DATA_REGIONS_OF_INTEREST);
442 if (sd && ctx->roi_allowed) {
443 const AVRegionOfInterest *roi;
445 VAEncMiscParameterBufferROI param_roi;
448 roi = (const AVRegionOfInterest*)sd->data;
449 roi_size = roi->self_size;
450 av_assert0(roi_size && sd->size % roi_size == 0);
451 nb_roi = sd->size / roi_size;
452 if (nb_roi > ctx->roi_max_regions) {
453 if (!ctx->roi_warned) {
454 av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
455 "supported by driver (%d > %d).\n",
456 nb_roi, ctx->roi_max_regions);
459 nb_roi = ctx->roi_max_regions;
462 pic->roi = av_mallocz_array(nb_roi, sizeof(*pic->roi));
464 err = AVERROR(ENOMEM);
467 // For overlapping regions, the first in the array takes priority.
468 for (i = 0; i < nb_roi; i++) {
469 roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
471 av_assert0(roi->qoffset.den != 0);
472 v = roi->qoffset.num * ctx->roi_quant_range / roi->qoffset.den;
473 av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
474 roi->top, roi->left, roi->bottom, roi->right, v);
476 pic->roi[i] = (VAEncROI) {
480 .width = roi->right - roi->left,
481 .height = roi->bottom - roi->top,
483 .roi_value = av_clip_int8(v),
487 param_roi = (VAEncMiscParameterBufferROI) {
489 .max_delta_qp = INT8_MAX,
490 .min_delta_qp = INT8_MIN,
492 .roi_flags.bits.roi_value_is_qp_delta = 1,
495 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
496 VAEncMiscParameterTypeROI,
504 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
506 if (vas != VA_STATUS_SUCCESS) {
507 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
508 "%d (%s).\n", vas, vaErrorStr(vas));
510 goto fail_with_picture;
513 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
514 pic->param_buffers, pic->nb_param_buffers);
515 if (vas != VA_STATUS_SUCCESS) {
516 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
517 "%d (%s).\n", vas, vaErrorStr(vas));
519 goto fail_with_picture;
522 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
523 if (vas != VA_STATUS_SUCCESS) {
524 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
525 "%d (%s).\n", vas, vaErrorStr(vas));
527 // vaRenderPicture() has been called here, so we should not destroy
528 // the parameter buffers unless separate destruction is required.
529 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
530 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
536 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
537 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
538 for (i = 0; i < pic->nb_param_buffers; i++) {
539 vas = vaDestroyBuffer(ctx->hwctx->display,
540 pic->param_buffers[i]);
541 if (vas != VA_STATUS_SUCCESS) {
542 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
543 "param buffer %#x: %d (%s).\n",
544 pic->param_buffers[i], vas, vaErrorStr(vas));
550 pic->encode_issued = 1;
555 vaEndPicture(ctx->hwctx->display, ctx->va_context);
557 for(i = 0; i < pic->nb_param_buffers; i++)
558 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
559 for (i = 0; i < pic->nb_slices; i++) {
561 av_freep(&pic->slices[i].priv_data);
562 av_freep(&pic->slices[i].codec_slice_params);
566 av_freep(&pic->codec_picture_params);
567 av_freep(&pic->param_buffers);
568 av_freep(&pic->slices);
570 av_frame_free(&pic->recon_image);
571 av_buffer_unref(&pic->output_buffer_ref);
572 pic->output_buffer = VA_INVALID_ID;
576 static int vaapi_encode_output(AVCodecContext *avctx,
577 VAAPIEncodePicture *pic, AVPacket *pkt)
579 VAAPIEncodeContext *ctx = avctx->priv_data;
580 VACodedBufferSegment *buf_list, *buf;
586 err = vaapi_encode_wait(avctx, pic);
591 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
593 if (vas != VA_STATUS_SUCCESS) {
594 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
595 "%d (%s).\n", vas, vaErrorStr(vas));
600 for (buf = buf_list; buf; buf = buf->next)
601 total_size += buf->size;
603 err = av_new_packet(pkt, total_size);
609 for (buf = buf_list; buf; buf = buf->next) {
610 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
611 "(status %08x).\n", buf->size, buf->status);
613 memcpy(ptr, buf->buf, buf->size);
617 if (pic->type == PICTURE_TYPE_IDR)
618 pkt->flags |= AV_PKT_FLAG_KEY;
622 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
623 if (vas != VA_STATUS_SUCCESS) {
624 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
625 "%d (%s).\n", vas, vaErrorStr(vas));
630 av_buffer_unref(&pic->output_buffer_ref);
631 pic->output_buffer = VA_INVALID_ID;
633 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
634 pic->display_order, pic->encode_order);
638 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
640 av_buffer_unref(&pic->output_buffer_ref);
641 pic->output_buffer = VA_INVALID_ID;
645 static int vaapi_encode_discard(AVCodecContext *avctx,
646 VAAPIEncodePicture *pic)
648 vaapi_encode_wait(avctx, pic);
650 if (pic->output_buffer_ref) {
651 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
652 "%"PRId64"/%"PRId64".\n",
653 pic->display_order, pic->encode_order);
655 av_buffer_unref(&pic->output_buffer_ref);
656 pic->output_buffer = VA_INVALID_ID;
662 static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
664 VAAPIEncodeContext *ctx = avctx->priv_data;
665 VAAPIEncodePicture *pic;
667 pic = av_mallocz(sizeof(*pic));
671 if (ctx->codec->picture_priv_data_size > 0) {
672 pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
673 if (!pic->priv_data) {
679 pic->input_surface = VA_INVALID_ID;
680 pic->recon_surface = VA_INVALID_ID;
681 pic->output_buffer = VA_INVALID_ID;
686 static int vaapi_encode_free(AVCodecContext *avctx,
687 VAAPIEncodePicture *pic)
691 if (pic->encode_issued)
692 vaapi_encode_discard(avctx, pic);
694 for (i = 0; i < pic->nb_slices; i++) {
696 av_freep(&pic->slices[i].priv_data);
697 av_freep(&pic->slices[i].codec_slice_params);
700 av_freep(&pic->codec_picture_params);
702 av_frame_free(&pic->input_image);
703 av_frame_free(&pic->recon_image);
705 av_freep(&pic->param_buffers);
706 av_freep(&pic->slices);
707 // Output buffer should already be destroyed.
708 av_assert0(pic->output_buffer == VA_INVALID_ID);
710 av_freep(&pic->priv_data);
711 av_freep(&pic->codec_picture_params);
719 static void vaapi_encode_add_ref(AVCodecContext *avctx,
720 VAAPIEncodePicture *pic,
721 VAAPIEncodePicture *target,
722 int is_ref, int in_dpb, int prev)
727 av_assert0(pic != target);
728 av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
729 pic->refs[pic->nb_refs++] = target;
734 av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
735 pic->dpb[pic->nb_dpb_pics++] = target;
740 av_assert0(!pic->prev);
745 target->ref_count[0] += refs;
746 target->ref_count[1] += refs;
749 static void vaapi_encode_remove_refs(AVCodecContext *avctx,
750 VAAPIEncodePicture *pic,
755 if (pic->ref_removed[level])
758 for (i = 0; i < pic->nb_refs; i++) {
759 av_assert0(pic->refs[i]);
760 --pic->refs[i]->ref_count[level];
761 av_assert0(pic->refs[i]->ref_count[level] >= 0);
764 for (i = 0; i < pic->nb_dpb_pics; i++) {
765 av_assert0(pic->dpb[i]);
766 --pic->dpb[i]->ref_count[level];
767 av_assert0(pic->dpb[i]->ref_count[level] >= 0);
770 av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
772 --pic->prev->ref_count[level];
773 av_assert0(pic->prev->ref_count[level] >= 0);
776 pic->ref_removed[level] = 1;
779 static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
780 VAAPIEncodePicture *start,
781 VAAPIEncodePicture *end,
782 VAAPIEncodePicture *prev,
784 VAAPIEncodePicture **last)
786 VAAPIEncodeContext *ctx = avctx->priv_data;
787 VAAPIEncodePicture *pic, *next, *ref;
790 av_assert0(start && end && start != end && start->next != end);
792 // If we are at the maximum depth then encode all pictures as
793 // non-referenced B-pictures. Also do this if there is exactly one
794 // picture left, since there will be nothing to reference it.
795 if (current_depth == ctx->max_b_depth || start->next->next == end) {
796 for (pic = start->next; pic; pic = pic->next) {
799 pic->type = PICTURE_TYPE_B;
800 pic->b_depth = current_depth;
802 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
803 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
804 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
806 for (ref = end->refs[1]; ref; ref = ref->refs[1])
807 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
812 // Split the current list at the midpoint with a referenced
813 // B-picture, then descend into each side separately.
815 for (pic = start->next; pic != end; pic = pic->next)
817 for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
819 pic->type = PICTURE_TYPE_B;
820 pic->b_depth = current_depth;
822 pic->is_reference = 1;
824 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
825 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
826 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
827 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
829 for (ref = end->refs[1]; ref; ref = ref->refs[1])
830 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
833 vaapi_encode_set_b_pictures(avctx, start, pic, pic,
834 current_depth + 1, &next);
838 vaapi_encode_set_b_pictures(avctx, pic, end, next,
839 current_depth + 1, last);
843 static int vaapi_encode_pick_next(AVCodecContext *avctx,
844 VAAPIEncodePicture **pic_out)
846 VAAPIEncodeContext *ctx = avctx->priv_data;
847 VAAPIEncodePicture *pic = NULL, *next, *start;
848 int i, b_counter, closed_gop_end;
850 // If there are any B-frames already queued, the next one to encode
851 // is the earliest not-yet-issued frame for which all references are
853 for (pic = ctx->pic_start; pic; pic = pic->next) {
854 if (pic->encode_issued)
856 if (pic->type != PICTURE_TYPE_B)
858 for (i = 0; i < pic->nb_refs; i++) {
859 if (!pic->refs[i]->encode_issued)
862 if (i == pic->nb_refs)
867 av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
868 "encode next.\n", pic->b_depth);
873 // Find the B-per-Pth available picture to become the next picture
877 closed_gop_end = ctx->closed_gop ||
878 ctx->idr_counter == ctx->gop_per_idr;
879 for (pic = ctx->pic_start; pic; pic = next) {
881 if (pic->encode_issued) {
885 // If the next available picture is force-IDR, encode it to start
886 // a new GOP immediately.
889 if (b_counter == ctx->b_per_p)
891 // If this picture ends a closed GOP or starts a new GOP then it
892 // needs to be in the top layer.
893 if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
895 // If the picture after this one is force-IDR, we need to encode
896 // this one in the top layer.
897 if (next && next->force_idr)
902 // At the end of the stream the last picture must be in the top layer.
903 if (!pic && ctx->end_of_stream) {
906 if (pic->encode_issued)
911 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
912 "need more input for reference pictures.\n");
913 return AVERROR(EAGAIN);
915 if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
916 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
917 "need more input for timestamps.\n");
918 return AVERROR(EAGAIN);
921 if (pic->force_idr) {
922 av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
924 pic->type = PICTURE_TYPE_IDR;
925 ctx->idr_counter = 1;
926 ctx->gop_counter = 1;
928 } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
929 if (ctx->idr_counter == ctx->gop_per_idr) {
930 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
932 pic->type = PICTURE_TYPE_IDR;
933 ctx->idr_counter = 1;
935 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
937 pic->type = PICTURE_TYPE_I;
940 ctx->gop_counter = 1;
943 if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
944 av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
947 av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
950 pic->type = PICTURE_TYPE_P;
952 ctx->gop_counter += 1 + b_counter;
954 pic->is_reference = 1;
957 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
958 if (pic->type != PICTURE_TYPE_IDR) {
959 vaapi_encode_add_ref(avctx, pic, start,
960 pic->type == PICTURE_TYPE_P,
962 vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
965 --ctx->next_prev->ref_count[0];
968 vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
971 ctx->next_prev = pic;
973 ++ctx->next_prev->ref_count[0];
977 static int vaapi_encode_clear_old(AVCodecContext *avctx)
979 VAAPIEncodeContext *ctx = avctx->priv_data;
980 VAAPIEncodePicture *pic, *prev, *next;
982 av_assert0(ctx->pic_start);
984 // Remove direct references once each picture is complete.
985 for (pic = ctx->pic_start; pic; pic = pic->next) {
986 if (pic->encode_complete && pic->next)
987 vaapi_encode_remove_refs(avctx, pic, 0);
990 // Remove indirect references once a picture has no direct references.
991 for (pic = ctx->pic_start; pic; pic = pic->next) {
992 if (pic->encode_complete && pic->ref_count[0] == 0)
993 vaapi_encode_remove_refs(avctx, pic, 1);
996 // Clear out all complete pictures with no remaining references.
998 for (pic = ctx->pic_start; pic; pic = next) {
1000 if (pic->encode_complete && pic->ref_count[1] == 0) {
1001 av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
1005 ctx->pic_start = next;
1006 vaapi_encode_free(avctx, pic);
1015 static int vaapi_encode_check_frame(AVCodecContext *avctx,
1016 const AVFrame *frame)
1018 VAAPIEncodeContext *ctx = avctx->priv_data;
1020 if ((frame->crop_top || frame->crop_bottom ||
1021 frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
1022 av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
1023 "frames ignored due to lack of API support.\n");
1024 ctx->crop_warned = 1;
1027 if (!ctx->roi_allowed) {
1028 AVFrameSideData *sd =
1029 av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
1031 if (sd && !ctx->roi_warned) {
1032 av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
1033 "frames ignored due to lack of driver support.\n");
1034 ctx->roi_warned = 1;
1041 int ff_vaapi_encode_send_frame(AVCodecContext *avctx, const AVFrame *frame)
1043 VAAPIEncodeContext *ctx = avctx->priv_data;
1044 VAAPIEncodePicture *pic;
1048 av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
1049 frame->width, frame->height, frame->pts);
1051 err = vaapi_encode_check_frame(avctx, frame);
1055 pic = vaapi_encode_alloc(avctx);
1057 return AVERROR(ENOMEM);
1059 pic->input_image = av_frame_alloc();
1060 if (!pic->input_image) {
1061 err = AVERROR(ENOMEM);
1064 err = av_frame_ref(pic->input_image, frame);
1068 if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
1071 pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
1072 pic->pts = frame->pts;
1074 if (ctx->input_order == 0)
1075 ctx->first_pts = pic->pts;
1076 if (ctx->input_order == ctx->decode_delay)
1077 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
1078 if (ctx->output_delay > 0)
1079 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
1081 pic->display_order = ctx->input_order;
1084 if (ctx->pic_start) {
1085 ctx->pic_end->next = pic;
1088 ctx->pic_start = pic;
1093 ctx->end_of_stream = 1;
1095 // Fix timestamps if we hit end-of-stream before the initial decode
1096 // delay has elapsed.
1097 if (ctx->input_order < ctx->decode_delay)
1098 ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
1107 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
1109 VAAPIEncodeContext *ctx = avctx->priv_data;
1110 VAAPIEncodePicture *pic;
1113 if (!ctx->pic_start) {
1114 if (ctx->end_of_stream)
1117 return AVERROR(EAGAIN);
1121 err = vaapi_encode_pick_next(avctx, &pic);
1126 pic->encode_order = ctx->encode_order++;
1128 err = vaapi_encode_issue(avctx, pic);
1130 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1134 err = vaapi_encode_output(avctx, pic, pkt);
1136 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1140 if (ctx->output_delay == 0) {
1141 pkt->dts = pkt->pts;
1142 } else if (pic->encode_order < ctx->decode_delay) {
1143 if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1144 pkt->dts = INT64_MIN;
1146 pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1148 pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1149 (3 * ctx->output_delay)];
1151 av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1152 pkt->pts, pkt->dts);
1154 ctx->output_order = pic->encode_order;
1155 vaapi_encode_clear_old(avctx);
1161 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
1162 void *buffer, size_t size)
1164 VAAPIEncodeContext *ctx = avctx->priv_data;
1166 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1168 ctx->global_params_type[ctx->nb_global_params] = type;
1169 ctx->global_params [ctx->nb_global_params] = buffer;
1170 ctx->global_params_size[ctx->nb_global_params] = size;
1172 ++ctx->nb_global_params;
1175 typedef struct VAAPIEncodeRTFormat {
1182 } VAAPIEncodeRTFormat;
1184 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1185 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
1186 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
1187 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
1188 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
1189 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
1190 #if VA_CHECK_VERSION(0, 38, 1)
1191 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1195 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1196 VAEntrypointEncSlice,
1197 VAEntrypointEncPicture,
1198 #if VA_CHECK_VERSION(0, 39, 2)
1199 VAEntrypointEncSliceLP,
1203 #if VA_CHECK_VERSION(0, 39, 2)
1204 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1205 VAEntrypointEncSliceLP,
1210 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1212 VAAPIEncodeContext *ctx = avctx->priv_data;
1213 VAProfile *va_profiles = NULL;
1214 VAEntrypoint *va_entrypoints = NULL;
1216 const VAEntrypoint *usable_entrypoints;
1217 const VAAPIEncodeProfile *profile;
1218 const AVPixFmtDescriptor *desc;
1219 VAConfigAttrib rt_format_attr;
1220 const VAAPIEncodeRTFormat *rt_format;
1221 const char *profile_string, *entrypoint_string;
1222 int i, j, n, depth, err;
1225 if (ctx->low_power) {
1226 #if VA_CHECK_VERSION(0, 39, 2)
1227 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1229 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1230 "supported with this VAAPI version.\n");
1231 return AVERROR(EINVAL);
1234 usable_entrypoints = vaapi_encode_entrypoints_normal;
1237 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1239 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1240 ctx->input_frames->sw_format);
1241 return AVERROR(EINVAL);
1243 depth = desc->comp[0].depth;
1244 for (i = 1; i < desc->nb_components; i++) {
1245 if (desc->comp[i].depth != depth) {
1246 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1248 return AVERROR(EINVAL);
1251 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1254 n = vaMaxNumProfiles(ctx->hwctx->display);
1255 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1257 err = AVERROR(ENOMEM);
1260 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1261 if (vas != VA_STATUS_SUCCESS) {
1262 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1263 vas, vaErrorStr(vas));
1264 err = AVERROR_EXTERNAL;
1268 av_assert0(ctx->codec->profiles);
1269 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1270 FF_PROFILE_UNKNOWN); i++) {
1271 profile = &ctx->codec->profiles[i];
1272 if (depth != profile->depth ||
1273 desc->nb_components != profile->nb_components)
1275 if (desc->nb_components > 1 &&
1276 (desc->log2_chroma_w != profile->log2_chroma_w ||
1277 desc->log2_chroma_h != profile->log2_chroma_h))
1279 if (avctx->profile != profile->av_profile &&
1280 avctx->profile != FF_PROFILE_UNKNOWN)
1283 #if VA_CHECK_VERSION(1, 0, 0)
1284 profile_string = vaProfileStr(profile->va_profile);
1286 profile_string = "(no profile names)";
1289 for (j = 0; j < n; j++) {
1290 if (va_profiles[j] == profile->va_profile)
1294 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1295 "is not supported by driver.\n", profile_string,
1296 profile->va_profile);
1300 ctx->profile = profile;
1303 if (!ctx->profile) {
1304 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1305 err = AVERROR(ENOSYS);
1309 avctx->profile = profile->av_profile;
1310 ctx->va_profile = profile->va_profile;
1311 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1312 profile_string, ctx->va_profile);
1314 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1315 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1316 if (!va_entrypoints) {
1317 err = AVERROR(ENOMEM);
1320 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1321 va_entrypoints, &n);
1322 if (vas != VA_STATUS_SUCCESS) {
1323 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1324 "profile %s (%d): %d (%s).\n", profile_string,
1325 ctx->va_profile, vas, vaErrorStr(vas));
1326 err = AVERROR_EXTERNAL;
1330 for (i = 0; i < n; i++) {
1331 for (j = 0; usable_entrypoints[j]; j++) {
1332 if (va_entrypoints[i] == usable_entrypoints[j])
1335 if (usable_entrypoints[j])
1339 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1340 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1341 err = AVERROR(ENOSYS);
1345 ctx->va_entrypoint = va_entrypoints[i];
1346 #if VA_CHECK_VERSION(1, 0, 0)
1347 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1349 entrypoint_string = "(no entrypoint names)";
1351 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1352 entrypoint_string, ctx->va_entrypoint);
1354 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1355 rt_format = &vaapi_encode_rt_formats[i];
1356 if (rt_format->depth == depth &&
1357 rt_format->nb_components == profile->nb_components &&
1358 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1359 rt_format->log2_chroma_h == profile->log2_chroma_h)
1362 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1363 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1364 "found for profile %s (%d) entrypoint %s (%d).\n",
1365 profile_string, ctx->va_profile,
1366 entrypoint_string, ctx->va_entrypoint);
1367 err = AVERROR(ENOSYS);
1371 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1372 vas = vaGetConfigAttributes(ctx->hwctx->display,
1373 ctx->va_profile, ctx->va_entrypoint,
1374 &rt_format_attr, 1);
1375 if (vas != VA_STATUS_SUCCESS) {
1376 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1377 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1378 err = AVERROR_EXTERNAL;
1382 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1383 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1384 "supported by driver: assuming surface RT format %s "
1385 "is valid.\n", rt_format->name);
1386 } else if (!(rt_format_attr.value & rt_format->value)) {
1387 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1388 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1389 rt_format->name, profile_string, ctx->va_profile,
1390 entrypoint_string, ctx->va_entrypoint);
1391 err = AVERROR(ENOSYS);
1394 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1395 "format %s (%#x).\n", rt_format->name, rt_format->value);
1396 ctx->config_attributes[ctx->nb_config_attributes++] =
1398 .type = VAConfigAttribRTFormat,
1399 .value = rt_format->value,
1405 av_freep(&va_profiles);
1406 av_freep(&va_entrypoints);
1410 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1412 // | Maxrate | HRD/VBV
1414 { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
1415 { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
1416 { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
1417 #if VA_CHECK_VERSION(1, 1, 0)
1418 { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
1420 { RC_MODE_ICQ, "ICQ", 0 },
1422 #if VA_CHECK_VERSION(1, 3, 0)
1423 { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
1424 { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
1426 { RC_MODE_QVBR, "QVBR", 0 },
1427 { RC_MODE_AVBR, "AVBR", 0 },
1431 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1433 VAAPIEncodeContext *ctx = avctx->priv_data;
1434 uint32_t supported_va_rc_modes;
1435 const VAAPIEncodeRCMode *rc_mode;
1436 int64_t rc_bits_per_second;
1437 int rc_target_percentage;
1440 int64_t hrd_buffer_size;
1441 int64_t hrd_initial_buffer_fullness;
1443 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1445 char supported_rc_modes_string[64];
1447 vas = vaGetConfigAttributes(ctx->hwctx->display,
1448 ctx->va_profile, ctx->va_entrypoint,
1450 if (vas != VA_STATUS_SUCCESS) {
1451 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1452 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1453 return AVERROR_EXTERNAL;
1455 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1456 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1457 "supported rate control modes: assuming CQP only.\n");
1458 supported_va_rc_modes = VA_RC_CQP;
1459 strcpy(supported_rc_modes_string, "unknown");
1461 char *str = supported_rc_modes_string;
1462 size_t len = sizeof(supported_rc_modes_string);
1463 int i, first = 1, res;
1465 supported_va_rc_modes = rc_attr.value;
1466 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1467 rc_mode = &vaapi_encode_rc_modes[i];
1468 if (supported_va_rc_modes & rc_mode->va_mode) {
1469 res = snprintf(str, len, "%s%s",
1470 first ? "" : ", ", rc_mode->name);
1483 av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1484 supported_rc_modes_string);
1487 // Rate control mode selection:
1488 // * If the user has set a mode explicitly with the rc_mode option,
1489 // use it and fail if it is not available.
1490 // * If an explicit QP option has been set, use CQP.
1491 // * If the codec is CQ-only, use CQP.
1492 // * If the QSCALE avcodec option is set, use CQP.
1493 // * If bitrate and quality are both set, try QVBR.
1494 // * If quality is set, try ICQ, then CQP.
1495 // * If bitrate and maxrate are set and have the same value, try CBR.
1496 // * If a bitrate is set, try AVBR, then VBR, then CBR.
1497 // * If no bitrate is set, try ICQ, then CQP.
1499 #define TRY_RC_MODE(mode, fail) do { \
1500 rc_mode = &vaapi_encode_rc_modes[mode]; \
1501 if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1503 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1504 "RC mode (supported modes: %s).\n", rc_mode->name, \
1505 supported_rc_modes_string); \
1506 return AVERROR(EINVAL); \
1508 av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1509 "RC mode.\n", rc_mode->name); \
1512 goto rc_mode_found; \
1516 if (ctx->explicit_rc_mode)
1517 TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1519 if (ctx->explicit_qp)
1520 TRY_RC_MODE(RC_MODE_CQP, 1);
1522 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1523 TRY_RC_MODE(RC_MODE_CQP, 1);
1525 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1526 TRY_RC_MODE(RC_MODE_CQP, 1);
1528 if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1529 TRY_RC_MODE(RC_MODE_QVBR, 0);
1531 if (avctx->global_quality > 0) {
1532 TRY_RC_MODE(RC_MODE_ICQ, 0);
1533 TRY_RC_MODE(RC_MODE_CQP, 0);
1536 if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1537 TRY_RC_MODE(RC_MODE_CBR, 0);
1539 if (avctx->bit_rate > 0) {
1540 TRY_RC_MODE(RC_MODE_AVBR, 0);
1541 TRY_RC_MODE(RC_MODE_VBR, 0);
1542 TRY_RC_MODE(RC_MODE_CBR, 0);
1544 TRY_RC_MODE(RC_MODE_ICQ, 0);
1545 TRY_RC_MODE(RC_MODE_CQP, 0);
1548 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1549 "RC mode compatible with selected options "
1550 "(supported modes: %s).\n", supported_rc_modes_string);
1551 return AVERROR(EINVAL);
1554 if (rc_mode->bitrate) {
1555 if (avctx->bit_rate <= 0) {
1556 av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1557 "RC mode.\n", rc_mode->name);
1558 return AVERROR(EINVAL);
1561 if (rc_mode->mode == RC_MODE_AVBR) {
1562 // For maximum confusion AVBR is hacked into the existing API
1563 // by overloading some of the fields with completely different
1566 // Target percentage does not apply in AVBR mode.
1567 rc_bits_per_second = avctx->bit_rate;
1569 // Accuracy tolerance range for meeting the specified target
1570 // bitrate. It's very unclear how this is actually intended
1571 // to work - since we do want to get the specified bitrate,
1572 // set the accuracy to 100% for now.
1573 rc_target_percentage = 100;
1575 // Convergence period in frames. The GOP size reflects the
1576 // user's intended block size for cutting, so reusing that
1577 // as the convergence period seems a reasonable default.
1578 rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1580 } else if (rc_mode->maxrate) {
1581 if (avctx->rc_max_rate > 0) {
1582 if (avctx->rc_max_rate < avctx->bit_rate) {
1583 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1584 "bitrate (%"PRId64") must not be greater than "
1585 "maxrate (%"PRId64").\n", avctx->bit_rate,
1586 avctx->rc_max_rate);
1587 return AVERROR(EINVAL);
1589 rc_bits_per_second = avctx->rc_max_rate;
1590 rc_target_percentage = (avctx->bit_rate * 100) /
1593 // We only have a target bitrate, but this mode requires
1594 // that a maximum rate be supplied as well. Since the
1595 // user does not want this to be a constraint, arbitrarily
1596 // pick a maximum rate of double the target rate.
1597 rc_bits_per_second = 2 * avctx->bit_rate;
1598 rc_target_percentage = 50;
1601 if (avctx->rc_max_rate > avctx->bit_rate) {
1602 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1603 "in %s RC mode.\n", rc_mode->name);
1605 rc_bits_per_second = avctx->bit_rate;
1606 rc_target_percentage = 100;
1609 rc_bits_per_second = 0;
1610 rc_target_percentage = 100;
1613 if (rc_mode->quality) {
1614 if (ctx->explicit_qp) {
1615 rc_quality = ctx->explicit_qp;
1616 } else if (avctx->global_quality > 0) {
1617 rc_quality = avctx->global_quality;
1619 rc_quality = ctx->codec->default_quality;
1620 av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1621 "using default (%d).\n", rc_quality);
1628 if (avctx->rc_buffer_size)
1629 hrd_buffer_size = avctx->rc_buffer_size;
1630 else if (avctx->rc_max_rate > 0)
1631 hrd_buffer_size = avctx->rc_max_rate;
1633 hrd_buffer_size = avctx->bit_rate;
1634 if (avctx->rc_initial_buffer_occupancy) {
1635 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1636 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1637 "must have initial buffer size (%d) <= "
1638 "buffer size (%"PRId64").\n",
1639 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1640 return AVERROR(EINVAL);
1642 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1644 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1647 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1649 if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1650 av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1651 "in %s RC mode.\n", rc_mode->name);
1654 hrd_buffer_size = 0;
1655 hrd_initial_buffer_fullness = 0;
1657 if (rc_mode->mode != RC_MODE_AVBR) {
1658 // Already set (with completely different meaning) for AVBR.
1659 rc_window_size = 1000;
1663 if (rc_bits_per_second > UINT32_MAX ||
1664 hrd_buffer_size > UINT32_MAX ||
1665 hrd_initial_buffer_fullness > UINT32_MAX) {
1666 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1667 "greater are not supported by VAAPI.\n");
1668 return AVERROR(EINVAL);
1671 ctx->rc_mode = rc_mode;
1672 ctx->rc_quality = rc_quality;
1673 ctx->va_rc_mode = rc_mode->va_mode;
1674 ctx->va_bit_rate = rc_bits_per_second;
1676 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1677 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1678 // This driver does not want the RC mode attribute to be set.
1680 ctx->config_attributes[ctx->nb_config_attributes++] =
1682 .type = VAConfigAttribRateControl,
1683 .value = ctx->va_rc_mode,
1687 if (rc_mode->quality)
1688 av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1690 if (rc_mode->va_mode != VA_RC_CQP) {
1691 if (rc_mode->mode == RC_MODE_AVBR) {
1692 av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1693 "converging in %d frames with %d%% accuracy.\n",
1694 rc_bits_per_second, rc_window_size,
1695 rc_target_percentage);
1696 } else if (rc_mode->bitrate) {
1697 av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1698 "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1699 rc_bits_per_second, rc_window_size);
1702 ctx->rc_params = (VAEncMiscParameterRateControl) {
1703 .bits_per_second = rc_bits_per_second,
1704 .target_percentage = rc_target_percentage,
1705 .window_size = rc_window_size,
1707 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1708 .basic_unit_size = 0,
1709 #if VA_CHECK_VERSION(1, 1, 0)
1710 .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1711 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1713 #if VA_CHECK_VERSION(1, 3, 0)
1714 .quality_factor = rc_quality,
1717 vaapi_encode_add_global_param(avctx,
1718 VAEncMiscParameterTypeRateControl,
1720 sizeof(ctx->rc_params));
1724 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1725 "initial fullness %"PRId64" bits.\n",
1726 hrd_buffer_size, hrd_initial_buffer_fullness);
1728 ctx->hrd_params = (VAEncMiscParameterHRD) {
1729 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1730 .buffer_size = hrd_buffer_size,
1732 vaapi_encode_add_global_param(avctx,
1733 VAEncMiscParameterTypeHRD,
1735 sizeof(ctx->hrd_params));
1738 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1739 av_reduce(&fr_num, &fr_den,
1740 avctx->framerate.num, avctx->framerate.den, 65535);
1742 av_reduce(&fr_num, &fr_den,
1743 avctx->time_base.den, avctx->time_base.num, 65535);
1745 av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1746 fr_num, fr_den, (double)fr_num / fr_den);
1748 ctx->fr_params = (VAEncMiscParameterFrameRate) {
1749 .framerate = (unsigned int)fr_den << 16 | fr_num,
1751 #if VA_CHECK_VERSION(0, 40, 0)
1752 vaapi_encode_add_global_param(avctx,
1753 VAEncMiscParameterTypeFrameRate,
1755 sizeof(ctx->fr_params));
1761 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1763 VAAPIEncodeContext *ctx = avctx->priv_data;
1765 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1766 uint32_t ref_l0, ref_l1;
1768 vas = vaGetConfigAttributes(ctx->hwctx->display,
1772 if (vas != VA_STATUS_SUCCESS) {
1773 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1774 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1775 return AVERROR_EXTERNAL;
1778 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1779 ref_l0 = ref_l1 = 0;
1781 ref_l0 = attr.value & 0xffff;
1782 ref_l1 = attr.value >> 16 & 0xffff;
1785 if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1786 avctx->gop_size <= 1) {
1787 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1789 } else if (ref_l0 < 1) {
1790 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1791 "reference frames.\n");
1792 return AVERROR(EINVAL);
1793 } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1794 ref_l1 < 1 || avctx->max_b_frames < 1) {
1795 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1796 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1797 ctx->gop_size = avctx->gop_size;
1798 ctx->p_per_i = INT_MAX;
1801 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1802 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1803 ctx->gop_size = avctx->gop_size;
1804 ctx->p_per_i = INT_MAX;
1805 ctx->b_per_p = avctx->max_b_frames;
1806 if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1807 ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1808 av_log2(ctx->b_per_p) + 1);
1810 ctx->max_b_depth = 1;
1814 if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1815 ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1816 ctx->gop_per_idr = ctx->idr_interval + 1;
1818 ctx->closed_gop = 1;
1819 ctx->gop_per_idr = 1;
1825 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1827 VAAPIEncodeContext *ctx = avctx->priv_data;
1828 VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1829 { VAConfigAttribEncSliceStructure } };
1831 uint32_t max_slices, slice_structure;
1834 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1835 if (avctx->slices > 0) {
1836 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1837 "but this codec does not support controlling slices.\n");
1842 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1843 ctx->slice_block_height;
1844 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
1845 ctx->slice_block_width;
1847 if (avctx->slices <= 1) {
1849 ctx->slice_size = ctx->slice_block_rows;
1853 vas = vaGetConfigAttributes(ctx->hwctx->display,
1856 attr, FF_ARRAY_ELEMS(attr));
1857 if (vas != VA_STATUS_SUCCESS) {
1858 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1859 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1860 return AVERROR_EXTERNAL;
1862 max_slices = attr[0].value;
1863 slice_structure = attr[1].value;
1864 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1865 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1866 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1867 "pictures as multiple slices.\n.");
1868 return AVERROR(EINVAL);
1871 // For fixed-size slices currently we only support whole rows, making
1872 // rectangular slices. This could be extended to arbitrary runs of
1873 // blocks, but since slices tend to be a conformance requirement and
1874 // most cases (such as broadcast or bluray) want rectangular slices
1875 // only it would need to be gated behind another option.
1876 if (avctx->slices > ctx->slice_block_rows) {
1877 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1878 "configured number of slices (%d < %d); using "
1879 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1880 req_slices = ctx->slice_block_rows;
1882 req_slices = avctx->slices;
1884 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1885 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1886 ctx->nb_slices = req_slices;
1887 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1888 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1890 for (k = 1;; k *= 2) {
1891 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1894 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1895 ctx->slice_size = k;
1896 #if VA_CHECK_VERSION(1, 0, 0)
1897 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1898 ctx->nb_slices = ctx->slice_block_rows;
1899 ctx->slice_size = 1;
1902 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1903 "slice structure modes (%#x).\n", slice_structure);
1904 return AVERROR(EINVAL);
1907 if (ctx->nb_slices > avctx->slices) {
1908 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1909 "%d (from %d) due to driver constraints on slice "
1910 "structure.\n", ctx->nb_slices, avctx->slices);
1912 if (ctx->nb_slices > max_slices) {
1913 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1914 "encoding with %d slices (max %"PRIu32").\n",
1915 ctx->nb_slices, max_slices);
1916 return AVERROR(EINVAL);
1919 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1920 "(default size %d block rows).\n",
1921 ctx->nb_slices, ctx->slice_size);
1925 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1927 VAAPIEncodeContext *ctx = avctx->priv_data;
1929 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1931 vas = vaGetConfigAttributes(ctx->hwctx->display,
1935 if (vas != VA_STATUS_SUCCESS) {
1936 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1937 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1938 return AVERROR_EXTERNAL;
1941 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1942 if (ctx->desired_packed_headers) {
1943 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1944 "packed headers (wanted %#x).\n",
1945 ctx->desired_packed_headers);
1947 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1948 "packed headers (none wanted).\n");
1950 ctx->va_packed_headers = 0;
1952 if (ctx->desired_packed_headers & ~attr.value) {
1953 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1954 "wanted packed headers (wanted %#x, found %#x).\n",
1955 ctx->desired_packed_headers, attr.value);
1957 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1958 "available (wanted %#x, found %#x).\n",
1959 ctx->desired_packed_headers, attr.value);
1961 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1964 if (ctx->va_packed_headers) {
1965 ctx->config_attributes[ctx->nb_config_attributes++] =
1967 .type = VAConfigAttribEncPackedHeaders,
1968 .value = ctx->va_packed_headers,
1972 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1973 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1974 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1975 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1976 "sequence headers, but a global header is requested.\n");
1977 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1978 "this may result in a stream which is not usable for some "
1979 "purposes (e.g. not muxable to some containers).\n");
1985 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1987 #if VA_CHECK_VERSION(0, 36, 0)
1988 VAAPIEncodeContext *ctx = avctx->priv_data;
1990 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1991 int quality = avctx->compression_level;
1993 vas = vaGetConfigAttributes(ctx->hwctx->display,
1997 if (vas != VA_STATUS_SUCCESS) {
1998 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1999 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2000 return AVERROR_EXTERNAL;
2003 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2005 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
2006 "supported: will use default quality level.\n");
2009 if (quality > attr.value) {
2010 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
2011 "valid range is 0-%d, using %d.\n",
2012 attr.value, attr.value);
2013 quality = attr.value;
2016 ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
2017 .quality_level = quality,
2019 vaapi_encode_add_global_param(avctx,
2020 VAEncMiscParameterTypeQualityLevel,
2021 &ctx->quality_params,
2022 sizeof(ctx->quality_params));
2025 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
2026 "not supported with this VAAPI version.\n");
2032 static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
2034 #if VA_CHECK_VERSION(1, 0, 0)
2035 VAAPIEncodeContext *ctx = avctx->priv_data;
2037 VAConfigAttrib attr = { VAConfigAttribEncROI };
2039 vas = vaGetConfigAttributes(ctx->hwctx->display,
2043 if (vas != VA_STATUS_SUCCESS) {
2044 av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
2045 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2046 return AVERROR_EXTERNAL;
2049 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2050 ctx->roi_allowed = 0;
2052 VAConfigAttribValEncROI roi = {
2053 .value = attr.value,
2056 ctx->roi_max_regions = roi.bits.num_roi_regions;
2057 ctx->roi_allowed = ctx->roi_max_regions > 0 &&
2058 (ctx->va_rc_mode == VA_RC_CQP ||
2059 roi.bits.roi_rc_qp_delta_support);
2065 static void vaapi_encode_free_output_buffer(void *opaque,
2068 AVCodecContext *avctx = opaque;
2069 VAAPIEncodeContext *ctx = avctx->priv_data;
2070 VABufferID buffer_id;
2072 buffer_id = (VABufferID)(uintptr_t)data;
2074 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2076 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
2079 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
2082 AVCodecContext *avctx = opaque;
2083 VAAPIEncodeContext *ctx = avctx->priv_data;
2084 VABufferID buffer_id;
2088 // The output buffer size is fixed, so it needs to be large enough
2089 // to hold the largest possible compressed frame. We assume here
2090 // that the uncompressed frame plus some header data is an upper
2092 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
2093 VAEncCodedBufferType,
2094 3 * ctx->surface_width * ctx->surface_height +
2095 (1 << 16), 1, 0, &buffer_id);
2096 if (vas != VA_STATUS_SUCCESS) {
2097 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
2098 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
2102 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
2104 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
2106 &vaapi_encode_free_output_buffer,
2107 avctx, AV_BUFFER_FLAG_READONLY);
2109 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2116 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
2118 VAAPIEncodeContext *ctx = avctx->priv_data;
2119 AVVAAPIHWConfig *hwconfig = NULL;
2120 AVHWFramesConstraints *constraints = NULL;
2121 enum AVPixelFormat recon_format;
2124 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
2126 err = AVERROR(ENOMEM);
2129 hwconfig->config_id = ctx->va_config;
2131 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
2134 err = AVERROR(ENOMEM);
2138 // Probably we can use the input surface format as the surface format
2139 // of the reconstructed frames. If not, we just pick the first (only?)
2140 // format in the valid list and hope that it all works.
2141 recon_format = AV_PIX_FMT_NONE;
2142 if (constraints->valid_sw_formats) {
2143 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
2144 if (ctx->input_frames->sw_format ==
2145 constraints->valid_sw_formats[i]) {
2146 recon_format = ctx->input_frames->sw_format;
2150 if (recon_format == AV_PIX_FMT_NONE) {
2151 // No match. Just use the first in the supported list and
2152 // hope for the best.
2153 recon_format = constraints->valid_sw_formats[0];
2156 // No idea what to use; copy input format.
2157 recon_format = ctx->input_frames->sw_format;
2159 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
2160 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
2162 if (ctx->surface_width < constraints->min_width ||
2163 ctx->surface_height < constraints->min_height ||
2164 ctx->surface_width > constraints->max_width ||
2165 ctx->surface_height > constraints->max_height) {
2166 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2167 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2168 ctx->surface_width, ctx->surface_height,
2169 constraints->min_width, constraints->max_width,
2170 constraints->min_height, constraints->max_height);
2171 err = AVERROR(EINVAL);
2175 av_freep(&hwconfig);
2176 av_hwframe_constraints_free(&constraints);
2178 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2179 if (!ctx->recon_frames_ref) {
2180 err = AVERROR(ENOMEM);
2183 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2185 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
2186 ctx->recon_frames->sw_format = recon_format;
2187 ctx->recon_frames->width = ctx->surface_width;
2188 ctx->recon_frames->height = ctx->surface_height;
2190 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2192 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2193 "frame context: %d.\n", err);
2199 av_freep(&hwconfig);
2200 av_hwframe_constraints_free(&constraints);
2204 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2206 VAAPIEncodeContext *ctx = avctx->priv_data;
2207 AVVAAPIFramesContext *recon_hwctx = NULL;
2211 if (!avctx->hw_frames_ctx) {
2212 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2213 "required to associate the encoding device.\n");
2214 return AVERROR(EINVAL);
2217 ctx->va_config = VA_INVALID_ID;
2218 ctx->va_context = VA_INVALID_ID;
2220 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2221 if (!ctx->input_frames_ref) {
2222 err = AVERROR(ENOMEM);
2225 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2227 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2228 if (!ctx->device_ref) {
2229 err = AVERROR(ENOMEM);
2232 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2233 ctx->hwctx = ctx->device->hwctx;
2235 err = vaapi_encode_profile_entrypoint(avctx);
2239 err = vaapi_encode_init_rate_control(avctx);
2243 err = vaapi_encode_init_gop_structure(avctx);
2247 err = vaapi_encode_init_slice_structure(avctx);
2251 err = vaapi_encode_init_packed_headers(avctx);
2255 err = vaapi_encode_init_roi(avctx);
2259 if (avctx->compression_level >= 0) {
2260 err = vaapi_encode_init_quality(avctx);
2265 vas = vaCreateConfig(ctx->hwctx->display,
2266 ctx->va_profile, ctx->va_entrypoint,
2267 ctx->config_attributes, ctx->nb_config_attributes,
2269 if (vas != VA_STATUS_SUCCESS) {
2270 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2271 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2276 err = vaapi_encode_create_recon_frames(avctx);
2280 recon_hwctx = ctx->recon_frames->hwctx;
2281 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2282 ctx->surface_width, ctx->surface_height,
2284 recon_hwctx->surface_ids,
2285 recon_hwctx->nb_surfaces,
2287 if (vas != VA_STATUS_SUCCESS) {
2288 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2289 "context: %d (%s).\n", vas, vaErrorStr(vas));
2294 ctx->output_buffer_pool =
2295 av_buffer_pool_init2(sizeof(VABufferID), avctx,
2296 &vaapi_encode_alloc_output_buffer, NULL);
2297 if (!ctx->output_buffer_pool) {
2298 err = AVERROR(ENOMEM);
2302 if (ctx->codec->configure) {
2303 err = ctx->codec->configure(avctx);
2308 ctx->output_delay = ctx->b_per_p;
2309 ctx->decode_delay = ctx->max_b_depth;
2311 if (ctx->codec->sequence_params_size > 0) {
2312 ctx->codec_sequence_params =
2313 av_mallocz(ctx->codec->sequence_params_size);
2314 if (!ctx->codec_sequence_params) {
2315 err = AVERROR(ENOMEM);
2319 if (ctx->codec->picture_params_size > 0) {
2320 ctx->codec_picture_params =
2321 av_mallocz(ctx->codec->picture_params_size);
2322 if (!ctx->codec_picture_params) {
2323 err = AVERROR(ENOMEM);
2328 if (ctx->codec->init_sequence_params) {
2329 err = ctx->codec->init_sequence_params(avctx);
2331 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2332 "failed: %d.\n", err);
2337 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2338 ctx->codec->write_sequence_header &&
2339 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2340 char data[MAX_PARAM_BUFFER_SIZE];
2341 size_t bit_len = 8 * sizeof(data);
2343 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2345 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2346 "for extradata: %d.\n", err);
2349 avctx->extradata_size = (bit_len + 7) / 8;
2350 avctx->extradata = av_mallocz(avctx->extradata_size +
2351 AV_INPUT_BUFFER_PADDING_SIZE);
2352 if (!avctx->extradata) {
2353 err = AVERROR(ENOMEM);
2356 memcpy(avctx->extradata, data, avctx->extradata_size);
2363 ff_vaapi_encode_close(avctx);
2367 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2369 VAAPIEncodeContext *ctx = avctx->priv_data;
2370 VAAPIEncodePicture *pic, *next;
2372 for (pic = ctx->pic_start; pic; pic = next) {
2374 vaapi_encode_free(avctx, pic);
2377 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2379 if (ctx->va_context != VA_INVALID_ID) {
2380 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2381 ctx->va_context = VA_INVALID_ID;
2384 if (ctx->va_config != VA_INVALID_ID) {
2385 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2386 ctx->va_config = VA_INVALID_ID;
2389 av_freep(&ctx->codec_sequence_params);
2390 av_freep(&ctx->codec_picture_params);
2392 av_buffer_unref(&ctx->recon_frames_ref);
2393 av_buffer_unref(&ctx->input_frames_ref);
2394 av_buffer_unref(&ctx->device_ref);