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);
323 pic->slices[i] = slice;
325 if (ctx->codec->slice_params_size > 0) {
326 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
327 if (!slice->codec_slice_params) {
328 err = AVERROR(ENOMEM);
333 if (ctx->codec->init_slice_params) {
334 err = ctx->codec->init_slice_params(avctx, pic, slice);
336 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
337 "parameters: %d.\n", err);
342 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
343 ctx->codec->write_slice_header) {
344 bit_len = 8 * sizeof(data);
345 err = ctx->codec->write_slice_header(avctx, pic, slice,
348 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
349 "header: %d.\n", err);
352 err = vaapi_encode_make_packed_header(avctx, pic,
353 ctx->codec->slice_header_type,
359 if (ctx->codec->init_slice_params) {
360 err = vaapi_encode_make_param_buffer(avctx, pic,
361 VAEncSliceParameterBufferType,
362 slice->codec_slice_params,
363 ctx->codec->slice_params_size);
369 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
371 if (vas != VA_STATUS_SUCCESS) {
372 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
373 "%d (%s).\n", vas, vaErrorStr(vas));
375 goto fail_with_picture;
378 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
379 pic->param_buffers, pic->nb_param_buffers);
380 if (vas != VA_STATUS_SUCCESS) {
381 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
382 "%d (%s).\n", vas, vaErrorStr(vas));
384 goto fail_with_picture;
387 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
388 if (vas != VA_STATUS_SUCCESS) {
389 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
390 "%d (%s).\n", vas, vaErrorStr(vas));
392 // vaRenderPicture() has been called here, so we should not destroy
393 // the parameter buffers unless separate destruction is required.
394 if (ctx->hwctx->driver_quirks &
395 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
401 if (ctx->hwctx->driver_quirks &
402 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
403 for (i = 0; i < pic->nb_param_buffers; i++) {
404 vas = vaDestroyBuffer(ctx->hwctx->display,
405 pic->param_buffers[i]);
406 if (vas != VA_STATUS_SUCCESS) {
407 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
408 "param buffer %#x: %d (%s).\n",
409 pic->param_buffers[i], vas, vaErrorStr(vas));
415 pic->encode_issued = 1;
417 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
418 return vaapi_encode_wait(avctx, pic);
423 vaEndPicture(ctx->hwctx->display, ctx->va_context);
425 for(i = 0; i < pic->nb_param_buffers; i++)
426 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
428 av_freep(&pic->codec_picture_params);
429 av_frame_free(&pic->recon_image);
433 static int vaapi_encode_output(AVCodecContext *avctx,
434 VAAPIEncodePicture *pic, AVPacket *pkt)
436 VAAPIEncodeContext *ctx = avctx->priv_data;
437 VACodedBufferSegment *buf_list, *buf;
441 err = vaapi_encode_wait(avctx, pic);
446 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
448 if (vas != VA_STATUS_SUCCESS) {
449 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
450 "%d (%s).\n", vas, vaErrorStr(vas));
455 for (buf = buf_list; buf; buf = buf->next) {
456 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
457 "(status %08x).\n", buf->size, buf->status);
459 err = av_new_packet(pkt, buf->size);
463 memcpy(pkt->data, buf->buf, buf->size);
466 if (pic->type == PICTURE_TYPE_IDR)
467 pkt->flags |= AV_PKT_FLAG_KEY;
471 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
472 if (vas != VA_STATUS_SUCCESS) {
473 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
474 "%d (%s).\n", vas, vaErrorStr(vas));
479 av_buffer_unref(&pic->output_buffer_ref);
480 pic->output_buffer = VA_INVALID_ID;
482 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
483 pic->display_order, pic->encode_order);
487 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
489 av_buffer_unref(&pic->output_buffer_ref);
490 pic->output_buffer = VA_INVALID_ID;
494 static int vaapi_encode_discard(AVCodecContext *avctx,
495 VAAPIEncodePicture *pic)
497 vaapi_encode_wait(avctx, pic);
499 if (pic->output_buffer_ref) {
500 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
501 "%"PRId64"/%"PRId64".\n",
502 pic->display_order, pic->encode_order);
504 av_buffer_unref(&pic->output_buffer_ref);
505 pic->output_buffer = VA_INVALID_ID;
511 static VAAPIEncodePicture *vaapi_encode_alloc(void)
513 VAAPIEncodePicture *pic;
515 pic = av_mallocz(sizeof(*pic));
519 pic->input_surface = VA_INVALID_ID;
520 pic->recon_surface = VA_INVALID_ID;
521 pic->output_buffer = VA_INVALID_ID;
526 static int vaapi_encode_free(AVCodecContext *avctx,
527 VAAPIEncodePicture *pic)
531 if (pic->encode_issued)
532 vaapi_encode_discard(avctx, pic);
534 for (i = 0; i < pic->nb_slices; i++) {
535 av_freep(&pic->slices[i]->priv_data);
536 av_freep(&pic->slices[i]->codec_slice_params);
537 av_freep(&pic->slices[i]);
539 av_freep(&pic->codec_picture_params);
541 av_frame_free(&pic->input_image);
542 av_frame_free(&pic->recon_image);
544 // Output buffer should already be destroyed.
545 av_assert0(pic->output_buffer == VA_INVALID_ID);
547 av_freep(&pic->priv_data);
548 av_freep(&pic->codec_picture_params);
555 static int vaapi_encode_step(AVCodecContext *avctx,
556 VAAPIEncodePicture *target)
558 VAAPIEncodeContext *ctx = avctx->priv_data;
559 VAAPIEncodePicture *pic;
562 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
563 ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
564 // These two modes are equivalent, except that we wait for
565 // immediate completion on each operation if serialised.
568 // No target, nothing to do yet.
572 if (target->encode_complete) {
578 for (i = 0; i < pic->nb_refs; i++) {
579 if (!pic->refs[i]->encode_complete) {
580 err = vaapi_encode_step(avctx, pic->refs[i]);
586 err = vaapi_encode_issue(avctx, pic);
590 } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
595 for (pic = ctx->pic_start; pic; pic = pic->next) {
596 if (!pic->input_available || pic->encode_issued)
598 for (i = 0; i < pic->nb_refs; i++) {
599 if (!pic->refs[i]->encode_issued)
602 if (i < pic->nb_refs)
604 err = vaapi_encode_issue(avctx, pic);
612 av_assert0(target->encode_issued && "broken dependencies?");
622 static int vaapi_encode_get_next(AVCodecContext *avctx,
623 VAAPIEncodePicture **pic_out)
625 VAAPIEncodeContext *ctx = avctx->priv_data;
626 VAAPIEncodePicture *start, *end, *pic;
629 for (pic = ctx->pic_start; pic; pic = pic->next) {
631 av_assert0(pic->display_order + 1 == pic->next->display_order);
632 if (pic->display_order == ctx->input_order) {
638 if (ctx->input_order == 0) {
639 // First frame is always an IDR frame.
640 av_assert0(!ctx->pic_start && !ctx->pic_end);
642 pic = vaapi_encode_alloc();
644 return AVERROR(ENOMEM);
646 pic->type = PICTURE_TYPE_IDR;
647 pic->display_order = 0;
648 pic->encode_order = 0;
650 ctx->pic_start = ctx->pic_end = pic;
656 pic = vaapi_encode_alloc();
658 return AVERROR(ENOMEM);
660 if (ctx->p_per_i == 0 || ctx->p_counter == ctx->p_per_i) {
661 if (ctx->i_per_idr == 0 || ctx->i_counter == ctx->i_per_idr) {
662 pic->type = PICTURE_TYPE_IDR;
665 pic->type = PICTURE_TYPE_I;
670 pic->type = PICTURE_TYPE_P;
671 pic->refs[0] = ctx->pic_end;
677 if (pic->type != PICTURE_TYPE_IDR) {
678 // If that was not an IDR frame, add B-frames display-before and
681 for (i = 0; i < ctx->b_per_p; i++) {
682 pic = vaapi_encode_alloc();
686 pic->type = PICTURE_TYPE_B;
687 pic->refs[0] = ctx->pic_end;
692 pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
693 pic->encode_order = pic->display_order + 1;
698 for (i = 0, pic = start; pic; i++, pic = pic->next) {
699 pic->display_order = ctx->input_order + i;
700 if (end->type == PICTURE_TYPE_IDR)
701 pic->encode_order = ctx->input_order + i;
703 pic->encode_order = ctx->input_order;
705 pic->encode_order = ctx->input_order + i + 1;
708 av_assert0(ctx->pic_end);
709 ctx->pic_end->next = start;
714 av_log(avctx, AV_LOG_DEBUG, "Pictures:");
715 for (pic = ctx->pic_start; pic; pic = pic->next) {
716 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
717 picture_type_name[pic->type],
718 pic->display_order, pic->encode_order);
720 av_log(avctx, AV_LOG_DEBUG, "\n");
727 vaapi_encode_free(avctx, start);
730 return AVERROR(ENOMEM);
733 static int vaapi_encode_mangle_end(AVCodecContext *avctx)
735 VAAPIEncodeContext *ctx = avctx->priv_data;
736 VAAPIEncodePicture *pic, *last_pic, *next;
738 // Find the last picture we actually have input for.
739 for (pic = ctx->pic_start; pic; pic = pic->next) {
740 if (!pic->input_available)
746 av_assert0(last_pic);
748 if (last_pic->type == PICTURE_TYPE_B) {
749 // Some fixing up is required. Change the type of this
750 // picture to P, then modify preceding B references which
751 // point beyond it to point at it instead.
753 last_pic->type = PICTURE_TYPE_P;
754 last_pic->encode_order = last_pic->refs[1]->encode_order;
756 for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
757 if (pic->type == PICTURE_TYPE_B &&
758 pic->refs[1] == last_pic->refs[1])
759 pic->refs[1] = last_pic;
762 last_pic->nb_refs = 1;
763 last_pic->refs[1] = NULL;
765 // We can use the current structure (no references point
766 // beyond the end), but there are unused pics to discard.
769 // Discard all following pics, they will never be used.
770 for (pic = last_pic->next; pic; pic = next) {
772 vaapi_encode_free(avctx, pic);
775 last_pic->next = NULL;
776 ctx->pic_end = last_pic;
779 // Input is available for all pictures, so we don't need to
783 av_log(avctx, AV_LOG_DEBUG, "Pictures at end of stream:");
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");
794 static int vaapi_encode_clear_old(AVCodecContext *avctx)
796 VAAPIEncodeContext *ctx = avctx->priv_data;
797 VAAPIEncodePicture *pic, *old;
800 while (ctx->pic_start != ctx->pic_end) {
801 old = ctx->pic_start;
802 if (old->encode_order > ctx->output_order)
805 for (pic = old->next; pic; pic = pic->next) {
806 if (pic->encode_complete)
808 for (i = 0; i < pic->nb_refs; i++) {
809 if (pic->refs[i] == old) {
810 // We still need this picture because it's referred to
811 // directly by a later one, so it and all following
812 // pictures have to stay.
818 pic = ctx->pic_start;
819 ctx->pic_start = pic->next;
820 vaapi_encode_free(avctx, pic);
826 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
827 const AVFrame *input_image, int *got_packet)
829 VAAPIEncodeContext *ctx = avctx->priv_data;
830 VAAPIEncodePicture *pic;
834 av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
835 input_image->width, input_image->height, input_image->pts);
837 err = vaapi_encode_get_next(avctx, &pic);
839 av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
843 pic->input_image = av_frame_alloc();
844 if (!pic->input_image) {
845 err = AVERROR(ENOMEM);
848 err = av_frame_ref(pic->input_image, input_image);
851 pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
852 pic->pts = input_image->pts;
854 if (ctx->input_order == 0)
855 ctx->first_pts = pic->pts;
856 if (ctx->input_order == ctx->decode_delay)
857 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
858 if (ctx->output_delay > 0)
859 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
861 pic->input_available = 1;
864 if (!ctx->end_of_stream) {
865 err = vaapi_encode_mangle_end(avctx);
868 ctx->end_of_stream = 1;
874 av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
876 for (pic = ctx->pic_start; pic; pic = pic->next)
877 if (pic->encode_order == ctx->output_order)
880 // pic can be null here if we don't have a specific target in this
881 // iteration. We might still issue encodes if things can be overlapped,
882 // even though we don't intend to output anything.
884 err = vaapi_encode_step(avctx, pic);
886 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
893 err = vaapi_encode_output(avctx, pic, pkt);
895 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
899 if (ctx->output_delay == 0) {
901 } else if (ctx->output_order < ctx->decode_delay) {
902 if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
903 pkt->dts = INT64_MIN;
905 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
907 pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
908 (3 * ctx->output_delay)];
914 err = vaapi_encode_clear_old(avctx);
916 av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
923 // Unclear what to clean up on failure. There are probably some things we
924 // could do usefully clean up here, but for now just leave them for uninit()
929 static av_cold int vaapi_encode_config_attributes(AVCodecContext *avctx)
931 VAAPIEncodeContext *ctx = avctx->priv_data;
934 VAProfile *profiles = NULL;
935 VAEntrypoint *entrypoints = NULL;
936 VAConfigAttrib attr[] = {
937 { VAConfigAttribRTFormat },
938 { VAConfigAttribRateControl },
939 { VAConfigAttribEncMaxRefFrames },
940 { VAConfigAttribEncPackedHeaders },
943 n = vaMaxNumProfiles(ctx->hwctx->display);
944 profiles = av_malloc_array(n, sizeof(VAProfile));
946 err = AVERROR(ENOMEM);
949 vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);
950 if (vas != VA_STATUS_SUCCESS) {
951 av_log(ctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
952 vas, vaErrorStr(vas));
953 err = AVERROR(ENOSYS);
956 for (i = 0; i < n; i++) {
957 if (profiles[i] == ctx->va_profile)
961 av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",
963 err = AVERROR(ENOSYS);
967 n = vaMaxNumEntrypoints(ctx->hwctx->display);
968 entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
970 err = AVERROR(ENOMEM);
973 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
975 if (vas != VA_STATUS_SUCCESS) {
976 av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "
977 "profile %u: %d (%s).\n", ctx->va_profile,
978 vas, vaErrorStr(vas));
979 err = AVERROR(ENOSYS);
982 for (i = 0; i < n; i++) {
983 if (entrypoints[i] == ctx->va_entrypoint)
987 av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "
988 "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);
989 err = AVERROR(ENOSYS);
993 vas = vaGetConfigAttributes(ctx->hwctx->display,
994 ctx->va_profile, ctx->va_entrypoint,
995 attr, FF_ARRAY_ELEMS(attr));
996 if (vas != VA_STATUS_SUCCESS) {
997 av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "
998 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
999 return AVERROR(EINVAL);
1002 for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {
1003 if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {
1004 // Unfortunately we have to treat this as "don't know" and hope
1005 // for the best, because the Intel MJPEG encoder returns this
1006 // for all the interesting attributes.
1009 switch (attr[i].type) {
1010 case VAConfigAttribRTFormat:
1011 if (!(ctx->va_rt_format & attr[i].value)) {
1012 av_log(avctx, AV_LOG_ERROR, "Surface RT format %#x "
1013 "is not supported (mask %#x).\n",
1014 ctx->va_rt_format, attr[i].value);
1015 err = AVERROR(EINVAL);
1018 ctx->config_attributes[ctx->nb_config_attributes++] =
1020 .type = VAConfigAttribRTFormat,
1021 .value = ctx->va_rt_format,
1024 case VAConfigAttribRateControl:
1025 if (!(ctx->va_rc_mode & attr[i].value)) {
1026 av_log(avctx, AV_LOG_ERROR, "Rate control mode %#x "
1027 "is not supported (mask: %#x).\n",
1028 ctx->va_rc_mode, attr[i].value);
1029 err = AVERROR(EINVAL);
1032 ctx->config_attributes[ctx->nb_config_attributes++] =
1034 .type = VAConfigAttribRateControl,
1035 .value = ctx->va_rc_mode,
1038 case VAConfigAttribEncMaxRefFrames:
1040 unsigned int ref_l0 = attr[i].value & 0xffff;
1041 unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;
1043 if (avctx->gop_size > 1 && ref_l0 < 1) {
1044 av_log(avctx, AV_LOG_ERROR, "P frames are not "
1045 "supported (%#x).\n", attr[i].value);
1046 err = AVERROR(EINVAL);
1049 if (avctx->max_b_frames > 0 && ref_l1 < 1) {
1050 av_log(avctx, AV_LOG_ERROR, "B frames are not "
1051 "supported (%#x).\n", attr[i].value);
1052 err = AVERROR(EINVAL);
1057 case VAConfigAttribEncPackedHeaders:
1058 if (ctx->va_packed_headers & ~attr[i].value) {
1059 // This isn't fatal, but packed headers are always
1060 // preferable because they are under our control.
1061 // When absent, the driver is generating them and some
1062 // features may not work (e.g. VUI or SEI in H.264).
1063 av_log(avctx, AV_LOG_WARNING, "Warning: some packed "
1064 "headers are not supported (want %#x, got %#x).\n",
1065 ctx->va_packed_headers, attr[i].value);
1066 ctx->va_packed_headers &= attr[i].value;
1068 ctx->config_attributes[ctx->nb_config_attributes++] =
1070 .type = VAConfigAttribEncPackedHeaders,
1071 .value = ctx->va_packed_headers,
1075 av_assert0(0 && "Unexpected config attribute.");
1081 av_freep(&profiles);
1082 av_freep(&entrypoints);
1086 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1088 VAAPIEncodeContext *ctx = avctx->priv_data;
1089 int hrd_buffer_size;
1090 int hrd_initial_buffer_fullness;
1092 if (avctx->bit_rate > INT32_MAX) {
1093 av_log(avctx, AV_LOG_ERROR, "Target bitrate of 2^31 bps or "
1094 "higher is not supported.\n");
1095 return AVERROR(EINVAL);
1098 if (avctx->rc_buffer_size)
1099 hrd_buffer_size = avctx->rc_buffer_size;
1101 hrd_buffer_size = avctx->bit_rate;
1102 if (avctx->rc_initial_buffer_occupancy)
1103 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1105 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1107 ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1108 ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1109 .bits_per_second = avctx->bit_rate,
1110 .target_percentage = 66,
1111 .window_size = 1000,
1112 .initial_qp = (avctx->qmax >= 0 ? avctx->qmax : 40),
1113 .min_qp = (avctx->qmin >= 0 ? avctx->qmin : 18),
1114 .basic_unit_size = 0,
1116 ctx->global_params[ctx->nb_global_params] =
1117 &ctx->rc_params.misc;
1118 ctx->global_params_size[ctx->nb_global_params++] =
1119 sizeof(ctx->rc_params);
1121 ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1122 ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1123 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1124 .buffer_size = hrd_buffer_size,
1126 ctx->global_params[ctx->nb_global_params] =
1127 &ctx->hrd_params.misc;
1128 ctx->global_params_size[ctx->nb_global_params++] =
1129 sizeof(ctx->hrd_params);
1134 static void vaapi_encode_free_output_buffer(void *opaque,
1137 AVCodecContext *avctx = opaque;
1138 VAAPIEncodeContext *ctx = avctx->priv_data;
1139 VABufferID buffer_id;
1141 buffer_id = (VABufferID)(uintptr_t)data;
1143 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1145 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1148 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1151 AVCodecContext *avctx = opaque;
1152 VAAPIEncodeContext *ctx = avctx->priv_data;
1153 VABufferID buffer_id;
1157 // The output buffer size is fixed, so it needs to be large enough
1158 // to hold the largest possible compressed frame. We assume here
1159 // that the uncompressed frame plus some header data is an upper
1161 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1162 VAEncCodedBufferType,
1163 3 * ctx->surface_width * ctx->surface_height +
1164 (1 << 16), 1, 0, &buffer_id);
1165 if (vas != VA_STATUS_SUCCESS) {
1166 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1167 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1171 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1173 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1175 &vaapi_encode_free_output_buffer,
1176 avctx, AV_BUFFER_FLAG_READONLY);
1178 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1185 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1187 VAAPIEncodeContext *ctx = avctx->priv_data;
1188 AVVAAPIHWConfig *hwconfig = NULL;
1189 AVHWFramesConstraints *constraints = NULL;
1190 enum AVPixelFormat recon_format;
1193 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1195 err = AVERROR(ENOMEM);
1198 hwconfig->config_id = ctx->va_config;
1200 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1203 err = AVERROR(ENOMEM);
1207 // Probably we can use the input surface format as the surface format
1208 // of the reconstructed frames. If not, we just pick the first (only?)
1209 // format in the valid list and hope that it all works.
1210 recon_format = AV_PIX_FMT_NONE;
1211 if (constraints->valid_sw_formats) {
1212 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1213 if (ctx->input_frames->sw_format ==
1214 constraints->valid_sw_formats[i]) {
1215 recon_format = ctx->input_frames->sw_format;
1219 if (recon_format == AV_PIX_FMT_NONE) {
1220 // No match. Just use the first in the supported list and
1221 // hope for the best.
1222 recon_format = constraints->valid_sw_formats[0];
1225 // No idea what to use; copy input format.
1226 recon_format = ctx->input_frames->sw_format;
1228 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1229 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1231 if (ctx->surface_width < constraints->min_width ||
1232 ctx->surface_height < constraints->min_height ||
1233 ctx->surface_width > constraints->max_width ||
1234 ctx->surface_height > constraints->max_height) {
1235 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1236 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1237 ctx->surface_width, ctx->surface_height,
1238 constraints->min_width, constraints->max_width,
1239 constraints->min_height, constraints->max_height);
1240 err = AVERROR(EINVAL);
1244 av_freep(&hwconfig);
1245 av_hwframe_constraints_free(&constraints);
1247 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1248 if (!ctx->recon_frames_ref) {
1249 err = AVERROR(ENOMEM);
1252 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1254 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
1255 ctx->recon_frames->sw_format = recon_format;
1256 ctx->recon_frames->width = ctx->surface_width;
1257 ctx->recon_frames->height = ctx->surface_height;
1258 ctx->recon_frames->initial_pool_size =
1259 avctx->max_b_frames + 3;
1261 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1263 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1264 "frame context: %d.\n", err);
1270 av_freep(&hwconfig);
1271 av_hwframe_constraints_free(&constraints);
1275 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
1277 VAAPIEncodeContext *ctx = avctx->priv_data;
1278 AVVAAPIFramesContext *recon_hwctx = NULL;
1282 if (!avctx->hw_frames_ctx) {
1283 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1284 "required to associate the encoding device.\n");
1285 return AVERROR(EINVAL);
1288 ctx->codec_options = ctx->codec_options_data;
1290 ctx->va_config = VA_INVALID_ID;
1291 ctx->va_context = VA_INVALID_ID;
1293 ctx->priv_data = av_mallocz(ctx->codec->priv_data_size);
1294 if (!ctx->priv_data) {
1295 err = AVERROR(ENOMEM);
1299 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1300 if (!ctx->input_frames_ref) {
1301 err = AVERROR(ENOMEM);
1304 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1306 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1307 if (!ctx->device_ref) {
1308 err = AVERROR(ENOMEM);
1311 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1312 ctx->hwctx = ctx->device->hwctx;
1314 err = vaapi_encode_config_attributes(avctx);
1318 vas = vaCreateConfig(ctx->hwctx->display,
1319 ctx->va_profile, ctx->va_entrypoint,
1320 ctx->config_attributes, ctx->nb_config_attributes,
1322 if (vas != VA_STATUS_SUCCESS) {
1323 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1324 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1329 err = vaapi_encode_create_recon_frames(avctx);
1333 recon_hwctx = ctx->recon_frames->hwctx;
1334 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1335 ctx->surface_width, ctx->surface_height,
1337 recon_hwctx->surface_ids,
1338 recon_hwctx->nb_surfaces,
1340 if (vas != VA_STATUS_SUCCESS) {
1341 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1342 "context: %d (%s).\n", vas, vaErrorStr(vas));
1347 ctx->output_buffer_pool =
1348 av_buffer_pool_init2(sizeof(VABufferID), avctx,
1349 &vaapi_encode_alloc_output_buffer, NULL);
1350 if (!ctx->output_buffer_pool) {
1351 err = AVERROR(ENOMEM);
1355 if (ctx->va_rc_mode & ~VA_RC_CQP) {
1356 err = vaapi_encode_init_rate_control(avctx);
1361 if (ctx->codec->configure) {
1362 err = ctx->codec->configure(avctx);
1367 ctx->input_order = 0;
1368 ctx->output_delay = avctx->max_b_frames;
1369 ctx->decode_delay = 1;
1370 ctx->output_order = - ctx->output_delay - 1;
1372 // Currently we never generate I frames, only IDR.
1374 ctx->p_per_i = ((avctx->gop_size + avctx->max_b_frames) /
1375 (avctx->max_b_frames + 1));
1376 ctx->b_per_p = avctx->max_b_frames;
1378 if (ctx->codec->sequence_params_size > 0) {
1379 ctx->codec_sequence_params =
1380 av_mallocz(ctx->codec->sequence_params_size);
1381 if (!ctx->codec_sequence_params) {
1382 err = AVERROR(ENOMEM);
1386 if (ctx->codec->picture_params_size > 0) {
1387 ctx->codec_picture_params =
1388 av_mallocz(ctx->codec->picture_params_size);
1389 if (!ctx->codec_picture_params) {
1390 err = AVERROR(ENOMEM);
1395 if (ctx->codec->init_sequence_params) {
1396 err = ctx->codec->init_sequence_params(avctx);
1398 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1399 "failed: %d.\n", err);
1404 // This should be configurable somehow. (Needs testing on a machine
1405 // where it actually overlaps properly, though.)
1406 ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1408 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
1409 ctx->codec->write_sequence_header) {
1410 char data[MAX_PARAM_BUFFER_SIZE];
1411 size_t bit_len = 8 * sizeof(data);
1413 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
1415 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
1416 "for extradata: %d.\n", err);
1419 avctx->extradata_size = (bit_len + 7) / 8;
1420 avctx->extradata = av_mallocz(avctx->extradata_size +
1421 AV_INPUT_BUFFER_PADDING_SIZE);
1422 if (!avctx->extradata) {
1423 err = AVERROR(ENOMEM);
1426 memcpy(avctx->extradata, data, avctx->extradata_size);
1433 ff_vaapi_encode_close(avctx);
1437 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
1439 VAAPIEncodeContext *ctx = avctx->priv_data;
1440 VAAPIEncodePicture *pic, *next;
1442 for (pic = ctx->pic_start; pic; pic = next) {
1444 vaapi_encode_free(avctx, pic);
1447 if (ctx->va_context != VA_INVALID_ID) {
1448 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
1449 ctx->va_context = VA_INVALID_ID;
1452 if (ctx->va_config != VA_INVALID_ID) {
1453 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
1454 ctx->va_config = VA_INVALID_ID;
1457 av_buffer_pool_uninit(&ctx->output_buffer_pool);
1459 av_freep(&ctx->codec_sequence_params);
1460 av_freep(&ctx->codec_picture_params);
1462 av_buffer_unref(&ctx->recon_frames_ref);
1463 av_buffer_unref(&ctx->input_frames_ref);
1464 av_buffer_unref(&ctx->device_ref);
1466 av_freep(&ctx->priv_data);