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 *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;
39 VAEncPackedHeaderParameterBuffer params = {
41 .bit_length = bit_len,
42 .has_emulation_bytes = 1,
45 av_assert0(pic->nb_param_buffers + 2 <= MAX_PARAM_BUFFERS);
47 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
48 VAEncPackedHeaderParameterBufferType,
49 sizeof(params), 1, ¶ms, ¶m_buffer);
50 if (vas != VA_STATUS_SUCCESS) {
51 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
52 "for packed header (type %d): %d (%s).\n",
53 type, vas, vaErrorStr(vas));
56 pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
58 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
59 VAEncPackedHeaderDataBufferType,
60 (bit_len + 7) / 8, 1, data, &data_buffer);
61 if (vas != VA_STATUS_SUCCESS) {
62 av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
63 "for packed header (type %d): %d (%s).\n",
64 type, vas, vaErrorStr(vas));
67 pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
69 av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
70 "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
74 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
75 VAAPIEncodePicture *pic,
76 int type, char *data, size_t len)
78 VAAPIEncodeContext *ctx = avctx->priv_data;
82 av_assert0(pic->nb_param_buffers + 1 <= MAX_PARAM_BUFFERS);
84 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
85 type, len, 1, data, &buffer);
86 if (vas != VA_STATUS_SUCCESS) {
87 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
88 "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
91 pic->param_buffers[pic->nb_param_buffers++] = buffer;
93 av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
98 static int vaapi_encode_wait(AVCodecContext *avctx,
99 VAAPIEncodePicture *pic)
101 VAAPIEncodeContext *ctx = avctx->priv_data;
104 av_assert0(pic->encode_issued);
106 if (pic->encode_complete) {
107 // Already waited for this picture.
111 av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
112 "(input surface %#x).\n", pic->display_order,
113 pic->encode_order, pic->input_surface);
115 vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
116 if (vas != VA_STATUS_SUCCESS) {
117 av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
118 "%d (%s).\n", vas, vaErrorStr(vas));
122 // Input is definitely finished with now.
123 av_frame_free(&pic->input_image);
125 pic->encode_complete = 1;
129 static int vaapi_encode_issue(AVCodecContext *avctx,
130 VAAPIEncodePicture *pic)
132 VAAPIEncodeContext *ctx = avctx->priv_data;
133 VAAPIEncodeSlice *slice;
136 char data[MAX_PARAM_BUFFER_SIZE];
139 av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
140 "as type %s.\n", pic->display_order, pic->encode_order,
141 picture_type_name[pic->type]);
142 if (pic->nb_refs == 0) {
143 av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
145 av_log(avctx, AV_LOG_DEBUG, "Refers to:");
146 for (i = 0; i < pic->nb_refs; i++) {
147 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
148 pic->refs[i]->display_order, pic->refs[i]->encode_order);
150 av_log(avctx, AV_LOG_DEBUG, ".\n");
153 av_assert0(pic->input_available && !pic->encode_issued);
154 for (i = 0; i < pic->nb_refs; i++) {
155 av_assert0(pic->refs[i]);
156 // If we are serialised then the references must have already
157 // completed. If not, they must have been issued but need not
158 // have completed yet.
159 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
160 av_assert0(pic->refs[i]->encode_complete);
162 av_assert0(pic->refs[i]->encode_issued);
165 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
167 pic->recon_image = av_frame_alloc();
168 if (!pic->recon_image) {
169 err = AVERROR(ENOMEM);
173 err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
175 err = AVERROR(ENOMEM);
178 pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
179 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
181 pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
182 if (!pic->output_buffer_ref) {
183 err = AVERROR(ENOMEM);
186 pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
187 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
190 if (ctx->codec->picture_params_size > 0) {
191 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
192 if (!pic->codec_picture_params)
194 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
195 ctx->codec->picture_params_size);
197 av_assert0(!ctx->codec_picture_params);
200 pic->nb_param_buffers = 0;
202 if (pic->encode_order == 0) {
203 // Global parameter buffers are set on the first picture only.
205 for (i = 0; i < ctx->nb_global_params; i++) {
206 err = vaapi_encode_make_param_buffer(avctx, pic,
207 VAEncMiscParameterBufferType,
208 (char*)ctx->global_params[i],
209 ctx->global_params_size[i]);
215 if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
216 err = vaapi_encode_make_param_buffer(avctx, pic,
217 VAEncSequenceParameterBufferType,
218 ctx->codec_sequence_params,
219 ctx->codec->sequence_params_size);
224 if (ctx->codec->init_picture_params) {
225 err = ctx->codec->init_picture_params(avctx, pic);
227 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
228 "parameters: %d.\n", err);
231 err = vaapi_encode_make_param_buffer(avctx, pic,
232 VAEncPictureParameterBufferType,
233 pic->codec_picture_params,
234 ctx->codec->picture_params_size);
239 if (pic->type == PICTURE_TYPE_IDR) {
240 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
241 ctx->codec->write_sequence_header) {
242 bit_len = 8 * sizeof(data);
243 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
245 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
246 "header: %d.\n", err);
249 err = vaapi_encode_make_packed_header(avctx, pic,
250 ctx->codec->sequence_header_type,
257 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
258 ctx->codec->write_picture_header) {
259 bit_len = 8 * sizeof(data);
260 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
262 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
263 "header: %d.\n", err);
266 err = vaapi_encode_make_packed_header(avctx, pic,
267 ctx->codec->picture_header_type,
273 if (ctx->codec->write_extra_buffer) {
275 size_t len = sizeof(data);
277 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
279 if (err == AVERROR_EOF)
282 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
283 "buffer %d: %d.\n", i, err);
287 err = vaapi_encode_make_param_buffer(avctx, pic, type,
294 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
295 ctx->codec->write_extra_header) {
298 bit_len = 8 * sizeof(data);
299 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
301 if (err == AVERROR_EOF)
304 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
305 "header %d: %d.\n", i, err);
309 err = vaapi_encode_make_packed_header(avctx, pic, type,
316 av_assert0(pic->nb_slices <= MAX_PICTURE_SLICES);
317 for (i = 0; i < pic->nb_slices; i++) {
318 slice = av_mallocz(sizeof(*slice));
320 err = AVERROR(ENOMEM);
324 pic->slices[i] = slice;
326 if (ctx->codec->slice_params_size > 0) {
327 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
328 if (!slice->codec_slice_params) {
329 err = AVERROR(ENOMEM);
334 if (ctx->codec->init_slice_params) {
335 err = ctx->codec->init_slice_params(avctx, pic, slice);
337 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
338 "parameters: %d.\n", err);
343 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
344 ctx->codec->write_slice_header) {
345 bit_len = 8 * sizeof(data);
346 err = ctx->codec->write_slice_header(avctx, pic, slice,
349 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
350 "header: %d.\n", err);
353 err = vaapi_encode_make_packed_header(avctx, pic,
354 ctx->codec->slice_header_type,
360 if (ctx->codec->init_slice_params) {
361 err = vaapi_encode_make_param_buffer(avctx, pic,
362 VAEncSliceParameterBufferType,
363 slice->codec_slice_params,
364 ctx->codec->slice_params_size);
370 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
372 if (vas != VA_STATUS_SUCCESS) {
373 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
374 "%d (%s).\n", vas, vaErrorStr(vas));
376 goto fail_with_picture;
379 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
380 pic->param_buffers, pic->nb_param_buffers);
381 if (vas != VA_STATUS_SUCCESS) {
382 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
383 "%d (%s).\n", vas, vaErrorStr(vas));
385 goto fail_with_picture;
388 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
389 if (vas != VA_STATUS_SUCCESS) {
390 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
391 "%d (%s).\n", vas, vaErrorStr(vas));
393 // vaRenderPicture() has been called here, so we should not destroy
394 // the parameter buffers unless separate destruction is required.
395 if (ctx->hwctx->driver_quirks &
396 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
402 if (ctx->hwctx->driver_quirks &
403 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
404 for (i = 0; i < pic->nb_param_buffers; i++) {
405 vas = vaDestroyBuffer(ctx->hwctx->display,
406 pic->param_buffers[i]);
407 if (vas != VA_STATUS_SUCCESS) {
408 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
409 "param buffer %#x: %d (%s).\n",
410 pic->param_buffers[i], vas, vaErrorStr(vas));
416 pic->encode_issued = 1;
418 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
419 return vaapi_encode_wait(avctx, pic);
424 vaEndPicture(ctx->hwctx->display, ctx->va_context);
426 for(i = 0; i < pic->nb_param_buffers; i++)
427 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
429 av_freep(&pic->codec_picture_params);
430 av_frame_free(&pic->recon_image);
434 static int vaapi_encode_output(AVCodecContext *avctx,
435 VAAPIEncodePicture *pic, AVPacket *pkt)
437 VAAPIEncodeContext *ctx = avctx->priv_data;
438 VACodedBufferSegment *buf_list, *buf;
442 err = vaapi_encode_wait(avctx, pic);
447 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
449 if (vas != VA_STATUS_SUCCESS) {
450 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
451 "%d (%s).\n", vas, vaErrorStr(vas));
456 for (buf = buf_list; buf; buf = buf->next) {
457 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
458 "(status %08x).\n", buf->size, buf->status);
460 err = av_new_packet(pkt, buf->size);
464 memcpy(pkt->data, buf->buf, buf->size);
467 if (pic->type == PICTURE_TYPE_IDR)
468 pkt->flags |= AV_PKT_FLAG_KEY;
472 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
473 if (vas != VA_STATUS_SUCCESS) {
474 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
475 "%d (%s).\n", vas, vaErrorStr(vas));
480 av_buffer_unref(&pic->output_buffer_ref);
481 pic->output_buffer = VA_INVALID_ID;
483 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
484 pic->display_order, pic->encode_order);
488 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
490 av_buffer_unref(&pic->output_buffer_ref);
491 pic->output_buffer = VA_INVALID_ID;
495 static int vaapi_encode_discard(AVCodecContext *avctx,
496 VAAPIEncodePicture *pic)
498 vaapi_encode_wait(avctx, pic);
500 if (pic->output_buffer_ref) {
501 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
502 "%"PRId64"/%"PRId64".\n",
503 pic->display_order, pic->encode_order);
505 av_buffer_unref(&pic->output_buffer_ref);
506 pic->output_buffer = VA_INVALID_ID;
512 static VAAPIEncodePicture *vaapi_encode_alloc(void)
514 VAAPIEncodePicture *pic;
516 pic = av_mallocz(sizeof(*pic));
520 pic->input_surface = VA_INVALID_ID;
521 pic->recon_surface = VA_INVALID_ID;
522 pic->output_buffer = VA_INVALID_ID;
527 static int vaapi_encode_free(AVCodecContext *avctx,
528 VAAPIEncodePicture *pic)
532 if (pic->encode_issued)
533 vaapi_encode_discard(avctx, pic);
535 for (i = 0; i < pic->nb_slices; i++) {
536 av_freep(&pic->slices[i]->priv_data);
537 av_freep(&pic->slices[i]->codec_slice_params);
538 av_freep(&pic->slices[i]);
540 av_freep(&pic->codec_picture_params);
542 av_frame_free(&pic->input_image);
543 av_frame_free(&pic->recon_image);
545 // Output buffer should already be destroyed.
546 av_assert0(pic->output_buffer == VA_INVALID_ID);
548 av_freep(&pic->priv_data);
549 av_freep(&pic->codec_picture_params);
556 static int vaapi_encode_step(AVCodecContext *avctx,
557 VAAPIEncodePicture *target)
559 VAAPIEncodeContext *ctx = avctx->priv_data;
560 VAAPIEncodePicture *pic;
563 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
564 ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
565 // These two modes are equivalent, except that we wait for
566 // immediate completion on each operation if serialised.
569 // No target, nothing to do yet.
573 if (target->encode_complete) {
579 for (i = 0; i < pic->nb_refs; i++) {
580 if (!pic->refs[i]->encode_complete) {
581 err = vaapi_encode_step(avctx, pic->refs[i]);
587 err = vaapi_encode_issue(avctx, pic);
591 } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
594 // Run through the list of all available pictures repeatedly
595 // and issue the first one found which has all dependencies
596 // available (including previously-issued but not necessarily
597 // completed pictures).
600 for (pic = ctx->pic_start; pic; pic = pic->next) {
601 if (!pic->input_available || pic->encode_issued)
603 for (i = 0; i < pic->nb_refs; i++) {
604 if (!pic->refs[i]->encode_issued)
607 if (i < pic->nb_refs)
609 err = vaapi_encode_issue(avctx, pic);
613 // Start again from the beginning of the list,
614 // because issuing this picture may have satisfied
615 // forward dependencies of earlier ones.
620 // If we had a defined target for this step then it will
621 // always have been issued by now.
623 av_assert0(target->encode_issued && "broken dependencies?");
633 static int vaapi_encode_get_next(AVCodecContext *avctx,
634 VAAPIEncodePicture **pic_out)
636 VAAPIEncodeContext *ctx = avctx->priv_data;
637 VAAPIEncodePicture *start, *end, *pic;
640 for (pic = ctx->pic_start; pic; pic = pic->next) {
642 av_assert0(pic->display_order + 1 == pic->next->display_order);
643 if (pic->display_order == ctx->input_order) {
649 pic = vaapi_encode_alloc();
651 return AVERROR(ENOMEM);
653 if (ctx->input_order == 0 || ctx->force_idr ||
654 ctx->gop_counter >= avctx->gop_size) {
655 pic->type = PICTURE_TYPE_IDR;
657 ctx->gop_counter = 1;
659 } else if (ctx->p_counter >= ctx->p_per_i) {
660 pic->type = PICTURE_TYPE_I;
664 pic->type = PICTURE_TYPE_P;
665 pic->refs[0] = ctx->pic_end;
672 if (pic->type != PICTURE_TYPE_IDR) {
673 // If that was not an IDR frame, add B-frames display-before and
674 // encode-after it, but not exceeding the GOP size.
676 for (i = 0; i < ctx->b_per_p &&
677 ctx->gop_counter < avctx->gop_size; i++) {
678 pic = vaapi_encode_alloc();
682 pic->type = PICTURE_TYPE_B;
683 pic->refs[0] = ctx->pic_end;
688 pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
689 pic->encode_order = pic->display_order + 1;
696 if (ctx->input_order == 0) {
697 pic->display_order = 0;
698 pic->encode_order = 0;
700 ctx->pic_start = ctx->pic_end = pic;
703 for (i = 0, pic = start; pic; i++, pic = pic->next) {
704 pic->display_order = ctx->input_order + i;
705 if (end->type == PICTURE_TYPE_IDR)
706 pic->encode_order = ctx->input_order + i;
708 pic->encode_order = ctx->input_order;
710 pic->encode_order = ctx->input_order + i + 1;
713 av_assert0(ctx->pic_end);
714 ctx->pic_end->next = start;
719 av_log(avctx, AV_LOG_DEBUG, "Pictures:");
720 for (pic = ctx->pic_start; pic; pic = pic->next) {
721 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
722 picture_type_name[pic->type],
723 pic->display_order, pic->encode_order);
725 av_log(avctx, AV_LOG_DEBUG, "\n");
732 vaapi_encode_free(avctx, start);
735 return AVERROR(ENOMEM);
738 static int vaapi_encode_truncate_gop(AVCodecContext *avctx)
740 VAAPIEncodeContext *ctx = avctx->priv_data;
741 VAAPIEncodePicture *pic, *last_pic, *next;
743 // Find the last picture we actually have input for.
744 for (pic = ctx->pic_start; pic; pic = pic->next) {
745 if (!pic->input_available)
751 av_assert0(last_pic);
753 if (last_pic->type == PICTURE_TYPE_B) {
754 // Some fixing up is required. Change the type of this
755 // picture to P, then modify preceding B references which
756 // point beyond it to point at it instead.
758 last_pic->type = PICTURE_TYPE_P;
759 last_pic->encode_order = last_pic->refs[1]->encode_order;
761 for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
762 if (pic->type == PICTURE_TYPE_B &&
763 pic->refs[1] == last_pic->refs[1])
764 pic->refs[1] = last_pic;
767 last_pic->nb_refs = 1;
768 last_pic->refs[1] = NULL;
770 // We can use the current structure (no references point
771 // beyond the end), but there are unused pics to discard.
774 // Discard all following pics, they will never be used.
775 for (pic = last_pic->next; pic; pic = next) {
777 vaapi_encode_free(avctx, pic);
780 last_pic->next = NULL;
781 ctx->pic_end = last_pic;
784 // Input is available for all pictures, so we don't need to
788 av_log(avctx, AV_LOG_DEBUG, "Pictures ending truncated GOP:");
789 for (pic = ctx->pic_start; pic; pic = pic->next) {
790 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
791 picture_type_name[pic->type],
792 pic->display_order, pic->encode_order);
794 av_log(avctx, AV_LOG_DEBUG, "\n");
799 static int vaapi_encode_clear_old(AVCodecContext *avctx)
801 VAAPIEncodeContext *ctx = avctx->priv_data;
802 VAAPIEncodePicture *pic, *old;
805 while (ctx->pic_start != ctx->pic_end) {
806 old = ctx->pic_start;
807 if (old->encode_order > ctx->output_order)
810 for (pic = old->next; pic; pic = pic->next) {
811 if (pic->encode_complete)
813 for (i = 0; i < pic->nb_refs; i++) {
814 if (pic->refs[i] == old) {
815 // We still need this picture because it's referred to
816 // directly by a later one, so it and all following
817 // pictures have to stay.
823 pic = ctx->pic_start;
824 ctx->pic_start = pic->next;
825 vaapi_encode_free(avctx, pic);
831 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
832 const AVFrame *input_image, int *got_packet)
834 VAAPIEncodeContext *ctx = avctx->priv_data;
835 VAAPIEncodePicture *pic;
839 av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
840 input_image->width, input_image->height, input_image->pts);
842 if (input_image->pict_type == AV_PICTURE_TYPE_I) {
843 err = vaapi_encode_truncate_gop(avctx);
849 err = vaapi_encode_get_next(avctx, &pic);
851 av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
855 pic->input_image = av_frame_alloc();
856 if (!pic->input_image) {
857 err = AVERROR(ENOMEM);
860 err = av_frame_ref(pic->input_image, input_image);
863 pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
864 pic->pts = input_image->pts;
866 if (ctx->input_order == 0)
867 ctx->first_pts = pic->pts;
868 if (ctx->input_order == ctx->decode_delay)
869 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
870 if (ctx->output_delay > 0)
871 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
873 pic->input_available = 1;
876 if (!ctx->end_of_stream) {
877 err = vaapi_encode_truncate_gop(avctx);
880 ctx->end_of_stream = 1;
886 av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
888 for (pic = ctx->pic_start; pic; pic = pic->next)
889 if (pic->encode_order == ctx->output_order)
892 // pic can be null here if we don't have a specific target in this
893 // iteration. We might still issue encodes if things can be overlapped,
894 // even though we don't intend to output anything.
896 err = vaapi_encode_step(avctx, pic);
898 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
905 err = vaapi_encode_output(avctx, pic, pkt);
907 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
911 if (ctx->output_delay == 0) {
913 } else if (ctx->output_order < ctx->decode_delay) {
914 if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
915 pkt->dts = INT64_MIN;
917 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
919 pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
920 (3 * ctx->output_delay)];
926 err = vaapi_encode_clear_old(avctx);
928 av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
935 // Unclear what to clean up on failure. There are probably some things we
936 // could do usefully clean up here, but for now just leave them for uninit()
941 static av_cold int vaapi_encode_config_attributes(AVCodecContext *avctx)
943 VAAPIEncodeContext *ctx = avctx->priv_data;
946 VAProfile *profiles = NULL;
947 VAEntrypoint *entrypoints = NULL;
948 VAConfigAttrib attr[] = {
949 { VAConfigAttribRTFormat },
950 { VAConfigAttribRateControl },
951 { VAConfigAttribEncMaxRefFrames },
952 { VAConfigAttribEncPackedHeaders },
955 n = vaMaxNumProfiles(ctx->hwctx->display);
956 profiles = av_malloc_array(n, sizeof(VAProfile));
958 err = AVERROR(ENOMEM);
961 vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);
962 if (vas != VA_STATUS_SUCCESS) {
963 av_log(ctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
964 vas, vaErrorStr(vas));
965 err = AVERROR(ENOSYS);
968 for (i = 0; i < n; i++) {
969 if (profiles[i] == ctx->va_profile)
973 av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",
975 err = AVERROR(ENOSYS);
979 n = vaMaxNumEntrypoints(ctx->hwctx->display);
980 entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
982 err = AVERROR(ENOMEM);
985 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
987 if (vas != VA_STATUS_SUCCESS) {
988 av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "
989 "profile %u: %d (%s).\n", ctx->va_profile,
990 vas, vaErrorStr(vas));
991 err = AVERROR(ENOSYS);
994 for (i = 0; i < n; i++) {
995 if (entrypoints[i] == ctx->va_entrypoint)
999 av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "
1000 "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);
1001 err = AVERROR(ENOSYS);
1005 vas = vaGetConfigAttributes(ctx->hwctx->display,
1006 ctx->va_profile, ctx->va_entrypoint,
1007 attr, FF_ARRAY_ELEMS(attr));
1008 if (vas != VA_STATUS_SUCCESS) {
1009 av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "
1010 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1011 return AVERROR(EINVAL);
1014 for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {
1015 if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {
1016 // Unfortunately we have to treat this as "don't know" and hope
1017 // for the best, because the Intel MJPEG encoder returns this
1018 // for all the interesting attributes.
1021 switch (attr[i].type) {
1022 case VAConfigAttribRTFormat:
1023 if (!(ctx->va_rt_format & attr[i].value)) {
1024 av_log(avctx, AV_LOG_ERROR, "Surface RT format %#x "
1025 "is not supported (mask %#x).\n",
1026 ctx->va_rt_format, attr[i].value);
1027 err = AVERROR(EINVAL);
1030 ctx->config_attributes[ctx->nb_config_attributes++] =
1032 .type = VAConfigAttribRTFormat,
1033 .value = ctx->va_rt_format,
1036 case VAConfigAttribRateControl:
1037 // Hack for backward compatibility: CBR was the only
1038 // usable RC mode for a long time, so old drivers will
1039 // only have it. Normal default options may now choose
1040 // VBR and then fail, however, so override it here with
1041 // CBR if that is the only supported mode.
1042 if (ctx->va_rc_mode == VA_RC_VBR &&
1043 !(attr[i].value & VA_RC_VBR) &&
1044 (attr[i].value & VA_RC_CBR)) {
1045 av_log(avctx, AV_LOG_WARNING, "VBR rate control is "
1046 "not supported with this driver version; "
1047 "using CBR instead.\n");
1048 ctx->va_rc_mode = VA_RC_CBR;
1050 if (!(ctx->va_rc_mode & attr[i].value)) {
1051 av_log(avctx, AV_LOG_ERROR, "Rate control mode %#x "
1052 "is not supported (mask: %#x).\n",
1053 ctx->va_rc_mode, attr[i].value);
1054 err = AVERROR(EINVAL);
1057 ctx->config_attributes[ctx->nb_config_attributes++] =
1059 .type = VAConfigAttribRateControl,
1060 .value = ctx->va_rc_mode,
1063 case VAConfigAttribEncMaxRefFrames:
1065 unsigned int ref_l0 = attr[i].value & 0xffff;
1066 unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;
1068 if (avctx->gop_size > 1 && ref_l0 < 1) {
1069 av_log(avctx, AV_LOG_ERROR, "P frames are not "
1070 "supported (%#x).\n", attr[i].value);
1071 err = AVERROR(EINVAL);
1074 if (avctx->max_b_frames > 0 && ref_l1 < 1) {
1075 av_log(avctx, AV_LOG_ERROR, "B frames are not "
1076 "supported (%#x).\n", attr[i].value);
1077 err = AVERROR(EINVAL);
1082 case VAConfigAttribEncPackedHeaders:
1083 if (ctx->va_packed_headers & ~attr[i].value) {
1084 // This isn't fatal, but packed headers are always
1085 // preferable because they are under our control.
1086 // When absent, the driver is generating them and some
1087 // features may not work (e.g. VUI or SEI in H.264).
1088 av_log(avctx, AV_LOG_WARNING, "Warning: some packed "
1089 "headers are not supported (want %#x, got %#x).\n",
1090 ctx->va_packed_headers, attr[i].value);
1091 ctx->va_packed_headers &= attr[i].value;
1093 ctx->config_attributes[ctx->nb_config_attributes++] =
1095 .type = VAConfigAttribEncPackedHeaders,
1096 .value = ctx->va_packed_headers,
1100 av_assert0(0 && "Unexpected config attribute.");
1106 av_freep(&profiles);
1107 av_freep(&entrypoints);
1111 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1113 VAAPIEncodeContext *ctx = avctx->priv_data;
1114 int rc_bits_per_second;
1115 int rc_target_percentage;
1117 int hrd_buffer_size;
1118 int hrd_initial_buffer_fullness;
1121 if (avctx->bit_rate > INT32_MAX) {
1122 av_log(avctx, AV_LOG_ERROR, "Target bitrate of 2^31 bps or "
1123 "higher is not supported.\n");
1124 return AVERROR(EINVAL);
1127 if (avctx->rc_buffer_size)
1128 hrd_buffer_size = avctx->rc_buffer_size;
1130 hrd_buffer_size = avctx->bit_rate;
1131 if (avctx->rc_initial_buffer_occupancy)
1132 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1134 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1136 if (ctx->va_rc_mode == VA_RC_CBR) {
1137 rc_bits_per_second = avctx->bit_rate;
1138 rc_target_percentage = 100;
1139 rc_window_size = 1000;
1141 if (avctx->rc_max_rate < avctx->bit_rate) {
1142 // Max rate is unset or invalid, just use the normal bitrate.
1143 rc_bits_per_second = avctx->bit_rate;
1144 rc_target_percentage = 100;
1146 rc_bits_per_second = avctx->rc_max_rate;
1147 rc_target_percentage = (avctx->bit_rate * 100) / rc_bits_per_second;
1149 rc_window_size = (hrd_buffer_size * 1000) / avctx->bit_rate;
1152 ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1153 ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1154 .bits_per_second = rc_bits_per_second,
1155 .target_percentage = rc_target_percentage,
1156 .window_size = rc_window_size,
1158 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1159 .basic_unit_size = 0,
1161 ctx->global_params[ctx->nb_global_params] =
1162 &ctx->rc_params.misc;
1163 ctx->global_params_size[ctx->nb_global_params++] =
1164 sizeof(ctx->rc_params);
1166 ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1167 ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1168 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1169 .buffer_size = hrd_buffer_size,
1171 ctx->global_params[ctx->nb_global_params] =
1172 &ctx->hrd_params.misc;
1173 ctx->global_params_size[ctx->nb_global_params++] =
1174 sizeof(ctx->hrd_params);
1176 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1177 av_reduce(&fr_num, &fr_den,
1178 avctx->framerate.num, avctx->framerate.den, 65535);
1180 av_reduce(&fr_num, &fr_den,
1181 avctx->time_base.den, avctx->time_base.num, 65535);
1183 ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1184 ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1186 #if VA_CHECK_VERSION(0, 40, 0)
1187 ctx->global_params[ctx->nb_global_params] =
1188 &ctx->fr_params.misc;
1189 ctx->global_params_size[ctx->nb_global_params++] =
1190 sizeof(ctx->fr_params);
1196 static void vaapi_encode_free_output_buffer(void *opaque,
1199 AVCodecContext *avctx = opaque;
1200 VAAPIEncodeContext *ctx = avctx->priv_data;
1201 VABufferID buffer_id;
1203 buffer_id = (VABufferID)(uintptr_t)data;
1205 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1207 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1210 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1213 AVCodecContext *avctx = opaque;
1214 VAAPIEncodeContext *ctx = avctx->priv_data;
1215 VABufferID buffer_id;
1219 // The output buffer size is fixed, so it needs to be large enough
1220 // to hold the largest possible compressed frame. We assume here
1221 // that the uncompressed frame plus some header data is an upper
1223 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1224 VAEncCodedBufferType,
1225 3 * ctx->surface_width * ctx->surface_height +
1226 (1 << 16), 1, 0, &buffer_id);
1227 if (vas != VA_STATUS_SUCCESS) {
1228 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1229 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1233 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1235 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1237 &vaapi_encode_free_output_buffer,
1238 avctx, AV_BUFFER_FLAG_READONLY);
1240 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1247 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1249 VAAPIEncodeContext *ctx = avctx->priv_data;
1250 AVVAAPIHWConfig *hwconfig = NULL;
1251 AVHWFramesConstraints *constraints = NULL;
1252 enum AVPixelFormat recon_format;
1255 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1257 err = AVERROR(ENOMEM);
1260 hwconfig->config_id = ctx->va_config;
1262 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1265 err = AVERROR(ENOMEM);
1269 // Probably we can use the input surface format as the surface format
1270 // of the reconstructed frames. If not, we just pick the first (only?)
1271 // format in the valid list and hope that it all works.
1272 recon_format = AV_PIX_FMT_NONE;
1273 if (constraints->valid_sw_formats) {
1274 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1275 if (ctx->input_frames->sw_format ==
1276 constraints->valid_sw_formats[i]) {
1277 recon_format = ctx->input_frames->sw_format;
1281 if (recon_format == AV_PIX_FMT_NONE) {
1282 // No match. Just use the first in the supported list and
1283 // hope for the best.
1284 recon_format = constraints->valid_sw_formats[0];
1287 // No idea what to use; copy input format.
1288 recon_format = ctx->input_frames->sw_format;
1290 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1291 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1293 if (ctx->surface_width < constraints->min_width ||
1294 ctx->surface_height < constraints->min_height ||
1295 ctx->surface_width > constraints->max_width ||
1296 ctx->surface_height > constraints->max_height) {
1297 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1298 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1299 ctx->surface_width, ctx->surface_height,
1300 constraints->min_width, constraints->max_width,
1301 constraints->min_height, constraints->max_height);
1302 err = AVERROR(EINVAL);
1306 av_freep(&hwconfig);
1307 av_hwframe_constraints_free(&constraints);
1309 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1310 if (!ctx->recon_frames_ref) {
1311 err = AVERROR(ENOMEM);
1314 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1316 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
1317 ctx->recon_frames->sw_format = recon_format;
1318 ctx->recon_frames->width = ctx->surface_width;
1319 ctx->recon_frames->height = ctx->surface_height;
1320 // At most three IDR/I/P frames and two runs of B frames can be in
1321 // flight at any one time.
1322 ctx->recon_frames->initial_pool_size = 3 + 2 * avctx->max_b_frames;
1324 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1326 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1327 "frame context: %d.\n", err);
1333 av_freep(&hwconfig);
1334 av_hwframe_constraints_free(&constraints);
1338 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
1340 VAAPIEncodeContext *ctx = avctx->priv_data;
1341 AVVAAPIFramesContext *recon_hwctx = NULL;
1345 if (!avctx->hw_frames_ctx) {
1346 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1347 "required to associate the encoding device.\n");
1348 return AVERROR(EINVAL);
1351 ctx->codec_options = ctx->codec_options_data;
1353 ctx->va_config = VA_INVALID_ID;
1354 ctx->va_context = VA_INVALID_ID;
1356 ctx->priv_data = av_mallocz(ctx->codec->priv_data_size);
1357 if (!ctx->priv_data) {
1358 err = AVERROR(ENOMEM);
1362 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1363 if (!ctx->input_frames_ref) {
1364 err = AVERROR(ENOMEM);
1367 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1369 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1370 if (!ctx->device_ref) {
1371 err = AVERROR(ENOMEM);
1374 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1375 ctx->hwctx = ctx->device->hwctx;
1377 err = vaapi_encode_config_attributes(avctx);
1381 vas = vaCreateConfig(ctx->hwctx->display,
1382 ctx->va_profile, ctx->va_entrypoint,
1383 ctx->config_attributes, ctx->nb_config_attributes,
1385 if (vas != VA_STATUS_SUCCESS) {
1386 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1387 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1392 err = vaapi_encode_create_recon_frames(avctx);
1396 recon_hwctx = ctx->recon_frames->hwctx;
1397 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1398 ctx->surface_width, ctx->surface_height,
1400 recon_hwctx->surface_ids,
1401 recon_hwctx->nb_surfaces,
1403 if (vas != VA_STATUS_SUCCESS) {
1404 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1405 "context: %d (%s).\n", vas, vaErrorStr(vas));
1410 ctx->output_buffer_pool =
1411 av_buffer_pool_init2(sizeof(VABufferID), avctx,
1412 &vaapi_encode_alloc_output_buffer, NULL);
1413 if (!ctx->output_buffer_pool) {
1414 err = AVERROR(ENOMEM);
1418 if (ctx->va_rc_mode & ~VA_RC_CQP) {
1419 err = vaapi_encode_init_rate_control(avctx);
1424 if (ctx->codec->configure) {
1425 err = ctx->codec->configure(avctx);
1430 ctx->input_order = 0;
1431 ctx->output_delay = avctx->max_b_frames;
1432 ctx->decode_delay = 1;
1433 ctx->output_order = - ctx->output_delay - 1;
1435 // Currently we never generate I frames, only IDR.
1436 ctx->p_per_i = ((avctx->gop_size + avctx->max_b_frames) /
1437 (avctx->max_b_frames + 1));
1438 ctx->b_per_p = avctx->max_b_frames;
1440 if (ctx->codec->sequence_params_size > 0) {
1441 ctx->codec_sequence_params =
1442 av_mallocz(ctx->codec->sequence_params_size);
1443 if (!ctx->codec_sequence_params) {
1444 err = AVERROR(ENOMEM);
1448 if (ctx->codec->picture_params_size > 0) {
1449 ctx->codec_picture_params =
1450 av_mallocz(ctx->codec->picture_params_size);
1451 if (!ctx->codec_picture_params) {
1452 err = AVERROR(ENOMEM);
1457 if (ctx->codec->init_sequence_params) {
1458 err = ctx->codec->init_sequence_params(avctx);
1460 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1461 "failed: %d.\n", err);
1466 // This should be configurable somehow. (Needs testing on a machine
1467 // where it actually overlaps properly, though.)
1468 ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1470 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
1471 ctx->codec->write_sequence_header) {
1472 char data[MAX_PARAM_BUFFER_SIZE];
1473 size_t bit_len = 8 * sizeof(data);
1475 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
1477 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
1478 "for extradata: %d.\n", err);
1481 avctx->extradata_size = (bit_len + 7) / 8;
1482 avctx->extradata = av_mallocz(avctx->extradata_size +
1483 AV_INPUT_BUFFER_PADDING_SIZE);
1484 if (!avctx->extradata) {
1485 err = AVERROR(ENOMEM);
1488 memcpy(avctx->extradata, data, avctx->extradata_size);
1495 ff_vaapi_encode_close(avctx);
1499 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
1501 VAAPIEncodeContext *ctx = avctx->priv_data;
1502 VAAPIEncodePicture *pic, *next;
1504 for (pic = ctx->pic_start; pic; pic = next) {
1506 vaapi_encode_free(avctx, pic);
1509 if (ctx->va_context != VA_INVALID_ID) {
1510 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
1511 ctx->va_context = VA_INVALID_ID;
1514 if (ctx->va_config != VA_INVALID_ID) {
1515 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
1516 ctx->va_config = VA_INVALID_ID;
1519 av_buffer_pool_uninit(&ctx->output_buffer_pool);
1521 av_freep(&ctx->codec_sequence_params);
1522 av_freep(&ctx->codec_picture_params);
1524 av_buffer_unref(&ctx->recon_frames_ref);
1525 av_buffer_unref(&ctx->input_frames_ref);
1526 av_buffer_unref(&ctx->device_ref);
1528 av_freep(&ctx->priv_data);