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 const AVCodecHWConfigInternal *ff_vaapi_encode_hw_configs[] = {
31 HW_CONFIG_ENCODER_FRAMES(VAAPI, VAAPI),
35 static const char * const picture_type_name[] = { "IDR", "I", "P", "B" };
37 static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
38 VAAPIEncodePicture *pic,
39 int type, char *data, size_t bit_len)
41 VAAPIEncodeContext *ctx = avctx->priv_data;
43 VABufferID param_buffer, data_buffer;
45 VAEncPackedHeaderParameterBuffer params = {
47 .bit_length = bit_len,
48 .has_emulation_bytes = 1,
51 tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 2);
53 return AVERROR(ENOMEM);
54 pic->param_buffers = tmp;
56 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
57 VAEncPackedHeaderParameterBufferType,
58 sizeof(params), 1, ¶ms, ¶m_buffer);
59 if (vas != VA_STATUS_SUCCESS) {
60 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
61 "for packed header (type %d): %d (%s).\n",
62 type, vas, vaErrorStr(vas));
65 pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
67 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
68 VAEncPackedHeaderDataBufferType,
69 (bit_len + 7) / 8, 1, data, &data_buffer);
70 if (vas != VA_STATUS_SUCCESS) {
71 av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
72 "for packed header (type %d): %d (%s).\n",
73 type, vas, vaErrorStr(vas));
76 pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
78 av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
79 "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
83 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
84 VAAPIEncodePicture *pic,
85 int type, char *data, size_t len)
87 VAAPIEncodeContext *ctx = avctx->priv_data;
92 tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 1);
94 return AVERROR(ENOMEM);
95 pic->param_buffers = tmp;
97 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
98 type, len, 1, data, &buffer);
99 if (vas != VA_STATUS_SUCCESS) {
100 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
101 "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
104 pic->param_buffers[pic->nb_param_buffers++] = buffer;
106 av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
111 static int vaapi_encode_make_misc_param_buffer(AVCodecContext *avctx,
112 VAAPIEncodePicture *pic,
114 const void *data, size_t len)
116 // Construct the buffer on the stack - 1KB is much larger than any
117 // current misc parameter buffer type (the largest is EncQuality at
119 uint8_t buffer[1024];
120 VAEncMiscParameterBuffer header = {
123 size_t buffer_size = sizeof(header) + len;
124 av_assert0(buffer_size <= sizeof(buffer));
126 memcpy(buffer, &header, sizeof(header));
127 memcpy(buffer + sizeof(header), data, len);
129 return vaapi_encode_make_param_buffer(avctx, pic,
130 VAEncMiscParameterBufferType,
131 buffer, buffer_size);
134 static int vaapi_encode_wait(AVCodecContext *avctx,
135 VAAPIEncodePicture *pic)
137 VAAPIEncodeContext *ctx = avctx->priv_data;
140 av_assert0(pic->encode_issued);
142 if (pic->encode_complete) {
143 // Already waited for this picture.
147 av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
148 "(input surface %#x).\n", pic->display_order,
149 pic->encode_order, pic->input_surface);
151 vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
152 if (vas != VA_STATUS_SUCCESS) {
153 av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
154 "%d (%s).\n", vas, vaErrorStr(vas));
158 // Input is definitely finished with now.
159 av_frame_free(&pic->input_image);
161 pic->encode_complete = 1;
165 static int vaapi_encode_issue(AVCodecContext *avctx,
166 VAAPIEncodePicture *pic)
168 VAAPIEncodeContext *ctx = avctx->priv_data;
169 VAAPIEncodeSlice *slice;
172 char data[MAX_PARAM_BUFFER_SIZE];
174 av_unused AVFrameSideData *sd;
176 av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
177 "as type %s.\n", pic->display_order, pic->encode_order,
178 picture_type_name[pic->type]);
179 if (pic->nb_refs == 0) {
180 av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
182 av_log(avctx, AV_LOG_DEBUG, "Refers to:");
183 for (i = 0; i < pic->nb_refs; i++) {
184 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
185 pic->refs[i]->display_order, pic->refs[i]->encode_order);
187 av_log(avctx, AV_LOG_DEBUG, ".\n");
190 av_assert0(!pic->encode_issued);
191 for (i = 0; i < pic->nb_refs; i++) {
192 av_assert0(pic->refs[i]);
193 av_assert0(pic->refs[i]->encode_issued);
196 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
198 pic->recon_image = av_frame_alloc();
199 if (!pic->recon_image) {
200 err = AVERROR(ENOMEM);
204 err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
206 err = AVERROR(ENOMEM);
209 pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
210 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
212 pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
213 if (!pic->output_buffer_ref) {
214 err = AVERROR(ENOMEM);
217 pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
218 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
221 if (ctx->codec->picture_params_size > 0) {
222 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
223 if (!pic->codec_picture_params)
225 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
226 ctx->codec->picture_params_size);
228 av_assert0(!ctx->codec_picture_params);
231 pic->nb_param_buffers = 0;
233 if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
234 err = vaapi_encode_make_param_buffer(avctx, pic,
235 VAEncSequenceParameterBufferType,
236 ctx->codec_sequence_params,
237 ctx->codec->sequence_params_size);
242 if (pic->type == PICTURE_TYPE_IDR) {
243 for (i = 0; i < ctx->nb_global_params; i++) {
244 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
245 ctx->global_params_type[i],
246 ctx->global_params[i],
247 ctx->global_params_size[i]);
253 if (ctx->codec->init_picture_params) {
254 err = ctx->codec->init_picture_params(avctx, pic);
256 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
257 "parameters: %d.\n", err);
260 err = vaapi_encode_make_param_buffer(avctx, pic,
261 VAEncPictureParameterBufferType,
262 pic->codec_picture_params,
263 ctx->codec->picture_params_size);
268 if (pic->type == PICTURE_TYPE_IDR) {
269 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
270 ctx->codec->write_sequence_header) {
271 bit_len = 8 * sizeof(data);
272 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
274 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
275 "header: %d.\n", err);
278 err = vaapi_encode_make_packed_header(avctx, pic,
279 ctx->codec->sequence_header_type,
286 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
287 ctx->codec->write_picture_header) {
288 bit_len = 8 * sizeof(data);
289 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
291 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
292 "header: %d.\n", err);
295 err = vaapi_encode_make_packed_header(avctx, pic,
296 ctx->codec->picture_header_type,
302 if (ctx->codec->write_extra_buffer) {
304 size_t len = sizeof(data);
306 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
308 if (err == AVERROR_EOF)
311 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
312 "buffer %d: %d.\n", i, err);
316 err = vaapi_encode_make_param_buffer(avctx, pic, type,
323 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
324 ctx->codec->write_extra_header) {
327 bit_len = 8 * sizeof(data);
328 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
330 if (err == AVERROR_EOF)
333 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
334 "header %d: %d.\n", i, err);
338 err = vaapi_encode_make_packed_header(avctx, pic, type,
345 if (pic->nb_slices == 0)
346 pic->nb_slices = ctx->nb_slices;
347 if (pic->nb_slices > 0) {
350 pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
352 err = AVERROR(ENOMEM);
356 for (i = 0; i < pic->nb_slices; i++)
357 pic->slices[i].row_size = ctx->slice_size;
359 rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
361 // Place rounding error at top and bottom of frame.
362 av_assert0(rounding < pic->nb_slices);
363 // Some Intel drivers contain a bug where the encoder will fail
364 // if the last slice is smaller than the one before it. Since
365 // that's straightforward to avoid here, just do so.
367 for (i = 0; i < rounding; i++)
368 ++pic->slices[i].row_size;
370 for (i = 0; i < (rounding + 1) / 2; i++)
371 ++pic->slices[pic->nb_slices - i - 1].row_size;
372 for (i = 0; i < rounding / 2; i++)
373 ++pic->slices[i].row_size;
375 } else if (rounding < 0) {
376 // Remove rounding error from last slice only.
377 av_assert0(rounding < ctx->slice_size);
378 pic->slices[pic->nb_slices - 1].row_size += rounding;
381 for (i = 0; i < pic->nb_slices; i++) {
382 slice = &pic->slices[i];
385 slice->row_start = 0;
386 slice->block_start = 0;
388 const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
389 slice->row_start = prev->row_start + prev->row_size;
390 slice->block_start = prev->block_start + prev->block_size;
392 slice->block_size = slice->row_size * ctx->slice_block_cols;
394 av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
395 "%d-%d (%d blocks).\n", i, slice->row_start,
396 slice->row_start + slice->row_size - 1, slice->row_size,
397 slice->block_start, slice->block_start + slice->block_size - 1,
400 if (ctx->codec->slice_params_size > 0) {
401 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
402 if (!slice->codec_slice_params) {
403 err = AVERROR(ENOMEM);
408 if (ctx->codec->init_slice_params) {
409 err = ctx->codec->init_slice_params(avctx, pic, slice);
411 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
412 "parameters: %d.\n", err);
417 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
418 ctx->codec->write_slice_header) {
419 bit_len = 8 * sizeof(data);
420 err = ctx->codec->write_slice_header(avctx, pic, slice,
423 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
424 "header: %d.\n", err);
427 err = vaapi_encode_make_packed_header(avctx, pic,
428 ctx->codec->slice_header_type,
434 if (ctx->codec->init_slice_params) {
435 err = vaapi_encode_make_param_buffer(avctx, pic,
436 VAEncSliceParameterBufferType,
437 slice->codec_slice_params,
438 ctx->codec->slice_params_size);
444 #if VA_CHECK_VERSION(1, 0, 0)
445 sd = av_frame_get_side_data(pic->input_image,
446 AV_FRAME_DATA_REGIONS_OF_INTEREST);
447 if (sd && ctx->roi_allowed) {
448 const AVRegionOfInterest *roi;
450 VAEncMiscParameterBufferROI param_roi;
453 roi = (const AVRegionOfInterest*)sd->data;
454 roi_size = roi->self_size;
455 av_assert0(roi_size && sd->size % roi_size == 0);
456 nb_roi = sd->size / roi_size;
457 if (nb_roi > ctx->roi_max_regions) {
458 if (!ctx->roi_warned) {
459 av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
460 "supported by driver (%d > %d).\n",
461 nb_roi, ctx->roi_max_regions);
464 nb_roi = ctx->roi_max_regions;
467 pic->roi = av_mallocz_array(nb_roi, sizeof(*pic->roi));
469 err = AVERROR(ENOMEM);
472 // For overlapping regions, the first in the array takes priority.
473 for (i = 0; i < nb_roi; i++) {
474 roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
476 av_assert0(roi->qoffset.den != 0);
477 v = roi->qoffset.num * ctx->roi_quant_range / roi->qoffset.den;
478 av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
479 roi->top, roi->left, roi->bottom, roi->right, v);
481 pic->roi[i] = (VAEncROI) {
485 .width = roi->right - roi->left,
486 .height = roi->bottom - roi->top,
488 .roi_value = av_clip_int8(v),
492 param_roi = (VAEncMiscParameterBufferROI) {
494 .max_delta_qp = INT8_MAX,
495 .min_delta_qp = INT8_MIN,
497 .roi_flags.bits.roi_value_is_qp_delta = 1,
500 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
501 VAEncMiscParameterTypeROI,
509 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
511 if (vas != VA_STATUS_SUCCESS) {
512 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
513 "%d (%s).\n", vas, vaErrorStr(vas));
515 goto fail_with_picture;
518 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
519 pic->param_buffers, pic->nb_param_buffers);
520 if (vas != VA_STATUS_SUCCESS) {
521 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
522 "%d (%s).\n", vas, vaErrorStr(vas));
524 goto fail_with_picture;
527 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
528 if (vas != VA_STATUS_SUCCESS) {
529 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
530 "%d (%s).\n", vas, vaErrorStr(vas));
532 // vaRenderPicture() has been called here, so we should not destroy
533 // the parameter buffers unless separate destruction is required.
534 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
535 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
541 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
542 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
543 for (i = 0; i < pic->nb_param_buffers; i++) {
544 vas = vaDestroyBuffer(ctx->hwctx->display,
545 pic->param_buffers[i]);
546 if (vas != VA_STATUS_SUCCESS) {
547 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
548 "param buffer %#x: %d (%s).\n",
549 pic->param_buffers[i], vas, vaErrorStr(vas));
555 pic->encode_issued = 1;
560 vaEndPicture(ctx->hwctx->display, ctx->va_context);
562 for(i = 0; i < pic->nb_param_buffers; i++)
563 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
564 for (i = 0; i < pic->nb_slices; i++) {
566 av_freep(&pic->slices[i].priv_data);
567 av_freep(&pic->slices[i].codec_slice_params);
571 av_freep(&pic->codec_picture_params);
572 av_freep(&pic->param_buffers);
573 av_freep(&pic->slices);
575 av_frame_free(&pic->recon_image);
576 av_buffer_unref(&pic->output_buffer_ref);
577 pic->output_buffer = VA_INVALID_ID;
581 static int vaapi_encode_output(AVCodecContext *avctx,
582 VAAPIEncodePicture *pic, AVPacket *pkt)
584 VAAPIEncodeContext *ctx = avctx->priv_data;
585 VACodedBufferSegment *buf_list, *buf;
591 err = vaapi_encode_wait(avctx, pic);
596 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
598 if (vas != VA_STATUS_SUCCESS) {
599 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
600 "%d (%s).\n", vas, vaErrorStr(vas));
605 for (buf = buf_list; buf; buf = buf->next)
606 total_size += buf->size;
608 err = av_new_packet(pkt, total_size);
614 for (buf = buf_list; buf; buf = buf->next) {
615 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
616 "(status %08x).\n", buf->size, buf->status);
618 memcpy(ptr, buf->buf, buf->size);
622 if (pic->type == PICTURE_TYPE_IDR)
623 pkt->flags |= AV_PKT_FLAG_KEY;
627 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
628 if (vas != VA_STATUS_SUCCESS) {
629 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
630 "%d (%s).\n", vas, vaErrorStr(vas));
635 av_buffer_unref(&pic->output_buffer_ref);
636 pic->output_buffer = VA_INVALID_ID;
638 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
639 pic->display_order, pic->encode_order);
643 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
645 av_buffer_unref(&pic->output_buffer_ref);
646 pic->output_buffer = VA_INVALID_ID;
650 static int vaapi_encode_discard(AVCodecContext *avctx,
651 VAAPIEncodePicture *pic)
653 vaapi_encode_wait(avctx, pic);
655 if (pic->output_buffer_ref) {
656 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
657 "%"PRId64"/%"PRId64".\n",
658 pic->display_order, pic->encode_order);
660 av_buffer_unref(&pic->output_buffer_ref);
661 pic->output_buffer = VA_INVALID_ID;
667 static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
669 VAAPIEncodeContext *ctx = avctx->priv_data;
670 VAAPIEncodePicture *pic;
672 pic = av_mallocz(sizeof(*pic));
676 if (ctx->codec->picture_priv_data_size > 0) {
677 pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
678 if (!pic->priv_data) {
684 pic->input_surface = VA_INVALID_ID;
685 pic->recon_surface = VA_INVALID_ID;
686 pic->output_buffer = VA_INVALID_ID;
691 static int vaapi_encode_free(AVCodecContext *avctx,
692 VAAPIEncodePicture *pic)
696 if (pic->encode_issued)
697 vaapi_encode_discard(avctx, pic);
699 for (i = 0; i < pic->nb_slices; i++) {
701 av_freep(&pic->slices[i].priv_data);
702 av_freep(&pic->slices[i].codec_slice_params);
705 av_freep(&pic->codec_picture_params);
707 av_frame_free(&pic->input_image);
708 av_frame_free(&pic->recon_image);
710 av_freep(&pic->param_buffers);
711 av_freep(&pic->slices);
712 // Output buffer should already be destroyed.
713 av_assert0(pic->output_buffer == VA_INVALID_ID);
715 av_freep(&pic->priv_data);
716 av_freep(&pic->codec_picture_params);
724 static void vaapi_encode_add_ref(AVCodecContext *avctx,
725 VAAPIEncodePicture *pic,
726 VAAPIEncodePicture *target,
727 int is_ref, int in_dpb, int prev)
732 av_assert0(pic != target);
733 av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
734 pic->refs[pic->nb_refs++] = target;
739 av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
740 pic->dpb[pic->nb_dpb_pics++] = target;
745 av_assert0(!pic->prev);
750 target->ref_count[0] += refs;
751 target->ref_count[1] += refs;
754 static void vaapi_encode_remove_refs(AVCodecContext *avctx,
755 VAAPIEncodePicture *pic,
760 if (pic->ref_removed[level])
763 for (i = 0; i < pic->nb_refs; i++) {
764 av_assert0(pic->refs[i]);
765 --pic->refs[i]->ref_count[level];
766 av_assert0(pic->refs[i]->ref_count[level] >= 0);
769 for (i = 0; i < pic->nb_dpb_pics; i++) {
770 av_assert0(pic->dpb[i]);
771 --pic->dpb[i]->ref_count[level];
772 av_assert0(pic->dpb[i]->ref_count[level] >= 0);
775 av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
777 --pic->prev->ref_count[level];
778 av_assert0(pic->prev->ref_count[level] >= 0);
781 pic->ref_removed[level] = 1;
784 static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
785 VAAPIEncodePicture *start,
786 VAAPIEncodePicture *end,
787 VAAPIEncodePicture *prev,
789 VAAPIEncodePicture **last)
791 VAAPIEncodeContext *ctx = avctx->priv_data;
792 VAAPIEncodePicture *pic, *next, *ref;
795 av_assert0(start && end && start != end && start->next != end);
797 // If we are at the maximum depth then encode all pictures as
798 // non-referenced B-pictures. Also do this if there is exactly one
799 // picture left, since there will be nothing to reference it.
800 if (current_depth == ctx->max_b_depth || start->next->next == end) {
801 for (pic = start->next; pic; pic = pic->next) {
804 pic->type = PICTURE_TYPE_B;
805 pic->b_depth = current_depth;
807 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
808 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
809 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
811 for (ref = end->refs[1]; ref; ref = ref->refs[1])
812 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
817 // Split the current list at the midpoint with a referenced
818 // B-picture, then descend into each side separately.
820 for (pic = start->next; pic != end; pic = pic->next)
822 for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
824 pic->type = PICTURE_TYPE_B;
825 pic->b_depth = current_depth;
827 pic->is_reference = 1;
829 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
830 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
831 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
832 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
834 for (ref = end->refs[1]; ref; ref = ref->refs[1])
835 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
838 vaapi_encode_set_b_pictures(avctx, start, pic, pic,
839 current_depth + 1, &next);
843 vaapi_encode_set_b_pictures(avctx, pic, end, next,
844 current_depth + 1, last);
848 static int vaapi_encode_pick_next(AVCodecContext *avctx,
849 VAAPIEncodePicture **pic_out)
851 VAAPIEncodeContext *ctx = avctx->priv_data;
852 VAAPIEncodePicture *pic = NULL, *next, *start;
853 int i, b_counter, closed_gop_end;
855 // If there are any B-frames already queued, the next one to encode
856 // is the earliest not-yet-issued frame for which all references are
858 for (pic = ctx->pic_start; pic; pic = pic->next) {
859 if (pic->encode_issued)
861 if (pic->type != PICTURE_TYPE_B)
863 for (i = 0; i < pic->nb_refs; i++) {
864 if (!pic->refs[i]->encode_issued)
867 if (i == pic->nb_refs)
872 av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
873 "encode next.\n", pic->b_depth);
878 // Find the B-per-Pth available picture to become the next picture
882 closed_gop_end = ctx->closed_gop ||
883 ctx->idr_counter == ctx->gop_per_idr;
884 for (pic = ctx->pic_start; pic; pic = next) {
886 if (pic->encode_issued) {
890 // If the next available picture is force-IDR, encode it to start
891 // a new GOP immediately.
894 if (b_counter == ctx->b_per_p)
896 // If this picture ends a closed GOP or starts a new GOP then it
897 // needs to be in the top layer.
898 if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
900 // If the picture after this one is force-IDR, we need to encode
901 // this one in the top layer.
902 if (next && next->force_idr)
907 // At the end of the stream the last picture must be in the top layer.
908 if (!pic && ctx->end_of_stream) {
911 if (pic->encode_issued)
916 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
917 "need more input for reference pictures.\n");
918 return AVERROR(EAGAIN);
920 if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
921 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
922 "need more input for timestamps.\n");
923 return AVERROR(EAGAIN);
926 if (pic->force_idr) {
927 av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
929 pic->type = PICTURE_TYPE_IDR;
930 ctx->idr_counter = 1;
931 ctx->gop_counter = 1;
933 } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
934 if (ctx->idr_counter == ctx->gop_per_idr) {
935 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
937 pic->type = PICTURE_TYPE_IDR;
938 ctx->idr_counter = 1;
940 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
942 pic->type = PICTURE_TYPE_I;
945 ctx->gop_counter = 1;
948 if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
949 av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
952 av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
955 pic->type = PICTURE_TYPE_P;
957 ctx->gop_counter += 1 + b_counter;
959 pic->is_reference = 1;
962 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
963 if (pic->type != PICTURE_TYPE_IDR) {
964 vaapi_encode_add_ref(avctx, pic, start,
965 pic->type == PICTURE_TYPE_P,
967 vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
970 --ctx->next_prev->ref_count[0];
973 vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
976 ctx->next_prev = pic;
978 ++ctx->next_prev->ref_count[0];
982 static int vaapi_encode_clear_old(AVCodecContext *avctx)
984 VAAPIEncodeContext *ctx = avctx->priv_data;
985 VAAPIEncodePicture *pic, *prev, *next;
987 av_assert0(ctx->pic_start);
989 // Remove direct references once each picture is complete.
990 for (pic = ctx->pic_start; pic; pic = pic->next) {
991 if (pic->encode_complete && pic->next)
992 vaapi_encode_remove_refs(avctx, pic, 0);
995 // Remove indirect references once a picture has no direct references.
996 for (pic = ctx->pic_start; pic; pic = pic->next) {
997 if (pic->encode_complete && pic->ref_count[0] == 0)
998 vaapi_encode_remove_refs(avctx, pic, 1);
1001 // Clear out all complete pictures with no remaining references.
1003 for (pic = ctx->pic_start; pic; pic = next) {
1005 if (pic->encode_complete && pic->ref_count[1] == 0) {
1006 av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
1010 ctx->pic_start = next;
1011 vaapi_encode_free(avctx, pic);
1020 static int vaapi_encode_check_frame(AVCodecContext *avctx,
1021 const AVFrame *frame)
1023 VAAPIEncodeContext *ctx = avctx->priv_data;
1025 if ((frame->crop_top || frame->crop_bottom ||
1026 frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
1027 av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
1028 "frames ignored due to lack of API support.\n");
1029 ctx->crop_warned = 1;
1032 if (!ctx->roi_allowed) {
1033 AVFrameSideData *sd =
1034 av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
1036 if (sd && !ctx->roi_warned) {
1037 av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
1038 "frames ignored due to lack of driver support.\n");
1039 ctx->roi_warned = 1;
1046 int ff_vaapi_encode_send_frame(AVCodecContext *avctx, const AVFrame *frame)
1048 VAAPIEncodeContext *ctx = avctx->priv_data;
1049 VAAPIEncodePicture *pic;
1053 av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
1054 frame->width, frame->height, frame->pts);
1056 err = vaapi_encode_check_frame(avctx, frame);
1060 pic = vaapi_encode_alloc(avctx);
1062 return AVERROR(ENOMEM);
1064 pic->input_image = av_frame_alloc();
1065 if (!pic->input_image) {
1066 err = AVERROR(ENOMEM);
1069 err = av_frame_ref(pic->input_image, frame);
1073 if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
1076 pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
1077 pic->pts = frame->pts;
1079 if (ctx->input_order == 0)
1080 ctx->first_pts = pic->pts;
1081 if (ctx->input_order == ctx->decode_delay)
1082 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
1083 if (ctx->output_delay > 0)
1084 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
1086 pic->display_order = ctx->input_order;
1089 if (ctx->pic_start) {
1090 ctx->pic_end->next = pic;
1093 ctx->pic_start = pic;
1098 ctx->end_of_stream = 1;
1100 // Fix timestamps if we hit end-of-stream before the initial decode
1101 // delay has elapsed.
1102 if (ctx->input_order < ctx->decode_delay)
1103 ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
1109 vaapi_encode_free(avctx, pic);
1113 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
1115 VAAPIEncodeContext *ctx = avctx->priv_data;
1116 VAAPIEncodePicture *pic;
1119 if (!ctx->pic_start) {
1120 if (ctx->end_of_stream)
1123 return AVERROR(EAGAIN);
1127 err = vaapi_encode_pick_next(avctx, &pic);
1132 pic->encode_order = ctx->encode_order++;
1134 err = vaapi_encode_issue(avctx, pic);
1136 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1140 err = vaapi_encode_output(avctx, pic, pkt);
1142 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1146 if (ctx->output_delay == 0) {
1147 pkt->dts = pkt->pts;
1148 } else if (pic->encode_order < ctx->decode_delay) {
1149 if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1150 pkt->dts = INT64_MIN;
1152 pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1154 pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1155 (3 * ctx->output_delay)];
1157 av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1158 pkt->pts, pkt->dts);
1160 ctx->output_order = pic->encode_order;
1161 vaapi_encode_clear_old(avctx);
1167 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
1168 void *buffer, size_t size)
1170 VAAPIEncodeContext *ctx = avctx->priv_data;
1172 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1174 ctx->global_params_type[ctx->nb_global_params] = type;
1175 ctx->global_params [ctx->nb_global_params] = buffer;
1176 ctx->global_params_size[ctx->nb_global_params] = size;
1178 ++ctx->nb_global_params;
1181 typedef struct VAAPIEncodeRTFormat {
1188 } VAAPIEncodeRTFormat;
1190 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1191 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
1192 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
1193 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
1194 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
1195 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
1196 #if VA_CHECK_VERSION(0, 38, 1)
1197 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1201 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1202 VAEntrypointEncSlice,
1203 VAEntrypointEncPicture,
1204 #if VA_CHECK_VERSION(0, 39, 2)
1205 VAEntrypointEncSliceLP,
1209 #if VA_CHECK_VERSION(0, 39, 2)
1210 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1211 VAEntrypointEncSliceLP,
1216 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1218 VAAPIEncodeContext *ctx = avctx->priv_data;
1219 VAProfile *va_profiles = NULL;
1220 VAEntrypoint *va_entrypoints = NULL;
1222 const VAEntrypoint *usable_entrypoints;
1223 const VAAPIEncodeProfile *profile;
1224 const AVPixFmtDescriptor *desc;
1225 VAConfigAttrib rt_format_attr;
1226 const VAAPIEncodeRTFormat *rt_format;
1227 const char *profile_string, *entrypoint_string;
1228 int i, j, n, depth, err;
1231 if (ctx->low_power) {
1232 #if VA_CHECK_VERSION(0, 39, 2)
1233 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1235 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1236 "supported with this VAAPI version.\n");
1237 return AVERROR(EINVAL);
1240 usable_entrypoints = vaapi_encode_entrypoints_normal;
1243 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1245 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1246 ctx->input_frames->sw_format);
1247 return AVERROR(EINVAL);
1249 depth = desc->comp[0].depth;
1250 for (i = 1; i < desc->nb_components; i++) {
1251 if (desc->comp[i].depth != depth) {
1252 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1254 return AVERROR(EINVAL);
1257 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1260 n = vaMaxNumProfiles(ctx->hwctx->display);
1261 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1263 err = AVERROR(ENOMEM);
1266 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1267 if (vas != VA_STATUS_SUCCESS) {
1268 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1269 vas, vaErrorStr(vas));
1270 err = AVERROR_EXTERNAL;
1274 av_assert0(ctx->codec->profiles);
1275 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1276 FF_PROFILE_UNKNOWN); i++) {
1277 profile = &ctx->codec->profiles[i];
1278 if (depth != profile->depth ||
1279 desc->nb_components != profile->nb_components)
1281 if (desc->nb_components > 1 &&
1282 (desc->log2_chroma_w != profile->log2_chroma_w ||
1283 desc->log2_chroma_h != profile->log2_chroma_h))
1285 if (avctx->profile != profile->av_profile &&
1286 avctx->profile != FF_PROFILE_UNKNOWN)
1289 #if VA_CHECK_VERSION(1, 0, 0)
1290 profile_string = vaProfileStr(profile->va_profile);
1292 profile_string = "(no profile names)";
1295 for (j = 0; j < n; j++) {
1296 if (va_profiles[j] == profile->va_profile)
1300 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1301 "is not supported by driver.\n", profile_string,
1302 profile->va_profile);
1306 ctx->profile = profile;
1309 if (!ctx->profile) {
1310 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1311 err = AVERROR(ENOSYS);
1315 avctx->profile = profile->av_profile;
1316 ctx->va_profile = profile->va_profile;
1317 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1318 profile_string, ctx->va_profile);
1320 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1321 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1322 if (!va_entrypoints) {
1323 err = AVERROR(ENOMEM);
1326 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1327 va_entrypoints, &n);
1328 if (vas != VA_STATUS_SUCCESS) {
1329 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1330 "profile %s (%d): %d (%s).\n", profile_string,
1331 ctx->va_profile, vas, vaErrorStr(vas));
1332 err = AVERROR_EXTERNAL;
1336 for (i = 0; i < n; i++) {
1337 for (j = 0; usable_entrypoints[j]; j++) {
1338 if (va_entrypoints[i] == usable_entrypoints[j])
1341 if (usable_entrypoints[j])
1345 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1346 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1347 err = AVERROR(ENOSYS);
1351 ctx->va_entrypoint = va_entrypoints[i];
1352 #if VA_CHECK_VERSION(1, 0, 0)
1353 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1355 entrypoint_string = "(no entrypoint names)";
1357 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1358 entrypoint_string, ctx->va_entrypoint);
1360 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1361 rt_format = &vaapi_encode_rt_formats[i];
1362 if (rt_format->depth == depth &&
1363 rt_format->nb_components == profile->nb_components &&
1364 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1365 rt_format->log2_chroma_h == profile->log2_chroma_h)
1368 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1369 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1370 "found for profile %s (%d) entrypoint %s (%d).\n",
1371 profile_string, ctx->va_profile,
1372 entrypoint_string, ctx->va_entrypoint);
1373 err = AVERROR(ENOSYS);
1377 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1378 vas = vaGetConfigAttributes(ctx->hwctx->display,
1379 ctx->va_profile, ctx->va_entrypoint,
1380 &rt_format_attr, 1);
1381 if (vas != VA_STATUS_SUCCESS) {
1382 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1383 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1384 err = AVERROR_EXTERNAL;
1388 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1389 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1390 "supported by driver: assuming surface RT format %s "
1391 "is valid.\n", rt_format->name);
1392 } else if (!(rt_format_attr.value & rt_format->value)) {
1393 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1394 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1395 rt_format->name, profile_string, ctx->va_profile,
1396 entrypoint_string, ctx->va_entrypoint);
1397 err = AVERROR(ENOSYS);
1400 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1401 "format %s (%#x).\n", rt_format->name, rt_format->value);
1402 ctx->config_attributes[ctx->nb_config_attributes++] =
1404 .type = VAConfigAttribRTFormat,
1405 .value = rt_format->value,
1411 av_freep(&va_profiles);
1412 av_freep(&va_entrypoints);
1416 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1418 // | Maxrate | HRD/VBV
1420 { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
1421 { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
1422 { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
1423 #if VA_CHECK_VERSION(1, 1, 0)
1424 { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
1426 { RC_MODE_ICQ, "ICQ", 0 },
1428 #if VA_CHECK_VERSION(1, 3, 0)
1429 { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
1430 { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
1432 { RC_MODE_QVBR, "QVBR", 0 },
1433 { RC_MODE_AVBR, "AVBR", 0 },
1437 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1439 VAAPIEncodeContext *ctx = avctx->priv_data;
1440 uint32_t supported_va_rc_modes;
1441 const VAAPIEncodeRCMode *rc_mode;
1442 int64_t rc_bits_per_second;
1443 int rc_target_percentage;
1446 int64_t hrd_buffer_size;
1447 int64_t hrd_initial_buffer_fullness;
1449 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1451 char supported_rc_modes_string[64];
1453 vas = vaGetConfigAttributes(ctx->hwctx->display,
1454 ctx->va_profile, ctx->va_entrypoint,
1456 if (vas != VA_STATUS_SUCCESS) {
1457 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1458 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1459 return AVERROR_EXTERNAL;
1461 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1462 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1463 "supported rate control modes: assuming CQP only.\n");
1464 supported_va_rc_modes = VA_RC_CQP;
1465 strcpy(supported_rc_modes_string, "unknown");
1467 char *str = supported_rc_modes_string;
1468 size_t len = sizeof(supported_rc_modes_string);
1469 int i, first = 1, res;
1471 supported_va_rc_modes = rc_attr.value;
1472 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1473 rc_mode = &vaapi_encode_rc_modes[i];
1474 if (supported_va_rc_modes & rc_mode->va_mode) {
1475 res = snprintf(str, len, "%s%s",
1476 first ? "" : ", ", rc_mode->name);
1489 av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1490 supported_rc_modes_string);
1493 // Rate control mode selection:
1494 // * If the user has set a mode explicitly with the rc_mode option,
1495 // use it and fail if it is not available.
1496 // * If an explicit QP option has been set, use CQP.
1497 // * If the codec is CQ-only, use CQP.
1498 // * If the QSCALE avcodec option is set, use CQP.
1499 // * If bitrate and quality are both set, try QVBR.
1500 // * If quality is set, try ICQ, then CQP.
1501 // * If bitrate and maxrate are set and have the same value, try CBR.
1502 // * If a bitrate is set, try AVBR, then VBR, then CBR.
1503 // * If no bitrate is set, try ICQ, then CQP.
1505 #define TRY_RC_MODE(mode, fail) do { \
1506 rc_mode = &vaapi_encode_rc_modes[mode]; \
1507 if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1509 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1510 "RC mode (supported modes: %s).\n", rc_mode->name, \
1511 supported_rc_modes_string); \
1512 return AVERROR(EINVAL); \
1514 av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1515 "RC mode.\n", rc_mode->name); \
1518 goto rc_mode_found; \
1522 if (ctx->explicit_rc_mode)
1523 TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1525 if (ctx->explicit_qp)
1526 TRY_RC_MODE(RC_MODE_CQP, 1);
1528 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1529 TRY_RC_MODE(RC_MODE_CQP, 1);
1531 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1532 TRY_RC_MODE(RC_MODE_CQP, 1);
1534 if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1535 TRY_RC_MODE(RC_MODE_QVBR, 0);
1537 if (avctx->global_quality > 0) {
1538 TRY_RC_MODE(RC_MODE_ICQ, 0);
1539 TRY_RC_MODE(RC_MODE_CQP, 0);
1542 if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1543 TRY_RC_MODE(RC_MODE_CBR, 0);
1545 if (avctx->bit_rate > 0) {
1546 TRY_RC_MODE(RC_MODE_AVBR, 0);
1547 TRY_RC_MODE(RC_MODE_VBR, 0);
1548 TRY_RC_MODE(RC_MODE_CBR, 0);
1550 TRY_RC_MODE(RC_MODE_ICQ, 0);
1551 TRY_RC_MODE(RC_MODE_CQP, 0);
1554 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1555 "RC mode compatible with selected options "
1556 "(supported modes: %s).\n", supported_rc_modes_string);
1557 return AVERROR(EINVAL);
1560 if (rc_mode->bitrate) {
1561 if (avctx->bit_rate <= 0) {
1562 av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1563 "RC mode.\n", rc_mode->name);
1564 return AVERROR(EINVAL);
1567 if (rc_mode->mode == RC_MODE_AVBR) {
1568 // For maximum confusion AVBR is hacked into the existing API
1569 // by overloading some of the fields with completely different
1572 // Target percentage does not apply in AVBR mode.
1573 rc_bits_per_second = avctx->bit_rate;
1575 // Accuracy tolerance range for meeting the specified target
1576 // bitrate. It's very unclear how this is actually intended
1577 // to work - since we do want to get the specified bitrate,
1578 // set the accuracy to 100% for now.
1579 rc_target_percentage = 100;
1581 // Convergence period in frames. The GOP size reflects the
1582 // user's intended block size for cutting, so reusing that
1583 // as the convergence period seems a reasonable default.
1584 rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1586 } else if (rc_mode->maxrate) {
1587 if (avctx->rc_max_rate > 0) {
1588 if (avctx->rc_max_rate < avctx->bit_rate) {
1589 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1590 "bitrate (%"PRId64") must not be greater than "
1591 "maxrate (%"PRId64").\n", avctx->bit_rate,
1592 avctx->rc_max_rate);
1593 return AVERROR(EINVAL);
1595 rc_bits_per_second = avctx->rc_max_rate;
1596 rc_target_percentage = (avctx->bit_rate * 100) /
1599 // We only have a target bitrate, but this mode requires
1600 // that a maximum rate be supplied as well. Since the
1601 // user does not want this to be a constraint, arbitrarily
1602 // pick a maximum rate of double the target rate.
1603 rc_bits_per_second = 2 * avctx->bit_rate;
1604 rc_target_percentage = 50;
1607 if (avctx->rc_max_rate > avctx->bit_rate) {
1608 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1609 "in %s RC mode.\n", rc_mode->name);
1611 rc_bits_per_second = avctx->bit_rate;
1612 rc_target_percentage = 100;
1615 rc_bits_per_second = 0;
1616 rc_target_percentage = 100;
1619 if (rc_mode->quality) {
1620 if (ctx->explicit_qp) {
1621 rc_quality = ctx->explicit_qp;
1622 } else if (avctx->global_quality > 0) {
1623 rc_quality = avctx->global_quality;
1625 rc_quality = ctx->codec->default_quality;
1626 av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1627 "using default (%d).\n", rc_quality);
1634 if (avctx->rc_buffer_size)
1635 hrd_buffer_size = avctx->rc_buffer_size;
1636 else if (avctx->rc_max_rate > 0)
1637 hrd_buffer_size = avctx->rc_max_rate;
1639 hrd_buffer_size = avctx->bit_rate;
1640 if (avctx->rc_initial_buffer_occupancy) {
1641 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1642 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1643 "must have initial buffer size (%d) <= "
1644 "buffer size (%"PRId64").\n",
1645 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1646 return AVERROR(EINVAL);
1648 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1650 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1653 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1655 if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1656 av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1657 "in %s RC mode.\n", rc_mode->name);
1660 hrd_buffer_size = 0;
1661 hrd_initial_buffer_fullness = 0;
1663 if (rc_mode->mode != RC_MODE_AVBR) {
1664 // Already set (with completely different meaning) for AVBR.
1665 rc_window_size = 1000;
1669 if (rc_bits_per_second > UINT32_MAX ||
1670 hrd_buffer_size > UINT32_MAX ||
1671 hrd_initial_buffer_fullness > UINT32_MAX) {
1672 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1673 "greater are not supported by VAAPI.\n");
1674 return AVERROR(EINVAL);
1677 ctx->rc_mode = rc_mode;
1678 ctx->rc_quality = rc_quality;
1679 ctx->va_rc_mode = rc_mode->va_mode;
1680 ctx->va_bit_rate = rc_bits_per_second;
1682 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1683 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1684 // This driver does not want the RC mode attribute to be set.
1686 ctx->config_attributes[ctx->nb_config_attributes++] =
1688 .type = VAConfigAttribRateControl,
1689 .value = ctx->va_rc_mode,
1693 if (rc_mode->quality)
1694 av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1696 if (rc_mode->va_mode != VA_RC_CQP) {
1697 if (rc_mode->mode == RC_MODE_AVBR) {
1698 av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1699 "converging in %d frames with %d%% accuracy.\n",
1700 rc_bits_per_second, rc_window_size,
1701 rc_target_percentage);
1702 } else if (rc_mode->bitrate) {
1703 av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1704 "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1705 rc_bits_per_second, rc_window_size);
1708 ctx->rc_params = (VAEncMiscParameterRateControl) {
1709 .bits_per_second = rc_bits_per_second,
1710 .target_percentage = rc_target_percentage,
1711 .window_size = rc_window_size,
1713 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1714 .basic_unit_size = 0,
1715 #if VA_CHECK_VERSION(1, 1, 0)
1716 .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1717 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1719 #if VA_CHECK_VERSION(1, 3, 0)
1720 .quality_factor = rc_quality,
1723 vaapi_encode_add_global_param(avctx,
1724 VAEncMiscParameterTypeRateControl,
1726 sizeof(ctx->rc_params));
1730 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1731 "initial fullness %"PRId64" bits.\n",
1732 hrd_buffer_size, hrd_initial_buffer_fullness);
1734 ctx->hrd_params = (VAEncMiscParameterHRD) {
1735 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1736 .buffer_size = hrd_buffer_size,
1738 vaapi_encode_add_global_param(avctx,
1739 VAEncMiscParameterTypeHRD,
1741 sizeof(ctx->hrd_params));
1744 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1745 av_reduce(&fr_num, &fr_den,
1746 avctx->framerate.num, avctx->framerate.den, 65535);
1748 av_reduce(&fr_num, &fr_den,
1749 avctx->time_base.den, avctx->time_base.num, 65535);
1751 av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1752 fr_num, fr_den, (double)fr_num / fr_den);
1754 ctx->fr_params = (VAEncMiscParameterFrameRate) {
1755 .framerate = (unsigned int)fr_den << 16 | fr_num,
1757 #if VA_CHECK_VERSION(0, 40, 0)
1758 vaapi_encode_add_global_param(avctx,
1759 VAEncMiscParameterTypeFrameRate,
1761 sizeof(ctx->fr_params));
1767 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1769 VAAPIEncodeContext *ctx = avctx->priv_data;
1771 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1772 uint32_t ref_l0, ref_l1;
1774 vas = vaGetConfigAttributes(ctx->hwctx->display,
1778 if (vas != VA_STATUS_SUCCESS) {
1779 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1780 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1781 return AVERROR_EXTERNAL;
1784 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1785 ref_l0 = ref_l1 = 0;
1787 ref_l0 = attr.value & 0xffff;
1788 ref_l1 = attr.value >> 16 & 0xffff;
1791 if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1792 avctx->gop_size <= 1) {
1793 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1795 } else if (ref_l0 < 1) {
1796 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1797 "reference frames.\n");
1798 return AVERROR(EINVAL);
1799 } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1800 ref_l1 < 1 || avctx->max_b_frames < 1) {
1801 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-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;
1807 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1808 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1809 ctx->gop_size = avctx->gop_size;
1810 ctx->p_per_i = INT_MAX;
1811 ctx->b_per_p = avctx->max_b_frames;
1812 if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1813 ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1814 av_log2(ctx->b_per_p) + 1);
1816 ctx->max_b_depth = 1;
1820 if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1821 ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1822 ctx->gop_per_idr = ctx->idr_interval + 1;
1824 ctx->closed_gop = 1;
1825 ctx->gop_per_idr = 1;
1831 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1833 VAAPIEncodeContext *ctx = avctx->priv_data;
1834 VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1835 { VAConfigAttribEncSliceStructure } };
1837 uint32_t max_slices, slice_structure;
1840 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1841 if (avctx->slices > 0) {
1842 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1843 "but this codec does not support controlling slices.\n");
1848 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1849 ctx->slice_block_height;
1850 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
1851 ctx->slice_block_width;
1853 if (avctx->slices <= 1) {
1855 ctx->slice_size = ctx->slice_block_rows;
1859 vas = vaGetConfigAttributes(ctx->hwctx->display,
1862 attr, FF_ARRAY_ELEMS(attr));
1863 if (vas != VA_STATUS_SUCCESS) {
1864 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1865 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1866 return AVERROR_EXTERNAL;
1868 max_slices = attr[0].value;
1869 slice_structure = attr[1].value;
1870 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1871 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1872 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1873 "pictures as multiple slices.\n.");
1874 return AVERROR(EINVAL);
1877 // For fixed-size slices currently we only support whole rows, making
1878 // rectangular slices. This could be extended to arbitrary runs of
1879 // blocks, but since slices tend to be a conformance requirement and
1880 // most cases (such as broadcast or bluray) want rectangular slices
1881 // only it would need to be gated behind another option.
1882 if (avctx->slices > ctx->slice_block_rows) {
1883 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1884 "configured number of slices (%d < %d); using "
1885 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1886 req_slices = ctx->slice_block_rows;
1888 req_slices = avctx->slices;
1890 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1891 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1892 ctx->nb_slices = req_slices;
1893 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1894 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1896 for (k = 1;; k *= 2) {
1897 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1900 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1901 ctx->slice_size = k;
1902 #if VA_CHECK_VERSION(1, 0, 0)
1903 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1904 ctx->nb_slices = ctx->slice_block_rows;
1905 ctx->slice_size = 1;
1908 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1909 "slice structure modes (%#x).\n", slice_structure);
1910 return AVERROR(EINVAL);
1913 if (ctx->nb_slices > avctx->slices) {
1914 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1915 "%d (from %d) due to driver constraints on slice "
1916 "structure.\n", ctx->nb_slices, avctx->slices);
1918 if (ctx->nb_slices > max_slices) {
1919 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1920 "encoding with %d slices (max %"PRIu32").\n",
1921 ctx->nb_slices, max_slices);
1922 return AVERROR(EINVAL);
1925 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1926 "(default size %d block rows).\n",
1927 ctx->nb_slices, ctx->slice_size);
1931 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1933 VAAPIEncodeContext *ctx = avctx->priv_data;
1935 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1937 vas = vaGetConfigAttributes(ctx->hwctx->display,
1941 if (vas != VA_STATUS_SUCCESS) {
1942 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1943 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1944 return AVERROR_EXTERNAL;
1947 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1948 if (ctx->desired_packed_headers) {
1949 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1950 "packed headers (wanted %#x).\n",
1951 ctx->desired_packed_headers);
1953 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1954 "packed headers (none wanted).\n");
1956 ctx->va_packed_headers = 0;
1958 if (ctx->desired_packed_headers & ~attr.value) {
1959 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1960 "wanted packed headers (wanted %#x, found %#x).\n",
1961 ctx->desired_packed_headers, attr.value);
1963 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1964 "available (wanted %#x, found %#x).\n",
1965 ctx->desired_packed_headers, attr.value);
1967 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1970 if (ctx->va_packed_headers) {
1971 ctx->config_attributes[ctx->nb_config_attributes++] =
1973 .type = VAConfigAttribEncPackedHeaders,
1974 .value = ctx->va_packed_headers,
1978 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1979 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1980 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1981 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1982 "sequence headers, but a global header is requested.\n");
1983 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1984 "this may result in a stream which is not usable for some "
1985 "purposes (e.g. not muxable to some containers).\n");
1991 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1993 #if VA_CHECK_VERSION(0, 36, 0)
1994 VAAPIEncodeContext *ctx = avctx->priv_data;
1996 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1997 int quality = avctx->compression_level;
1999 vas = vaGetConfigAttributes(ctx->hwctx->display,
2003 if (vas != VA_STATUS_SUCCESS) {
2004 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
2005 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2006 return AVERROR_EXTERNAL;
2009 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2011 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
2012 "supported: will use default quality level.\n");
2015 if (quality > attr.value) {
2016 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
2017 "valid range is 0-%d, using %d.\n",
2018 attr.value, attr.value);
2019 quality = attr.value;
2022 ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
2023 .quality_level = quality,
2025 vaapi_encode_add_global_param(avctx,
2026 VAEncMiscParameterTypeQualityLevel,
2027 &ctx->quality_params,
2028 sizeof(ctx->quality_params));
2031 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
2032 "not supported with this VAAPI version.\n");
2038 static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
2040 #if VA_CHECK_VERSION(1, 0, 0)
2041 VAAPIEncodeContext *ctx = avctx->priv_data;
2043 VAConfigAttrib attr = { VAConfigAttribEncROI };
2045 vas = vaGetConfigAttributes(ctx->hwctx->display,
2049 if (vas != VA_STATUS_SUCCESS) {
2050 av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
2051 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2052 return AVERROR_EXTERNAL;
2055 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2056 ctx->roi_allowed = 0;
2058 VAConfigAttribValEncROI roi = {
2059 .value = attr.value,
2062 ctx->roi_max_regions = roi.bits.num_roi_regions;
2063 ctx->roi_allowed = ctx->roi_max_regions > 0 &&
2064 (ctx->va_rc_mode == VA_RC_CQP ||
2065 roi.bits.roi_rc_qp_delta_support);
2071 static void vaapi_encode_free_output_buffer(void *opaque,
2074 AVCodecContext *avctx = opaque;
2075 VAAPIEncodeContext *ctx = avctx->priv_data;
2076 VABufferID buffer_id;
2078 buffer_id = (VABufferID)(uintptr_t)data;
2080 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2082 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
2085 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
2088 AVCodecContext *avctx = opaque;
2089 VAAPIEncodeContext *ctx = avctx->priv_data;
2090 VABufferID buffer_id;
2094 // The output buffer size is fixed, so it needs to be large enough
2095 // to hold the largest possible compressed frame. We assume here
2096 // that the uncompressed frame plus some header data is an upper
2098 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
2099 VAEncCodedBufferType,
2100 3 * ctx->surface_width * ctx->surface_height +
2101 (1 << 16), 1, 0, &buffer_id);
2102 if (vas != VA_STATUS_SUCCESS) {
2103 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
2104 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
2108 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
2110 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
2112 &vaapi_encode_free_output_buffer,
2113 avctx, AV_BUFFER_FLAG_READONLY);
2115 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2122 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
2124 VAAPIEncodeContext *ctx = avctx->priv_data;
2125 AVVAAPIHWConfig *hwconfig = NULL;
2126 AVHWFramesConstraints *constraints = NULL;
2127 enum AVPixelFormat recon_format;
2130 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
2132 err = AVERROR(ENOMEM);
2135 hwconfig->config_id = ctx->va_config;
2137 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
2140 err = AVERROR(ENOMEM);
2144 // Probably we can use the input surface format as the surface format
2145 // of the reconstructed frames. If not, we just pick the first (only?)
2146 // format in the valid list and hope that it all works.
2147 recon_format = AV_PIX_FMT_NONE;
2148 if (constraints->valid_sw_formats) {
2149 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
2150 if (ctx->input_frames->sw_format ==
2151 constraints->valid_sw_formats[i]) {
2152 recon_format = ctx->input_frames->sw_format;
2156 if (recon_format == AV_PIX_FMT_NONE) {
2157 // No match. Just use the first in the supported list and
2158 // hope for the best.
2159 recon_format = constraints->valid_sw_formats[0];
2162 // No idea what to use; copy input format.
2163 recon_format = ctx->input_frames->sw_format;
2165 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
2166 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
2168 if (ctx->surface_width < constraints->min_width ||
2169 ctx->surface_height < constraints->min_height ||
2170 ctx->surface_width > constraints->max_width ||
2171 ctx->surface_height > constraints->max_height) {
2172 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2173 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2174 ctx->surface_width, ctx->surface_height,
2175 constraints->min_width, constraints->max_width,
2176 constraints->min_height, constraints->max_height);
2177 err = AVERROR(EINVAL);
2181 av_freep(&hwconfig);
2182 av_hwframe_constraints_free(&constraints);
2184 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2185 if (!ctx->recon_frames_ref) {
2186 err = AVERROR(ENOMEM);
2189 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2191 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
2192 ctx->recon_frames->sw_format = recon_format;
2193 ctx->recon_frames->width = ctx->surface_width;
2194 ctx->recon_frames->height = ctx->surface_height;
2196 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2198 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2199 "frame context: %d.\n", err);
2205 av_freep(&hwconfig);
2206 av_hwframe_constraints_free(&constraints);
2210 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2212 VAAPIEncodeContext *ctx = avctx->priv_data;
2213 AVVAAPIFramesContext *recon_hwctx = NULL;
2217 if (!avctx->hw_frames_ctx) {
2218 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2219 "required to associate the encoding device.\n");
2220 return AVERROR(EINVAL);
2223 ctx->va_config = VA_INVALID_ID;
2224 ctx->va_context = VA_INVALID_ID;
2226 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2227 if (!ctx->input_frames_ref) {
2228 err = AVERROR(ENOMEM);
2231 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2233 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2234 if (!ctx->device_ref) {
2235 err = AVERROR(ENOMEM);
2238 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2239 ctx->hwctx = ctx->device->hwctx;
2241 err = vaapi_encode_profile_entrypoint(avctx);
2245 err = vaapi_encode_init_rate_control(avctx);
2249 err = vaapi_encode_init_gop_structure(avctx);
2253 err = vaapi_encode_init_slice_structure(avctx);
2257 err = vaapi_encode_init_packed_headers(avctx);
2261 err = vaapi_encode_init_roi(avctx);
2265 if (avctx->compression_level >= 0) {
2266 err = vaapi_encode_init_quality(avctx);
2271 vas = vaCreateConfig(ctx->hwctx->display,
2272 ctx->va_profile, ctx->va_entrypoint,
2273 ctx->config_attributes, ctx->nb_config_attributes,
2275 if (vas != VA_STATUS_SUCCESS) {
2276 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2277 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2282 err = vaapi_encode_create_recon_frames(avctx);
2286 recon_hwctx = ctx->recon_frames->hwctx;
2287 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2288 ctx->surface_width, ctx->surface_height,
2290 recon_hwctx->surface_ids,
2291 recon_hwctx->nb_surfaces,
2293 if (vas != VA_STATUS_SUCCESS) {
2294 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2295 "context: %d (%s).\n", vas, vaErrorStr(vas));
2300 ctx->output_buffer_pool =
2301 av_buffer_pool_init2(sizeof(VABufferID), avctx,
2302 &vaapi_encode_alloc_output_buffer, NULL);
2303 if (!ctx->output_buffer_pool) {
2304 err = AVERROR(ENOMEM);
2308 if (ctx->codec->configure) {
2309 err = ctx->codec->configure(avctx);
2314 ctx->output_delay = ctx->b_per_p;
2315 ctx->decode_delay = ctx->max_b_depth;
2317 if (ctx->codec->sequence_params_size > 0) {
2318 ctx->codec_sequence_params =
2319 av_mallocz(ctx->codec->sequence_params_size);
2320 if (!ctx->codec_sequence_params) {
2321 err = AVERROR(ENOMEM);
2325 if (ctx->codec->picture_params_size > 0) {
2326 ctx->codec_picture_params =
2327 av_mallocz(ctx->codec->picture_params_size);
2328 if (!ctx->codec_picture_params) {
2329 err = AVERROR(ENOMEM);
2334 if (ctx->codec->init_sequence_params) {
2335 err = ctx->codec->init_sequence_params(avctx);
2337 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2338 "failed: %d.\n", err);
2343 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2344 ctx->codec->write_sequence_header &&
2345 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2346 char data[MAX_PARAM_BUFFER_SIZE];
2347 size_t bit_len = 8 * sizeof(data);
2349 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2351 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2352 "for extradata: %d.\n", err);
2355 avctx->extradata_size = (bit_len + 7) / 8;
2356 avctx->extradata = av_mallocz(avctx->extradata_size +
2357 AV_INPUT_BUFFER_PADDING_SIZE);
2358 if (!avctx->extradata) {
2359 err = AVERROR(ENOMEM);
2362 memcpy(avctx->extradata, data, avctx->extradata_size);
2372 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2374 VAAPIEncodeContext *ctx = avctx->priv_data;
2375 VAAPIEncodePicture *pic, *next;
2377 for (pic = ctx->pic_start; pic; pic = next) {
2379 vaapi_encode_free(avctx, pic);
2382 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2384 if (ctx->va_context != VA_INVALID_ID) {
2385 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2386 ctx->va_context = VA_INVALID_ID;
2389 if (ctx->va_config != VA_INVALID_ID) {
2390 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2391 ctx->va_config = VA_INVALID_ID;
2394 av_freep(&ctx->codec_sequence_params);
2395 av_freep(&ctx->codec_picture_params);
2397 av_buffer_unref(&ctx->recon_frames_ref);
2398 av_buffer_unref(&ctx->input_frames_ref);
2399 av_buffer_unref(&ctx->device_ref);