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->input_available && !pic->encode_issued);
162 for (i = 0; i < pic->nb_refs; i++) {
163 av_assert0(pic->refs[i]);
164 // If we are serialised then the references must have already
165 // completed. If not, they must have been issued but need not
166 // have completed yet.
167 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
168 av_assert0(pic->refs[i]->encode_complete);
170 av_assert0(pic->refs[i]->encode_issued);
173 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
175 pic->recon_image = av_frame_alloc();
176 if (!pic->recon_image) {
177 err = AVERROR(ENOMEM);
181 err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
183 err = AVERROR(ENOMEM);
186 pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
187 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
189 pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
190 if (!pic->output_buffer_ref) {
191 err = AVERROR(ENOMEM);
194 pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
195 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
198 if (ctx->codec->picture_params_size > 0) {
199 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
200 if (!pic->codec_picture_params)
202 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
203 ctx->codec->picture_params_size);
205 av_assert0(!ctx->codec_picture_params);
208 pic->nb_param_buffers = 0;
210 if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
211 err = vaapi_encode_make_param_buffer(avctx, pic,
212 VAEncSequenceParameterBufferType,
213 ctx->codec_sequence_params,
214 ctx->codec->sequence_params_size);
219 if (pic->type == PICTURE_TYPE_IDR) {
220 for (i = 0; i < ctx->nb_global_params; i++) {
221 err = vaapi_encode_make_param_buffer(avctx, pic,
222 VAEncMiscParameterBufferType,
223 (char*)ctx->global_params[i],
224 ctx->global_params_size[i]);
230 if (ctx->codec->init_picture_params) {
231 err = ctx->codec->init_picture_params(avctx, pic);
233 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
234 "parameters: %d.\n", err);
237 err = vaapi_encode_make_param_buffer(avctx, pic,
238 VAEncPictureParameterBufferType,
239 pic->codec_picture_params,
240 ctx->codec->picture_params_size);
245 if (pic->type == PICTURE_TYPE_IDR) {
246 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
247 ctx->codec->write_sequence_header) {
248 bit_len = 8 * sizeof(data);
249 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
251 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
252 "header: %d.\n", err);
255 err = vaapi_encode_make_packed_header(avctx, pic,
256 ctx->codec->sequence_header_type,
263 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
264 ctx->codec->write_picture_header) {
265 bit_len = 8 * sizeof(data);
266 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
268 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
269 "header: %d.\n", err);
272 err = vaapi_encode_make_packed_header(avctx, pic,
273 ctx->codec->picture_header_type,
279 if (ctx->codec->write_extra_buffer) {
281 size_t len = sizeof(data);
283 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
285 if (err == AVERROR_EOF)
288 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
289 "buffer %d: %d.\n", i, err);
293 err = vaapi_encode_make_param_buffer(avctx, pic, type,
300 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
301 ctx->codec->write_extra_header) {
304 bit_len = 8 * sizeof(data);
305 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
307 if (err == AVERROR_EOF)
310 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
311 "header %d: %d.\n", i, err);
315 err = vaapi_encode_make_packed_header(avctx, pic, type,
322 if (pic->nb_slices == 0)
323 pic->nb_slices = ctx->nb_slices;
324 if (pic->nb_slices > 0) {
327 pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
329 err = AVERROR(ENOMEM);
333 for (i = 0; i < pic->nb_slices; i++)
334 pic->slices[i].row_size = ctx->slice_size;
336 rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
338 // Place rounding error at top and bottom of frame.
339 av_assert0(rounding < pic->nb_slices);
340 // Some Intel drivers contain a bug where the encoder will fail
341 // if the last slice is smaller than the one before it. Since
342 // that's straightforward to avoid here, just do so.
344 for (i = 0; i < rounding; i++)
345 ++pic->slices[i].row_size;
347 for (i = 0; i < (rounding + 1) / 2; i++)
348 ++pic->slices[pic->nb_slices - i - 1].row_size;
349 for (i = 0; i < rounding / 2; i++)
350 ++pic->slices[i].row_size;
352 } else if (rounding < 0) {
353 // Remove rounding error from last slice only.
354 av_assert0(rounding < ctx->slice_size);
355 pic->slices[pic->nb_slices - 1].row_size += rounding;
358 for (i = 0; i < pic->nb_slices; i++) {
359 slice = &pic->slices[i];
362 slice->row_start = 0;
363 slice->block_start = 0;
365 const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
366 slice->row_start = prev->row_start + prev->row_size;
367 slice->block_start = prev->block_start + prev->block_size;
369 slice->block_size = slice->row_size * ctx->slice_block_cols;
371 av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
372 "%d-%d (%d blocks).\n", i, slice->row_start,
373 slice->row_start + slice->row_size - 1, slice->row_size,
374 slice->block_start, slice->block_start + slice->block_size - 1,
377 if (ctx->codec->slice_params_size > 0) {
378 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
379 if (!slice->codec_slice_params) {
380 err = AVERROR(ENOMEM);
385 if (ctx->codec->init_slice_params) {
386 err = ctx->codec->init_slice_params(avctx, pic, slice);
388 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
389 "parameters: %d.\n", err);
394 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
395 ctx->codec->write_slice_header) {
396 bit_len = 8 * sizeof(data);
397 err = ctx->codec->write_slice_header(avctx, pic, slice,
400 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
401 "header: %d.\n", err);
404 err = vaapi_encode_make_packed_header(avctx, pic,
405 ctx->codec->slice_header_type,
411 if (ctx->codec->init_slice_params) {
412 err = vaapi_encode_make_param_buffer(avctx, pic,
413 VAEncSliceParameterBufferType,
414 slice->codec_slice_params,
415 ctx->codec->slice_params_size);
421 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
423 if (vas != VA_STATUS_SUCCESS) {
424 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
425 "%d (%s).\n", vas, vaErrorStr(vas));
427 goto fail_with_picture;
430 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
431 pic->param_buffers, pic->nb_param_buffers);
432 if (vas != VA_STATUS_SUCCESS) {
433 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
434 "%d (%s).\n", vas, vaErrorStr(vas));
436 goto fail_with_picture;
439 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
440 if (vas != VA_STATUS_SUCCESS) {
441 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
442 "%d (%s).\n", vas, vaErrorStr(vas));
444 // vaRenderPicture() has been called here, so we should not destroy
445 // the parameter buffers unless separate destruction is required.
446 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
447 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
453 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
454 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
455 for (i = 0; i < pic->nb_param_buffers; i++) {
456 vas = vaDestroyBuffer(ctx->hwctx->display,
457 pic->param_buffers[i]);
458 if (vas != VA_STATUS_SUCCESS) {
459 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
460 "param buffer %#x: %d (%s).\n",
461 pic->param_buffers[i], vas, vaErrorStr(vas));
467 pic->encode_issued = 1;
469 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
470 return vaapi_encode_wait(avctx, pic);
475 vaEndPicture(ctx->hwctx->display, ctx->va_context);
477 for(i = 0; i < pic->nb_param_buffers; i++)
478 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
479 for (i = 0; i < pic->nb_slices; i++) {
481 av_freep(&pic->slices[i].priv_data);
482 av_freep(&pic->slices[i].codec_slice_params);
486 av_freep(&pic->codec_picture_params);
487 av_freep(&pic->param_buffers);
488 av_freep(&pic->slices);
489 av_frame_free(&pic->recon_image);
490 av_buffer_unref(&pic->output_buffer_ref);
491 pic->output_buffer = VA_INVALID_ID;
495 static int vaapi_encode_output(AVCodecContext *avctx,
496 VAAPIEncodePicture *pic, AVPacket *pkt)
498 VAAPIEncodeContext *ctx = avctx->priv_data;
499 VACodedBufferSegment *buf_list, *buf;
503 err = vaapi_encode_wait(avctx, pic);
508 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
510 if (vas != VA_STATUS_SUCCESS) {
511 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
512 "%d (%s).\n", vas, vaErrorStr(vas));
517 for (buf = buf_list; buf; buf = buf->next) {
518 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
519 "(status %08x).\n", buf->size, buf->status);
521 err = av_new_packet(pkt, buf->size);
525 memcpy(pkt->data, buf->buf, buf->size);
528 if (pic->type == PICTURE_TYPE_IDR)
529 pkt->flags |= AV_PKT_FLAG_KEY;
533 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
534 if (vas != VA_STATUS_SUCCESS) {
535 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
536 "%d (%s).\n", vas, vaErrorStr(vas));
541 av_buffer_unref(&pic->output_buffer_ref);
542 pic->output_buffer = VA_INVALID_ID;
544 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
545 pic->display_order, pic->encode_order);
549 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
551 av_buffer_unref(&pic->output_buffer_ref);
552 pic->output_buffer = VA_INVALID_ID;
556 static int vaapi_encode_discard(AVCodecContext *avctx,
557 VAAPIEncodePicture *pic)
559 vaapi_encode_wait(avctx, pic);
561 if (pic->output_buffer_ref) {
562 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
563 "%"PRId64"/%"PRId64".\n",
564 pic->display_order, pic->encode_order);
566 av_buffer_unref(&pic->output_buffer_ref);
567 pic->output_buffer = VA_INVALID_ID;
573 static VAAPIEncodePicture *vaapi_encode_alloc(void)
575 VAAPIEncodePicture *pic;
577 pic = av_mallocz(sizeof(*pic));
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 int vaapi_encode_step(AVCodecContext *avctx,
621 VAAPIEncodePicture *target)
623 VAAPIEncodeContext *ctx = avctx->priv_data;
624 VAAPIEncodePicture *pic;
627 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
628 ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
629 // These two modes are equivalent, except that we wait for
630 // immediate completion on each operation if serialised.
633 // No target, nothing to do yet.
637 if (target->encode_complete) {
643 for (i = 0; i < pic->nb_refs; i++) {
644 if (!pic->refs[i]->encode_complete) {
645 err = vaapi_encode_step(avctx, pic->refs[i]);
651 err = vaapi_encode_issue(avctx, pic);
655 } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
658 // Run through the list of all available pictures repeatedly
659 // and issue the first one found which has all dependencies
660 // available (including previously-issued but not necessarily
661 // completed pictures).
664 for (pic = ctx->pic_start; pic; pic = pic->next) {
665 if (!pic->input_available || pic->encode_issued)
667 for (i = 0; i < pic->nb_refs; i++) {
668 if (!pic->refs[i]->encode_issued)
671 if (i < pic->nb_refs)
673 err = vaapi_encode_issue(avctx, pic);
677 // Start again from the beginning of the list,
678 // because issuing this picture may have satisfied
679 // forward dependencies of earlier ones.
684 // If we had a defined target for this step then it will
685 // always have been issued by now.
687 av_assert0(target->encode_issued && "broken dependencies?");
697 static int vaapi_encode_get_next(AVCodecContext *avctx,
698 VAAPIEncodePicture **pic_out)
700 VAAPIEncodeContext *ctx = avctx->priv_data;
701 VAAPIEncodePicture *start, *end, *pic;
704 for (pic = ctx->pic_start; pic; pic = pic->next) {
706 av_assert0(pic->display_order + 1 == pic->next->display_order);
707 if (pic->display_order == ctx->input_order) {
713 pic = vaapi_encode_alloc();
715 return AVERROR(ENOMEM);
717 if (ctx->input_order == 0 || ctx->force_idr ||
718 ctx->gop_counter >= ctx->gop_size) {
719 pic->type = PICTURE_TYPE_IDR;
721 ctx->gop_counter = 1;
723 } else if (ctx->p_counter >= ctx->p_per_i) {
724 pic->type = PICTURE_TYPE_I;
728 pic->type = PICTURE_TYPE_P;
729 pic->refs[0] = ctx->pic_end;
736 if (pic->type != PICTURE_TYPE_IDR) {
737 // If that was not an IDR frame, add B-frames display-before and
738 // encode-after it, but not exceeding the GOP size.
740 for (i = 0; i < ctx->b_per_p &&
741 ctx->gop_counter < ctx->gop_size; i++) {
742 pic = vaapi_encode_alloc();
746 pic->type = PICTURE_TYPE_B;
747 pic->refs[0] = ctx->pic_end;
752 pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
753 pic->encode_order = pic->display_order + 1;
760 if (ctx->input_order == 0) {
761 pic->display_order = 0;
762 pic->encode_order = 0;
764 ctx->pic_start = ctx->pic_end = pic;
767 for (i = 0, pic = start; pic; i++, pic = pic->next) {
768 pic->display_order = ctx->input_order + i;
769 if (end->type == PICTURE_TYPE_IDR)
770 pic->encode_order = ctx->input_order + i;
772 pic->encode_order = ctx->input_order;
774 pic->encode_order = ctx->input_order + i + 1;
777 av_assert0(ctx->pic_end);
778 ctx->pic_end->next = start;
783 av_log(avctx, AV_LOG_DEBUG, "Pictures:");
784 for (pic = ctx->pic_start; pic; pic = pic->next) {
785 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
786 picture_type_name[pic->type],
787 pic->display_order, pic->encode_order);
789 av_log(avctx, AV_LOG_DEBUG, "\n");
796 vaapi_encode_free(avctx, start);
799 return AVERROR(ENOMEM);
802 static int vaapi_encode_truncate_gop(AVCodecContext *avctx)
804 VAAPIEncodeContext *ctx = avctx->priv_data;
805 VAAPIEncodePicture *pic, *last_pic, *next;
807 av_assert0(!ctx->pic_start || ctx->pic_start->input_available);
809 // Find the last picture we actually have input for.
810 for (pic = ctx->pic_start; pic; pic = pic->next) {
811 if (!pic->input_available)
817 if (last_pic->type == PICTURE_TYPE_B) {
818 // Some fixing up is required. Change the type of this
819 // picture to P, then modify preceding B references which
820 // point beyond it to point at it instead.
822 last_pic->type = PICTURE_TYPE_P;
823 last_pic->encode_order = last_pic->refs[1]->encode_order;
825 for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
826 if (pic->type == PICTURE_TYPE_B &&
827 pic->refs[1] == last_pic->refs[1])
828 pic->refs[1] = last_pic;
831 last_pic->nb_refs = 1;
832 last_pic->refs[1] = NULL;
834 // We can use the current structure (no references point
835 // beyond the end), but there are unused pics to discard.
838 // Discard all following pics, they will never be used.
839 for (pic = last_pic->next; pic; pic = next) {
841 vaapi_encode_free(avctx, pic);
844 last_pic->next = NULL;
845 ctx->pic_end = last_pic;
848 // Input is available for all pictures, so we don't need to
852 av_log(avctx, AV_LOG_DEBUG, "Pictures ending truncated GOP:");
853 for (pic = ctx->pic_start; pic; pic = pic->next) {
854 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
855 picture_type_name[pic->type],
856 pic->display_order, pic->encode_order);
858 av_log(avctx, AV_LOG_DEBUG, "\n");
863 static int vaapi_encode_clear_old(AVCodecContext *avctx)
865 VAAPIEncodeContext *ctx = avctx->priv_data;
866 VAAPIEncodePicture *pic, *old;
869 while (ctx->pic_start != ctx->pic_end) {
870 old = ctx->pic_start;
871 if (old->encode_order > ctx->output_order)
874 for (pic = old->next; pic; pic = pic->next) {
875 if (pic->encode_complete)
877 for (i = 0; i < pic->nb_refs; i++) {
878 if (pic->refs[i] == old) {
879 // We still need this picture because it's referred to
880 // directly by a later one, so it and all following
881 // pictures have to stay.
887 pic = ctx->pic_start;
888 ctx->pic_start = pic->next;
889 vaapi_encode_free(avctx, pic);
895 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
896 const AVFrame *input_image, int *got_packet)
898 VAAPIEncodeContext *ctx = avctx->priv_data;
899 VAAPIEncodePicture *pic;
903 av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
904 input_image->width, input_image->height, input_image->pts);
906 if (input_image->pict_type == AV_PICTURE_TYPE_I) {
907 err = vaapi_encode_truncate_gop(avctx);
913 err = vaapi_encode_get_next(avctx, &pic);
915 av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
919 pic->input_image = av_frame_alloc();
920 if (!pic->input_image) {
921 err = AVERROR(ENOMEM);
924 err = av_frame_ref(pic->input_image, input_image);
927 pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
928 pic->pts = input_image->pts;
930 if (ctx->input_order == 0)
931 ctx->first_pts = pic->pts;
932 if (ctx->input_order == ctx->decode_delay)
933 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
934 if (ctx->output_delay > 0)
935 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
937 pic->input_available = 1;
940 if (!ctx->end_of_stream) {
941 err = vaapi_encode_truncate_gop(avctx);
944 ctx->end_of_stream = 1;
950 av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
952 for (pic = ctx->pic_start; pic; pic = pic->next)
953 if (pic->encode_order == ctx->output_order)
956 // pic can be null here if we don't have a specific target in this
957 // iteration. We might still issue encodes if things can be overlapped,
958 // even though we don't intend to output anything.
960 err = vaapi_encode_step(avctx, pic);
962 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
969 err = vaapi_encode_output(avctx, pic, pkt);
971 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
975 if (ctx->output_delay == 0) {
977 } else if (ctx->output_order < ctx->decode_delay) {
978 if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
979 pkt->dts = INT64_MIN;
981 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
983 pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
984 (3 * ctx->output_delay)];
990 err = vaapi_encode_clear_old(avctx);
992 av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
999 // Unclear what to clean up on failure. There are probably some things we
1000 // could do usefully clean up here, but for now just leave them for uninit()
1005 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx,
1006 VAEncMiscParameterBuffer *buffer,
1009 VAAPIEncodeContext *ctx = avctx->priv_data;
1011 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1013 ctx->global_params [ctx->nb_global_params] = buffer;
1014 ctx->global_params_size[ctx->nb_global_params] = size;
1016 ++ctx->nb_global_params;
1019 typedef struct VAAPIEncodeRTFormat {
1026 } VAAPIEncodeRTFormat;
1028 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1029 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
1030 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
1031 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
1032 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
1033 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
1034 #if VA_CHECK_VERSION(0, 38, 1)
1035 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1039 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1040 VAEntrypointEncSlice,
1041 VAEntrypointEncPicture,
1042 #if VA_CHECK_VERSION(0, 39, 2)
1043 VAEntrypointEncSliceLP,
1047 #if VA_CHECK_VERSION(0, 39, 2)
1048 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1049 VAEntrypointEncSliceLP,
1054 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1056 VAAPIEncodeContext *ctx = avctx->priv_data;
1057 VAProfile *va_profiles = NULL;
1058 VAEntrypoint *va_entrypoints = NULL;
1060 const VAEntrypoint *usable_entrypoints;
1061 const VAAPIEncodeProfile *profile;
1062 const AVPixFmtDescriptor *desc;
1063 VAConfigAttrib rt_format_attr;
1064 const VAAPIEncodeRTFormat *rt_format;
1065 const char *profile_string, *entrypoint_string;
1066 int i, j, n, depth, err;
1069 if (ctx->low_power) {
1070 #if VA_CHECK_VERSION(0, 39, 2)
1071 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1073 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1074 "supported with this VAAPI version.\n");
1075 return AVERROR(EINVAL);
1078 usable_entrypoints = vaapi_encode_entrypoints_normal;
1081 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1083 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1084 ctx->input_frames->sw_format);
1085 return AVERROR(EINVAL);
1087 depth = desc->comp[0].depth;
1088 for (i = 1; i < desc->nb_components; i++) {
1089 if (desc->comp[i].depth != depth) {
1090 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1092 return AVERROR(EINVAL);
1095 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1098 n = vaMaxNumProfiles(ctx->hwctx->display);
1099 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1101 err = AVERROR(ENOMEM);
1104 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1105 if (vas != VA_STATUS_SUCCESS) {
1106 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1107 vas, vaErrorStr(vas));
1108 err = AVERROR_EXTERNAL;
1112 av_assert0(ctx->codec->profiles);
1113 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1114 FF_PROFILE_UNKNOWN); i++) {
1115 profile = &ctx->codec->profiles[i];
1116 if (depth != profile->depth ||
1117 desc->nb_components != profile->nb_components)
1119 if (desc->nb_components > 1 &&
1120 (desc->log2_chroma_w != profile->log2_chroma_w ||
1121 desc->log2_chroma_h != profile->log2_chroma_h))
1123 if (avctx->profile != profile->av_profile &&
1124 avctx->profile != FF_PROFILE_UNKNOWN)
1127 #if VA_CHECK_VERSION(1, 0, 0)
1128 profile_string = vaProfileStr(profile->va_profile);
1130 profile_string = "(no profile names)";
1133 for (j = 0; j < n; j++) {
1134 if (va_profiles[j] == profile->va_profile)
1138 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1139 "is not supported by driver.\n", profile_string,
1140 profile->va_profile);
1144 ctx->profile = profile;
1147 if (!ctx->profile) {
1148 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1149 err = AVERROR(ENOSYS);
1153 avctx->profile = profile->av_profile;
1154 ctx->va_profile = profile->va_profile;
1155 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1156 profile_string, ctx->va_profile);
1158 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1159 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1160 if (!va_entrypoints) {
1161 err = AVERROR(ENOMEM);
1164 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1165 va_entrypoints, &n);
1166 if (vas != VA_STATUS_SUCCESS) {
1167 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1168 "profile %s (%d): %d (%s).\n", profile_string,
1169 ctx->va_profile, vas, vaErrorStr(vas));
1170 err = AVERROR_EXTERNAL;
1174 for (i = 0; i < n; i++) {
1175 for (j = 0; usable_entrypoints[j]; j++) {
1176 if (va_entrypoints[i] == usable_entrypoints[j])
1179 if (usable_entrypoints[j])
1183 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1184 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1185 err = AVERROR(ENOSYS);
1189 ctx->va_entrypoint = va_entrypoints[i];
1190 #if VA_CHECK_VERSION(1, 0, 0)
1191 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1193 entrypoint_string = "(no entrypoint names)";
1195 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1196 entrypoint_string, ctx->va_entrypoint);
1198 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1199 rt_format = &vaapi_encode_rt_formats[i];
1200 if (rt_format->depth == depth &&
1201 rt_format->nb_components == profile->nb_components &&
1202 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1203 rt_format->log2_chroma_h == profile->log2_chroma_h)
1206 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1207 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1208 "found for profile %s (%d) entrypoint %s (%d).\n",
1209 profile_string, ctx->va_profile,
1210 entrypoint_string, ctx->va_entrypoint);
1211 err = AVERROR(ENOSYS);
1215 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1216 vas = vaGetConfigAttributes(ctx->hwctx->display,
1217 ctx->va_profile, ctx->va_entrypoint,
1218 &rt_format_attr, 1);
1219 if (vas != VA_STATUS_SUCCESS) {
1220 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1221 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1222 err = AVERROR_EXTERNAL;
1226 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1227 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1228 "supported by driver: assuming surface RT format %s "
1229 "is valid.\n", rt_format->name);
1230 } else if (!(rt_format_attr.value & rt_format->value)) {
1231 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1232 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1233 rt_format->name, profile_string, ctx->va_profile,
1234 entrypoint_string, ctx->va_entrypoint);
1235 err = AVERROR(ENOSYS);
1238 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1239 "format %s (%#x).\n", rt_format->name, rt_format->value);
1240 ctx->config_attributes[ctx->nb_config_attributes++] =
1242 .type = VAConfigAttribRTFormat,
1243 .value = rt_format->value,
1249 av_freep(&va_profiles);
1250 av_freep(&va_entrypoints);
1254 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1256 VAAPIEncodeContext *ctx = avctx->priv_data;
1257 int64_t rc_bits_per_second;
1258 int rc_target_percentage;
1260 int64_t hrd_buffer_size;
1261 int64_t hrd_initial_buffer_fullness;
1263 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1266 vas = vaGetConfigAttributes(ctx->hwctx->display,
1267 ctx->va_profile, ctx->va_entrypoint,
1269 if (vas != VA_STATUS_SUCCESS) {
1270 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1271 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1272 return AVERROR_EXTERNAL;
1275 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1276 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1277 "supported rate control modes: assuming constant-quality.\n");
1278 ctx->va_rc_mode = VA_RC_CQP;
1281 if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY ||
1282 avctx->flags & AV_CODEC_FLAG_QSCALE ||
1283 avctx->bit_rate <= 0) {
1284 if (rc_attr.value & VA_RC_CQP) {
1285 av_log(avctx, AV_LOG_VERBOSE, "Using constant-quality mode.\n");
1286 ctx->va_rc_mode = VA_RC_CQP;
1287 if (avctx->bit_rate > 0 || avctx->rc_max_rate > 0) {
1288 av_log(avctx, AV_LOG_WARNING, "Bitrate target parameters "
1289 "ignored in constant-quality mode.\n");
1293 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1294 "constant-quality mode (%#x).\n", rc_attr.value);
1295 return AVERROR(EINVAL);
1299 if (!(rc_attr.value & (VA_RC_CBR | VA_RC_VBR))) {
1300 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1301 "bitrate-targetted rate control modes.\n");
1302 return AVERROR(EINVAL);
1305 if (avctx->rc_buffer_size)
1306 hrd_buffer_size = avctx->rc_buffer_size;
1307 else if (avctx->rc_max_rate > 0)
1308 hrd_buffer_size = avctx->rc_max_rate;
1310 hrd_buffer_size = avctx->bit_rate;
1311 if (avctx->rc_initial_buffer_occupancy) {
1312 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1313 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1314 "must have initial buffer size (%d) < "
1315 "buffer size (%"PRId64").\n",
1316 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1317 return AVERROR(EINVAL);
1319 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1321 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1324 if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {
1325 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: must have "
1326 "bitrate (%"PRId64") <= maxrate (%"PRId64").\n",
1327 avctx->bit_rate, avctx->rc_max_rate);
1328 return AVERROR(EINVAL);
1331 if (avctx->rc_max_rate > avctx->bit_rate) {
1332 if (!(rc_attr.value & VA_RC_VBR)) {
1333 av_log(avctx, AV_LOG_WARNING, "Driver does not support "
1334 "VBR mode (%#x), using CBR mode instead.\n",
1336 ctx->va_rc_mode = VA_RC_CBR;
1338 rc_bits_per_second = avctx->bit_rate;
1339 rc_target_percentage = 100;
1341 ctx->va_rc_mode = VA_RC_VBR;
1343 rc_bits_per_second = avctx->rc_max_rate;
1344 rc_target_percentage = (avctx->bit_rate * 100) /
1348 } else if (avctx->rc_max_rate == avctx->bit_rate) {
1349 if (!(rc_attr.value & VA_RC_CBR)) {
1350 av_log(avctx, AV_LOG_WARNING, "Driver does not support "
1351 "CBR mode (%#x), using VBR mode instead.\n",
1353 ctx->va_rc_mode = VA_RC_VBR;
1355 ctx->va_rc_mode = VA_RC_CBR;
1358 rc_bits_per_second = avctx->bit_rate;
1359 rc_target_percentage = 100;
1362 if (rc_attr.value & VA_RC_VBR) {
1363 ctx->va_rc_mode = VA_RC_VBR;
1365 // We only have a target bitrate, but VAAPI requires that a
1366 // maximum rate be supplied as well. Since the user has
1367 // offered no particular constraint, arbitrarily pick a
1368 // maximum rate of double the target rate.
1369 rc_bits_per_second = 2 * avctx->bit_rate;
1370 rc_target_percentage = 50;
1372 ctx->va_rc_mode = VA_RC_CBR;
1374 rc_bits_per_second = avctx->bit_rate;
1375 rc_target_percentage = 100;
1379 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1381 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s, %d%% of %"PRId64" bps "
1382 "over %d ms.\n", ctx->va_rc_mode == VA_RC_VBR ? "VBR" : "CBR",
1383 rc_target_percentage, rc_bits_per_second, rc_window_size);
1384 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1385 "initial fullness %"PRId64" bits.\n",
1386 hrd_buffer_size, hrd_initial_buffer_fullness);
1388 if (rc_bits_per_second > UINT32_MAX ||
1389 hrd_buffer_size > UINT32_MAX ||
1390 hrd_initial_buffer_fullness > UINT32_MAX) {
1391 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1392 "greater are not supported by VAAPI.\n");
1393 return AVERROR(EINVAL);
1396 ctx->va_bit_rate = rc_bits_per_second;
1398 ctx->config_attributes[ctx->nb_config_attributes++] =
1400 .type = VAConfigAttribRateControl,
1401 .value = ctx->va_rc_mode,
1404 ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1405 ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1406 .bits_per_second = rc_bits_per_second,
1407 .target_percentage = rc_target_percentage,
1408 .window_size = rc_window_size,
1410 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1411 .basic_unit_size = 0,
1412 #if VA_CHECK_VERSION(1, 1, 0)
1413 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1416 vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
1417 sizeof(ctx->rc_params));
1419 ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1420 ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1421 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1422 .buffer_size = hrd_buffer_size,
1424 vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
1425 sizeof(ctx->hrd_params));
1427 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1428 av_reduce(&fr_num, &fr_den,
1429 avctx->framerate.num, avctx->framerate.den, 65535);
1431 av_reduce(&fr_num, &fr_den,
1432 avctx->time_base.den, avctx->time_base.num, 65535);
1434 ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1435 ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1437 #if VA_CHECK_VERSION(0, 40, 0)
1438 vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
1439 sizeof(ctx->fr_params));
1445 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1447 VAAPIEncodeContext *ctx = avctx->priv_data;
1449 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1450 uint32_t ref_l0, ref_l1;
1452 vas = vaGetConfigAttributes(ctx->hwctx->display,
1456 if (vas != VA_STATUS_SUCCESS) {
1457 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1458 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1459 return AVERROR_EXTERNAL;
1462 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1463 ref_l0 = ref_l1 = 0;
1465 ref_l0 = attr.value & 0xffff;
1466 ref_l1 = attr.value >> 16 & 0xffff;
1469 if (avctx->gop_size <= 1) {
1470 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1472 } else if (ref_l0 < 1) {
1473 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1474 "reference frames.\n");
1475 return AVERROR(EINVAL);
1476 } else if (ref_l1 < 1 || avctx->max_b_frames < 1) {
1477 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1478 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1479 ctx->gop_size = avctx->gop_size;
1480 ctx->p_per_i = INT_MAX;
1483 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1484 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1485 ctx->gop_size = avctx->gop_size;
1486 ctx->p_per_i = INT_MAX;
1487 ctx->b_per_p = avctx->max_b_frames;
1493 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1495 VAAPIEncodeContext *ctx = avctx->priv_data;
1496 VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1497 { VAConfigAttribEncSliceStructure } };
1499 uint32_t max_slices, slice_structure;
1502 if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1503 if (avctx->slices > 0) {
1504 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1505 "but this codec does not support controlling slices.\n");
1510 ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1511 ctx->slice_block_height;
1512 ctx->slice_block_cols = (avctx->width + ctx->slice_block_width - 1) /
1513 ctx->slice_block_width;
1515 if (avctx->slices <= 1) {
1517 ctx->slice_size = ctx->slice_block_rows;
1521 vas = vaGetConfigAttributes(ctx->hwctx->display,
1524 attr, FF_ARRAY_ELEMS(attr));
1525 if (vas != VA_STATUS_SUCCESS) {
1526 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1527 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1528 return AVERROR_EXTERNAL;
1530 max_slices = attr[0].value;
1531 slice_structure = attr[1].value;
1532 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1533 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1534 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1535 "pictures as multiple slices.\n.");
1536 return AVERROR(EINVAL);
1539 // For fixed-size slices currently we only support whole rows, making
1540 // rectangular slices. This could be extended to arbitrary runs of
1541 // blocks, but since slices tend to be a conformance requirement and
1542 // most cases (such as broadcast or bluray) want rectangular slices
1543 // only it would need to be gated behind another option.
1544 if (avctx->slices > ctx->slice_block_rows) {
1545 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1546 "configured number of slices (%d < %d); using "
1547 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1548 req_slices = ctx->slice_block_rows;
1550 req_slices = avctx->slices;
1552 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1553 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1554 ctx->nb_slices = req_slices;
1555 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1556 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1558 for (k = 1;; k *= 2) {
1559 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1562 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1563 ctx->slice_size = k;
1564 #if VA_CHECK_VERSION(1, 0, 0)
1565 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1566 ctx->nb_slices = ctx->slice_block_rows;
1567 ctx->slice_size = 1;
1570 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1571 "slice structure modes (%#x).\n", slice_structure);
1572 return AVERROR(EINVAL);
1575 if (ctx->nb_slices > avctx->slices) {
1576 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1577 "%d (from %d) due to driver constraints on slice "
1578 "structure.\n", ctx->nb_slices, avctx->slices);
1580 if (ctx->nb_slices > max_slices) {
1581 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1582 "encoding with %d slices (max %"PRIu32").\n",
1583 ctx->nb_slices, max_slices);
1584 return AVERROR(EINVAL);
1587 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1588 "(default size %d block rows).\n",
1589 ctx->nb_slices, ctx->slice_size);
1593 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1595 VAAPIEncodeContext *ctx = avctx->priv_data;
1597 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1599 vas = vaGetConfigAttributes(ctx->hwctx->display,
1603 if (vas != VA_STATUS_SUCCESS) {
1604 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1605 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1606 return AVERROR_EXTERNAL;
1609 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1610 if (ctx->desired_packed_headers) {
1611 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1612 "packed headers (wanted %#x).\n",
1613 ctx->desired_packed_headers);
1615 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1616 "packed headers (none wanted).\n");
1618 ctx->va_packed_headers = 0;
1620 if (ctx->desired_packed_headers & ~attr.value) {
1621 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1622 "wanted packed headers (wanted %#x, found %#x).\n",
1623 ctx->desired_packed_headers, attr.value);
1625 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1626 "available (wanted %#x, found %#x).\n",
1627 ctx->desired_packed_headers, attr.value);
1629 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1632 if (ctx->va_packed_headers) {
1633 ctx->config_attributes[ctx->nb_config_attributes++] =
1635 .type = VAConfigAttribEncPackedHeaders,
1636 .value = ctx->va_packed_headers,
1640 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1641 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1642 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1643 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1644 "sequence headers, but a global header is requested.\n");
1645 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1646 "this may result in a stream which is not usable for some "
1647 "purposes (e.g. not muxable to some containers).\n");
1653 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1655 #if VA_CHECK_VERSION(0, 36, 0)
1656 VAAPIEncodeContext *ctx = avctx->priv_data;
1658 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1659 int quality = avctx->compression_level;
1661 vas = vaGetConfigAttributes(ctx->hwctx->display,
1665 if (vas != VA_STATUS_SUCCESS) {
1666 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1667 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1668 return AVERROR_EXTERNAL;
1671 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1673 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1674 "supported: will use default quality level.\n");
1677 if (quality > attr.value) {
1678 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1679 "valid range is 0-%d, using %d.\n",
1680 attr.value, attr.value);
1681 quality = attr.value;
1684 ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
1685 ctx->quality_params.quality.quality_level = quality;
1687 vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
1688 sizeof(ctx->quality_params));
1691 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1692 "not supported with this VAAPI version.\n");
1698 static void vaapi_encode_free_output_buffer(void *opaque,
1701 AVCodecContext *avctx = opaque;
1702 VAAPIEncodeContext *ctx = avctx->priv_data;
1703 VABufferID buffer_id;
1705 buffer_id = (VABufferID)(uintptr_t)data;
1707 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1709 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1712 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1715 AVCodecContext *avctx = opaque;
1716 VAAPIEncodeContext *ctx = avctx->priv_data;
1717 VABufferID buffer_id;
1721 // The output buffer size is fixed, so it needs to be large enough
1722 // to hold the largest possible compressed frame. We assume here
1723 // that the uncompressed frame plus some header data is an upper
1725 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1726 VAEncCodedBufferType,
1727 3 * ctx->surface_width * ctx->surface_height +
1728 (1 << 16), 1, 0, &buffer_id);
1729 if (vas != VA_STATUS_SUCCESS) {
1730 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1731 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1735 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1737 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1739 &vaapi_encode_free_output_buffer,
1740 avctx, AV_BUFFER_FLAG_READONLY);
1742 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1749 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1751 VAAPIEncodeContext *ctx = avctx->priv_data;
1752 AVVAAPIHWConfig *hwconfig = NULL;
1753 AVHWFramesConstraints *constraints = NULL;
1754 enum AVPixelFormat recon_format;
1757 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1759 err = AVERROR(ENOMEM);
1762 hwconfig->config_id = ctx->va_config;
1764 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1767 err = AVERROR(ENOMEM);
1771 // Probably we can use the input surface format as the surface format
1772 // of the reconstructed frames. If not, we just pick the first (only?)
1773 // format in the valid list and hope that it all works.
1774 recon_format = AV_PIX_FMT_NONE;
1775 if (constraints->valid_sw_formats) {
1776 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1777 if (ctx->input_frames->sw_format ==
1778 constraints->valid_sw_formats[i]) {
1779 recon_format = ctx->input_frames->sw_format;
1783 if (recon_format == AV_PIX_FMT_NONE) {
1784 // No match. Just use the first in the supported list and
1785 // hope for the best.
1786 recon_format = constraints->valid_sw_formats[0];
1789 // No idea what to use; copy input format.
1790 recon_format = ctx->input_frames->sw_format;
1792 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1793 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1795 if (ctx->surface_width < constraints->min_width ||
1796 ctx->surface_height < constraints->min_height ||
1797 ctx->surface_width > constraints->max_width ||
1798 ctx->surface_height > constraints->max_height) {
1799 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1800 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1801 ctx->surface_width, ctx->surface_height,
1802 constraints->min_width, constraints->max_width,
1803 constraints->min_height, constraints->max_height);
1804 err = AVERROR(EINVAL);
1808 av_freep(&hwconfig);
1809 av_hwframe_constraints_free(&constraints);
1811 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1812 if (!ctx->recon_frames_ref) {
1813 err = AVERROR(ENOMEM);
1816 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1818 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
1819 ctx->recon_frames->sw_format = recon_format;
1820 ctx->recon_frames->width = ctx->surface_width;
1821 ctx->recon_frames->height = ctx->surface_height;
1822 // At most three IDR/I/P frames and two runs of B frames can be in
1823 // flight at any one time.
1824 ctx->recon_frames->initial_pool_size = 3 + 2 * ctx->b_per_p;
1826 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1828 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1829 "frame context: %d.\n", err);
1835 av_freep(&hwconfig);
1836 av_hwframe_constraints_free(&constraints);
1840 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
1842 VAAPIEncodeContext *ctx = avctx->priv_data;
1843 AVVAAPIFramesContext *recon_hwctx = NULL;
1847 if (!avctx->hw_frames_ctx) {
1848 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1849 "required to associate the encoding device.\n");
1850 return AVERROR(EINVAL);
1853 ctx->va_config = VA_INVALID_ID;
1854 ctx->va_context = VA_INVALID_ID;
1856 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1857 if (!ctx->input_frames_ref) {
1858 err = AVERROR(ENOMEM);
1861 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1863 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1864 if (!ctx->device_ref) {
1865 err = AVERROR(ENOMEM);
1868 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1869 ctx->hwctx = ctx->device->hwctx;
1871 err = vaapi_encode_profile_entrypoint(avctx);
1875 err = vaapi_encode_init_rate_control(avctx);
1879 err = vaapi_encode_init_gop_structure(avctx);
1883 err = vaapi_encode_init_slice_structure(avctx);
1887 err = vaapi_encode_init_packed_headers(avctx);
1891 if (avctx->compression_level >= 0) {
1892 err = vaapi_encode_init_quality(avctx);
1897 vas = vaCreateConfig(ctx->hwctx->display,
1898 ctx->va_profile, ctx->va_entrypoint,
1899 ctx->config_attributes, ctx->nb_config_attributes,
1901 if (vas != VA_STATUS_SUCCESS) {
1902 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1903 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1908 err = vaapi_encode_create_recon_frames(avctx);
1912 recon_hwctx = ctx->recon_frames->hwctx;
1913 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1914 ctx->surface_width, ctx->surface_height,
1916 recon_hwctx->surface_ids,
1917 recon_hwctx->nb_surfaces,
1919 if (vas != VA_STATUS_SUCCESS) {
1920 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1921 "context: %d (%s).\n", vas, vaErrorStr(vas));
1926 ctx->output_buffer_pool =
1927 av_buffer_pool_init2(sizeof(VABufferID), avctx,
1928 &vaapi_encode_alloc_output_buffer, NULL);
1929 if (!ctx->output_buffer_pool) {
1930 err = AVERROR(ENOMEM);
1934 if (ctx->codec->configure) {
1935 err = ctx->codec->configure(avctx);
1940 ctx->input_order = 0;
1941 ctx->output_delay = ctx->b_per_p;
1942 ctx->decode_delay = 1;
1943 ctx->output_order = - ctx->output_delay - 1;
1945 if (ctx->codec->sequence_params_size > 0) {
1946 ctx->codec_sequence_params =
1947 av_mallocz(ctx->codec->sequence_params_size);
1948 if (!ctx->codec_sequence_params) {
1949 err = AVERROR(ENOMEM);
1953 if (ctx->codec->picture_params_size > 0) {
1954 ctx->codec_picture_params =
1955 av_mallocz(ctx->codec->picture_params_size);
1956 if (!ctx->codec_picture_params) {
1957 err = AVERROR(ENOMEM);
1962 if (ctx->codec->init_sequence_params) {
1963 err = ctx->codec->init_sequence_params(avctx);
1965 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1966 "failed: %d.\n", err);
1971 // This should be configurable somehow. (Needs testing on a machine
1972 // where it actually overlaps properly, though.)
1973 ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1975 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
1976 ctx->codec->write_sequence_header &&
1977 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1978 char data[MAX_PARAM_BUFFER_SIZE];
1979 size_t bit_len = 8 * sizeof(data);
1981 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
1983 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
1984 "for extradata: %d.\n", err);
1987 avctx->extradata_size = (bit_len + 7) / 8;
1988 avctx->extradata = av_mallocz(avctx->extradata_size +
1989 AV_INPUT_BUFFER_PADDING_SIZE);
1990 if (!avctx->extradata) {
1991 err = AVERROR(ENOMEM);
1994 memcpy(avctx->extradata, data, avctx->extradata_size);
2001 ff_vaapi_encode_close(avctx);
2005 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2007 VAAPIEncodeContext *ctx = avctx->priv_data;
2008 VAAPIEncodePicture *pic, *next;
2010 for (pic = ctx->pic_start; pic; pic = next) {
2012 vaapi_encode_free(avctx, pic);
2015 av_buffer_pool_uninit(&ctx->output_buffer_pool);
2017 if (ctx->va_context != VA_INVALID_ID) {
2018 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2019 ctx->va_context = VA_INVALID_ID;
2022 if (ctx->va_config != VA_INVALID_ID) {
2023 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2024 ctx->va_config = VA_INVALID_ID;
2027 av_freep(&ctx->codec_sequence_params);
2028 av_freep(&ctx->codec_picture_params);
2030 av_buffer_unref(&ctx->recon_frames_ref);
2031 av_buffer_unref(&ctx->input_frames_ref);
2032 av_buffer_unref(&ctx->device_ref);