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->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
325 err = AVERROR(ENOMEM);
329 for (i = 0; i < pic->nb_slices; i++) {
330 slice = &pic->slices[i];
333 if (ctx->codec->slice_params_size > 0) {
334 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
335 if (!slice->codec_slice_params) {
336 err = AVERROR(ENOMEM);
341 if (ctx->codec->init_slice_params) {
342 err = ctx->codec->init_slice_params(avctx, pic, slice);
344 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
345 "parameters: %d.\n", err);
350 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
351 ctx->codec->write_slice_header) {
352 bit_len = 8 * sizeof(data);
353 err = ctx->codec->write_slice_header(avctx, pic, slice,
356 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
357 "header: %d.\n", err);
360 err = vaapi_encode_make_packed_header(avctx, pic,
361 ctx->codec->slice_header_type,
367 if (ctx->codec->init_slice_params) {
368 err = vaapi_encode_make_param_buffer(avctx, pic,
369 VAEncSliceParameterBufferType,
370 slice->codec_slice_params,
371 ctx->codec->slice_params_size);
377 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
379 if (vas != VA_STATUS_SUCCESS) {
380 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
381 "%d (%s).\n", vas, vaErrorStr(vas));
383 goto fail_with_picture;
386 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
387 pic->param_buffers, pic->nb_param_buffers);
388 if (vas != VA_STATUS_SUCCESS) {
389 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
390 "%d (%s).\n", vas, vaErrorStr(vas));
392 goto fail_with_picture;
395 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
396 if (vas != VA_STATUS_SUCCESS) {
397 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
398 "%d (%s).\n", vas, vaErrorStr(vas));
400 // vaRenderPicture() has been called here, so we should not destroy
401 // the parameter buffers unless separate destruction is required.
402 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
403 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
409 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
410 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
411 for (i = 0; i < pic->nb_param_buffers; i++) {
412 vas = vaDestroyBuffer(ctx->hwctx->display,
413 pic->param_buffers[i]);
414 if (vas != VA_STATUS_SUCCESS) {
415 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
416 "param buffer %#x: %d (%s).\n",
417 pic->param_buffers[i], vas, vaErrorStr(vas));
423 pic->encode_issued = 1;
425 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
426 return vaapi_encode_wait(avctx, pic);
431 vaEndPicture(ctx->hwctx->display, ctx->va_context);
433 for(i = 0; i < pic->nb_param_buffers; i++)
434 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
435 for (i = 0; i < pic->nb_slices; i++) {
437 av_freep(&pic->slices[i].priv_data);
438 av_freep(&pic->slices[i].codec_slice_params);
442 av_freep(&pic->codec_picture_params);
443 av_freep(&pic->param_buffers);
444 av_freep(&pic->slices);
445 av_frame_free(&pic->recon_image);
446 av_buffer_unref(&pic->output_buffer_ref);
447 pic->output_buffer = VA_INVALID_ID;
451 static int vaapi_encode_output(AVCodecContext *avctx,
452 VAAPIEncodePicture *pic, AVPacket *pkt)
454 VAAPIEncodeContext *ctx = avctx->priv_data;
455 VACodedBufferSegment *buf_list, *buf;
459 err = vaapi_encode_wait(avctx, pic);
464 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
466 if (vas != VA_STATUS_SUCCESS) {
467 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
468 "%d (%s).\n", vas, vaErrorStr(vas));
473 for (buf = buf_list; buf; buf = buf->next) {
474 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
475 "(status %08x).\n", buf->size, buf->status);
477 err = av_new_packet(pkt, buf->size);
481 memcpy(pkt->data, buf->buf, buf->size);
484 if (pic->type == PICTURE_TYPE_IDR)
485 pkt->flags |= AV_PKT_FLAG_KEY;
489 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
490 if (vas != VA_STATUS_SUCCESS) {
491 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
492 "%d (%s).\n", vas, vaErrorStr(vas));
497 av_buffer_unref(&pic->output_buffer_ref);
498 pic->output_buffer = VA_INVALID_ID;
500 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
501 pic->display_order, pic->encode_order);
505 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
507 av_buffer_unref(&pic->output_buffer_ref);
508 pic->output_buffer = VA_INVALID_ID;
512 static int vaapi_encode_discard(AVCodecContext *avctx,
513 VAAPIEncodePicture *pic)
515 vaapi_encode_wait(avctx, pic);
517 if (pic->output_buffer_ref) {
518 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
519 "%"PRId64"/%"PRId64".\n",
520 pic->display_order, pic->encode_order);
522 av_buffer_unref(&pic->output_buffer_ref);
523 pic->output_buffer = VA_INVALID_ID;
529 static VAAPIEncodePicture *vaapi_encode_alloc(void)
531 VAAPIEncodePicture *pic;
533 pic = av_mallocz(sizeof(*pic));
537 pic->input_surface = VA_INVALID_ID;
538 pic->recon_surface = VA_INVALID_ID;
539 pic->output_buffer = VA_INVALID_ID;
544 static int vaapi_encode_free(AVCodecContext *avctx,
545 VAAPIEncodePicture *pic)
549 if (pic->encode_issued)
550 vaapi_encode_discard(avctx, pic);
552 for (i = 0; i < pic->nb_slices; i++) {
554 av_freep(&pic->slices[i].priv_data);
555 av_freep(&pic->slices[i].codec_slice_params);
558 av_freep(&pic->codec_picture_params);
560 av_frame_free(&pic->input_image);
561 av_frame_free(&pic->recon_image);
563 av_freep(&pic->param_buffers);
564 av_freep(&pic->slices);
565 // Output buffer should already be destroyed.
566 av_assert0(pic->output_buffer == VA_INVALID_ID);
568 av_freep(&pic->priv_data);
569 av_freep(&pic->codec_picture_params);
576 static int vaapi_encode_step(AVCodecContext *avctx,
577 VAAPIEncodePicture *target)
579 VAAPIEncodeContext *ctx = avctx->priv_data;
580 VAAPIEncodePicture *pic;
583 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
584 ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
585 // These two modes are equivalent, except that we wait for
586 // immediate completion on each operation if serialised.
589 // No target, nothing to do yet.
593 if (target->encode_complete) {
599 for (i = 0; i < pic->nb_refs; i++) {
600 if (!pic->refs[i]->encode_complete) {
601 err = vaapi_encode_step(avctx, pic->refs[i]);
607 err = vaapi_encode_issue(avctx, pic);
611 } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
614 // Run through the list of all available pictures repeatedly
615 // and issue the first one found which has all dependencies
616 // available (including previously-issued but not necessarily
617 // completed pictures).
620 for (pic = ctx->pic_start; pic; pic = pic->next) {
621 if (!pic->input_available || pic->encode_issued)
623 for (i = 0; i < pic->nb_refs; i++) {
624 if (!pic->refs[i]->encode_issued)
627 if (i < pic->nb_refs)
629 err = vaapi_encode_issue(avctx, pic);
633 // Start again from the beginning of the list,
634 // because issuing this picture may have satisfied
635 // forward dependencies of earlier ones.
640 // If we had a defined target for this step then it will
641 // always have been issued by now.
643 av_assert0(target->encode_issued && "broken dependencies?");
653 static int vaapi_encode_get_next(AVCodecContext *avctx,
654 VAAPIEncodePicture **pic_out)
656 VAAPIEncodeContext *ctx = avctx->priv_data;
657 VAAPIEncodePicture *start, *end, *pic;
660 for (pic = ctx->pic_start; pic; pic = pic->next) {
662 av_assert0(pic->display_order + 1 == pic->next->display_order);
663 if (pic->display_order == ctx->input_order) {
669 pic = vaapi_encode_alloc();
671 return AVERROR(ENOMEM);
673 if (ctx->input_order == 0 || ctx->force_idr ||
674 ctx->gop_counter >= ctx->gop_size) {
675 pic->type = PICTURE_TYPE_IDR;
677 ctx->gop_counter = 1;
679 } else if (ctx->p_counter >= ctx->p_per_i) {
680 pic->type = PICTURE_TYPE_I;
684 pic->type = PICTURE_TYPE_P;
685 pic->refs[0] = ctx->pic_end;
692 if (pic->type != PICTURE_TYPE_IDR) {
693 // If that was not an IDR frame, add B-frames display-before and
694 // encode-after it, but not exceeding the GOP size.
696 for (i = 0; i < ctx->b_per_p &&
697 ctx->gop_counter < ctx->gop_size; i++) {
698 pic = vaapi_encode_alloc();
702 pic->type = PICTURE_TYPE_B;
703 pic->refs[0] = ctx->pic_end;
708 pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
709 pic->encode_order = pic->display_order + 1;
716 if (ctx->input_order == 0) {
717 pic->display_order = 0;
718 pic->encode_order = 0;
720 ctx->pic_start = ctx->pic_end = pic;
723 for (i = 0, pic = start; pic; i++, pic = pic->next) {
724 pic->display_order = ctx->input_order + i;
725 if (end->type == PICTURE_TYPE_IDR)
726 pic->encode_order = ctx->input_order + i;
728 pic->encode_order = ctx->input_order;
730 pic->encode_order = ctx->input_order + i + 1;
733 av_assert0(ctx->pic_end);
734 ctx->pic_end->next = start;
739 av_log(avctx, AV_LOG_DEBUG, "Pictures:");
740 for (pic = ctx->pic_start; pic; pic = pic->next) {
741 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
742 picture_type_name[pic->type],
743 pic->display_order, pic->encode_order);
745 av_log(avctx, AV_LOG_DEBUG, "\n");
752 vaapi_encode_free(avctx, start);
755 return AVERROR(ENOMEM);
758 static int vaapi_encode_truncate_gop(AVCodecContext *avctx)
760 VAAPIEncodeContext *ctx = avctx->priv_data;
761 VAAPIEncodePicture *pic, *last_pic, *next;
763 av_assert0(!ctx->pic_start || ctx->pic_start->input_available);
765 // Find the last picture we actually have input for.
766 for (pic = ctx->pic_start; pic; pic = pic->next) {
767 if (!pic->input_available)
773 if (last_pic->type == PICTURE_TYPE_B) {
774 // Some fixing up is required. Change the type of this
775 // picture to P, then modify preceding B references which
776 // point beyond it to point at it instead.
778 last_pic->type = PICTURE_TYPE_P;
779 last_pic->encode_order = last_pic->refs[1]->encode_order;
781 for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
782 if (pic->type == PICTURE_TYPE_B &&
783 pic->refs[1] == last_pic->refs[1])
784 pic->refs[1] = last_pic;
787 last_pic->nb_refs = 1;
788 last_pic->refs[1] = NULL;
790 // We can use the current structure (no references point
791 // beyond the end), but there are unused pics to discard.
794 // Discard all following pics, they will never be used.
795 for (pic = last_pic->next; pic; pic = next) {
797 vaapi_encode_free(avctx, pic);
800 last_pic->next = NULL;
801 ctx->pic_end = last_pic;
804 // Input is available for all pictures, so we don't need to
808 av_log(avctx, AV_LOG_DEBUG, "Pictures ending truncated GOP:");
809 for (pic = ctx->pic_start; pic; pic = pic->next) {
810 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
811 picture_type_name[pic->type],
812 pic->display_order, pic->encode_order);
814 av_log(avctx, AV_LOG_DEBUG, "\n");
819 static int vaapi_encode_clear_old(AVCodecContext *avctx)
821 VAAPIEncodeContext *ctx = avctx->priv_data;
822 VAAPIEncodePicture *pic, *old;
825 while (ctx->pic_start != ctx->pic_end) {
826 old = ctx->pic_start;
827 if (old->encode_order > ctx->output_order)
830 for (pic = old->next; pic; pic = pic->next) {
831 if (pic->encode_complete)
833 for (i = 0; i < pic->nb_refs; i++) {
834 if (pic->refs[i] == old) {
835 // We still need this picture because it's referred to
836 // directly by a later one, so it and all following
837 // pictures have to stay.
843 pic = ctx->pic_start;
844 ctx->pic_start = pic->next;
845 vaapi_encode_free(avctx, pic);
851 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
852 const AVFrame *input_image, int *got_packet)
854 VAAPIEncodeContext *ctx = avctx->priv_data;
855 VAAPIEncodePicture *pic;
859 av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
860 input_image->width, input_image->height, input_image->pts);
862 if (input_image->pict_type == AV_PICTURE_TYPE_I) {
863 err = vaapi_encode_truncate_gop(avctx);
869 err = vaapi_encode_get_next(avctx, &pic);
871 av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
875 pic->input_image = av_frame_alloc();
876 if (!pic->input_image) {
877 err = AVERROR(ENOMEM);
880 err = av_frame_ref(pic->input_image, input_image);
883 pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
884 pic->pts = input_image->pts;
886 if (ctx->input_order == 0)
887 ctx->first_pts = pic->pts;
888 if (ctx->input_order == ctx->decode_delay)
889 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
890 if (ctx->output_delay > 0)
891 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
893 pic->input_available = 1;
896 if (!ctx->end_of_stream) {
897 err = vaapi_encode_truncate_gop(avctx);
900 ctx->end_of_stream = 1;
906 av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
908 for (pic = ctx->pic_start; pic; pic = pic->next)
909 if (pic->encode_order == ctx->output_order)
912 // pic can be null here if we don't have a specific target in this
913 // iteration. We might still issue encodes if things can be overlapped,
914 // even though we don't intend to output anything.
916 err = vaapi_encode_step(avctx, pic);
918 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
925 err = vaapi_encode_output(avctx, pic, pkt);
927 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
931 if (ctx->output_delay == 0) {
933 } else if (ctx->output_order < ctx->decode_delay) {
934 if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
935 pkt->dts = INT64_MIN;
937 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
939 pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
940 (3 * ctx->output_delay)];
946 err = vaapi_encode_clear_old(avctx);
948 av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
955 // Unclear what to clean up on failure. There are probably some things we
956 // could do usefully clean up here, but for now just leave them for uninit()
961 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx,
962 VAEncMiscParameterBuffer *buffer,
965 VAAPIEncodeContext *ctx = avctx->priv_data;
967 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
969 ctx->global_params [ctx->nb_global_params] = buffer;
970 ctx->global_params_size[ctx->nb_global_params] = size;
972 ++ctx->nb_global_params;
975 typedef struct VAAPIEncodeRTFormat {
982 } VAAPIEncodeRTFormat;
984 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
985 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
986 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
987 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
988 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
989 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
990 #if VA_CHECK_VERSION(0, 38, 1)
991 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
995 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
996 VAEntrypointEncSlice,
997 VAEntrypointEncPicture,
998 #if VA_CHECK_VERSION(0, 39, 2)
999 VAEntrypointEncSliceLP,
1003 #if VA_CHECK_VERSION(0, 39, 2)
1004 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1005 VAEntrypointEncSliceLP,
1010 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1012 VAAPIEncodeContext *ctx = avctx->priv_data;
1013 VAProfile *va_profiles = NULL;
1014 VAEntrypoint *va_entrypoints = NULL;
1016 const VAEntrypoint *usable_entrypoints;
1017 const VAAPIEncodeProfile *profile;
1018 const AVPixFmtDescriptor *desc;
1019 VAConfigAttrib rt_format_attr;
1020 const VAAPIEncodeRTFormat *rt_format;
1021 const char *profile_string, *entrypoint_string;
1022 int i, j, n, depth, err;
1025 if (ctx->low_power) {
1026 #if VA_CHECK_VERSION(0, 39, 2)
1027 usable_entrypoints = vaapi_encode_entrypoints_low_power;
1029 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1030 "supported with this VAAPI version.\n");
1031 return AVERROR(EINVAL);
1034 usable_entrypoints = vaapi_encode_entrypoints_normal;
1037 desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1039 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1040 ctx->input_frames->sw_format);
1041 return AVERROR(EINVAL);
1043 depth = desc->comp[0].depth;
1044 for (i = 1; i < desc->nb_components; i++) {
1045 if (desc->comp[i].depth != depth) {
1046 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1048 return AVERROR(EINVAL);
1051 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1054 n = vaMaxNumProfiles(ctx->hwctx->display);
1055 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1057 err = AVERROR(ENOMEM);
1060 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1061 if (vas != VA_STATUS_SUCCESS) {
1062 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1063 vas, vaErrorStr(vas));
1064 err = AVERROR_EXTERNAL;
1068 av_assert0(ctx->codec->profiles);
1069 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1070 FF_PROFILE_UNKNOWN); i++) {
1071 profile = &ctx->codec->profiles[i];
1072 if (depth != profile->depth ||
1073 desc->nb_components != profile->nb_components)
1075 if (desc->nb_components > 1 &&
1076 (desc->log2_chroma_w != profile->log2_chroma_w ||
1077 desc->log2_chroma_h != profile->log2_chroma_h))
1079 if (avctx->profile != profile->av_profile &&
1080 avctx->profile != FF_PROFILE_UNKNOWN)
1083 #if VA_CHECK_VERSION(1, 0, 0)
1084 profile_string = vaProfileStr(profile->va_profile);
1086 profile_string = "(no profile names)";
1089 for (j = 0; j < n; j++) {
1090 if (va_profiles[j] == profile->va_profile)
1094 av_log(avctx, AV_LOG_VERBOSE, "Matching profile %d is "
1095 "not supported by driver.\n", profile->va_profile);
1099 ctx->profile = profile;
1102 if (!ctx->profile) {
1103 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1104 err = AVERROR(ENOSYS);
1108 avctx->profile = profile->av_profile;
1109 ctx->va_profile = profile->va_profile;
1110 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1111 profile_string, ctx->va_profile);
1113 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1114 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1115 if (!va_entrypoints) {
1116 err = AVERROR(ENOMEM);
1119 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1120 va_entrypoints, &n);
1121 if (vas != VA_STATUS_SUCCESS) {
1122 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1123 "profile %s (%d): %d (%s).\n", profile_string,
1124 ctx->va_profile, vas, vaErrorStr(vas));
1125 err = AVERROR_EXTERNAL;
1129 for (i = 0; i < n; i++) {
1130 for (j = 0; usable_entrypoints[j]; j++) {
1131 if (va_entrypoints[i] == usable_entrypoints[j])
1134 if (usable_entrypoints[j])
1138 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1139 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1140 err = AVERROR(ENOSYS);
1144 ctx->va_entrypoint = va_entrypoints[i];
1145 #if VA_CHECK_VERSION(1, 0, 0)
1146 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1148 entrypoint_string = "(no entrypoint names)";
1150 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1151 entrypoint_string, ctx->va_entrypoint);
1153 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1154 rt_format = &vaapi_encode_rt_formats[i];
1155 if (rt_format->depth == depth &&
1156 rt_format->nb_components == profile->nb_components &&
1157 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1158 rt_format->log2_chroma_h == profile->log2_chroma_h)
1161 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1162 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1163 "found for profile %s (%d) entrypoint %s (%d).\n",
1164 profile_string, ctx->va_profile,
1165 entrypoint_string, ctx->va_entrypoint);
1166 err = AVERROR(ENOSYS);
1170 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1171 vas = vaGetConfigAttributes(ctx->hwctx->display,
1172 ctx->va_profile, ctx->va_entrypoint,
1173 &rt_format_attr, 1);
1174 if (vas != VA_STATUS_SUCCESS) {
1175 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1176 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1177 err = AVERROR_EXTERNAL;
1181 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1182 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1183 "supported by driver: assuming surface RT format %s "
1184 "is valid.\n", rt_format->name);
1185 } else if (!(rt_format_attr.value & rt_format->value)) {
1186 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1187 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1188 rt_format->name, profile_string, ctx->va_profile,
1189 entrypoint_string, ctx->va_entrypoint);
1190 err = AVERROR(ENOSYS);
1193 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1194 "format %s (%#x).\n", rt_format->name, rt_format->value);
1195 ctx->config_attributes[ctx->nb_config_attributes++] =
1197 .type = VAConfigAttribRTFormat,
1198 .value = rt_format->value,
1204 av_freep(&va_profiles);
1205 av_freep(&va_entrypoints);
1209 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1211 VAAPIEncodeContext *ctx = avctx->priv_data;
1212 int64_t rc_bits_per_second;
1213 int rc_target_percentage;
1215 int64_t hrd_buffer_size;
1216 int64_t hrd_initial_buffer_fullness;
1218 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1221 vas = vaGetConfigAttributes(ctx->hwctx->display,
1222 ctx->va_profile, ctx->va_entrypoint,
1224 if (vas != VA_STATUS_SUCCESS) {
1225 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1226 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1227 return AVERROR_EXTERNAL;
1230 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1231 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1232 "supported rate control modes: assuming constant-quality.\n");
1233 ctx->va_rc_mode = VA_RC_CQP;
1236 if (avctx->flags & AV_CODEC_FLAG_QSCALE ||
1237 avctx->bit_rate <= 0) {
1238 if (rc_attr.value & VA_RC_CQP) {
1239 av_log(avctx, AV_LOG_VERBOSE, "Using constant-quality mode.\n");
1240 ctx->va_rc_mode = VA_RC_CQP;
1241 if (avctx->bit_rate > 0 || avctx->rc_max_rate > 0) {
1242 av_log(avctx, AV_LOG_WARNING, "Bitrate target parameters "
1243 "ignored in constant-quality mode.\n");
1247 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1248 "constant-quality mode (%#x).\n", rc_attr.value);
1249 return AVERROR(EINVAL);
1253 if (!(rc_attr.value & (VA_RC_CBR | VA_RC_VBR))) {
1254 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1255 "bitrate-targetted rate control modes.\n");
1256 return AVERROR(EINVAL);
1259 if (avctx->rc_buffer_size)
1260 hrd_buffer_size = avctx->rc_buffer_size;
1261 else if (avctx->rc_max_rate > 0)
1262 hrd_buffer_size = avctx->rc_max_rate;
1264 hrd_buffer_size = avctx->bit_rate;
1265 if (avctx->rc_initial_buffer_occupancy) {
1266 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1267 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1268 "must have initial buffer size (%d) < "
1269 "buffer size (%"PRId64").\n",
1270 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1271 return AVERROR(EINVAL);
1273 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1275 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1278 if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {
1279 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: must have "
1280 "bitrate (%"PRId64") <= maxrate (%"PRId64").\n",
1281 avctx->bit_rate, avctx->rc_max_rate);
1282 return AVERROR(EINVAL);
1285 if (avctx->rc_max_rate > avctx->bit_rate) {
1286 if (!(rc_attr.value & VA_RC_VBR)) {
1287 av_log(avctx, AV_LOG_WARNING, "Driver does not support "
1288 "VBR mode (%#x), using CBR mode instead.\n",
1290 ctx->va_rc_mode = VA_RC_CBR;
1292 rc_bits_per_second = avctx->bit_rate;
1293 rc_target_percentage = 100;
1295 ctx->va_rc_mode = VA_RC_VBR;
1297 rc_bits_per_second = avctx->rc_max_rate;
1298 rc_target_percentage = (avctx->bit_rate * 100) /
1302 } else if (avctx->rc_max_rate == avctx->bit_rate) {
1303 if (!(rc_attr.value & VA_RC_CBR)) {
1304 av_log(avctx, AV_LOG_WARNING, "Driver does not support "
1305 "CBR mode (%#x), using VBR mode instead.\n",
1307 ctx->va_rc_mode = VA_RC_VBR;
1309 ctx->va_rc_mode = VA_RC_CBR;
1312 rc_bits_per_second = avctx->bit_rate;
1313 rc_target_percentage = 100;
1316 if (rc_attr.value & VA_RC_VBR) {
1317 ctx->va_rc_mode = VA_RC_VBR;
1319 // We only have a target bitrate, but VAAPI requires that a
1320 // maximum rate be supplied as well. Since the user has
1321 // offered no particular constraint, arbitrarily pick a
1322 // maximum rate of double the target rate.
1323 rc_bits_per_second = 2 * avctx->bit_rate;
1324 rc_target_percentage = 50;
1326 ctx->va_rc_mode = VA_RC_CBR;
1328 rc_bits_per_second = avctx->bit_rate;
1329 rc_target_percentage = 100;
1333 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1335 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s, %d%% of %"PRId64" bps "
1336 "over %d ms.\n", ctx->va_rc_mode == VA_RC_VBR ? "VBR" : "CBR",
1337 rc_target_percentage, rc_bits_per_second, rc_window_size);
1338 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1339 "initial fullness %"PRId64" bits.\n",
1340 hrd_buffer_size, hrd_initial_buffer_fullness);
1342 if (rc_bits_per_second > UINT32_MAX ||
1343 hrd_buffer_size > UINT32_MAX ||
1344 hrd_initial_buffer_fullness > UINT32_MAX) {
1345 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1346 "greater are not supported by VAAPI.\n");
1347 return AVERROR(EINVAL);
1350 ctx->va_bit_rate = rc_bits_per_second;
1352 ctx->config_attributes[ctx->nb_config_attributes++] =
1354 .type = VAConfigAttribRateControl,
1355 .value = ctx->va_rc_mode,
1358 ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1359 ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1360 .bits_per_second = rc_bits_per_second,
1361 .target_percentage = rc_target_percentage,
1362 .window_size = rc_window_size,
1364 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1365 .basic_unit_size = 0,
1366 #if VA_CHECK_VERSION(1, 1, 0)
1367 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1370 vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
1371 sizeof(ctx->rc_params));
1373 ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1374 ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1375 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1376 .buffer_size = hrd_buffer_size,
1378 vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
1379 sizeof(ctx->hrd_params));
1381 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1382 av_reduce(&fr_num, &fr_den,
1383 avctx->framerate.num, avctx->framerate.den, 65535);
1385 av_reduce(&fr_num, &fr_den,
1386 avctx->time_base.den, avctx->time_base.num, 65535);
1388 ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1389 ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1391 #if VA_CHECK_VERSION(0, 40, 0)
1392 vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
1393 sizeof(ctx->fr_params));
1399 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1401 VAAPIEncodeContext *ctx = avctx->priv_data;
1403 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1404 uint32_t ref_l0, ref_l1;
1406 vas = vaGetConfigAttributes(ctx->hwctx->display,
1410 if (vas != VA_STATUS_SUCCESS) {
1411 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1412 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1413 return AVERROR_EXTERNAL;
1416 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1417 ref_l0 = ref_l1 = 0;
1419 ref_l0 = attr.value & 0xffff;
1420 ref_l1 = attr.value >> 16 & 0xffff;
1423 if (avctx->gop_size <= 1) {
1424 av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1426 } else if (ref_l0 < 1) {
1427 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1428 "reference frames.\n");
1429 return AVERROR(EINVAL);
1430 } else if (ref_l1 < 1 || avctx->max_b_frames < 1) {
1431 av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1432 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1433 ctx->gop_size = avctx->gop_size;
1434 ctx->p_per_i = INT_MAX;
1437 av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1438 "(supported references: %d / %d).\n", ref_l0, ref_l1);
1439 ctx->gop_size = avctx->gop_size;
1440 ctx->p_per_i = INT_MAX;
1441 ctx->b_per_p = avctx->max_b_frames;
1447 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1449 VAAPIEncodeContext *ctx = avctx->priv_data;
1451 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1453 vas = vaGetConfigAttributes(ctx->hwctx->display,
1457 if (vas != VA_STATUS_SUCCESS) {
1458 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1459 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1460 return AVERROR_EXTERNAL;
1463 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1464 if (ctx->desired_packed_headers) {
1465 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1466 "packed headers (wanted %#x).\n",
1467 ctx->desired_packed_headers);
1469 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1470 "packed headers (none wanted).\n");
1472 ctx->va_packed_headers = 0;
1474 if (ctx->desired_packed_headers & ~attr.value) {
1475 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1476 "wanted packed headers (wanted %#x, found %#x).\n",
1477 ctx->desired_packed_headers, attr.value);
1479 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1480 "available (wanted %#x, found %#x).\n",
1481 ctx->desired_packed_headers, attr.value);
1483 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1486 if (ctx->va_packed_headers) {
1487 ctx->config_attributes[ctx->nb_config_attributes++] =
1489 .type = VAConfigAttribEncPackedHeaders,
1490 .value = ctx->va_packed_headers,
1494 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1495 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1496 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1497 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1498 "sequence headers, but a global header is requested.\n");
1499 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1500 "this may result in a stream which is not usable for some "
1501 "purposes (e.g. not muxable to some containers).\n");
1507 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1509 #if VA_CHECK_VERSION(0, 36, 0)
1510 VAAPIEncodeContext *ctx = avctx->priv_data;
1512 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1513 int quality = avctx->compression_level;
1515 vas = vaGetConfigAttributes(ctx->hwctx->display,
1519 if (vas != VA_STATUS_SUCCESS) {
1520 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1521 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1522 return AVERROR_EXTERNAL;
1525 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1527 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1528 "supported: will use default quality level.\n");
1531 if (quality > attr.value) {
1532 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1533 "valid range is 0-%d, using %d.\n",
1534 attr.value, attr.value);
1535 quality = attr.value;
1538 ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
1539 ctx->quality_params.quality.quality_level = quality;
1541 vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
1542 sizeof(ctx->quality_params));
1545 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1546 "not supported with this VAAPI version.\n");
1552 static void vaapi_encode_free_output_buffer(void *opaque,
1555 AVCodecContext *avctx = opaque;
1556 VAAPIEncodeContext *ctx = avctx->priv_data;
1557 VABufferID buffer_id;
1559 buffer_id = (VABufferID)(uintptr_t)data;
1561 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1563 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1566 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1569 AVCodecContext *avctx = opaque;
1570 VAAPIEncodeContext *ctx = avctx->priv_data;
1571 VABufferID buffer_id;
1575 // The output buffer size is fixed, so it needs to be large enough
1576 // to hold the largest possible compressed frame. We assume here
1577 // that the uncompressed frame plus some header data is an upper
1579 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1580 VAEncCodedBufferType,
1581 3 * ctx->surface_width * ctx->surface_height +
1582 (1 << 16), 1, 0, &buffer_id);
1583 if (vas != VA_STATUS_SUCCESS) {
1584 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1585 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1589 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1591 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1593 &vaapi_encode_free_output_buffer,
1594 avctx, AV_BUFFER_FLAG_READONLY);
1596 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1603 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1605 VAAPIEncodeContext *ctx = avctx->priv_data;
1606 AVVAAPIHWConfig *hwconfig = NULL;
1607 AVHWFramesConstraints *constraints = NULL;
1608 enum AVPixelFormat recon_format;
1611 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1613 err = AVERROR(ENOMEM);
1616 hwconfig->config_id = ctx->va_config;
1618 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1621 err = AVERROR(ENOMEM);
1625 // Probably we can use the input surface format as the surface format
1626 // of the reconstructed frames. If not, we just pick the first (only?)
1627 // format in the valid list and hope that it all works.
1628 recon_format = AV_PIX_FMT_NONE;
1629 if (constraints->valid_sw_formats) {
1630 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1631 if (ctx->input_frames->sw_format ==
1632 constraints->valid_sw_formats[i]) {
1633 recon_format = ctx->input_frames->sw_format;
1637 if (recon_format == AV_PIX_FMT_NONE) {
1638 // No match. Just use the first in the supported list and
1639 // hope for the best.
1640 recon_format = constraints->valid_sw_formats[0];
1643 // No idea what to use; copy input format.
1644 recon_format = ctx->input_frames->sw_format;
1646 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1647 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1649 if (ctx->surface_width < constraints->min_width ||
1650 ctx->surface_height < constraints->min_height ||
1651 ctx->surface_width > constraints->max_width ||
1652 ctx->surface_height > constraints->max_height) {
1653 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1654 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1655 ctx->surface_width, ctx->surface_height,
1656 constraints->min_width, constraints->max_width,
1657 constraints->min_height, constraints->max_height);
1658 err = AVERROR(EINVAL);
1662 av_freep(&hwconfig);
1663 av_hwframe_constraints_free(&constraints);
1665 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1666 if (!ctx->recon_frames_ref) {
1667 err = AVERROR(ENOMEM);
1670 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1672 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
1673 ctx->recon_frames->sw_format = recon_format;
1674 ctx->recon_frames->width = ctx->surface_width;
1675 ctx->recon_frames->height = ctx->surface_height;
1676 // At most three IDR/I/P frames and two runs of B frames can be in
1677 // flight at any one time.
1678 ctx->recon_frames->initial_pool_size = 3 + 2 * ctx->b_per_p;
1680 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1682 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1683 "frame context: %d.\n", err);
1689 av_freep(&hwconfig);
1690 av_hwframe_constraints_free(&constraints);
1694 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
1696 VAAPIEncodeContext *ctx = avctx->priv_data;
1697 AVVAAPIFramesContext *recon_hwctx = NULL;
1701 if (!avctx->hw_frames_ctx) {
1702 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1703 "required to associate the encoding device.\n");
1704 return AVERROR(EINVAL);
1707 ctx->va_config = VA_INVALID_ID;
1708 ctx->va_context = VA_INVALID_ID;
1710 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1711 if (!ctx->input_frames_ref) {
1712 err = AVERROR(ENOMEM);
1715 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1717 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1718 if (!ctx->device_ref) {
1719 err = AVERROR(ENOMEM);
1722 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1723 ctx->hwctx = ctx->device->hwctx;
1725 err = vaapi_encode_profile_entrypoint(avctx);
1729 err = vaapi_encode_init_rate_control(avctx);
1733 err = vaapi_encode_init_gop_structure(avctx);
1737 err = vaapi_encode_init_packed_headers(avctx);
1741 if (avctx->compression_level >= 0) {
1742 err = vaapi_encode_init_quality(avctx);
1747 vas = vaCreateConfig(ctx->hwctx->display,
1748 ctx->va_profile, ctx->va_entrypoint,
1749 ctx->config_attributes, ctx->nb_config_attributes,
1751 if (vas != VA_STATUS_SUCCESS) {
1752 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1753 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1758 err = vaapi_encode_create_recon_frames(avctx);
1762 recon_hwctx = ctx->recon_frames->hwctx;
1763 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1764 ctx->surface_width, ctx->surface_height,
1766 recon_hwctx->surface_ids,
1767 recon_hwctx->nb_surfaces,
1769 if (vas != VA_STATUS_SUCCESS) {
1770 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1771 "context: %d (%s).\n", vas, vaErrorStr(vas));
1776 ctx->output_buffer_pool =
1777 av_buffer_pool_init2(sizeof(VABufferID), avctx,
1778 &vaapi_encode_alloc_output_buffer, NULL);
1779 if (!ctx->output_buffer_pool) {
1780 err = AVERROR(ENOMEM);
1784 if (ctx->codec->configure) {
1785 err = ctx->codec->configure(avctx);
1790 ctx->input_order = 0;
1791 ctx->output_delay = ctx->b_per_p;
1792 ctx->decode_delay = 1;
1793 ctx->output_order = - ctx->output_delay - 1;
1795 if (ctx->codec->sequence_params_size > 0) {
1796 ctx->codec_sequence_params =
1797 av_mallocz(ctx->codec->sequence_params_size);
1798 if (!ctx->codec_sequence_params) {
1799 err = AVERROR(ENOMEM);
1803 if (ctx->codec->picture_params_size > 0) {
1804 ctx->codec_picture_params =
1805 av_mallocz(ctx->codec->picture_params_size);
1806 if (!ctx->codec_picture_params) {
1807 err = AVERROR(ENOMEM);
1812 if (ctx->codec->init_sequence_params) {
1813 err = ctx->codec->init_sequence_params(avctx);
1815 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1816 "failed: %d.\n", err);
1821 // This should be configurable somehow. (Needs testing on a machine
1822 // where it actually overlaps properly, though.)
1823 ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1825 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
1826 ctx->codec->write_sequence_header &&
1827 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1828 char data[MAX_PARAM_BUFFER_SIZE];
1829 size_t bit_len = 8 * sizeof(data);
1831 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
1833 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
1834 "for extradata: %d.\n", err);
1837 avctx->extradata_size = (bit_len + 7) / 8;
1838 avctx->extradata = av_mallocz(avctx->extradata_size +
1839 AV_INPUT_BUFFER_PADDING_SIZE);
1840 if (!avctx->extradata) {
1841 err = AVERROR(ENOMEM);
1844 memcpy(avctx->extradata, data, avctx->extradata_size);
1851 ff_vaapi_encode_close(avctx);
1855 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
1857 VAAPIEncodeContext *ctx = avctx->priv_data;
1858 VAAPIEncodePicture *pic, *next;
1860 for (pic = ctx->pic_start; pic; pic = next) {
1862 vaapi_encode_free(avctx, pic);
1865 av_buffer_pool_uninit(&ctx->output_buffer_pool);
1867 if (ctx->va_context != VA_INVALID_ID) {
1868 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
1869 ctx->va_context = VA_INVALID_ID;
1872 if (ctx->va_config != VA_INVALID_ID) {
1873 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
1874 ctx->va_config = VA_INVALID_ID;
1877 av_freep(&ctx->codec_sequence_params);
1878 av_freep(&ctx->codec_picture_params);
1880 av_buffer_unref(&ctx->recon_frames_ref);
1881 av_buffer_unref(&ctx->input_frames_ref);
1882 av_buffer_unref(&ctx->device_ref);