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 int ff_vaapi_encode_send_frame(AVCodecContext *avctx, const AVFrame *frame)
918 VAAPIEncodeContext *ctx = avctx->priv_data;
919 VAAPIEncodePicture *pic;
923 av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
924 frame->width, frame->height, frame->pts);
926 pic = vaapi_encode_alloc(avctx);
928 return AVERROR(ENOMEM);
930 pic->input_image = av_frame_alloc();
931 if (!pic->input_image) {
932 err = AVERROR(ENOMEM);
935 err = av_frame_ref(pic->input_image, frame);
939 if (ctx->input_order == 0)
942 pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
943 pic->pts = frame->pts;
945 if (ctx->input_order == 0)
946 ctx->first_pts = pic->pts;
947 if (ctx->input_order == ctx->decode_delay)
948 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
949 if (ctx->output_delay > 0)
950 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
952 pic->display_order = ctx->input_order;
955 if (ctx->pic_start) {
956 ctx->pic_end->next = pic;
959 ctx->pic_start = pic;
964 ctx->end_of_stream = 1;
966 // Fix timestamps if we hit end-of-stream before the initial decode
967 // delay has elapsed.
968 if (ctx->input_order < ctx->decode_delay)
969 ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
978 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
980 VAAPIEncodeContext *ctx = avctx->priv_data;
981 VAAPIEncodePicture *pic;
984 if (!ctx->pic_start) {
985 if (ctx->end_of_stream)
988 return AVERROR(EAGAIN);
992 err = vaapi_encode_pick_next(avctx, &pic);
997 pic->encode_order = ctx->encode_order++;
999 err = vaapi_encode_issue(avctx, pic);
1001 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1005 err = vaapi_encode_output(avctx, pic, pkt);
1007 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1011 if (ctx->output_delay == 0) {
1012 pkt->dts = pkt->pts;
1013 } else if (pic->encode_order < ctx->decode_delay) {
1014 if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1015 pkt->dts = INT64_MIN;
1017 pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1019 pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1020 (3 * ctx->output_delay)];
1022 av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1023 pkt->pts, pkt->dts);
1025 ctx->output_order = pic->encode_order;
1026 vaapi_encode_clear_old(avctx);
1031 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
1032 const AVFrame *input_image, int *got_packet)
1034 return AVERROR(ENOSYS);
1037 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx,
1038 VAEncMiscParameterBuffer *buffer,
1041 VAAPIEncodeContext *ctx = avctx->priv_data;
1043 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1045 ctx->global_params [ctx->nb_global_params] = buffer;
1046 ctx->global_params_size[ctx->nb_global_params] = size;
1048 ++ctx->nb_global_params;
1051 typedef struct VAAPIEncodeRTFormat {
1058 } VAAPIEncodeRTFormat;
1060 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1061 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
1062 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
1063 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
1064 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
1065 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
1066 #if VA_CHECK_VERSION(0, 38, 1)
1067 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1071 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1072 VAEntrypointEncSlice,
1073 VAEntrypointEncPicture,
1074 #if VA_CHECK_VERSION(0, 39, 2)
1075 VAEntrypointEncSliceLP,
1079 #if VA_CHECK_VERSION(0, 39, 2)
1080 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1081 VAEntrypointEncSliceLP,
1086 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1088 VAAPIEncodeContext *ctx = avctx->priv_data;
1089 VAProfile *va_profiles = NULL;
1090 VAEntrypoint *va_entrypoints = NULL;
1092 const VAEntrypoint *usable_entrypoints;
1093 const VAAPIEncodeProfile *profile;
1094 const AVPixFmtDescriptor *desc;
1095 VAConfigAttrib rt_format_attr;
1096 const VAAPIEncodeRTFormat *rt_format;
1097 const char *profile_string, *entrypoint_string;
1098 int i, j, n, depth, err;
1101 if (ctx->low_power) {
1102 #if VA_CHECK_VERSION(0, 39, 2)
1103 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1105 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1106 "supported with this VAAPI version.\n");
1107 return AVERROR(EINVAL);
1110 usable_entrypoints = vaapi_encode_entrypoints_normal;
1113 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1115 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1116 ctx->input_frames->sw_format);
1117 return AVERROR(EINVAL);
1119 depth = desc->comp[0].depth;
1120 for (i = 1; i < desc->nb_components; i++) {
1121 if (desc->comp[i].depth != depth) {
1122 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1124 return AVERROR(EINVAL);
1127 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1130 n = vaMaxNumProfiles(ctx->hwctx->display);
1131 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1133 err = AVERROR(ENOMEM);
1136 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1137 if (vas != VA_STATUS_SUCCESS) {
1138 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1139 vas, vaErrorStr(vas));
1140 err = AVERROR_EXTERNAL;
1144 av_assert0(ctx->codec->profiles);
1145 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1146 FF_PROFILE_UNKNOWN); i++) {
1147 profile = &ctx->codec->profiles[i];
1148 if (depth != profile->depth ||
1149 desc->nb_components != profile->nb_components)
1151 if (desc->nb_components > 1 &&
1152 (desc->log2_chroma_w != profile->log2_chroma_w ||
1153 desc->log2_chroma_h != profile->log2_chroma_h))
1155 if (avctx->profile != profile->av_profile &&
1156 avctx->profile != FF_PROFILE_UNKNOWN)
1159 #if VA_CHECK_VERSION(1, 0, 0)
1160 profile_string = vaProfileStr(profile->va_profile);
1162 profile_string = "(no profile names)";
1165 for (j = 0; j < n; j++) {
1166 if (va_profiles[j] == profile->va_profile)
1170 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1171 "is not supported by driver.\n", profile_string,
1172 profile->va_profile);
1176 ctx->profile = profile;
1179 if (!ctx->profile) {
1180 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1181 err = AVERROR(ENOSYS);
1185 avctx->profile = profile->av_profile;
1186 ctx->va_profile = profile->va_profile;
1187 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1188 profile_string, ctx->va_profile);
1190 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1191 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1192 if (!va_entrypoints) {
1193 err = AVERROR(ENOMEM);
1196 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1197 va_entrypoints, &n);
1198 if (vas != VA_STATUS_SUCCESS) {
1199 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1200 "profile %s (%d): %d (%s).\n", profile_string,
1201 ctx->va_profile, vas, vaErrorStr(vas));
1202 err = AVERROR_EXTERNAL;
1206 for (i = 0; i < n; i++) {
1207 for (j = 0; usable_entrypoints[j]; j++) {
1208 if (va_entrypoints[i] == usable_entrypoints[j])
1211 if (usable_entrypoints[j])
1215 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1216 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1217 err = AVERROR(ENOSYS);
1221 ctx->va_entrypoint = va_entrypoints[i];
1222 #if VA_CHECK_VERSION(1, 0, 0)
1223 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1225 entrypoint_string = "(no entrypoint names)";
1227 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1228 entrypoint_string, ctx->va_entrypoint);
1230 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1231 rt_format = &vaapi_encode_rt_formats[i];
1232 if (rt_format->depth == depth &&
1233 rt_format->nb_components == profile->nb_components &&
1234 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1235 rt_format->log2_chroma_h == profile->log2_chroma_h)
1238 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1239 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1240 "found for profile %s (%d) entrypoint %s (%d).\n",
1241 profile_string, ctx->va_profile,
1242 entrypoint_string, ctx->va_entrypoint);
1243 err = AVERROR(ENOSYS);
1247 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1248 vas = vaGetConfigAttributes(ctx->hwctx->display,
1249 ctx->va_profile, ctx->va_entrypoint,
1250 &rt_format_attr, 1);
1251 if (vas != VA_STATUS_SUCCESS) {
1252 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1253 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1254 err = AVERROR_EXTERNAL;
1258 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1259 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1260 "supported by driver: assuming surface RT format %s "
1261 "is valid.\n", rt_format->name);
1262 } else if (!(rt_format_attr.value & rt_format->value)) {
1263 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1264 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1265 rt_format->name, profile_string, ctx->va_profile,
1266 entrypoint_string, ctx->va_entrypoint);
1267 err = AVERROR(ENOSYS);
1270 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1271 "format %s (%#x).\n", rt_format->name, rt_format->value);
1272 ctx->config_attributes[ctx->nb_config_attributes++] =
1274 .type = VAConfigAttribRTFormat,
1275 .value = rt_format->value,
1281 av_freep(&va_profiles);
1282 av_freep(&va_entrypoints);
1286 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1288 // | Maxrate | HRD/VBV
1290 { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
1291 { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
1292 { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
1293 #if VA_CHECK_VERSION(1, 1, 0)
1294 { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
1296 { RC_MODE_ICQ, "ICQ", 0 },
1298 #if VA_CHECK_VERSION(1, 3, 0)
1299 { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
1300 { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
1302 { RC_MODE_QVBR, "QVBR", 0 },
1303 { RC_MODE_AVBR, "AVBR", 0 },
1307 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1309 VAAPIEncodeContext *ctx = avctx->priv_data;
1310 uint32_t supported_va_rc_modes;
1311 const VAAPIEncodeRCMode *rc_mode;
1312 int64_t rc_bits_per_second;
1313 int rc_target_percentage;
1316 int64_t hrd_buffer_size;
1317 int64_t hrd_initial_buffer_fullness;
1319 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1321 char supported_rc_modes_string[64];
1323 vas = vaGetConfigAttributes(ctx->hwctx->display,
1324 ctx->va_profile, ctx->va_entrypoint,
1326 if (vas != VA_STATUS_SUCCESS) {
1327 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1328 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1329 return AVERROR_EXTERNAL;
1331 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1332 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1333 "supported rate control modes: assuming CQP only.\n");
1334 supported_va_rc_modes = VA_RC_CQP;
1335 strcpy(supported_rc_modes_string, "unknown");
1337 char *str = supported_rc_modes_string;
1338 size_t len = sizeof(supported_rc_modes_string);
1339 int i, first = 1, res;
1341 supported_va_rc_modes = rc_attr.value;
1342 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1343 rc_mode = &vaapi_encode_rc_modes[i];
1344 if (supported_va_rc_modes & rc_mode->va_mode) {
1345 res = snprintf(str, len, "%s%s",
1346 first ? "" : ", ", rc_mode->name);
1359 av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1360 supported_rc_modes_string);
1363 // Rate control mode selection:
1364 // * If the user has set a mode explicitly with the rc_mode option,
1365 // use it and fail if it is not available.
1366 // * If an explicit QP option has been set, use CQP.
1367 // * If the codec is CQ-only, use CQP.
1368 // * If the QSCALE avcodec option is set, use CQP.
1369 // * If bitrate and quality are both set, try QVBR.
1370 // * If quality is set, try ICQ, then CQP.
1371 // * If bitrate and maxrate are set and have the same value, try CBR.
1372 // * If a bitrate is set, try AVBR, then VBR, then CBR.
1373 // * If no bitrate is set, try ICQ, then CQP.
1375 #define TRY_RC_MODE(mode, fail) do { \
1376 rc_mode = &vaapi_encode_rc_modes[mode]; \
1377 if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1379 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1380 "RC mode (supported modes: %s).\n", rc_mode->name, \
1381 supported_rc_modes_string); \
1382 return AVERROR(EINVAL); \
1384 av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1385 "RC mode.\n", rc_mode->name); \
1388 goto rc_mode_found; \
1392 if (ctx->explicit_rc_mode)
1393 TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1395 if (ctx->explicit_qp)
1396 TRY_RC_MODE(RC_MODE_CQP, 1);
1398 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1399 TRY_RC_MODE(RC_MODE_CQP, 1);
1401 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1402 TRY_RC_MODE(RC_MODE_CQP, 1);
1404 if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1405 TRY_RC_MODE(RC_MODE_QVBR, 0);
1407 if (avctx->global_quality > 0) {
1408 TRY_RC_MODE(RC_MODE_ICQ, 0);
1409 TRY_RC_MODE(RC_MODE_CQP, 0);
1412 if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1413 TRY_RC_MODE(RC_MODE_CBR, 0);
1415 if (avctx->bit_rate > 0) {
1416 TRY_RC_MODE(RC_MODE_AVBR, 0);
1417 TRY_RC_MODE(RC_MODE_VBR, 0);
1418 TRY_RC_MODE(RC_MODE_CBR, 0);
1420 TRY_RC_MODE(RC_MODE_ICQ, 0);
1421 TRY_RC_MODE(RC_MODE_CQP, 0);
1424 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1425 "RC mode compatible with selected options "
1426 "(supported modes: %s).\n", supported_rc_modes_string);
1427 return AVERROR(EINVAL);
1430 if (rc_mode->bitrate) {
1431 if (avctx->bit_rate <= 0) {
1432 av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1433 "RC mode.\n", rc_mode->name);
1434 return AVERROR(EINVAL);
1437 if (rc_mode->mode == RC_MODE_AVBR) {
1438 // For maximum confusion AVBR is hacked into the existing API
1439 // by overloading some of the fields with completely different
1442 // Target percentage does not apply in AVBR mode.
1443 rc_bits_per_second = avctx->bit_rate;
1445 // Accuracy tolerance range for meeting the specified target
1446 // bitrate. It's very unclear how this is actually intended
1447 // to work - since we do want to get the specified bitrate,
1448 // set the accuracy to 100% for now.
1449 rc_target_percentage = 100;
1451 // Convergence period in frames. The GOP size reflects the
1452 // user's intended block size for cutting, so reusing that
1453 // as the convergence period seems a reasonable default.
1454 rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1456 } else if (rc_mode->maxrate) {
1457 if (avctx->rc_max_rate > 0) {
1458 if (avctx->rc_max_rate < avctx->bit_rate) {
1459 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1460 "bitrate (%"PRId64") must not be greater than "
1461 "maxrate (%"PRId64").\n", avctx->bit_rate,
1462 avctx->rc_max_rate);
1463 return AVERROR(EINVAL);
1465 rc_bits_per_second = avctx->rc_max_rate;
1466 rc_target_percentage = (avctx->bit_rate * 100) /
1469 // We only have a target bitrate, but this mode requires
1470 // that a maximum rate be supplied as well. Since the
1471 // user does not want this to be a constraint, arbitrarily
1472 // pick a maximum rate of double the target rate.
1473 rc_bits_per_second = 2 * avctx->bit_rate;
1474 rc_target_percentage = 50;
1477 if (avctx->rc_max_rate > avctx->bit_rate) {
1478 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1479 "in %s RC mode.\n", rc_mode->name);
1481 rc_bits_per_second = avctx->bit_rate;
1482 rc_target_percentage = 100;
1485 rc_bits_per_second = 0;
1486 rc_target_percentage = 100;
1489 if (rc_mode->quality) {
1490 if (ctx->explicit_qp) {
1491 rc_quality = ctx->explicit_qp;
1492 } else if (avctx->global_quality > 0) {
1493 rc_quality = avctx->global_quality;
1495 rc_quality = ctx->codec->default_quality;
1496 av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1497 "using default (%d).\n", rc_quality);
1504 if (avctx->rc_buffer_size)
1505 hrd_buffer_size = avctx->rc_buffer_size;
1506 else if (avctx->rc_max_rate > 0)
1507 hrd_buffer_size = avctx->rc_max_rate;
1509 hrd_buffer_size = avctx->bit_rate;
1510 if (avctx->rc_initial_buffer_occupancy) {
1511 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1512 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1513 "must have initial buffer size (%d) <= "
1514 "buffer size (%"PRId64").\n",
1515 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1516 return AVERROR(EINVAL);
1518 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1520 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1523 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1525 if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1526 av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1527 "in %s RC mode.\n", rc_mode->name);
1530 hrd_buffer_size = 0;
1531 hrd_initial_buffer_fullness = 0;
1533 if (rc_mode->mode != RC_MODE_AVBR) {
1534 // Already set (with completely different meaning) for AVBR.
1535 rc_window_size = 1000;
1539 if (rc_bits_per_second > UINT32_MAX ||
1540 hrd_buffer_size > UINT32_MAX ||
1541 hrd_initial_buffer_fullness > UINT32_MAX) {
1542 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1543 "greater are not supported by VAAPI.\n");
1544 return AVERROR(EINVAL);
1547 ctx->rc_mode = rc_mode;
1548 ctx->rc_quality = rc_quality;
1549 ctx->va_rc_mode = rc_mode->va_mode;
1550 ctx->va_bit_rate = rc_bits_per_second;
1552 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1553 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1554 // This driver does not want the RC mode attribute to be set.
1556 ctx->config_attributes[ctx->nb_config_attributes++] =
1558 .type = VAConfigAttribRateControl,
1559 .value = ctx->va_rc_mode,
1563 if (rc_mode->quality)
1564 av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1566 if (rc_mode->va_mode != VA_RC_CQP) {
1567 if (rc_mode->mode == RC_MODE_AVBR) {
1568 av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1569 "converging in %d frames with %d%% accuracy.\n",
1570 rc_bits_per_second, rc_window_size,
1571 rc_target_percentage);
1572 } else if (rc_mode->bitrate) {
1573 av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1574 "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1575 rc_bits_per_second, rc_window_size);
1578 ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1579 ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1580 .bits_per_second = rc_bits_per_second,
1581 .target_percentage = rc_target_percentage,
1582 .window_size = rc_window_size,
1584 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1585 .basic_unit_size = 0,
1586 #if VA_CHECK_VERSION(1, 1, 0)
1587 .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1588 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1590 #if VA_CHECK_VERSION(1, 3, 0)
1591 .quality_factor = rc_quality,
1594 vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
1595 sizeof(ctx->rc_params));
1599 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1600 "initial fullness %"PRId64" bits.\n",
1601 hrd_buffer_size, hrd_initial_buffer_fullness);
1603 ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1604 ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1605 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1606 .buffer_size = hrd_buffer_size,
1608 vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
1609 sizeof(ctx->hrd_params));
1612 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1613 av_reduce(&fr_num, &fr_den,
1614 avctx->framerate.num, avctx->framerate.den, 65535);
1616 av_reduce(&fr_num, &fr_den,
1617 avctx->time_base.den, avctx->time_base.num, 65535);
1619 av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1620 fr_num, fr_den, (double)fr_num / fr_den);
1622 ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1623 ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1625 #if VA_CHECK_VERSION(0, 40, 0)
1626 vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
1627 sizeof(ctx->fr_params));
1633 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1635 VAAPIEncodeContext *ctx = avctx->priv_data;
1637 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1638 uint32_t ref_l0, ref_l1;
1640 vas = vaGetConfigAttributes(ctx->hwctx->display,
1644 if (vas != VA_STATUS_SUCCESS) {
1645 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1646 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1647 return AVERROR_EXTERNAL;
1650 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1651 ref_l0 = ref_l1 = 0;
1653 ref_l0 = attr.value & 0xffff;
1654 ref_l1 = attr.value >> 16 & 0xffff;
1657 if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1658 avctx->gop_size <= 1) {
1659 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1661 } else if (ref_l0 < 1) {
1662 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1663 "reference frames.\n");
1664 return AVERROR(EINVAL);
1665 } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1666 ref_l1 < 1 || avctx->max_b_frames < 1) {
1667 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1668 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1669 ctx->gop_size = avctx->gop_size;
1670 ctx->p_per_i = INT_MAX;
1673 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1674 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1675 ctx->gop_size = avctx->gop_size;
1676 ctx->p_per_i = INT_MAX;
1677 ctx->b_per_p = avctx->max_b_frames;
1678 if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1679 ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1680 av_log2(ctx->b_per_p) + 1);
1682 ctx->max_b_depth = 1;
1686 if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1687 ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1688 ctx->gop_per_idr = ctx->idr_interval + 1;
1690 ctx->closed_gop = 1;
1691 ctx->gop_per_idr = 1;
1697 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1699 VAAPIEncodeContext *ctx = avctx->priv_data;
1700 VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1701 { VAConfigAttribEncSliceStructure } };
1703 uint32_t max_slices, slice_structure;
1706 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1707 if (avctx->slices > 0) {
1708 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1709 "but this codec does not support controlling slices.\n");
1714 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1715 ctx->slice_block_height;
1716 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
1717 ctx->slice_block_width;
1719 if (avctx->slices <= 1) {
1721 ctx->slice_size = ctx->slice_block_rows;
1725 vas = vaGetConfigAttributes(ctx->hwctx->display,
1728 attr, FF_ARRAY_ELEMS(attr));
1729 if (vas != VA_STATUS_SUCCESS) {
1730 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1731 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1732 return AVERROR_EXTERNAL;
1734 max_slices = attr[0].value;
1735 slice_structure = attr[1].value;
1736 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1737 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1738 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1739 "pictures as multiple slices.\n.");
1740 return AVERROR(EINVAL);
1743 // For fixed-size slices currently we only support whole rows, making
1744 // rectangular slices. This could be extended to arbitrary runs of
1745 // blocks, but since slices tend to be a conformance requirement and
1746 // most cases (such as broadcast or bluray) want rectangular slices
1747 // only it would need to be gated behind another option.
1748 if (avctx->slices > ctx->slice_block_rows) {
1749 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1750 "configured number of slices (%d < %d); using "
1751 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1752 req_slices = ctx->slice_block_rows;
1754 req_slices = avctx->slices;
1756 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1757 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1758 ctx->nb_slices = req_slices;
1759 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1760 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1762 for (k = 1;; k *= 2) {
1763 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1766 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1767 ctx->slice_size = k;
1768 #if VA_CHECK_VERSION(1, 0, 0)
1769 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1770 ctx->nb_slices = ctx->slice_block_rows;
1771 ctx->slice_size = 1;
1774 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1775 "slice structure modes (%#x).\n", slice_structure);
1776 return AVERROR(EINVAL);
1779 if (ctx->nb_slices > avctx->slices) {
1780 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1781 "%d (from %d) due to driver constraints on slice "
1782 "structure.\n", ctx->nb_slices, avctx->slices);
1784 if (ctx->nb_slices > max_slices) {
1785 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1786 "encoding with %d slices (max %"PRIu32").\n",
1787 ctx->nb_slices, max_slices);
1788 return AVERROR(EINVAL);
1791 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1792 "(default size %d block rows).\n",
1793 ctx->nb_slices, ctx->slice_size);
1797 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1799 VAAPIEncodeContext *ctx = avctx->priv_data;
1801 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1803 vas = vaGetConfigAttributes(ctx->hwctx->display,
1807 if (vas != VA_STATUS_SUCCESS) {
1808 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1809 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1810 return AVERROR_EXTERNAL;
1813 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1814 if (ctx->desired_packed_headers) {
1815 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1816 "packed headers (wanted %#x).\n",
1817 ctx->desired_packed_headers);
1819 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1820 "packed headers (none wanted).\n");
1822 ctx->va_packed_headers = 0;
1824 if (ctx->desired_packed_headers & ~attr.value) {
1825 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1826 "wanted packed headers (wanted %#x, found %#x).\n",
1827 ctx->desired_packed_headers, attr.value);
1829 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1830 "available (wanted %#x, found %#x).\n",
1831 ctx->desired_packed_headers, attr.value);
1833 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1836 if (ctx->va_packed_headers) {
1837 ctx->config_attributes[ctx->nb_config_attributes++] =
1839 .type = VAConfigAttribEncPackedHeaders,
1840 .value = ctx->va_packed_headers,
1844 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1845 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1846 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1847 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1848 "sequence headers, but a global header is requested.\n");
1849 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1850 "this may result in a stream which is not usable for some "
1851 "purposes (e.g. not muxable to some containers).\n");
1857 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1859 #if VA_CHECK_VERSION(0, 36, 0)
1860 VAAPIEncodeContext *ctx = avctx->priv_data;
1862 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1863 int quality = avctx->compression_level;
1865 vas = vaGetConfigAttributes(ctx->hwctx->display,
1869 if (vas != VA_STATUS_SUCCESS) {
1870 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1871 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1872 return AVERROR_EXTERNAL;
1875 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1877 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1878 "supported: will use default quality level.\n");
1881 if (quality > attr.value) {
1882 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1883 "valid range is 0-%d, using %d.\n",
1884 attr.value, attr.value);
1885 quality = attr.value;
1888 ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
1889 ctx->quality_params.quality.quality_level = quality;
1891 vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
1892 sizeof(ctx->quality_params));
1895 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1896 "not supported with this VAAPI version.\n");
1902 static void vaapi_encode_free_output_buffer(void *opaque,
1905 AVCodecContext *avctx = opaque;
1906 VAAPIEncodeContext *ctx = avctx->priv_data;
1907 VABufferID buffer_id;
1909 buffer_id = (VABufferID)(uintptr_t)data;
1911 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1913 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1916 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1919 AVCodecContext *avctx = opaque;
1920 VAAPIEncodeContext *ctx = avctx->priv_data;
1921 VABufferID buffer_id;
1925 // The output buffer size is fixed, so it needs to be large enough
1926 // to hold the largest possible compressed frame. We assume here
1927 // that the uncompressed frame plus some header data is an upper
1929 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1930 VAEncCodedBufferType,
1931 3 * ctx->surface_width * ctx->surface_height +
1932 (1 << 16), 1, 0, &buffer_id);
1933 if (vas != VA_STATUS_SUCCESS) {
1934 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1935 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1939 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1941 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1943 &vaapi_encode_free_output_buffer,
1944 avctx, AV_BUFFER_FLAG_READONLY);
1946 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1953 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1955 VAAPIEncodeContext *ctx = avctx->priv_data;
1956 AVVAAPIHWConfig *hwconfig = NULL;
1957 AVHWFramesConstraints *constraints = NULL;
1958 enum AVPixelFormat recon_format;
1961 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1963 err = AVERROR(ENOMEM);
1966 hwconfig->config_id = ctx->va_config;
1968 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1971 err = AVERROR(ENOMEM);
1975 // Probably we can use the input surface format as the surface format
1976 // of the reconstructed frames. If not, we just pick the first (only?)
1977 // format in the valid list and hope that it all works.
1978 recon_format = AV_PIX_FMT_NONE;
1979 if (constraints->valid_sw_formats) {
1980 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1981 if (ctx->input_frames->sw_format ==
1982 constraints->valid_sw_formats[i]) {
1983 recon_format = ctx->input_frames->sw_format;
1987 if (recon_format == AV_PIX_FMT_NONE) {
1988 // No match. Just use the first in the supported list and
1989 // hope for the best.
1990 recon_format = constraints->valid_sw_formats[0];
1993 // No idea what to use; copy input format.
1994 recon_format = ctx->input_frames->sw_format;
1996 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1997 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1999 if (ctx->surface_width < constraints->min_width ||
2000 ctx->surface_height < constraints->min_height ||
2001 ctx->surface_width > constraints->max_width ||
2002 ctx->surface_height > constraints->max_height) {
2003 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2004 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2005 ctx->surface_width, ctx->surface_height,
2006 constraints->min_width, constraints->max_width,
2007 constraints->min_height, constraints->max_height);
2008 err = AVERROR(EINVAL);
2012 av_freep(&hwconfig);
2013 av_hwframe_constraints_free(&constraints);
2015 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2016 if (!ctx->recon_frames_ref) {
2017 err = AVERROR(ENOMEM);
2020 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2022 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
2023 ctx->recon_frames->sw_format = recon_format;
2024 ctx->recon_frames->width = ctx->surface_width;
2025 ctx->recon_frames->height = ctx->surface_height;
2027 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2029 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2030 "frame context: %d.\n", err);
2036 av_freep(&hwconfig);
2037 av_hwframe_constraints_free(&constraints);
2041 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2043 VAAPIEncodeContext *ctx = avctx->priv_data;
2044 AVVAAPIFramesContext *recon_hwctx = NULL;
2048 if (!avctx->hw_frames_ctx) {
2049 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2050 "required to associate the encoding device.\n");
2051 return AVERROR(EINVAL);
2054 ctx->va_config = VA_INVALID_ID;
2055 ctx->va_context = VA_INVALID_ID;
2057 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2058 if (!ctx->input_frames_ref) {
2059 err = AVERROR(ENOMEM);
2062 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2064 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2065 if (!ctx->device_ref) {
2066 err = AVERROR(ENOMEM);
2069 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2070 ctx->hwctx = ctx->device->hwctx;
2072 err = vaapi_encode_profile_entrypoint(avctx);
2076 err = vaapi_encode_init_rate_control(avctx);
2080 err = vaapi_encode_init_gop_structure(avctx);
2084 err = vaapi_encode_init_slice_structure(avctx);
2088 err = vaapi_encode_init_packed_headers(avctx);
2092 if (avctx->compression_level >= 0) {
2093 err = vaapi_encode_init_quality(avctx);
2098 vas = vaCreateConfig(ctx->hwctx->display,
2099 ctx->va_profile, ctx->va_entrypoint,
2100 ctx->config_attributes, ctx->nb_config_attributes,
2102 if (vas != VA_STATUS_SUCCESS) {
2103 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2104 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2109 err = vaapi_encode_create_recon_frames(avctx);
2113 recon_hwctx = ctx->recon_frames->hwctx;
2114 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2115 ctx->surface_width, ctx->surface_height,
2117 recon_hwctx->surface_ids,
2118 recon_hwctx->nb_surfaces,
2120 if (vas != VA_STATUS_SUCCESS) {
2121 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2122 "context: %d (%s).\n", vas, vaErrorStr(vas));
2127 ctx->output_buffer_pool =
2128 av_buffer_pool_init2(sizeof(VABufferID), avctx,
2129 &vaapi_encode_alloc_output_buffer, NULL);
2130 if (!ctx->output_buffer_pool) {
2131 err = AVERROR(ENOMEM);
2135 if (ctx->codec->configure) {
2136 err = ctx->codec->configure(avctx);
2141 ctx->output_delay = ctx->b_per_p;
2142 ctx->decode_delay = ctx->max_b_depth;
2144 if (ctx->codec->sequence_params_size > 0) {
2145 ctx->codec_sequence_params =
2146 av_mallocz(ctx->codec->sequence_params_size);
2147 if (!ctx->codec_sequence_params) {
2148 err = AVERROR(ENOMEM);
2152 if (ctx->codec->picture_params_size > 0) {
2153 ctx->codec_picture_params =
2154 av_mallocz(ctx->codec->picture_params_size);
2155 if (!ctx->codec_picture_params) {
2156 err = AVERROR(ENOMEM);
2161 if (ctx->codec->init_sequence_params) {
2162 err = ctx->codec->init_sequence_params(avctx);
2164 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2165 "failed: %d.\n", err);
2170 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2171 ctx->codec->write_sequence_header &&
2172 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2173 char data[MAX_PARAM_BUFFER_SIZE];
2174 size_t bit_len = 8 * sizeof(data);
2176 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2178 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2179 "for extradata: %d.\n", err);
2182 avctx->extradata_size = (bit_len + 7) / 8;
2183 avctx->extradata = av_mallocz(avctx->extradata_size +
2184 AV_INPUT_BUFFER_PADDING_SIZE);
2185 if (!avctx->extradata) {
2186 err = AVERROR(ENOMEM);
2189 memcpy(avctx->extradata, data, avctx->extradata_size);
2196 ff_vaapi_encode_close(avctx);
2200 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2202 VAAPIEncodeContext *ctx = avctx->priv_data;
2203 VAAPIEncodePicture *pic, *next;
2205 for (pic = ctx->pic_start; pic; pic = next) {
2207 vaapi_encode_free(avctx, pic);
2210 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2212 if (ctx->va_context != VA_INVALID_ID) {
2213 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2214 ctx->va_context = VA_INVALID_ID;
2217 if (ctx->va_config != VA_INVALID_ID) {
2218 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2219 ctx->va_config = VA_INVALID_ID;
2222 av_freep(&ctx->codec_sequence_params);
2223 av_freep(&ctx->codec_picture_params);
2225 av_buffer_unref(&ctx->recon_frames_ref);
2226 av_buffer_unref(&ctx->input_frames_ref);
2227 av_buffer_unref(&ctx->device_ref);