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_wait(AVCodecContext *avctx,
107 VAAPIEncodePicture *pic)
109 VAAPIEncodeContext *ctx = avctx->priv_data;
112 av_assert0(pic->encode_issued);
114 if (pic->encode_complete) {
115 // Already waited for this picture.
119 av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
120 "(input surface %#x).\n", pic->display_order,
121 pic->encode_order, pic->input_surface);
123 vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
124 if (vas != VA_STATUS_SUCCESS) {
125 av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
126 "%d (%s).\n", vas, vaErrorStr(vas));
130 // Input is definitely finished with now.
131 av_frame_free(&pic->input_image);
133 pic->encode_complete = 1;
137 static int vaapi_encode_issue(AVCodecContext *avctx,
138 VAAPIEncodePicture *pic)
140 VAAPIEncodeContext *ctx = avctx->priv_data;
141 VAAPIEncodeSlice *slice;
144 char data[MAX_PARAM_BUFFER_SIZE];
147 av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
148 "as type %s.\n", pic->display_order, pic->encode_order,
149 picture_type_name[pic->type]);
150 if (pic->nb_refs == 0) {
151 av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
153 av_log(avctx, AV_LOG_DEBUG, "Refers to:");
154 for (i = 0; i < pic->nb_refs; i++) {
155 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
156 pic->refs[i]->display_order, pic->refs[i]->encode_order);
158 av_log(avctx, AV_LOG_DEBUG, ".\n");
161 av_assert0(!pic->encode_issued);
162 for (i = 0; i < pic->nb_refs; i++) {
163 av_assert0(pic->refs[i]);
164 av_assert0(pic->refs[i]->encode_issued);
167 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
169 pic->recon_image = av_frame_alloc();
170 if (!pic->recon_image) {
171 err = AVERROR(ENOMEM);
175 err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
177 err = AVERROR(ENOMEM);
180 pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
181 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
183 pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
184 if (!pic->output_buffer_ref) {
185 err = AVERROR(ENOMEM);
188 pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
189 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
192 if (ctx->codec->picture_params_size > 0) {
193 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
194 if (!pic->codec_picture_params)
196 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
197 ctx->codec->picture_params_size);
199 av_assert0(!ctx->codec_picture_params);
202 pic->nb_param_buffers = 0;
204 if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
205 err = vaapi_encode_make_param_buffer(avctx, pic,
206 VAEncSequenceParameterBufferType,
207 ctx->codec_sequence_params,
208 ctx->codec->sequence_params_size);
213 if (pic->type == PICTURE_TYPE_IDR) {
214 for (i = 0; i < ctx->nb_global_params; i++) {
215 err = vaapi_encode_make_param_buffer(avctx, pic,
216 VAEncMiscParameterBufferType,
217 (char*)ctx->global_params[i],
218 ctx->global_params_size[i]);
224 if (ctx->codec->init_picture_params) {
225 err = ctx->codec->init_picture_params(avctx, pic);
227 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
228 "parameters: %d.\n", err);
231 err = vaapi_encode_make_param_buffer(avctx, pic,
232 VAEncPictureParameterBufferType,
233 pic->codec_picture_params,
234 ctx->codec->picture_params_size);
239 if (pic->type == PICTURE_TYPE_IDR) {
240 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
241 ctx->codec->write_sequence_header) {
242 bit_len = 8 * sizeof(data);
243 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
245 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
246 "header: %d.\n", err);
249 err = vaapi_encode_make_packed_header(avctx, pic,
250 ctx->codec->sequence_header_type,
257 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
258 ctx->codec->write_picture_header) {
259 bit_len = 8 * sizeof(data);
260 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
262 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
263 "header: %d.\n", err);
266 err = vaapi_encode_make_packed_header(avctx, pic,
267 ctx->codec->picture_header_type,
273 if (ctx->codec->write_extra_buffer) {
275 size_t len = sizeof(data);
277 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
279 if (err == AVERROR_EOF)
282 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
283 "buffer %d: %d.\n", i, err);
287 err = vaapi_encode_make_param_buffer(avctx, pic, type,
294 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
295 ctx->codec->write_extra_header) {
298 bit_len = 8 * sizeof(data);
299 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
301 if (err == AVERROR_EOF)
304 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
305 "header %d: %d.\n", i, err);
309 err = vaapi_encode_make_packed_header(avctx, pic, type,
316 if (pic->nb_slices == 0)
317 pic->nb_slices = ctx->nb_slices;
318 if (pic->nb_slices > 0) {
321 pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
323 err = AVERROR(ENOMEM);
327 for (i = 0; i < pic->nb_slices; i++)
328 pic->slices[i].row_size = ctx->slice_size;
330 rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
332 // Place rounding error at top and bottom of frame.
333 av_assert0(rounding < pic->nb_slices);
334 // Some Intel drivers contain a bug where the encoder will fail
335 // if the last slice is smaller than the one before it. Since
336 // that's straightforward to avoid here, just do so.
338 for (i = 0; i < rounding; i++)
339 ++pic->slices[i].row_size;
341 for (i = 0; i < (rounding + 1) / 2; i++)
342 ++pic->slices[pic->nb_slices - i - 1].row_size;
343 for (i = 0; i < rounding / 2; i++)
344 ++pic->slices[i].row_size;
346 } else if (rounding < 0) {
347 // Remove rounding error from last slice only.
348 av_assert0(rounding < ctx->slice_size);
349 pic->slices[pic->nb_slices - 1].row_size += rounding;
352 for (i = 0; i < pic->nb_slices; i++) {
353 slice = &pic->slices[i];
356 slice->row_start = 0;
357 slice->block_start = 0;
359 const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
360 slice->row_start = prev->row_start + prev->row_size;
361 slice->block_start = prev->block_start + prev->block_size;
363 slice->block_size = slice->row_size * ctx->slice_block_cols;
365 av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
366 "%d-%d (%d blocks).\n", i, slice->row_start,
367 slice->row_start + slice->row_size - 1, slice->row_size,
368 slice->block_start, slice->block_start + slice->block_size - 1,
371 if (ctx->codec->slice_params_size > 0) {
372 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
373 if (!slice->codec_slice_params) {
374 err = AVERROR(ENOMEM);
379 if (ctx->codec->init_slice_params) {
380 err = ctx->codec->init_slice_params(avctx, pic, slice);
382 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
383 "parameters: %d.\n", err);
388 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
389 ctx->codec->write_slice_header) {
390 bit_len = 8 * sizeof(data);
391 err = ctx->codec->write_slice_header(avctx, pic, slice,
394 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
395 "header: %d.\n", err);
398 err = vaapi_encode_make_packed_header(avctx, pic,
399 ctx->codec->slice_header_type,
405 if (ctx->codec->init_slice_params) {
406 err = vaapi_encode_make_param_buffer(avctx, pic,
407 VAEncSliceParameterBufferType,
408 slice->codec_slice_params,
409 ctx->codec->slice_params_size);
415 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
417 if (vas != VA_STATUS_SUCCESS) {
418 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
419 "%d (%s).\n", vas, vaErrorStr(vas));
421 goto fail_with_picture;
424 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
425 pic->param_buffers, pic->nb_param_buffers);
426 if (vas != VA_STATUS_SUCCESS) {
427 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
428 "%d (%s).\n", vas, vaErrorStr(vas));
430 goto fail_with_picture;
433 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
434 if (vas != VA_STATUS_SUCCESS) {
435 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
436 "%d (%s).\n", vas, vaErrorStr(vas));
438 // vaRenderPicture() has been called here, so we should not destroy
439 // the parameter buffers unless separate destruction is required.
440 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
441 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
447 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
448 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
449 for (i = 0; i < pic->nb_param_buffers; i++) {
450 vas = vaDestroyBuffer(ctx->hwctx->display,
451 pic->param_buffers[i]);
452 if (vas != VA_STATUS_SUCCESS) {
453 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
454 "param buffer %#x: %d (%s).\n",
455 pic->param_buffers[i], vas, vaErrorStr(vas));
461 pic->encode_issued = 1;
466 vaEndPicture(ctx->hwctx->display, ctx->va_context);
468 for(i = 0; i < pic->nb_param_buffers; i++)
469 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
470 for (i = 0; i < pic->nb_slices; i++) {
472 av_freep(&pic->slices[i].priv_data);
473 av_freep(&pic->slices[i].codec_slice_params);
477 av_freep(&pic->codec_picture_params);
478 av_freep(&pic->param_buffers);
479 av_freep(&pic->slices);
480 av_frame_free(&pic->recon_image);
481 av_buffer_unref(&pic->output_buffer_ref);
482 pic->output_buffer = VA_INVALID_ID;
486 static int vaapi_encode_output(AVCodecContext *avctx,
487 VAAPIEncodePicture *pic, AVPacket *pkt)
489 VAAPIEncodeContext *ctx = avctx->priv_data;
490 VACodedBufferSegment *buf_list, *buf;
494 err = vaapi_encode_wait(avctx, pic);
499 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
501 if (vas != VA_STATUS_SUCCESS) {
502 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
503 "%d (%s).\n", vas, vaErrorStr(vas));
508 for (buf = buf_list; buf; buf = buf->next) {
509 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
510 "(status %08x).\n", buf->size, buf->status);
512 err = av_new_packet(pkt, buf->size);
516 memcpy(pkt->data, buf->buf, buf->size);
519 if (pic->type == PICTURE_TYPE_IDR)
520 pkt->flags |= AV_PKT_FLAG_KEY;
524 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
525 if (vas != VA_STATUS_SUCCESS) {
526 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
527 "%d (%s).\n", vas, vaErrorStr(vas));
532 av_buffer_unref(&pic->output_buffer_ref);
533 pic->output_buffer = VA_INVALID_ID;
535 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
536 pic->display_order, pic->encode_order);
540 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
542 av_buffer_unref(&pic->output_buffer_ref);
543 pic->output_buffer = VA_INVALID_ID;
547 static int vaapi_encode_discard(AVCodecContext *avctx,
548 VAAPIEncodePicture *pic)
550 vaapi_encode_wait(avctx, pic);
552 if (pic->output_buffer_ref) {
553 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
554 "%"PRId64"/%"PRId64".\n",
555 pic->display_order, pic->encode_order);
557 av_buffer_unref(&pic->output_buffer_ref);
558 pic->output_buffer = VA_INVALID_ID;
564 static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
566 VAAPIEncodeContext *ctx = avctx->priv_data;
567 VAAPIEncodePicture *pic;
569 pic = av_mallocz(sizeof(*pic));
573 if (ctx->codec->picture_priv_data_size > 0) {
574 pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
575 if (!pic->priv_data) {
581 pic->input_surface = VA_INVALID_ID;
582 pic->recon_surface = VA_INVALID_ID;
583 pic->output_buffer = VA_INVALID_ID;
588 static int vaapi_encode_free(AVCodecContext *avctx,
589 VAAPIEncodePicture *pic)
593 if (pic->encode_issued)
594 vaapi_encode_discard(avctx, pic);
596 for (i = 0; i < pic->nb_slices; i++) {
598 av_freep(&pic->slices[i].priv_data);
599 av_freep(&pic->slices[i].codec_slice_params);
602 av_freep(&pic->codec_picture_params);
604 av_frame_free(&pic->input_image);
605 av_frame_free(&pic->recon_image);
607 av_freep(&pic->param_buffers);
608 av_freep(&pic->slices);
609 // Output buffer should already be destroyed.
610 av_assert0(pic->output_buffer == VA_INVALID_ID);
612 av_freep(&pic->priv_data);
613 av_freep(&pic->codec_picture_params);
620 static void vaapi_encode_add_ref(AVCodecContext *avctx,
621 VAAPIEncodePicture *pic,
622 VAAPIEncodePicture *target,
623 int is_ref, int in_dpb, int prev)
628 av_assert0(pic != target);
629 av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
630 pic->refs[pic->nb_refs++] = target;
635 av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
636 pic->dpb[pic->nb_dpb_pics++] = target;
641 av_assert0(!pic->prev);
646 target->ref_count[0] += refs;
647 target->ref_count[1] += refs;
650 static void vaapi_encode_remove_refs(AVCodecContext *avctx,
651 VAAPIEncodePicture *pic,
656 if (pic->ref_removed[level])
659 for (i = 0; i < pic->nb_refs; i++) {
660 av_assert0(pic->refs[i]);
661 --pic->refs[i]->ref_count[level];
662 av_assert0(pic->refs[i]->ref_count[level] >= 0);
665 for (i = 0; i < pic->nb_dpb_pics; i++) {
666 av_assert0(pic->dpb[i]);
667 --pic->dpb[i]->ref_count[level];
668 av_assert0(pic->dpb[i]->ref_count[level] >= 0);
671 av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
673 --pic->prev->ref_count[level];
674 av_assert0(pic->prev->ref_count[level] >= 0);
677 pic->ref_removed[level] = 1;
680 static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
681 VAAPIEncodePicture *start,
682 VAAPIEncodePicture *end,
683 VAAPIEncodePicture *prev,
685 VAAPIEncodePicture **last)
687 VAAPIEncodeContext *ctx = avctx->priv_data;
688 VAAPIEncodePicture *pic, *next, *ref;
691 av_assert0(start && end && start != end && start->next != end);
693 // If we are at the maximum depth then encode all pictures as
694 // non-referenced B-pictures. Also do this if there is exactly one
695 // picture left, since there will be nothing to reference it.
696 if (current_depth == ctx->max_b_depth || start->next->next == end) {
697 for (pic = start->next; pic; pic = pic->next) {
700 pic->type = PICTURE_TYPE_B;
701 pic->b_depth = current_depth;
703 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
704 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
705 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
707 for (ref = end->refs[1]; ref; ref = ref->refs[1])
708 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
713 // Split the current list at the midpoint with a referenced
714 // B-picture, then descend into each side separately.
716 for (pic = start->next; pic != end; pic = pic->next)
718 for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
720 pic->type = PICTURE_TYPE_B;
721 pic->b_depth = current_depth;
723 pic->is_reference = 1;
725 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
726 vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
727 vaapi_encode_add_ref(avctx, pic, end, 1, 1, 0);
728 vaapi_encode_add_ref(avctx, pic, prev, 0, 0, 1);
730 for (ref = end->refs[1]; ref; ref = ref->refs[1])
731 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
734 vaapi_encode_set_b_pictures(avctx, start, pic, pic,
735 current_depth + 1, &next);
739 vaapi_encode_set_b_pictures(avctx, pic, end, next,
740 current_depth + 1, last);
744 static int vaapi_encode_pick_next(AVCodecContext *avctx,
745 VAAPIEncodePicture **pic_out)
747 VAAPIEncodeContext *ctx = avctx->priv_data;
748 VAAPIEncodePicture *pic = NULL, *next, *start;
749 int i, b_counter, closed_gop_end;
751 // If there are any B-frames already queued, the next one to encode
752 // is the earliest not-yet-issued frame for which all references are
754 for (pic = ctx->pic_start; pic; pic = pic->next) {
755 if (pic->encode_issued)
757 if (pic->type != PICTURE_TYPE_B)
759 for (i = 0; i < pic->nb_refs; i++) {
760 if (!pic->refs[i]->encode_issued)
763 if (i == pic->nb_refs)
768 av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
769 "encode next.\n", pic->b_depth);
774 // Find the B-per-Pth available picture to become the next picture
778 closed_gop_end = ctx->closed_gop ||
779 ctx->idr_counter == ctx->gop_per_idr;
780 for (pic = ctx->pic_start; pic; pic = next) {
782 if (pic->encode_issued) {
786 // If the next available picture is force-IDR, encode it to start
787 // a new GOP immediately.
790 if (b_counter == ctx->b_per_p)
792 // If this picture ends a closed GOP or starts a new GOP then it
793 // needs to be in the top layer.
794 if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
796 // If the picture after this one is force-IDR, we need to encode
797 // this one in the top layer.
798 if (next && next->force_idr)
803 // At the end of the stream the last picture must be in the top layer.
804 if (!pic && ctx->end_of_stream) {
807 if (pic->encode_issued)
812 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
813 "need more input for reference pictures.\n");
814 return AVERROR(EAGAIN);
816 if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
817 av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
818 "need more input for timestamps.\n");
819 return AVERROR(EAGAIN);
822 if (pic->force_idr) {
823 av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
825 pic->type = PICTURE_TYPE_IDR;
826 ctx->idr_counter = 1;
827 ctx->gop_counter = 1;
829 } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
830 if (ctx->idr_counter == ctx->gop_per_idr) {
831 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
833 pic->type = PICTURE_TYPE_IDR;
834 ctx->idr_counter = 1;
836 av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
838 pic->type = PICTURE_TYPE_I;
841 ctx->gop_counter = 1;
844 if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
845 av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
848 av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
851 pic->type = PICTURE_TYPE_P;
853 ctx->gop_counter += 1 + b_counter;
855 pic->is_reference = 1;
858 vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
859 if (pic->type != PICTURE_TYPE_IDR) {
860 vaapi_encode_add_ref(avctx, pic, start,
861 pic->type == PICTURE_TYPE_P,
863 vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
866 --ctx->next_prev->ref_count[0];
869 vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
872 ctx->next_prev = pic;
874 ++ctx->next_prev->ref_count[0];
878 static int vaapi_encode_clear_old(AVCodecContext *avctx)
880 VAAPIEncodeContext *ctx = avctx->priv_data;
881 VAAPIEncodePicture *pic, *prev, *next;
883 av_assert0(ctx->pic_start);
885 // Remove direct references once each picture is complete.
886 for (pic = ctx->pic_start; pic; pic = pic->next) {
887 if (pic->encode_complete && pic->next)
888 vaapi_encode_remove_refs(avctx, pic, 0);
891 // Remove indirect references once a picture has no direct references.
892 for (pic = ctx->pic_start; pic; pic = pic->next) {
893 if (pic->encode_complete && pic->ref_count[0] == 0)
894 vaapi_encode_remove_refs(avctx, pic, 1);
897 // Clear out all complete pictures with no remaining references.
899 for (pic = ctx->pic_start; pic; pic = next) {
901 if (pic->encode_complete && pic->ref_count[1] == 0) {
902 av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
906 ctx->pic_start = next;
907 vaapi_encode_free(avctx, pic);
916 static int vaapi_encode_check_frame(AVCodecContext *avctx,
917 const AVFrame *frame)
919 VAAPIEncodeContext *ctx = avctx->priv_data;
921 if ((frame->crop_top || frame->crop_bottom ||
922 frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
923 av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
924 "frames ignored due to lack of API support.\n");
925 ctx->crop_warned = 1;
931 int ff_vaapi_encode_send_frame(AVCodecContext *avctx, const AVFrame *frame)
933 VAAPIEncodeContext *ctx = avctx->priv_data;
934 VAAPIEncodePicture *pic;
938 av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
939 frame->width, frame->height, frame->pts);
941 err = vaapi_encode_check_frame(avctx, frame);
945 pic = vaapi_encode_alloc(avctx);
947 return AVERROR(ENOMEM);
949 pic->input_image = av_frame_alloc();
950 if (!pic->input_image) {
951 err = AVERROR(ENOMEM);
954 err = av_frame_ref(pic->input_image, frame);
958 if (ctx->input_order == 0)
961 pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
962 pic->pts = frame->pts;
964 if (ctx->input_order == 0)
965 ctx->first_pts = pic->pts;
966 if (ctx->input_order == ctx->decode_delay)
967 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
968 if (ctx->output_delay > 0)
969 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
971 pic->display_order = ctx->input_order;
974 if (ctx->pic_start) {
975 ctx->pic_end->next = pic;
978 ctx->pic_start = pic;
983 ctx->end_of_stream = 1;
985 // Fix timestamps if we hit end-of-stream before the initial decode
986 // delay has elapsed.
987 if (ctx->input_order < ctx->decode_delay)
988 ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
997 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
999 VAAPIEncodeContext *ctx = avctx->priv_data;
1000 VAAPIEncodePicture *pic;
1003 if (!ctx->pic_start) {
1004 if (ctx->end_of_stream)
1007 return AVERROR(EAGAIN);
1011 err = vaapi_encode_pick_next(avctx, &pic);
1016 pic->encode_order = ctx->encode_order++;
1018 err = vaapi_encode_issue(avctx, pic);
1020 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1024 err = vaapi_encode_output(avctx, pic, pkt);
1026 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1030 if (ctx->output_delay == 0) {
1031 pkt->dts = pkt->pts;
1032 } else if (pic->encode_order < ctx->decode_delay) {
1033 if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1034 pkt->dts = INT64_MIN;
1036 pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1038 pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1039 (3 * ctx->output_delay)];
1041 av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1042 pkt->pts, pkt->dts);
1044 ctx->output_order = pic->encode_order;
1045 vaapi_encode_clear_old(avctx);
1050 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
1051 const AVFrame *input_image, int *got_packet)
1053 return AVERROR(ENOSYS);
1056 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx,
1057 VAEncMiscParameterBuffer *buffer,
1060 VAAPIEncodeContext *ctx = avctx->priv_data;
1062 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1064 ctx->global_params [ctx->nb_global_params] = buffer;
1065 ctx->global_params_size[ctx->nb_global_params] = size;
1067 ++ctx->nb_global_params;
1070 typedef struct VAAPIEncodeRTFormat {
1077 } VAAPIEncodeRTFormat;
1079 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1080 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
1081 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
1082 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
1083 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
1084 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
1085 #if VA_CHECK_VERSION(0, 38, 1)
1086 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1090 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1091 VAEntrypointEncSlice,
1092 VAEntrypointEncPicture,
1093 #if VA_CHECK_VERSION(0, 39, 2)
1094 VAEntrypointEncSliceLP,
1098 #if VA_CHECK_VERSION(0, 39, 2)
1099 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1100 VAEntrypointEncSliceLP,
1105 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1107 VAAPIEncodeContext *ctx = avctx->priv_data;
1108 VAProfile *va_profiles = NULL;
1109 VAEntrypoint *va_entrypoints = NULL;
1111 const VAEntrypoint *usable_entrypoints;
1112 const VAAPIEncodeProfile *profile;
1113 const AVPixFmtDescriptor *desc;
1114 VAConfigAttrib rt_format_attr;
1115 const VAAPIEncodeRTFormat *rt_format;
1116 const char *profile_string, *entrypoint_string;
1117 int i, j, n, depth, err;
1120 if (ctx->low_power) {
1121 #if VA_CHECK_VERSION(0, 39, 2)
1122 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1124 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1125 "supported with this VAAPI version.\n");
1126 return AVERROR(EINVAL);
1129 usable_entrypoints = vaapi_encode_entrypoints_normal;
1132 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1134 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1135 ctx->input_frames->sw_format);
1136 return AVERROR(EINVAL);
1138 depth = desc->comp[0].depth;
1139 for (i = 1; i < desc->nb_components; i++) {
1140 if (desc->comp[i].depth != depth) {
1141 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1143 return AVERROR(EINVAL);
1146 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1149 n = vaMaxNumProfiles(ctx->hwctx->display);
1150 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1152 err = AVERROR(ENOMEM);
1155 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1156 if (vas != VA_STATUS_SUCCESS) {
1157 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1158 vas, vaErrorStr(vas));
1159 err = AVERROR_EXTERNAL;
1163 av_assert0(ctx->codec->profiles);
1164 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1165 FF_PROFILE_UNKNOWN); i++) {
1166 profile = &ctx->codec->profiles[i];
1167 if (depth != profile->depth ||
1168 desc->nb_components != profile->nb_components)
1170 if (desc->nb_components > 1 &&
1171 (desc->log2_chroma_w != profile->log2_chroma_w ||
1172 desc->log2_chroma_h != profile->log2_chroma_h))
1174 if (avctx->profile != profile->av_profile &&
1175 avctx->profile != FF_PROFILE_UNKNOWN)
1178 #if VA_CHECK_VERSION(1, 0, 0)
1179 profile_string = vaProfileStr(profile->va_profile);
1181 profile_string = "(no profile names)";
1184 for (j = 0; j < n; j++) {
1185 if (va_profiles[j] == profile->va_profile)
1189 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1190 "is not supported by driver.\n", profile_string,
1191 profile->va_profile);
1195 ctx->profile = profile;
1198 if (!ctx->profile) {
1199 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1200 err = AVERROR(ENOSYS);
1204 avctx->profile = profile->av_profile;
1205 ctx->va_profile = profile->va_profile;
1206 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1207 profile_string, ctx->va_profile);
1209 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1210 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1211 if (!va_entrypoints) {
1212 err = AVERROR(ENOMEM);
1215 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1216 va_entrypoints, &n);
1217 if (vas != VA_STATUS_SUCCESS) {
1218 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1219 "profile %s (%d): %d (%s).\n", profile_string,
1220 ctx->va_profile, vas, vaErrorStr(vas));
1221 err = AVERROR_EXTERNAL;
1225 for (i = 0; i < n; i++) {
1226 for (j = 0; usable_entrypoints[j]; j++) {
1227 if (va_entrypoints[i] == usable_entrypoints[j])
1230 if (usable_entrypoints[j])
1234 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1235 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1236 err = AVERROR(ENOSYS);
1240 ctx->va_entrypoint = va_entrypoints[i];
1241 #if VA_CHECK_VERSION(1, 0, 0)
1242 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1244 entrypoint_string = "(no entrypoint names)";
1246 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1247 entrypoint_string, ctx->va_entrypoint);
1249 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1250 rt_format = &vaapi_encode_rt_formats[i];
1251 if (rt_format->depth == depth &&
1252 rt_format->nb_components == profile->nb_components &&
1253 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1254 rt_format->log2_chroma_h == profile->log2_chroma_h)
1257 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1258 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1259 "found for profile %s (%d) entrypoint %s (%d).\n",
1260 profile_string, ctx->va_profile,
1261 entrypoint_string, ctx->va_entrypoint);
1262 err = AVERROR(ENOSYS);
1266 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1267 vas = vaGetConfigAttributes(ctx->hwctx->display,
1268 ctx->va_profile, ctx->va_entrypoint,
1269 &rt_format_attr, 1);
1270 if (vas != VA_STATUS_SUCCESS) {
1271 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1272 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1273 err = AVERROR_EXTERNAL;
1277 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1278 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1279 "supported by driver: assuming surface RT format %s "
1280 "is valid.\n", rt_format->name);
1281 } else if (!(rt_format_attr.value & rt_format->value)) {
1282 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1283 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1284 rt_format->name, profile_string, ctx->va_profile,
1285 entrypoint_string, ctx->va_entrypoint);
1286 err = AVERROR(ENOSYS);
1289 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1290 "format %s (%#x).\n", rt_format->name, rt_format->value);
1291 ctx->config_attributes[ctx->nb_config_attributes++] =
1293 .type = VAConfigAttribRTFormat,
1294 .value = rt_format->value,
1300 av_freep(&va_profiles);
1301 av_freep(&va_entrypoints);
1305 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1307 // | Maxrate | HRD/VBV
1309 { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
1310 { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
1311 { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
1312 #if VA_CHECK_VERSION(1, 1, 0)
1313 { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
1315 { RC_MODE_ICQ, "ICQ", 0 },
1317 #if VA_CHECK_VERSION(1, 3, 0)
1318 { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
1319 { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
1321 { RC_MODE_QVBR, "QVBR", 0 },
1322 { RC_MODE_AVBR, "AVBR", 0 },
1326 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1328 VAAPIEncodeContext *ctx = avctx->priv_data;
1329 uint32_t supported_va_rc_modes;
1330 const VAAPIEncodeRCMode *rc_mode;
1331 int64_t rc_bits_per_second;
1332 int rc_target_percentage;
1335 int64_t hrd_buffer_size;
1336 int64_t hrd_initial_buffer_fullness;
1338 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1340 char supported_rc_modes_string[64];
1342 vas = vaGetConfigAttributes(ctx->hwctx->display,
1343 ctx->va_profile, ctx->va_entrypoint,
1345 if (vas != VA_STATUS_SUCCESS) {
1346 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1347 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1348 return AVERROR_EXTERNAL;
1350 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1351 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1352 "supported rate control modes: assuming CQP only.\n");
1353 supported_va_rc_modes = VA_RC_CQP;
1354 strcpy(supported_rc_modes_string, "unknown");
1356 char *str = supported_rc_modes_string;
1357 size_t len = sizeof(supported_rc_modes_string);
1358 int i, first = 1, res;
1360 supported_va_rc_modes = rc_attr.value;
1361 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1362 rc_mode = &vaapi_encode_rc_modes[i];
1363 if (supported_va_rc_modes & rc_mode->va_mode) {
1364 res = snprintf(str, len, "%s%s",
1365 first ? "" : ", ", rc_mode->name);
1378 av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1379 supported_rc_modes_string);
1382 // Rate control mode selection:
1383 // * If the user has set a mode explicitly with the rc_mode option,
1384 // use it and fail if it is not available.
1385 // * If an explicit QP option has been set, use CQP.
1386 // * If the codec is CQ-only, use CQP.
1387 // * If the QSCALE avcodec option is set, use CQP.
1388 // * If bitrate and quality are both set, try QVBR.
1389 // * If quality is set, try ICQ, then CQP.
1390 // * If bitrate and maxrate are set and have the same value, try CBR.
1391 // * If a bitrate is set, try AVBR, then VBR, then CBR.
1392 // * If no bitrate is set, try ICQ, then CQP.
1394 #define TRY_RC_MODE(mode, fail) do { \
1395 rc_mode = &vaapi_encode_rc_modes[mode]; \
1396 if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1398 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1399 "RC mode (supported modes: %s).\n", rc_mode->name, \
1400 supported_rc_modes_string); \
1401 return AVERROR(EINVAL); \
1403 av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1404 "RC mode.\n", rc_mode->name); \
1407 goto rc_mode_found; \
1411 if (ctx->explicit_rc_mode)
1412 TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1414 if (ctx->explicit_qp)
1415 TRY_RC_MODE(RC_MODE_CQP, 1);
1417 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1418 TRY_RC_MODE(RC_MODE_CQP, 1);
1420 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1421 TRY_RC_MODE(RC_MODE_CQP, 1);
1423 if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1424 TRY_RC_MODE(RC_MODE_QVBR, 0);
1426 if (avctx->global_quality > 0) {
1427 TRY_RC_MODE(RC_MODE_ICQ, 0);
1428 TRY_RC_MODE(RC_MODE_CQP, 0);
1431 if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1432 TRY_RC_MODE(RC_MODE_CBR, 0);
1434 if (avctx->bit_rate > 0) {
1435 TRY_RC_MODE(RC_MODE_AVBR, 0);
1436 TRY_RC_MODE(RC_MODE_VBR, 0);
1437 TRY_RC_MODE(RC_MODE_CBR, 0);
1439 TRY_RC_MODE(RC_MODE_ICQ, 0);
1440 TRY_RC_MODE(RC_MODE_CQP, 0);
1443 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1444 "RC mode compatible with selected options "
1445 "(supported modes: %s).\n", supported_rc_modes_string);
1446 return AVERROR(EINVAL);
1449 if (rc_mode->bitrate) {
1450 if (avctx->bit_rate <= 0) {
1451 av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1452 "RC mode.\n", rc_mode->name);
1453 return AVERROR(EINVAL);
1456 if (rc_mode->mode == RC_MODE_AVBR) {
1457 // For maximum confusion AVBR is hacked into the existing API
1458 // by overloading some of the fields with completely different
1461 // Target percentage does not apply in AVBR mode.
1462 rc_bits_per_second = avctx->bit_rate;
1464 // Accuracy tolerance range for meeting the specified target
1465 // bitrate. It's very unclear how this is actually intended
1466 // to work - since we do want to get the specified bitrate,
1467 // set the accuracy to 100% for now.
1468 rc_target_percentage = 100;
1470 // Convergence period in frames. The GOP size reflects the
1471 // user's intended block size for cutting, so reusing that
1472 // as the convergence period seems a reasonable default.
1473 rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1475 } else if (rc_mode->maxrate) {
1476 if (avctx->rc_max_rate > 0) {
1477 if (avctx->rc_max_rate < avctx->bit_rate) {
1478 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1479 "bitrate (%"PRId64") must not be greater than "
1480 "maxrate (%"PRId64").\n", avctx->bit_rate,
1481 avctx->rc_max_rate);
1482 return AVERROR(EINVAL);
1484 rc_bits_per_second = avctx->rc_max_rate;
1485 rc_target_percentage = (avctx->bit_rate * 100) /
1488 // We only have a target bitrate, but this mode requires
1489 // that a maximum rate be supplied as well. Since the
1490 // user does not want this to be a constraint, arbitrarily
1491 // pick a maximum rate of double the target rate.
1492 rc_bits_per_second = 2 * avctx->bit_rate;
1493 rc_target_percentage = 50;
1496 if (avctx->rc_max_rate > avctx->bit_rate) {
1497 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1498 "in %s RC mode.\n", rc_mode->name);
1500 rc_bits_per_second = avctx->bit_rate;
1501 rc_target_percentage = 100;
1504 rc_bits_per_second = 0;
1505 rc_target_percentage = 100;
1508 if (rc_mode->quality) {
1509 if (ctx->explicit_qp) {
1510 rc_quality = ctx->explicit_qp;
1511 } else if (avctx->global_quality > 0) {
1512 rc_quality = avctx->global_quality;
1514 rc_quality = ctx->codec->default_quality;
1515 av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1516 "using default (%d).\n", rc_quality);
1523 if (avctx->rc_buffer_size)
1524 hrd_buffer_size = avctx->rc_buffer_size;
1525 else if (avctx->rc_max_rate > 0)
1526 hrd_buffer_size = avctx->rc_max_rate;
1528 hrd_buffer_size = avctx->bit_rate;
1529 if (avctx->rc_initial_buffer_occupancy) {
1530 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1531 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1532 "must have initial buffer size (%d) <= "
1533 "buffer size (%"PRId64").\n",
1534 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1535 return AVERROR(EINVAL);
1537 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1539 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1542 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1544 if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1545 av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1546 "in %s RC mode.\n", rc_mode->name);
1549 hrd_buffer_size = 0;
1550 hrd_initial_buffer_fullness = 0;
1552 if (rc_mode->mode != RC_MODE_AVBR) {
1553 // Already set (with completely different meaning) for AVBR.
1554 rc_window_size = 1000;
1558 if (rc_bits_per_second > UINT32_MAX ||
1559 hrd_buffer_size > UINT32_MAX ||
1560 hrd_initial_buffer_fullness > UINT32_MAX) {
1561 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1562 "greater are not supported by VAAPI.\n");
1563 return AVERROR(EINVAL);
1566 ctx->rc_mode = rc_mode;
1567 ctx->rc_quality = rc_quality;
1568 ctx->va_rc_mode = rc_mode->va_mode;
1569 ctx->va_bit_rate = rc_bits_per_second;
1571 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1572 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1573 // This driver does not want the RC mode attribute to be set.
1575 ctx->config_attributes[ctx->nb_config_attributes++] =
1577 .type = VAConfigAttribRateControl,
1578 .value = ctx->va_rc_mode,
1582 if (rc_mode->quality)
1583 av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1585 if (rc_mode->va_mode != VA_RC_CQP) {
1586 if (rc_mode->mode == RC_MODE_AVBR) {
1587 av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1588 "converging in %d frames with %d%% accuracy.\n",
1589 rc_bits_per_second, rc_window_size,
1590 rc_target_percentage);
1591 } else if (rc_mode->bitrate) {
1592 av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1593 "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1594 rc_bits_per_second, rc_window_size);
1597 ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1598 ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1599 .bits_per_second = rc_bits_per_second,
1600 .target_percentage = rc_target_percentage,
1601 .window_size = rc_window_size,
1603 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1604 .basic_unit_size = 0,
1605 #if VA_CHECK_VERSION(1, 1, 0)
1606 .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1607 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1609 #if VA_CHECK_VERSION(1, 3, 0)
1610 .quality_factor = rc_quality,
1613 vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
1614 sizeof(ctx->rc_params));
1618 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1619 "initial fullness %"PRId64" bits.\n",
1620 hrd_buffer_size, hrd_initial_buffer_fullness);
1622 ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1623 ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1624 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1625 .buffer_size = hrd_buffer_size,
1627 vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
1628 sizeof(ctx->hrd_params));
1631 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1632 av_reduce(&fr_num, &fr_den,
1633 avctx->framerate.num, avctx->framerate.den, 65535);
1635 av_reduce(&fr_num, &fr_den,
1636 avctx->time_base.den, avctx->time_base.num, 65535);
1638 av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1639 fr_num, fr_den, (double)fr_num / fr_den);
1641 ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1642 ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1644 #if VA_CHECK_VERSION(0, 40, 0)
1645 vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
1646 sizeof(ctx->fr_params));
1652 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1654 VAAPIEncodeContext *ctx = avctx->priv_data;
1656 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1657 uint32_t ref_l0, ref_l1;
1659 vas = vaGetConfigAttributes(ctx->hwctx->display,
1663 if (vas != VA_STATUS_SUCCESS) {
1664 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1665 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1666 return AVERROR_EXTERNAL;
1669 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1670 ref_l0 = ref_l1 = 0;
1672 ref_l0 = attr.value & 0xffff;
1673 ref_l1 = attr.value >> 16 & 0xffff;
1676 if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1677 avctx->gop_size <= 1) {
1678 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1680 } else if (ref_l0 < 1) {
1681 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1682 "reference frames.\n");
1683 return AVERROR(EINVAL);
1684 } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1685 ref_l1 < 1 || avctx->max_b_frames < 1) {
1686 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1687 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1688 ctx->gop_size = avctx->gop_size;
1689 ctx->p_per_i = INT_MAX;
1692 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1693 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1694 ctx->gop_size = avctx->gop_size;
1695 ctx->p_per_i = INT_MAX;
1696 ctx->b_per_p = avctx->max_b_frames;
1697 if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1698 ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1699 av_log2(ctx->b_per_p) + 1);
1701 ctx->max_b_depth = 1;
1705 if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1706 ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1707 ctx->gop_per_idr = ctx->idr_interval + 1;
1709 ctx->closed_gop = 1;
1710 ctx->gop_per_idr = 1;
1716 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1718 VAAPIEncodeContext *ctx = avctx->priv_data;
1719 VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1720 { VAConfigAttribEncSliceStructure } };
1722 uint32_t max_slices, slice_structure;
1725 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1726 if (avctx->slices > 0) {
1727 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1728 "but this codec does not support controlling slices.\n");
1733 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1734 ctx->slice_block_height;
1735 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
1736 ctx->slice_block_width;
1738 if (avctx->slices <= 1) {
1740 ctx->slice_size = ctx->slice_block_rows;
1744 vas = vaGetConfigAttributes(ctx->hwctx->display,
1747 attr, FF_ARRAY_ELEMS(attr));
1748 if (vas != VA_STATUS_SUCCESS) {
1749 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1750 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1751 return AVERROR_EXTERNAL;
1753 max_slices = attr[0].value;
1754 slice_structure = attr[1].value;
1755 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1756 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1757 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1758 "pictures as multiple slices.\n.");
1759 return AVERROR(EINVAL);
1762 // For fixed-size slices currently we only support whole rows, making
1763 // rectangular slices. This could be extended to arbitrary runs of
1764 // blocks, but since slices tend to be a conformance requirement and
1765 // most cases (such as broadcast or bluray) want rectangular slices
1766 // only it would need to be gated behind another option.
1767 if (avctx->slices > ctx->slice_block_rows) {
1768 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1769 "configured number of slices (%d < %d); using "
1770 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1771 req_slices = ctx->slice_block_rows;
1773 req_slices = avctx->slices;
1775 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1776 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1777 ctx->nb_slices = req_slices;
1778 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1779 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1781 for (k = 1;; k *= 2) {
1782 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1785 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1786 ctx->slice_size = k;
1787 #if VA_CHECK_VERSION(1, 0, 0)
1788 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1789 ctx->nb_slices = ctx->slice_block_rows;
1790 ctx->slice_size = 1;
1793 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1794 "slice structure modes (%#x).\n", slice_structure);
1795 return AVERROR(EINVAL);
1798 if (ctx->nb_slices > avctx->slices) {
1799 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1800 "%d (from %d) due to driver constraints on slice "
1801 "structure.\n", ctx->nb_slices, avctx->slices);
1803 if (ctx->nb_slices > max_slices) {
1804 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1805 "encoding with %d slices (max %"PRIu32").\n",
1806 ctx->nb_slices, max_slices);
1807 return AVERROR(EINVAL);
1810 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1811 "(default size %d block rows).\n",
1812 ctx->nb_slices, ctx->slice_size);
1816 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1818 VAAPIEncodeContext *ctx = avctx->priv_data;
1820 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1822 vas = vaGetConfigAttributes(ctx->hwctx->display,
1826 if (vas != VA_STATUS_SUCCESS) {
1827 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1828 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1829 return AVERROR_EXTERNAL;
1832 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1833 if (ctx->desired_packed_headers) {
1834 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1835 "packed headers (wanted %#x).\n",
1836 ctx->desired_packed_headers);
1838 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1839 "packed headers (none wanted).\n");
1841 ctx->va_packed_headers = 0;
1843 if (ctx->desired_packed_headers & ~attr.value) {
1844 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1845 "wanted packed headers (wanted %#x, found %#x).\n",
1846 ctx->desired_packed_headers, attr.value);
1848 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1849 "available (wanted %#x, found %#x).\n",
1850 ctx->desired_packed_headers, attr.value);
1852 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1855 if (ctx->va_packed_headers) {
1856 ctx->config_attributes[ctx->nb_config_attributes++] =
1858 .type = VAConfigAttribEncPackedHeaders,
1859 .value = ctx->va_packed_headers,
1863 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1864 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1865 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1866 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1867 "sequence headers, but a global header is requested.\n");
1868 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1869 "this may result in a stream which is not usable for some "
1870 "purposes (e.g. not muxable to some containers).\n");
1876 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1878 #if VA_CHECK_VERSION(0, 36, 0)
1879 VAAPIEncodeContext *ctx = avctx->priv_data;
1881 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1882 int quality = avctx->compression_level;
1884 vas = vaGetConfigAttributes(ctx->hwctx->display,
1888 if (vas != VA_STATUS_SUCCESS) {
1889 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1890 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1891 return AVERROR_EXTERNAL;
1894 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1896 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1897 "supported: will use default quality level.\n");
1900 if (quality > attr.value) {
1901 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1902 "valid range is 0-%d, using %d.\n",
1903 attr.value, attr.value);
1904 quality = attr.value;
1907 ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
1908 ctx->quality_params.quality.quality_level = quality;
1910 vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
1911 sizeof(ctx->quality_params));
1914 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1915 "not supported with this VAAPI version.\n");
1921 static void vaapi_encode_free_output_buffer(void *opaque,
1924 AVCodecContext *avctx = opaque;
1925 VAAPIEncodeContext *ctx = avctx->priv_data;
1926 VABufferID buffer_id;
1928 buffer_id = (VABufferID)(uintptr_t)data;
1930 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1932 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1935 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1938 AVCodecContext *avctx = opaque;
1939 VAAPIEncodeContext *ctx = avctx->priv_data;
1940 VABufferID buffer_id;
1944 // The output buffer size is fixed, so it needs to be large enough
1945 // to hold the largest possible compressed frame. We assume here
1946 // that the uncompressed frame plus some header data is an upper
1948 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1949 VAEncCodedBufferType,
1950 3 * ctx->surface_width * ctx->surface_height +
1951 (1 << 16), 1, 0, &buffer_id);
1952 if (vas != VA_STATUS_SUCCESS) {
1953 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1954 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1958 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1960 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1962 &vaapi_encode_free_output_buffer,
1963 avctx, AV_BUFFER_FLAG_READONLY);
1965 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1972 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1974 VAAPIEncodeContext *ctx = avctx->priv_data;
1975 AVVAAPIHWConfig *hwconfig = NULL;
1976 AVHWFramesConstraints *constraints = NULL;
1977 enum AVPixelFormat recon_format;
1980 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1982 err = AVERROR(ENOMEM);
1985 hwconfig->config_id = ctx->va_config;
1987 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1990 err = AVERROR(ENOMEM);
1994 // Probably we can use the input surface format as the surface format
1995 // of the reconstructed frames. If not, we just pick the first (only?)
1996 // format in the valid list and hope that it all works.
1997 recon_format = AV_PIX_FMT_NONE;
1998 if (constraints->valid_sw_formats) {
1999 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
2000 if (ctx->input_frames->sw_format ==
2001 constraints->valid_sw_formats[i]) {
2002 recon_format = ctx->input_frames->sw_format;
2006 if (recon_format == AV_PIX_FMT_NONE) {
2007 // No match. Just use the first in the supported list and
2008 // hope for the best.
2009 recon_format = constraints->valid_sw_formats[0];
2012 // No idea what to use; copy input format.
2013 recon_format = ctx->input_frames->sw_format;
2015 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
2016 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
2018 if (ctx->surface_width < constraints->min_width ||
2019 ctx->surface_height < constraints->min_height ||
2020 ctx->surface_width > constraints->max_width ||
2021 ctx->surface_height > constraints->max_height) {
2022 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2023 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2024 ctx->surface_width, ctx->surface_height,
2025 constraints->min_width, constraints->max_width,
2026 constraints->min_height, constraints->max_height);
2027 err = AVERROR(EINVAL);
2031 av_freep(&hwconfig);
2032 av_hwframe_constraints_free(&constraints);
2034 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2035 if (!ctx->recon_frames_ref) {
2036 err = AVERROR(ENOMEM);
2039 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2041 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
2042 ctx->recon_frames->sw_format = recon_format;
2043 ctx->recon_frames->width = ctx->surface_width;
2044 ctx->recon_frames->height = ctx->surface_height;
2046 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2048 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2049 "frame context: %d.\n", err);
2055 av_freep(&hwconfig);
2056 av_hwframe_constraints_free(&constraints);
2060 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2062 VAAPIEncodeContext *ctx = avctx->priv_data;
2063 AVVAAPIFramesContext *recon_hwctx = NULL;
2067 if (!avctx->hw_frames_ctx) {
2068 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2069 "required to associate the encoding device.\n");
2070 return AVERROR(EINVAL);
2073 ctx->va_config = VA_INVALID_ID;
2074 ctx->va_context = VA_INVALID_ID;
2076 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2077 if (!ctx->input_frames_ref) {
2078 err = AVERROR(ENOMEM);
2081 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2083 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2084 if (!ctx->device_ref) {
2085 err = AVERROR(ENOMEM);
2088 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2089 ctx->hwctx = ctx->device->hwctx;
2091 err = vaapi_encode_profile_entrypoint(avctx);
2095 err = vaapi_encode_init_rate_control(avctx);
2099 err = vaapi_encode_init_gop_structure(avctx);
2103 err = vaapi_encode_init_slice_structure(avctx);
2107 err = vaapi_encode_init_packed_headers(avctx);
2111 if (avctx->compression_level >= 0) {
2112 err = vaapi_encode_init_quality(avctx);
2117 vas = vaCreateConfig(ctx->hwctx->display,
2118 ctx->va_profile, ctx->va_entrypoint,
2119 ctx->config_attributes, ctx->nb_config_attributes,
2121 if (vas != VA_STATUS_SUCCESS) {
2122 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2123 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2128 err = vaapi_encode_create_recon_frames(avctx);
2132 recon_hwctx = ctx->recon_frames->hwctx;
2133 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2134 ctx->surface_width, ctx->surface_height,
2136 recon_hwctx->surface_ids,
2137 recon_hwctx->nb_surfaces,
2139 if (vas != VA_STATUS_SUCCESS) {
2140 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2141 "context: %d (%s).\n", vas, vaErrorStr(vas));
2146 ctx->output_buffer_pool =
2147 av_buffer_pool_init2(sizeof(VABufferID), avctx,
2148 &vaapi_encode_alloc_output_buffer, NULL);
2149 if (!ctx->output_buffer_pool) {
2150 err = AVERROR(ENOMEM);
2154 if (ctx->codec->configure) {
2155 err = ctx->codec->configure(avctx);
2160 ctx->output_delay = ctx->b_per_p;
2161 ctx->decode_delay = ctx->max_b_depth;
2163 if (ctx->codec->sequence_params_size > 0) {
2164 ctx->codec_sequence_params =
2165 av_mallocz(ctx->codec->sequence_params_size);
2166 if (!ctx->codec_sequence_params) {
2167 err = AVERROR(ENOMEM);
2171 if (ctx->codec->picture_params_size > 0) {
2172 ctx->codec_picture_params =
2173 av_mallocz(ctx->codec->picture_params_size);
2174 if (!ctx->codec_picture_params) {
2175 err = AVERROR(ENOMEM);
2180 if (ctx->codec->init_sequence_params) {
2181 err = ctx->codec->init_sequence_params(avctx);
2183 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2184 "failed: %d.\n", err);
2189 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2190 ctx->codec->write_sequence_header &&
2191 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2192 char data[MAX_PARAM_BUFFER_SIZE];
2193 size_t bit_len = 8 * sizeof(data);
2195 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2197 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2198 "for extradata: %d.\n", err);
2201 avctx->extradata_size = (bit_len + 7) / 8;
2202 avctx->extradata = av_mallocz(avctx->extradata_size +
2203 AV_INPUT_BUFFER_PADDING_SIZE);
2204 if (!avctx->extradata) {
2205 err = AVERROR(ENOMEM);
2208 memcpy(avctx->extradata, data, avctx->extradata_size);
2215 ff_vaapi_encode_close(avctx);
2219 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2221 VAAPIEncodeContext *ctx = avctx->priv_data;
2222 VAAPIEncodePicture *pic, *next;
2224 for (pic = ctx->pic_start; pic; pic = next) {
2226 vaapi_encode_free(avctx, pic);
2229 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2231 if (ctx->va_context != VA_INVALID_ID) {
2232 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2233 ctx->va_context = VA_INVALID_ID;
2236 if (ctx->va_config != VA_INVALID_ID) {
2237 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2238 ctx->va_config = VA_INVALID_ID;
2241 av_freep(&ctx->codec_sequence_params);
2242 av_freep(&ctx->codec_picture_params);
2244 av_buffer_unref(&ctx->recon_frames_ref);
2245 av_buffer_unref(&ctx->input_frames_ref);
2246 av_buffer_unref(&ctx->device_ref);