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 "(recon surface %#x).\n", pic->display_order,
113 pic->encode_order, pic->recon_surface);
115 vas = vaSyncSurface(ctx->hwctx->display, pic->recon_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->codec->write_sequence_header) {
241 bit_len = 8 * sizeof(data);
242 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
244 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
245 "header: %d.\n", err);
248 err = vaapi_encode_make_packed_header(avctx, pic,
249 ctx->codec->sequence_header_type,
256 if (ctx->codec->write_picture_header) {
257 bit_len = 8 * sizeof(data);
258 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
260 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
261 "header: %d.\n", err);
264 err = vaapi_encode_make_packed_header(avctx, pic,
265 ctx->codec->picture_header_type,
271 if (ctx->codec->write_extra_buffer) {
273 size_t len = sizeof(data);
275 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
277 if (err == AVERROR_EOF)
280 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
281 "buffer %d: %d.\n", i, err);
285 err = vaapi_encode_make_param_buffer(avctx, pic, type,
292 if (ctx->codec->write_extra_header) {
295 bit_len = 8 * sizeof(data);
296 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
298 if (err == AVERROR_EOF)
301 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
302 "header %d: %d.\n", i, err);
306 err = vaapi_encode_make_packed_header(avctx, pic, type,
313 av_assert0(pic->nb_slices <= MAX_PICTURE_SLICES);
314 for (i = 0; i < pic->nb_slices; i++) {
315 slice = av_mallocz(sizeof(*slice));
317 err = AVERROR(ENOMEM);
320 pic->slices[i] = slice;
322 if (ctx->codec->slice_params_size > 0) {
323 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
324 if (!slice->codec_slice_params) {
325 err = AVERROR(ENOMEM);
330 if (ctx->codec->init_slice_params) {
331 err = ctx->codec->init_slice_params(avctx, pic, slice);
333 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
334 "parameters: %d.\n", err);
339 if (ctx->codec->write_slice_header) {
340 bit_len = 8 * sizeof(data);
341 err = ctx->codec->write_slice_header(avctx, pic, slice,
344 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
345 "header: %d.\n", err);
348 err = vaapi_encode_make_packed_header(avctx, pic,
349 ctx->codec->slice_header_type,
355 if (ctx->codec->init_slice_params) {
356 err = vaapi_encode_make_param_buffer(avctx, pic,
357 VAEncSliceParameterBufferType,
358 slice->codec_slice_params,
359 ctx->codec->slice_params_size);
365 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
367 if (vas != VA_STATUS_SUCCESS) {
368 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
369 "%d (%s).\n", vas, vaErrorStr(vas));
371 goto fail_with_picture;
374 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
375 pic->param_buffers, pic->nb_param_buffers);
376 if (vas != VA_STATUS_SUCCESS) {
377 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
378 "%d (%s).\n", vas, vaErrorStr(vas));
380 goto fail_with_picture;
383 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
384 if (vas != VA_STATUS_SUCCESS) {
385 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
386 "%d (%s).\n", vas, vaErrorStr(vas));
388 // vaRenderPicture() has been called here, so we should not destroy
389 // the parameter buffers unless separate destruction is required.
390 if (ctx->hwctx->driver_quirks &
391 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
397 if (ctx->hwctx->driver_quirks &
398 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
399 for (i = 0; i < pic->nb_param_buffers; i++) {
400 vas = vaDestroyBuffer(ctx->hwctx->display,
401 pic->param_buffers[i]);
402 if (vas != VA_STATUS_SUCCESS) {
403 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
404 "param buffer %#x: %d (%s).\n",
405 pic->param_buffers[i], vas, vaErrorStr(vas));
411 pic->encode_issued = 1;
413 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
414 return vaapi_encode_wait(avctx, pic);
419 vaEndPicture(ctx->hwctx->display, ctx->va_context);
421 for(i = 0; i < pic->nb_param_buffers; i++)
422 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
424 av_freep(&pic->codec_picture_params);
425 av_frame_free(&pic->recon_image);
429 static int vaapi_encode_output(AVCodecContext *avctx,
430 VAAPIEncodePicture *pic, AVPacket *pkt)
432 VAAPIEncodeContext *ctx = avctx->priv_data;
433 VACodedBufferSegment *buf_list, *buf;
437 err = vaapi_encode_wait(avctx, pic);
442 vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
444 if (vas != VA_STATUS_SUCCESS) {
445 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
446 "%d (%s).\n", vas, vaErrorStr(vas));
451 for (buf = buf_list; buf; buf = buf->next) {
452 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
453 "(status %08x).\n", buf->size, buf->status);
455 err = av_new_packet(pkt, buf->size);
459 memcpy(pkt->data, buf->buf, buf->size);
462 if (pic->type == PICTURE_TYPE_IDR)
463 pkt->flags |= AV_PKT_FLAG_KEY;
467 vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
468 if (vas != VA_STATUS_SUCCESS) {
469 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
470 "%d (%s).\n", vas, vaErrorStr(vas));
475 av_buffer_unref(&pic->output_buffer_ref);
476 pic->output_buffer = VA_INVALID_ID;
478 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
479 pic->display_order, pic->encode_order);
483 vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
485 av_buffer_unref(&pic->output_buffer_ref);
486 pic->output_buffer = VA_INVALID_ID;
490 static int vaapi_encode_discard(AVCodecContext *avctx,
491 VAAPIEncodePicture *pic)
493 vaapi_encode_wait(avctx, pic);
495 if (pic->output_buffer_ref) {
496 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
497 "%"PRId64"/%"PRId64".\n",
498 pic->display_order, pic->encode_order);
500 av_buffer_unref(&pic->output_buffer_ref);
501 pic->output_buffer = VA_INVALID_ID;
507 static VAAPIEncodePicture *vaapi_encode_alloc(void)
509 VAAPIEncodePicture *pic;
511 pic = av_mallocz(sizeof(*pic));
515 pic->input_surface = VA_INVALID_ID;
516 pic->recon_surface = VA_INVALID_ID;
517 pic->output_buffer = VA_INVALID_ID;
522 static int vaapi_encode_free(AVCodecContext *avctx,
523 VAAPIEncodePicture *pic)
527 if (pic->encode_issued)
528 vaapi_encode_discard(avctx, pic);
530 for (i = 0; i < pic->nb_slices; i++) {
531 av_freep(&pic->slices[i]->priv_data);
532 av_freep(&pic->slices[i]->codec_slice_params);
533 av_freep(&pic->slices[i]);
535 av_freep(&pic->codec_picture_params);
537 av_frame_free(&pic->input_image);
538 av_frame_free(&pic->recon_image);
540 // Output buffer should already be destroyed.
541 av_assert0(pic->output_buffer == VA_INVALID_ID);
543 av_freep(&pic->priv_data);
544 av_freep(&pic->codec_picture_params);
551 static int vaapi_encode_step(AVCodecContext *avctx,
552 VAAPIEncodePicture *target)
554 VAAPIEncodeContext *ctx = avctx->priv_data;
555 VAAPIEncodePicture *pic;
558 if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
559 ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
560 // These two modes are equivalent, except that we wait for
561 // immediate completion on each operation if serialised.
564 // No target, nothing to do yet.
568 if (target->encode_complete) {
574 for (i = 0; i < pic->nb_refs; i++) {
575 if (!pic->refs[i]->encode_complete) {
576 err = vaapi_encode_step(avctx, pic->refs[i]);
582 err = vaapi_encode_issue(avctx, pic);
586 } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
591 for (pic = ctx->pic_start; pic; pic = pic->next) {
592 if (!pic->input_available || pic->encode_issued)
594 for (i = 0; i < pic->nb_refs; i++) {
595 if (!pic->refs[i]->encode_issued)
598 if (i < pic->nb_refs)
600 err = vaapi_encode_issue(avctx, pic);
608 av_assert0(target->encode_issued && "broken dependencies?");
618 static int vaapi_encode_get_next(AVCodecContext *avctx,
619 VAAPIEncodePicture **pic_out)
621 VAAPIEncodeContext *ctx = avctx->priv_data;
622 VAAPIEncodePicture *start, *end, *pic;
625 for (pic = ctx->pic_start; pic; pic = pic->next) {
627 av_assert0(pic->display_order + 1 == pic->next->display_order);
628 if (pic->display_order == ctx->input_order) {
634 if (ctx->input_order == 0) {
635 // First frame is always an IDR frame.
636 av_assert0(!ctx->pic_start && !ctx->pic_end);
638 pic = vaapi_encode_alloc();
640 return AVERROR(ENOMEM);
642 pic->type = PICTURE_TYPE_IDR;
643 pic->display_order = 0;
644 pic->encode_order = 0;
646 ctx->pic_start = ctx->pic_end = pic;
652 pic = vaapi_encode_alloc();
654 return AVERROR(ENOMEM);
656 if (ctx->p_per_i == 0 || ctx->p_counter == ctx->p_per_i) {
657 if (ctx->i_per_idr == 0 || ctx->i_counter == ctx->i_per_idr) {
658 pic->type = PICTURE_TYPE_IDR;
661 pic->type = PICTURE_TYPE_I;
666 pic->type = PICTURE_TYPE_P;
667 pic->refs[0] = ctx->pic_end;
673 if (pic->type != PICTURE_TYPE_IDR) {
674 // If that was not an IDR frame, add B-frames display-before and
677 for (i = 0; i < ctx->b_per_p; 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;
694 for (i = 0, pic = start; pic; i++, pic = pic->next) {
695 pic->display_order = ctx->input_order + i;
696 if (end->type == PICTURE_TYPE_IDR)
697 pic->encode_order = ctx->input_order + i;
699 pic->encode_order = ctx->input_order;
701 pic->encode_order = ctx->input_order + i + 1;
704 av_assert0(ctx->pic_end);
705 ctx->pic_end->next = start;
710 av_log(avctx, AV_LOG_DEBUG, "Pictures:");
711 for (pic = ctx->pic_start; pic; pic = pic->next) {
712 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
713 picture_type_name[pic->type],
714 pic->display_order, pic->encode_order);
716 av_log(avctx, AV_LOG_DEBUG, "\n");
723 vaapi_encode_free(avctx, start);
726 return AVERROR(ENOMEM);
729 static int vaapi_encode_mangle_end(AVCodecContext *avctx)
731 VAAPIEncodeContext *ctx = avctx->priv_data;
732 VAAPIEncodePicture *pic, *last_pic, *next;
734 // Find the last picture we actually have input for.
735 for (pic = ctx->pic_start; pic; pic = pic->next) {
736 if (!pic->input_available)
742 av_assert0(last_pic);
744 if (last_pic->type == PICTURE_TYPE_B) {
745 // Some fixing up is required. Change the type of this
746 // picture to P, then modify preceding B references which
747 // point beyond it to point at it instead.
749 last_pic->type = PICTURE_TYPE_P;
750 last_pic->encode_order = last_pic->refs[1]->encode_order;
752 for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
753 if (pic->type == PICTURE_TYPE_B &&
754 pic->refs[1] == last_pic->refs[1])
755 pic->refs[1] = last_pic;
758 last_pic->nb_refs = 1;
759 last_pic->refs[1] = NULL;
761 // We can use the current structure (no references point
762 // beyond the end), but there are unused pics to discard.
765 // Discard all following pics, they will never be used.
766 for (pic = last_pic->next; pic; pic = next) {
768 vaapi_encode_free(avctx, pic);
771 last_pic->next = NULL;
772 ctx->pic_end = last_pic;
775 // Input is available for all pictures, so we don't need to
779 av_log(avctx, AV_LOG_DEBUG, "Pictures at end of stream:");
780 for (pic = ctx->pic_start; pic; pic = pic->next) {
781 av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
782 picture_type_name[pic->type],
783 pic->display_order, pic->encode_order);
785 av_log(avctx, AV_LOG_DEBUG, "\n");
790 static int vaapi_encode_clear_old(AVCodecContext *avctx)
792 VAAPIEncodeContext *ctx = avctx->priv_data;
793 VAAPIEncodePicture *pic, *old;
796 while (ctx->pic_start != ctx->pic_end) {
797 old = ctx->pic_start;
798 if (old->encode_order > ctx->output_order)
801 for (pic = old->next; pic; pic = pic->next) {
802 if (pic->encode_complete)
804 for (i = 0; i < pic->nb_refs; i++) {
805 if (pic->refs[i] == old) {
806 // We still need this picture because it's referred to
807 // directly by a later one, so it and all following
808 // pictures have to stay.
814 pic = ctx->pic_start;
815 ctx->pic_start = pic->next;
816 vaapi_encode_free(avctx, pic);
822 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
823 const AVFrame *input_image, int *got_packet)
825 VAAPIEncodeContext *ctx = avctx->priv_data;
826 VAAPIEncodePicture *pic;
830 av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
831 input_image->width, input_image->height, input_image->pts);
833 err = vaapi_encode_get_next(avctx, &pic);
835 av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
839 pic->input_image = av_frame_alloc();
840 if (!pic->input_image) {
841 err = AVERROR(ENOMEM);
844 err = av_frame_ref(pic->input_image, input_image);
847 pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
848 pic->pts = input_image->pts;
850 if (ctx->input_order == 0)
851 ctx->first_pts = pic->pts;
852 if (ctx->input_order == ctx->decode_delay)
853 ctx->dts_pts_diff = pic->pts - ctx->first_pts;
854 if (ctx->output_delay > 0)
855 ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
857 pic->input_available = 1;
860 if (!ctx->end_of_stream) {
861 err = vaapi_encode_mangle_end(avctx);
864 ctx->end_of_stream = 1;
870 av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
872 for (pic = ctx->pic_start; pic; pic = pic->next)
873 if (pic->encode_order == ctx->output_order)
876 // pic can be null here if we don't have a specific target in this
877 // iteration. We might still issue encodes if things can be overlapped,
878 // even though we don't intend to output anything.
880 err = vaapi_encode_step(avctx, pic);
882 av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
889 err = vaapi_encode_output(avctx, pic, pkt);
891 av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
895 if (ctx->output_delay == 0) {
897 } else if (ctx->output_order < ctx->decode_delay) {
898 if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
899 pkt->dts = INT64_MIN;
901 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
903 pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
904 (3 * ctx->output_delay)];
910 err = vaapi_encode_clear_old(avctx);
912 av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
919 // Unclear what to clean up on failure. There are probably some things we
920 // could do usefully clean up here, but for now just leave them for uninit()
925 static av_cold int vaapi_encode_check_config(AVCodecContext *avctx)
927 VAAPIEncodeContext *ctx = avctx->priv_data;
930 VAProfile *profiles = NULL;
931 VAEntrypoint *entrypoints = NULL;
932 VAConfigAttrib attr[] = {
933 { VAConfigAttribRateControl },
934 { VAConfigAttribEncMaxRefFrames },
937 n = vaMaxNumProfiles(ctx->hwctx->display);
938 profiles = av_malloc_array(n, sizeof(VAProfile));
940 err = AVERROR(ENOMEM);
943 vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);
944 if (vas != VA_STATUS_SUCCESS) {
945 av_log(ctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
946 vas, vaErrorStr(vas));
947 err = AVERROR(ENOSYS);
950 for (i = 0; i < n; i++) {
951 if (profiles[i] == ctx->va_profile)
955 av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",
957 err = AVERROR(ENOSYS);
961 n = vaMaxNumEntrypoints(ctx->hwctx->display);
962 entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
964 err = AVERROR(ENOMEM);
967 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
969 if (vas != VA_STATUS_SUCCESS) {
970 av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "
971 "profile %u: %d (%s).\n", ctx->va_profile,
972 vas, vaErrorStr(vas));
973 err = AVERROR(ENOSYS);
976 for (i = 0; i < n; i++) {
977 if (entrypoints[i] == ctx->va_entrypoint)
981 av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "
982 "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);
983 err = AVERROR(ENOSYS);
987 vas = vaGetConfigAttributes(ctx->hwctx->display,
988 ctx->va_profile, ctx->va_entrypoint,
989 attr, FF_ARRAY_ELEMS(attr));
990 if (vas != VA_STATUS_SUCCESS) {
991 av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "
992 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
993 return AVERROR(EINVAL);
996 for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {
997 if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {
998 // Unfortunately we have to treat this as "don't know" and hope
999 // for the best, because the Intel MJPEG encoder returns this
1000 // for all the interesting attributes.
1003 switch (attr[i].type) {
1004 case VAConfigAttribRateControl:
1005 if (!(ctx->va_rc_mode & attr[i].value)) {
1006 av_log(avctx, AV_LOG_ERROR, "Rate control mode is not "
1007 "supported: %x\n", attr[i].value);
1008 err = AVERROR(EINVAL);
1012 case VAConfigAttribEncMaxRefFrames:
1014 unsigned int ref_l0 = attr[i].value & 0xffff;
1015 unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;
1017 if (avctx->gop_size > 1 && ref_l0 < 1) {
1018 av_log(avctx, AV_LOG_ERROR, "P frames are not "
1019 "supported (%x).\n", attr[i].value);
1020 err = AVERROR(EINVAL);
1023 if (avctx->max_b_frames > 0 && ref_l1 < 1) {
1024 av_log(avctx, AV_LOG_ERROR, "B frames are not "
1025 "supported (%x).\n", attr[i].value);
1026 err = AVERROR(EINVAL);
1036 av_freep(&profiles);
1037 av_freep(&entrypoints);
1041 static void vaapi_encode_free_output_buffer(void *opaque,
1044 AVCodecContext *avctx = opaque;
1045 VAAPIEncodeContext *ctx = avctx->priv_data;
1046 VABufferID buffer_id;
1048 buffer_id = (VABufferID)(uintptr_t)data;
1050 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1052 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1055 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1058 AVCodecContext *avctx = opaque;
1059 VAAPIEncodeContext *ctx = avctx->priv_data;
1060 VABufferID buffer_id;
1064 // The output buffer size is fixed, so it needs to be large enough
1065 // to hold the largest possible compressed frame. We assume here
1066 // that the uncompressed frame plus some header data is an upper
1068 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1069 VAEncCodedBufferType,
1070 3 * ctx->aligned_width * ctx->aligned_height +
1071 (1 << 16), 1, 0, &buffer_id);
1072 if (vas != VA_STATUS_SUCCESS) {
1073 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1074 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1078 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1080 ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1082 &vaapi_encode_free_output_buffer,
1083 avctx, AV_BUFFER_FLAG_READONLY);
1085 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1092 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx,
1093 const VAAPIEncodeType *type)
1095 VAAPIEncodeContext *ctx = avctx->priv_data;
1096 AVVAAPIFramesContext *recon_hwctx = NULL;
1097 AVVAAPIHWConfig *hwconfig = NULL;
1098 AVHWFramesConstraints *constraints = NULL;
1099 enum AVPixelFormat recon_format;
1103 if (!avctx->hw_frames_ctx) {
1104 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1105 "required to associate the encoding device.\n");
1106 return AVERROR(EINVAL);
1110 ctx->codec_options = ctx->codec_options_data;
1112 ctx->va_config = VA_INVALID_ID;
1113 ctx->va_context = VA_INVALID_ID;
1115 ctx->priv_data = av_mallocz(type->priv_data_size);
1116 if (!ctx->priv_data) {
1117 err = AVERROR(ENOMEM);
1121 ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1122 if (!ctx->input_frames_ref) {
1123 err = AVERROR(ENOMEM);
1126 ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1128 ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1129 if (!ctx->device_ref) {
1130 err = AVERROR(ENOMEM);
1133 ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1134 ctx->hwctx = ctx->device->hwctx;
1136 err = ctx->codec->init(avctx);
1140 err = vaapi_encode_check_config(avctx);
1144 vas = vaCreateConfig(ctx->hwctx->display,
1145 ctx->va_profile, ctx->va_entrypoint,
1146 ctx->config_attributes, ctx->nb_config_attributes,
1148 if (vas != VA_STATUS_SUCCESS) {
1149 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1150 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1155 hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1157 err = AVERROR(ENOMEM);
1160 hwconfig->config_id = ctx->va_config;
1162 constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1165 err = AVERROR(ENOMEM);
1169 // Probably we can use the input surface format as the surface format
1170 // of the reconstructed frames. If not, we just pick the first (only?)
1171 // format in the valid list and hope that it all works.
1172 recon_format = AV_PIX_FMT_NONE;
1173 if (constraints->valid_sw_formats) {
1174 for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1175 if (ctx->input_frames->sw_format ==
1176 constraints->valid_sw_formats[i]) {
1177 recon_format = ctx->input_frames->sw_format;
1181 if (recon_format == AV_PIX_FMT_NONE) {
1182 // No match. Just use the first in the supported list and
1183 // hope for the best.
1184 recon_format = constraints->valid_sw_formats[0];
1187 // No idea what to use; copy input format.
1188 recon_format = ctx->input_frames->sw_format;
1190 av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1191 "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1193 if (ctx->aligned_width < constraints->min_width ||
1194 ctx->aligned_height < constraints->min_height ||
1195 ctx->aligned_width > constraints->max_width ||
1196 ctx->aligned_height > constraints->max_height) {
1197 av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1198 "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1199 ctx->aligned_width, ctx->aligned_height,
1200 constraints->min_width, constraints->max_width,
1201 constraints->min_height, constraints->max_height);
1202 err = AVERROR(EINVAL);
1206 av_freep(&hwconfig);
1207 av_hwframe_constraints_free(&constraints);
1209 ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1210 if (!ctx->recon_frames_ref) {
1211 err = AVERROR(ENOMEM);
1214 ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1216 ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
1217 ctx->recon_frames->sw_format = recon_format;
1218 ctx->recon_frames->width = ctx->aligned_width;
1219 ctx->recon_frames->height = ctx->aligned_height;
1220 ctx->recon_frames->initial_pool_size = ctx->nb_recon_frames;
1222 err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1224 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1225 "frame context: %d.\n", err);
1228 recon_hwctx = ctx->recon_frames->hwctx;
1230 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1231 ctx->aligned_width, ctx->aligned_height,
1233 recon_hwctx->surface_ids,
1234 recon_hwctx->nb_surfaces,
1236 if (vas != VA_STATUS_SUCCESS) {
1237 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1238 "context: %d (%s).\n", vas, vaErrorStr(vas));
1243 ctx->input_order = 0;
1244 ctx->output_delay = avctx->max_b_frames;
1245 ctx->decode_delay = 1;
1246 ctx->output_order = - ctx->output_delay - 1;
1248 if (ctx->codec->sequence_params_size > 0) {
1249 ctx->codec_sequence_params =
1250 av_mallocz(ctx->codec->sequence_params_size);
1251 if (!ctx->codec_sequence_params) {
1252 err = AVERROR(ENOMEM);
1256 if (ctx->codec->picture_params_size > 0) {
1257 ctx->codec_picture_params =
1258 av_mallocz(ctx->codec->picture_params_size);
1259 if (!ctx->codec_picture_params) {
1260 err = AVERROR(ENOMEM);
1265 if (ctx->codec->init_sequence_params) {
1266 err = ctx->codec->init_sequence_params(avctx);
1268 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1269 "failed: %d.\n", err);
1274 ctx->output_buffer_pool =
1275 av_buffer_pool_init2(sizeof(VABufferID), avctx,
1276 &vaapi_encode_alloc_output_buffer, NULL);
1277 if (!ctx->output_buffer_pool) {
1278 err = AVERROR(ENOMEM);
1282 // All I are IDR for now.
1284 ctx->p_per_i = ((avctx->gop_size + avctx->max_b_frames) /
1285 (avctx->max_b_frames + 1));
1286 ctx->b_per_p = avctx->max_b_frames;
1288 // This should be configurable somehow. (Needs testing on a machine
1289 // where it actually overlaps properly, though.)
1290 ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1295 av_freep(&hwconfig);
1296 av_hwframe_constraints_free(&constraints);
1297 ff_vaapi_encode_close(avctx);
1301 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
1303 VAAPIEncodeContext *ctx = avctx->priv_data;
1304 VAAPIEncodePicture *pic, *next;
1306 for (pic = ctx->pic_start; pic; pic = next) {
1308 vaapi_encode_free(avctx, pic);
1311 if (ctx->va_context != VA_INVALID_ID) {
1312 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
1313 ctx->va_context = VA_INVALID_ID;
1316 if (ctx->va_config != VA_INVALID_ID) {
1317 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
1318 ctx->va_config = VA_INVALID_ID;
1321 if (ctx->codec->close)
1322 ctx->codec->close(avctx);
1324 av_buffer_pool_uninit(&ctx->output_buffer_pool);
1326 av_freep(&ctx->codec_sequence_params);
1327 av_freep(&ctx->codec_picture_params);
1329 av_buffer_unref(&ctx->recon_frames_ref);
1330 av_buffer_unref(&ctx->input_frames_ref);
1331 av_buffer_unref(&ctx->device_ref);
1333 av_freep(&ctx->priv_data);