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 av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1288 VAAPIEncodeContext *ctx = avctx->priv_data;
1289 int64_t rc_bits_per_second;
1290 int rc_target_percentage;
1292 int64_t hrd_buffer_size;
1293 int64_t hrd_initial_buffer_fullness;
1295 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1298 vas = vaGetConfigAttributes(ctx->hwctx->display,
1299 ctx->va_profile, ctx->va_entrypoint,
1301 if (vas != VA_STATUS_SUCCESS) {
1302 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1303 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1304 return AVERROR_EXTERNAL;
1307 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1308 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1309 "supported rate control modes: assuming constant-quality.\n");
1310 ctx->va_rc_mode = VA_RC_CQP;
1313 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY ||
1314 avctx->flags & AV_CODEC_FLAG_QSCALE ||
1315 avctx->bit_rate <= 0) {
1316 if (rc_attr.value & VA_RC_CQP) {
1317 av_log(avctx, AV_LOG_VERBOSE, "Using constant-quality mode.\n");
1318 ctx->va_rc_mode = VA_RC_CQP;
1319 if (avctx->bit_rate > 0 || avctx->rc_max_rate > 0) {
1320 av_log(avctx, AV_LOG_WARNING, "Bitrate target parameters "
1321 "ignored in constant-quality mode.\n");
1325 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1326 "constant-quality mode (%#x).\n", rc_attr.value);
1327 return AVERROR(EINVAL);
1331 if (!(rc_attr.value & (VA_RC_CBR | VA_RC_VBR))) {
1332 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1333 "bitrate-targetted rate control modes.\n");
1334 return AVERROR(EINVAL);
1337 if (avctx->rc_buffer_size)
1338 hrd_buffer_size = avctx->rc_buffer_size;
1339 else if (avctx->rc_max_rate > 0)
1340 hrd_buffer_size = avctx->rc_max_rate;
1342 hrd_buffer_size = avctx->bit_rate;
1343 if (avctx->rc_initial_buffer_occupancy) {
1344 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1345 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1346 "must have initial buffer size (%d) < "
1347 "buffer size (%"PRId64").\n",
1348 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1349 return AVERROR(EINVAL);
1351 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1353 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1356 if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {
1357 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: must have "
1358 "bitrate (%"PRId64") <= maxrate (%"PRId64").\n",
1359 avctx->bit_rate, avctx->rc_max_rate);
1360 return AVERROR(EINVAL);
1363 if (avctx->rc_max_rate > avctx->bit_rate) {
1364 if (!(rc_attr.value & VA_RC_VBR)) {
1365 av_log(avctx, AV_LOG_WARNING, "Driver does not support "
1366 "VBR mode (%#x), using CBR mode instead.\n",
1368 ctx->va_rc_mode = VA_RC_CBR;
1370 rc_bits_per_second = avctx->bit_rate;
1371 rc_target_percentage = 100;
1373 ctx->va_rc_mode = VA_RC_VBR;
1375 rc_bits_per_second = avctx->rc_max_rate;
1376 rc_target_percentage = (avctx->bit_rate * 100) /
1380 } else if (avctx->rc_max_rate == avctx->bit_rate) {
1381 if (!(rc_attr.value & VA_RC_CBR)) {
1382 av_log(avctx, AV_LOG_WARNING, "Driver does not support "
1383 "CBR mode (%#x), using VBR mode instead.\n",
1385 ctx->va_rc_mode = VA_RC_VBR;
1387 ctx->va_rc_mode = VA_RC_CBR;
1390 rc_bits_per_second = avctx->bit_rate;
1391 rc_target_percentage = 100;
1394 if (rc_attr.value & VA_RC_VBR) {
1395 ctx->va_rc_mode = VA_RC_VBR;
1397 // We only have a target bitrate, but VAAPI requires that a
1398 // maximum rate be supplied as well. Since the user has
1399 // offered no particular constraint, arbitrarily pick a
1400 // maximum rate of double the target rate.
1401 rc_bits_per_second = 2 * avctx->bit_rate;
1402 rc_target_percentage = 50;
1404 ctx->va_rc_mode = VA_RC_CBR;
1406 rc_bits_per_second = avctx->bit_rate;
1407 rc_target_percentage = 100;
1411 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1413 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s, %d%% of %"PRId64" bps "
1414 "over %d ms.\n", ctx->va_rc_mode == VA_RC_VBR ? "VBR" : "CBR",
1415 rc_target_percentage, rc_bits_per_second, rc_window_size);
1416 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1417 "initial fullness %"PRId64" bits.\n",
1418 hrd_buffer_size, hrd_initial_buffer_fullness);
1420 if (rc_bits_per_second > UINT32_MAX ||
1421 hrd_buffer_size > UINT32_MAX ||
1422 hrd_initial_buffer_fullness > UINT32_MAX) {
1423 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1424 "greater are not supported by VAAPI.\n");
1425 return AVERROR(EINVAL);
1428 ctx->va_bit_rate = rc_bits_per_second;
1430 ctx->config_attributes[ctx->nb_config_attributes++] =
1432 .type = VAConfigAttribRateControl,
1433 .value = ctx->va_rc_mode,
1436 ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1437 ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1438 .bits_per_second = rc_bits_per_second,
1439 .target_percentage = rc_target_percentage,
1440 .window_size = rc_window_size,
1442 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1443 .basic_unit_size = 0,
1444 #if VA_CHECK_VERSION(1, 1, 0)
1445 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1448 vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
1449 sizeof(ctx->rc_params));
1451 ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1452 ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1453 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1454 .buffer_size = hrd_buffer_size,
1456 vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
1457 sizeof(ctx->hrd_params));
1459 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1460 av_reduce(&fr_num, &fr_den,
1461 avctx->framerate.num, avctx->framerate.den, 65535);
1463 av_reduce(&fr_num, &fr_den,
1464 avctx->time_base.den, avctx->time_base.num, 65535);
1466 ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1467 ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1469 #if VA_CHECK_VERSION(0, 40, 0)
1470 vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
1471 sizeof(ctx->fr_params));
1477 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1479 VAAPIEncodeContext *ctx = avctx->priv_data;
1481 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1482 uint32_t ref_l0, ref_l1;
1484 vas = vaGetConfigAttributes(ctx->hwctx->display,
1488 if (vas != VA_STATUS_SUCCESS) {
1489 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1490 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1491 return AVERROR_EXTERNAL;
1494 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1495 ref_l0 = ref_l1 = 0;
1497 ref_l0 = attr.value & 0xffff;
1498 ref_l1 = attr.value >> 16 & 0xffff;
1501 if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1502 avctx->gop_size <= 1) {
1503 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1505 } else if (ref_l0 < 1) {
1506 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1507 "reference frames.\n");
1508 return AVERROR(EINVAL);
1509 } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1510 ref_l1 < 1 || avctx->max_b_frames < 1) {
1511 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1512 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1513 ctx->gop_size = avctx->gop_size;
1514 ctx->p_per_i = INT_MAX;
1517 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1518 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1519 ctx->gop_size = avctx->gop_size;
1520 ctx->p_per_i = INT_MAX;
1521 ctx->b_per_p = avctx->max_b_frames;
1522 if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1523 ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1524 av_log2(ctx->b_per_p) + 1);
1526 ctx->max_b_depth = 1;
1530 if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1531 ctx->closed_gop = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1532 ctx->gop_per_idr = ctx->idr_interval + 1;
1534 ctx->closed_gop = 1;
1535 ctx->gop_per_idr = 1;
1541 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1543 VAAPIEncodeContext *ctx = avctx->priv_data;
1544 VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1545 { VAConfigAttribEncSliceStructure } };
1547 uint32_t max_slices, slice_structure;
1550 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1551 if (avctx->slices > 0) {
1552 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1553 "but this codec does not support controlling slices.\n");
1558 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1559 ctx->slice_block_height;
1560 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
1561 ctx->slice_block_width;
1563 if (avctx->slices <= 1) {
1565 ctx->slice_size = ctx->slice_block_rows;
1569 vas = vaGetConfigAttributes(ctx->hwctx->display,
1572 attr, FF_ARRAY_ELEMS(attr));
1573 if (vas != VA_STATUS_SUCCESS) {
1574 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1575 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1576 return AVERROR_EXTERNAL;
1578 max_slices = attr[0].value;
1579 slice_structure = attr[1].value;
1580 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1581 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1582 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1583 "pictures as multiple slices.\n.");
1584 return AVERROR(EINVAL);
1587 // For fixed-size slices currently we only support whole rows, making
1588 // rectangular slices. This could be extended to arbitrary runs of
1589 // blocks, but since slices tend to be a conformance requirement and
1590 // most cases (such as broadcast or bluray) want rectangular slices
1591 // only it would need to be gated behind another option.
1592 if (avctx->slices > ctx->slice_block_rows) {
1593 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1594 "configured number of slices (%d < %d); using "
1595 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1596 req_slices = ctx->slice_block_rows;
1598 req_slices = avctx->slices;
1600 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1601 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1602 ctx->nb_slices = req_slices;
1603 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1604 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1606 for (k = 1;; k *= 2) {
1607 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1610 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1611 ctx->slice_size = k;
1612 #if VA_CHECK_VERSION(1, 0, 0)
1613 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1614 ctx->nb_slices = ctx->slice_block_rows;
1615 ctx->slice_size = 1;
1618 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1619 "slice structure modes (%#x).\n", slice_structure);
1620 return AVERROR(EINVAL);
1623 if (ctx->nb_slices > avctx->slices) {
1624 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1625 "%d (from %d) due to driver constraints on slice "
1626 "structure.\n", ctx->nb_slices, avctx->slices);
1628 if (ctx->nb_slices > max_slices) {
1629 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1630 "encoding with %d slices (max %"PRIu32").\n",
1631 ctx->nb_slices, max_slices);
1632 return AVERROR(EINVAL);
1635 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1636 "(default size %d block rows).\n",
1637 ctx->nb_slices, ctx->slice_size);
1641 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1643 VAAPIEncodeContext *ctx = avctx->priv_data;
1645 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1647 vas = vaGetConfigAttributes(ctx->hwctx->display,
1651 if (vas != VA_STATUS_SUCCESS) {
1652 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1653 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1654 return AVERROR_EXTERNAL;
1657 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1658 if (ctx->desired_packed_headers) {
1659 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1660 "packed headers (wanted %#x).\n",
1661 ctx->desired_packed_headers);
1663 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1664 "packed headers (none wanted).\n");
1666 ctx->va_packed_headers = 0;
1668 if (ctx->desired_packed_headers & ~attr.value) {
1669 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1670 "wanted packed headers (wanted %#x, found %#x).\n",
1671 ctx->desired_packed_headers, attr.value);
1673 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1674 "available (wanted %#x, found %#x).\n",
1675 ctx->desired_packed_headers, attr.value);
1677 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1680 if (ctx->va_packed_headers) {
1681 ctx->config_attributes[ctx->nb_config_attributes++] =
1683 .type = VAConfigAttribEncPackedHeaders,
1684 .value = ctx->va_packed_headers,
1688 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1689 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1690 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1691 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1692 "sequence headers, but a global header is requested.\n");
1693 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1694 "this may result in a stream which is not usable for some "
1695 "purposes (e.g. not muxable to some containers).\n");
1701 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1703 #if VA_CHECK_VERSION(0, 36, 0)
1704 VAAPIEncodeContext *ctx = avctx->priv_data;
1706 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1707 int quality = avctx->compression_level;
1709 vas = vaGetConfigAttributes(ctx->hwctx->display,
1713 if (vas != VA_STATUS_SUCCESS) {
1714 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1715 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1716 return AVERROR_EXTERNAL;
1719 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1721 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1722 "supported: will use default quality level.\n");
1725 if (quality > attr.value) {
1726 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1727 "valid range is 0-%d, using %d.\n",
1728 attr.value, attr.value);
1729 quality = attr.value;
1732 ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
1733 ctx->quality_params.quality.quality_level = quality;
1735 vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
1736 sizeof(ctx->quality_params));
1739 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1740 "not supported with this VAAPI version.\n");
1746 static void vaapi_encode_free_output_buffer(void *opaque,
1749 AVCodecContext *avctx = opaque;
1750 VAAPIEncodeContext *ctx = avctx->priv_data;
1751 VABufferID buffer_id;
1753 buffer_id = (VABufferID)(uintptr_t)data;
1755 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1757 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1760 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1763 AVCodecContext *avctx = opaque;
1764 VAAPIEncodeContext *ctx = avctx->priv_data;
1765 VABufferID buffer_id;
1769 // The output buffer size is fixed, so it needs to be large enough
1770 // to hold the largest possible compressed frame. We assume here
1771 // that the uncompressed frame plus some header data is an upper
1773 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1774 VAEncCodedBufferType,
1775 3 * ctx->surface_width * ctx->surface_height +
1776 (1 << 16), 1, 0, &buffer_id);
1777 if (vas != VA_STATUS_SUCCESS) {
1778 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1779 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1783 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1785 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1787 &vaapi_encode_free_output_buffer,
1788 avctx, AV_BUFFER_FLAG_READONLY);
1790 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1797 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1799 VAAPIEncodeContext *ctx = avctx->priv_data;
1800 AVVAAPIHWConfig *hwconfig = NULL;
1801 AVHWFramesConstraints *constraints = NULL;
1802 enum AVPixelFormat recon_format;
1805 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1807 err = AVERROR(ENOMEM);
1810 hwconfig->config_id = ctx->va_config;
1812 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1815 err = AVERROR(ENOMEM);
1819 // Probably we can use the input surface format as the surface format
1820 // of the reconstructed frames. If not, we just pick the first (only?)
1821 // format in the valid list and hope that it all works.
1822 recon_format = AV_PIX_FMT_NONE;
1823 if (constraints->valid_sw_formats) {
1824 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1825 if (ctx->input_frames->sw_format ==
1826 constraints->valid_sw_formats[i]) {
1827 recon_format = ctx->input_frames->sw_format;
1831 if (recon_format == AV_PIX_FMT_NONE) {
1832 // No match. Just use the first in the supported list and
1833 // hope for the best.
1834 recon_format = constraints->valid_sw_formats[0];
1837 // No idea what to use; copy input format.
1838 recon_format = ctx->input_frames->sw_format;
1840 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1841 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1843 if (ctx->surface_width < constraints->min_width ||
1844 ctx->surface_height < constraints->min_height ||
1845 ctx->surface_width > constraints->max_width ||
1846 ctx->surface_height > constraints->max_height) {
1847 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1848 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1849 ctx->surface_width, ctx->surface_height,
1850 constraints->min_width, constraints->max_width,
1851 constraints->min_height, constraints->max_height);
1852 err = AVERROR(EINVAL);
1856 av_freep(&hwconfig);
1857 av_hwframe_constraints_free(&constraints);
1859 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1860 if (!ctx->recon_frames_ref) {
1861 err = AVERROR(ENOMEM);
1864 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1866 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
1867 ctx->recon_frames->sw_format = recon_format;
1868 ctx->recon_frames->width = ctx->surface_width;
1869 ctx->recon_frames->height = ctx->surface_height;
1871 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1873 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1874 "frame context: %d.\n", err);
1880 av_freep(&hwconfig);
1881 av_hwframe_constraints_free(&constraints);
1885 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
1887 VAAPIEncodeContext *ctx = avctx->priv_data;
1888 AVVAAPIFramesContext *recon_hwctx = NULL;
1892 if (!avctx->hw_frames_ctx) {
1893 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1894 "required to associate the encoding device.\n");
1895 return AVERROR(EINVAL);
1898 ctx->va_config = VA_INVALID_ID;
1899 ctx->va_context = VA_INVALID_ID;
1901 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1902 if (!ctx->input_frames_ref) {
1903 err = AVERROR(ENOMEM);
1906 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1908 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1909 if (!ctx->device_ref) {
1910 err = AVERROR(ENOMEM);
1913 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1914 ctx->hwctx = ctx->device->hwctx;
1916 err = vaapi_encode_profile_entrypoint(avctx);
1920 err = vaapi_encode_init_rate_control(avctx);
1924 err = vaapi_encode_init_gop_structure(avctx);
1928 err = vaapi_encode_init_slice_structure(avctx);
1932 err = vaapi_encode_init_packed_headers(avctx);
1936 if (avctx->compression_level >= 0) {
1937 err = vaapi_encode_init_quality(avctx);
1942 vas = vaCreateConfig(ctx->hwctx->display,
1943 ctx->va_profile, ctx->va_entrypoint,
1944 ctx->config_attributes, ctx->nb_config_attributes,
1946 if (vas != VA_STATUS_SUCCESS) {
1947 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1948 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1953 err = vaapi_encode_create_recon_frames(avctx);
1957 recon_hwctx = ctx->recon_frames->hwctx;
1958 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1959 ctx->surface_width, ctx->surface_height,
1961 recon_hwctx->surface_ids,
1962 recon_hwctx->nb_surfaces,
1964 if (vas != VA_STATUS_SUCCESS) {
1965 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1966 "context: %d (%s).\n", vas, vaErrorStr(vas));
1971 ctx->output_buffer_pool =
1972 av_buffer_pool_init2(sizeof(VABufferID), avctx,
1973 &vaapi_encode_alloc_output_buffer, NULL);
1974 if (!ctx->output_buffer_pool) {
1975 err = AVERROR(ENOMEM);
1979 if (ctx->codec->configure) {
1980 err = ctx->codec->configure(avctx);
1985 ctx->output_delay = ctx->b_per_p;
1986 ctx->decode_delay = ctx->max_b_depth;
1988 if (ctx->codec->sequence_params_size > 0) {
1989 ctx->codec_sequence_params =
1990 av_mallocz(ctx->codec->sequence_params_size);
1991 if (!ctx->codec_sequence_params) {
1992 err = AVERROR(ENOMEM);
1996 if (ctx->codec->picture_params_size > 0) {
1997 ctx->codec_picture_params =
1998 av_mallocz(ctx->codec->picture_params_size);
1999 if (!ctx->codec_picture_params) {
2000 err = AVERROR(ENOMEM);
2005 if (ctx->codec->init_sequence_params) {
2006 err = ctx->codec->init_sequence_params(avctx);
2008 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2009 "failed: %d.\n", err);
2014 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2015 ctx->codec->write_sequence_header &&
2016 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2017 char data[MAX_PARAM_BUFFER_SIZE];
2018 size_t bit_len = 8 * sizeof(data);
2020 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2022 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2023 "for extradata: %d.\n", err);
2026 avctx->extradata_size = (bit_len + 7) / 8;
2027 avctx->extradata = av_mallocz(avctx->extradata_size +
2028 AV_INPUT_BUFFER_PADDING_SIZE);
2029 if (!avctx->extradata) {
2030 err = AVERROR(ENOMEM);
2033 memcpy(avctx->extradata, data, avctx->extradata_size);
2040 ff_vaapi_encode_close(avctx);
2044 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2046 VAAPIEncodeContext *ctx = avctx->priv_data;
2047 VAAPIEncodePicture *pic, *next;
2049 for (pic = ctx->pic_start; pic; pic = next) {
2051 vaapi_encode_free(avctx, pic);
2054 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2056 if (ctx->va_context != VA_INVALID_ID) {
2057 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2058 ctx->va_context = VA_INVALID_ID;
2061 if (ctx->va_config != VA_INVALID_ID) {
2062 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2063 ctx->va_config = VA_INVALID_ID;
2066 av_freep(&ctx->codec_sequence_params);
2067 av_freep(&ctx->codec_picture_params);
2069 av_buffer_unref(&ctx->recon_frames_ref);
2070 av_buffer_unref(&ctx->input_frames_ref);
2071 av_buffer_unref(&ctx->device_ref);