]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_encode.c
lavc/vaapi_encode: wrap slice codes into row slice functions
[ffmpeg] / libavcodec / vaapi_encode.c
1 /*
2  * This file is part of FFmpeg.
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include <inttypes.h>
20 #include <string.h>
21
22 #include "libavutil/avassert.h"
23 #include "libavutil/common.h"
24 #include "libavutil/log.h"
25 #include "libavutil/pixdesc.h"
26
27 #include "vaapi_encode.h"
28 #include "encode.h"
29 #include "avcodec.h"
30
31 const AVCodecHWConfigInternal *ff_vaapi_encode_hw_configs[] = {
32     HW_CONFIG_ENCODER_FRAMES(VAAPI, VAAPI),
33     NULL,
34 };
35
36 static const char * const picture_type_name[] = { "IDR", "I", "P", "B" };
37
38 static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
39                                            VAAPIEncodePicture *pic,
40                                            int type, char *data, size_t bit_len)
41 {
42     VAAPIEncodeContext *ctx = avctx->priv_data;
43     VAStatus vas;
44     VABufferID param_buffer, data_buffer;
45     VABufferID *tmp;
46     VAEncPackedHeaderParameterBuffer params = {
47         .type = type,
48         .bit_length = bit_len,
49         .has_emulation_bytes = 1,
50     };
51
52     tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 2);
53     if (!tmp)
54         return AVERROR(ENOMEM);
55     pic->param_buffers = tmp;
56
57     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
58                          VAEncPackedHeaderParameterBufferType,
59                          sizeof(params), 1, &params, &param_buffer);
60     if (vas != VA_STATUS_SUCCESS) {
61         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
62                "for packed header (type %d): %d (%s).\n",
63                type, vas, vaErrorStr(vas));
64         return AVERROR(EIO);
65     }
66     pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
67
68     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
69                          VAEncPackedHeaderDataBufferType,
70                          (bit_len + 7) / 8, 1, data, &data_buffer);
71     if (vas != VA_STATUS_SUCCESS) {
72         av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
73                "for packed header (type %d): %d (%s).\n",
74                type, vas, vaErrorStr(vas));
75         return AVERROR(EIO);
76     }
77     pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
78
79     av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
80            "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
81     return 0;
82 }
83
84 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
85                                           VAAPIEncodePicture *pic,
86                                           int type, char *data, size_t len)
87 {
88     VAAPIEncodeContext *ctx = avctx->priv_data;
89     VAStatus vas;
90     VABufferID *tmp;
91     VABufferID buffer;
92
93     tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 1);
94     if (!tmp)
95         return AVERROR(ENOMEM);
96     pic->param_buffers = tmp;
97
98     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
99                          type, len, 1, data, &buffer);
100     if (vas != VA_STATUS_SUCCESS) {
101         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
102                "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
103         return AVERROR(EIO);
104     }
105     pic->param_buffers[pic->nb_param_buffers++] = buffer;
106
107     av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
108            type, buffer);
109     return 0;
110 }
111
112 static int vaapi_encode_make_misc_param_buffer(AVCodecContext *avctx,
113                                                VAAPIEncodePicture *pic,
114                                                int type,
115                                                const void *data, size_t len)
116 {
117     // Construct the buffer on the stack - 1KB is much larger than any
118     // current misc parameter buffer type (the largest is EncQuality at
119     // 224 bytes).
120     uint8_t buffer[1024];
121     VAEncMiscParameterBuffer header = {
122         .type = type,
123     };
124     size_t buffer_size = sizeof(header) + len;
125     av_assert0(buffer_size <= sizeof(buffer));
126
127     memcpy(buffer, &header, sizeof(header));
128     memcpy(buffer + sizeof(header), data, len);
129
130     return vaapi_encode_make_param_buffer(avctx, pic,
131                                           VAEncMiscParameterBufferType,
132                                           buffer, buffer_size);
133 }
134
135 static int vaapi_encode_wait(AVCodecContext *avctx,
136                              VAAPIEncodePicture *pic)
137 {
138     VAAPIEncodeContext *ctx = avctx->priv_data;
139     VAStatus vas;
140
141     av_assert0(pic->encode_issued);
142
143     if (pic->encode_complete) {
144         // Already waited for this picture.
145         return 0;
146     }
147
148     av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
149            "(input surface %#x).\n", pic->display_order,
150            pic->encode_order, pic->input_surface);
151
152     vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
153     if (vas != VA_STATUS_SUCCESS) {
154         av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
155                "%d (%s).\n", vas, vaErrorStr(vas));
156         return AVERROR(EIO);
157     }
158
159     // Input is definitely finished with now.
160     av_frame_free(&pic->input_image);
161
162     pic->encode_complete = 1;
163     return 0;
164 }
165
166 static int vaapi_encode_make_row_slice(AVCodecContext *avctx,
167                                        VAAPIEncodePicture *pic)
168 {
169     VAAPIEncodeContext *ctx = avctx->priv_data;
170     VAAPIEncodeSlice *slice;
171     int i, rounding;
172
173     for (i = 0; i < pic->nb_slices; i++)
174         pic->slices[i].row_size = ctx->slice_size;
175
176     rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
177     if (rounding > 0) {
178         // Place rounding error at top and bottom of frame.
179         av_assert0(rounding < pic->nb_slices);
180         // Some Intel drivers contain a bug where the encoder will fail
181         // if the last slice is smaller than the one before it.  Since
182         // that's straightforward to avoid here, just do so.
183         if (rounding <= 2) {
184             for (i = 0; i < rounding; i++)
185                 ++pic->slices[i].row_size;
186         } else {
187             for (i = 0; i < (rounding + 1) / 2; i++)
188                 ++pic->slices[pic->nb_slices - i - 1].row_size;
189             for (i = 0; i < rounding / 2; i++)
190                 ++pic->slices[i].row_size;
191         }
192     } else if (rounding < 0) {
193         // Remove rounding error from last slice only.
194         av_assert0(rounding < ctx->slice_size);
195         pic->slices[pic->nb_slices - 1].row_size += rounding;
196     }
197
198     for (i = 0; i < pic->nb_slices; i++) {
199         slice = &pic->slices[i];
200         slice->index = i;
201         if (i == 0) {
202             slice->row_start   = 0;
203             slice->block_start = 0;
204         } else {
205             const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
206             slice->row_start   = prev->row_start   + prev->row_size;
207             slice->block_start = prev->block_start + prev->block_size;
208         }
209         slice->block_size  = slice->row_size * ctx->slice_block_cols;
210
211         av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
212                "%d-%d (%d blocks).\n", i, slice->row_start,
213                slice->row_start + slice->row_size - 1, slice->row_size,
214                slice->block_start, slice->block_start + slice->block_size - 1,
215                slice->block_size);
216     }
217
218     return 0;
219 }
220
221 static int vaapi_encode_issue(AVCodecContext *avctx,
222                               VAAPIEncodePicture *pic)
223 {
224     VAAPIEncodeContext *ctx = avctx->priv_data;
225     VAAPIEncodeSlice *slice;
226     VAStatus vas;
227     int err, i;
228     char data[MAX_PARAM_BUFFER_SIZE];
229     size_t bit_len;
230     av_unused AVFrameSideData *sd;
231
232     av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
233            "as type %s.\n", pic->display_order, pic->encode_order,
234            picture_type_name[pic->type]);
235     if (pic->nb_refs == 0) {
236         av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
237     } else {
238         av_log(avctx, AV_LOG_DEBUG, "Refers to:");
239         for (i = 0; i < pic->nb_refs; i++) {
240             av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
241                    pic->refs[i]->display_order, pic->refs[i]->encode_order);
242         }
243         av_log(avctx, AV_LOG_DEBUG, ".\n");
244     }
245
246     av_assert0(!pic->encode_issued);
247     for (i = 0; i < pic->nb_refs; i++) {
248         av_assert0(pic->refs[i]);
249         av_assert0(pic->refs[i]->encode_issued);
250     }
251
252     av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
253
254     pic->recon_image = av_frame_alloc();
255     if (!pic->recon_image) {
256         err = AVERROR(ENOMEM);
257         goto fail;
258     }
259
260     err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
261     if (err < 0) {
262         err = AVERROR(ENOMEM);
263         goto fail;
264     }
265     pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
266     av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
267
268     pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
269     if (!pic->output_buffer_ref) {
270         err = AVERROR(ENOMEM);
271         goto fail;
272     }
273     pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
274     av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
275            pic->output_buffer);
276
277     if (ctx->codec->picture_params_size > 0) {
278         pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
279         if (!pic->codec_picture_params)
280             goto fail;
281         memcpy(pic->codec_picture_params, ctx->codec_picture_params,
282                ctx->codec->picture_params_size);
283     } else {
284         av_assert0(!ctx->codec_picture_params);
285     }
286
287     pic->nb_param_buffers = 0;
288
289     if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
290         err = vaapi_encode_make_param_buffer(avctx, pic,
291                                              VAEncSequenceParameterBufferType,
292                                              ctx->codec_sequence_params,
293                                              ctx->codec->sequence_params_size);
294         if (err < 0)
295             goto fail;
296     }
297
298     if (pic->type == PICTURE_TYPE_IDR) {
299         for (i = 0; i < ctx->nb_global_params; i++) {
300             err = vaapi_encode_make_misc_param_buffer(avctx, pic,
301                                                       ctx->global_params_type[i],
302                                                       ctx->global_params[i],
303                                                       ctx->global_params_size[i]);
304             if (err < 0)
305                 goto fail;
306         }
307     }
308
309     if (ctx->codec->init_picture_params) {
310         err = ctx->codec->init_picture_params(avctx, pic);
311         if (err < 0) {
312             av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
313                    "parameters: %d.\n", err);
314             goto fail;
315         }
316         err = vaapi_encode_make_param_buffer(avctx, pic,
317                                              VAEncPictureParameterBufferType,
318                                              pic->codec_picture_params,
319                                              ctx->codec->picture_params_size);
320         if (err < 0)
321             goto fail;
322     }
323
324     if (pic->type == PICTURE_TYPE_IDR) {
325         if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
326             ctx->codec->write_sequence_header) {
327             bit_len = 8 * sizeof(data);
328             err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
329             if (err < 0) {
330                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
331                        "header: %d.\n", err);
332                 goto fail;
333             }
334             err = vaapi_encode_make_packed_header(avctx, pic,
335                                                   ctx->codec->sequence_header_type,
336                                                   data, bit_len);
337             if (err < 0)
338                 goto fail;
339         }
340     }
341
342     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
343         ctx->codec->write_picture_header) {
344         bit_len = 8 * sizeof(data);
345         err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
346         if (err < 0) {
347             av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
348                    "header: %d.\n", err);
349             goto fail;
350         }
351         err = vaapi_encode_make_packed_header(avctx, pic,
352                                               ctx->codec->picture_header_type,
353                                               data, bit_len);
354         if (err < 0)
355             goto fail;
356     }
357
358     if (ctx->codec->write_extra_buffer) {
359         for (i = 0;; i++) {
360             size_t len = sizeof(data);
361             int type;
362             err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
363                                                  data, &len);
364             if (err == AVERROR_EOF)
365                 break;
366             if (err < 0) {
367                 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
368                        "buffer %d: %d.\n", i, err);
369                 goto fail;
370             }
371
372             err = vaapi_encode_make_param_buffer(avctx, pic, type,
373                                                  data, len);
374             if (err < 0)
375                 goto fail;
376         }
377     }
378
379     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
380         ctx->codec->write_extra_header) {
381         for (i = 0;; i++) {
382             int type;
383             bit_len = 8 * sizeof(data);
384             err = ctx->codec->write_extra_header(avctx, pic, i, &type,
385                                                  data, &bit_len);
386             if (err == AVERROR_EOF)
387                 break;
388             if (err < 0) {
389                 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
390                        "header %d: %d.\n", i, err);
391                 goto fail;
392             }
393
394             err = vaapi_encode_make_packed_header(avctx, pic, type,
395                                                   data, bit_len);
396             if (err < 0)
397                 goto fail;
398         }
399     }
400
401     if (pic->nb_slices == 0)
402         pic->nb_slices = ctx->nb_slices;
403     if (pic->nb_slices > 0) {
404         pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
405         if (!pic->slices) {
406             err = AVERROR(ENOMEM);
407             goto fail;
408         }
409
410         vaapi_encode_make_row_slice(avctx, pic);
411     }
412
413     for (i = 0; i < pic->nb_slices; i++) {
414         slice = &pic->slices[i];
415
416         if (ctx->codec->slice_params_size > 0) {
417             slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
418             if (!slice->codec_slice_params) {
419                 err = AVERROR(ENOMEM);
420                 goto fail;
421             }
422         }
423
424         if (ctx->codec->init_slice_params) {
425             err = ctx->codec->init_slice_params(avctx, pic, slice);
426             if (err < 0) {
427                 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
428                        "parameters: %d.\n", err);
429                 goto fail;
430             }
431         }
432
433         if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
434             ctx->codec->write_slice_header) {
435             bit_len = 8 * sizeof(data);
436             err = ctx->codec->write_slice_header(avctx, pic, slice,
437                                                  data, &bit_len);
438             if (err < 0) {
439                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
440                        "header: %d.\n", err);
441                 goto fail;
442             }
443             err = vaapi_encode_make_packed_header(avctx, pic,
444                                                   ctx->codec->slice_header_type,
445                                                   data, bit_len);
446             if (err < 0)
447                 goto fail;
448         }
449
450         if (ctx->codec->init_slice_params) {
451             err = vaapi_encode_make_param_buffer(avctx, pic,
452                                                  VAEncSliceParameterBufferType,
453                                                  slice->codec_slice_params,
454                                                  ctx->codec->slice_params_size);
455             if (err < 0)
456                 goto fail;
457         }
458     }
459
460 #if VA_CHECK_VERSION(1, 0, 0)
461     sd = av_frame_get_side_data(pic->input_image,
462                                 AV_FRAME_DATA_REGIONS_OF_INTEREST);
463     if (sd && ctx->roi_allowed) {
464         const AVRegionOfInterest *roi;
465         uint32_t roi_size;
466         VAEncMiscParameterBufferROI param_roi;
467         int nb_roi, i, v;
468
469         roi = (const AVRegionOfInterest*)sd->data;
470         roi_size = roi->self_size;
471         av_assert0(roi_size && sd->size % roi_size == 0);
472         nb_roi = sd->size / roi_size;
473         if (nb_roi > ctx->roi_max_regions) {
474             if (!ctx->roi_warned) {
475                 av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
476                        "supported by driver (%d > %d).\n",
477                        nb_roi, ctx->roi_max_regions);
478                 ctx->roi_warned = 1;
479             }
480             nb_roi = ctx->roi_max_regions;
481         }
482
483         pic->roi = av_mallocz_array(nb_roi, sizeof(*pic->roi));
484         if (!pic->roi) {
485             err = AVERROR(ENOMEM);
486             goto fail;
487         }
488         // For overlapping regions, the first in the array takes priority.
489         for (i = 0; i < nb_roi; i++) {
490             roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
491
492             av_assert0(roi->qoffset.den != 0);
493             v = roi->qoffset.num * ctx->roi_quant_range / roi->qoffset.den;
494             av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
495                    roi->top, roi->left, roi->bottom, roi->right, v);
496
497             pic->roi[i] = (VAEncROI) {
498                 .roi_rectangle = {
499                     .x      = roi->left,
500                     .y      = roi->top,
501                     .width  = roi->right  - roi->left,
502                     .height = roi->bottom - roi->top,
503                 },
504                 .roi_value = av_clip_int8(v),
505             };
506         }
507
508         param_roi = (VAEncMiscParameterBufferROI) {
509             .num_roi      = nb_roi,
510             .max_delta_qp = INT8_MAX,
511             .min_delta_qp = INT8_MIN,
512             .roi          = pic->roi,
513             .roi_flags.bits.roi_value_is_qp_delta = 1,
514         };
515
516         err = vaapi_encode_make_misc_param_buffer(avctx, pic,
517                                                   VAEncMiscParameterTypeROI,
518                                                   &param_roi,
519                                                   sizeof(param_roi));
520         if (err < 0)
521             goto fail;
522     }
523 #endif
524
525     vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
526                          pic->input_surface);
527     if (vas != VA_STATUS_SUCCESS) {
528         av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
529                "%d (%s).\n", vas, vaErrorStr(vas));
530         err = AVERROR(EIO);
531         goto fail_with_picture;
532     }
533
534     vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
535                           pic->param_buffers, pic->nb_param_buffers);
536     if (vas != VA_STATUS_SUCCESS) {
537         av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
538                "%d (%s).\n", vas, vaErrorStr(vas));
539         err = AVERROR(EIO);
540         goto fail_with_picture;
541     }
542
543     vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
544     if (vas != VA_STATUS_SUCCESS) {
545         av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
546                "%d (%s).\n", vas, vaErrorStr(vas));
547         err = AVERROR(EIO);
548         // vaRenderPicture() has been called here, so we should not destroy
549         // the parameter buffers unless separate destruction is required.
550         if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
551             AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
552             goto fail;
553         else
554             goto fail_at_end;
555     }
556
557     if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
558         AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
559         for (i = 0; i < pic->nb_param_buffers; i++) {
560             vas = vaDestroyBuffer(ctx->hwctx->display,
561                                   pic->param_buffers[i]);
562             if (vas != VA_STATUS_SUCCESS) {
563                 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
564                        "param buffer %#x: %d (%s).\n",
565                        pic->param_buffers[i], vas, vaErrorStr(vas));
566                 // And ignore.
567             }
568         }
569     }
570
571     pic->encode_issued = 1;
572
573     return 0;
574
575 fail_with_picture:
576     vaEndPicture(ctx->hwctx->display, ctx->va_context);
577 fail:
578     for(i = 0; i < pic->nb_param_buffers; i++)
579         vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
580     for (i = 0; i < pic->nb_slices; i++) {
581         if (pic->slices) {
582             av_freep(&pic->slices[i].priv_data);
583             av_freep(&pic->slices[i].codec_slice_params);
584         }
585     }
586 fail_at_end:
587     av_freep(&pic->codec_picture_params);
588     av_freep(&pic->param_buffers);
589     av_freep(&pic->slices);
590     av_freep(&pic->roi);
591     av_frame_free(&pic->recon_image);
592     av_buffer_unref(&pic->output_buffer_ref);
593     pic->output_buffer = VA_INVALID_ID;
594     return err;
595 }
596
597 static int vaapi_encode_output(AVCodecContext *avctx,
598                                VAAPIEncodePicture *pic, AVPacket *pkt)
599 {
600     VAAPIEncodeContext *ctx = avctx->priv_data;
601     VACodedBufferSegment *buf_list, *buf;
602     VAStatus vas;
603     int total_size = 0;
604     uint8_t *ptr;
605     int err;
606
607     err = vaapi_encode_wait(avctx, pic);
608     if (err < 0)
609         return err;
610
611     buf_list = NULL;
612     vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
613                       (void**)&buf_list);
614     if (vas != VA_STATUS_SUCCESS) {
615         av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
616                "%d (%s).\n", vas, vaErrorStr(vas));
617         err = AVERROR(EIO);
618         goto fail;
619     }
620
621     for (buf = buf_list; buf; buf = buf->next)
622         total_size += buf->size;
623
624     err = av_new_packet(pkt, total_size);
625     ptr = pkt->data;
626
627     if (err < 0)
628         goto fail_mapped;
629
630     for (buf = buf_list; buf; buf = buf->next) {
631         av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
632                "(status %08x).\n", buf->size, buf->status);
633
634         memcpy(ptr, buf->buf, buf->size);
635         ptr += buf->size;
636     }
637
638     if (pic->type == PICTURE_TYPE_IDR)
639         pkt->flags |= AV_PKT_FLAG_KEY;
640
641     pkt->pts = pic->pts;
642
643     vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
644     if (vas != VA_STATUS_SUCCESS) {
645         av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
646                "%d (%s).\n", vas, vaErrorStr(vas));
647         err = AVERROR(EIO);
648         goto fail;
649     }
650
651     av_buffer_unref(&pic->output_buffer_ref);
652     pic->output_buffer = VA_INVALID_ID;
653
654     av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
655            pic->display_order, pic->encode_order);
656     return 0;
657
658 fail_mapped:
659     vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
660 fail:
661     av_buffer_unref(&pic->output_buffer_ref);
662     pic->output_buffer = VA_INVALID_ID;
663     return err;
664 }
665
666 static int vaapi_encode_discard(AVCodecContext *avctx,
667                                 VAAPIEncodePicture *pic)
668 {
669     vaapi_encode_wait(avctx, pic);
670
671     if (pic->output_buffer_ref) {
672         av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
673                "%"PRId64"/%"PRId64".\n",
674                pic->display_order, pic->encode_order);
675
676         av_buffer_unref(&pic->output_buffer_ref);
677         pic->output_buffer = VA_INVALID_ID;
678     }
679
680     return 0;
681 }
682
683 static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
684 {
685     VAAPIEncodeContext *ctx = avctx->priv_data;
686     VAAPIEncodePicture *pic;
687
688     pic = av_mallocz(sizeof(*pic));
689     if (!pic)
690         return NULL;
691
692     if (ctx->codec->picture_priv_data_size > 0) {
693         pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
694         if (!pic->priv_data) {
695             av_freep(&pic);
696             return NULL;
697         }
698     }
699
700     pic->input_surface = VA_INVALID_ID;
701     pic->recon_surface = VA_INVALID_ID;
702     pic->output_buffer = VA_INVALID_ID;
703
704     return pic;
705 }
706
707 static int vaapi_encode_free(AVCodecContext *avctx,
708                              VAAPIEncodePicture *pic)
709 {
710     int i;
711
712     if (pic->encode_issued)
713         vaapi_encode_discard(avctx, pic);
714
715     for (i = 0; i < pic->nb_slices; i++) {
716         if (pic->slices) {
717             av_freep(&pic->slices[i].priv_data);
718             av_freep(&pic->slices[i].codec_slice_params);
719         }
720     }
721     av_freep(&pic->codec_picture_params);
722
723     av_frame_free(&pic->input_image);
724     av_frame_free(&pic->recon_image);
725
726     av_freep(&pic->param_buffers);
727     av_freep(&pic->slices);
728     // Output buffer should already be destroyed.
729     av_assert0(pic->output_buffer == VA_INVALID_ID);
730
731     av_freep(&pic->priv_data);
732     av_freep(&pic->codec_picture_params);
733     av_freep(&pic->roi);
734
735     av_free(pic);
736
737     return 0;
738 }
739
740 static void vaapi_encode_add_ref(AVCodecContext *avctx,
741                                  VAAPIEncodePicture *pic,
742                                  VAAPIEncodePicture *target,
743                                  int is_ref, int in_dpb, int prev)
744 {
745     int refs = 0;
746
747     if (is_ref) {
748         av_assert0(pic != target);
749         av_assert0(pic->nb_refs < MAX_PICTURE_REFERENCES);
750         pic->refs[pic->nb_refs++] = target;
751         ++refs;
752     }
753
754     if (in_dpb) {
755         av_assert0(pic->nb_dpb_pics < MAX_DPB_SIZE);
756         pic->dpb[pic->nb_dpb_pics++] = target;
757         ++refs;
758     }
759
760     if (prev) {
761         av_assert0(!pic->prev);
762         pic->prev = target;
763         ++refs;
764     }
765
766     target->ref_count[0] += refs;
767     target->ref_count[1] += refs;
768 }
769
770 static void vaapi_encode_remove_refs(AVCodecContext *avctx,
771                                      VAAPIEncodePicture *pic,
772                                      int level)
773 {
774     int i;
775
776     if (pic->ref_removed[level])
777         return;
778
779     for (i = 0; i < pic->nb_refs; i++) {
780         av_assert0(pic->refs[i]);
781         --pic->refs[i]->ref_count[level];
782         av_assert0(pic->refs[i]->ref_count[level] >= 0);
783     }
784
785     for (i = 0; i < pic->nb_dpb_pics; i++) {
786         av_assert0(pic->dpb[i]);
787         --pic->dpb[i]->ref_count[level];
788         av_assert0(pic->dpb[i]->ref_count[level] >= 0);
789     }
790
791     av_assert0(pic->prev || pic->type == PICTURE_TYPE_IDR);
792     if (pic->prev) {
793         --pic->prev->ref_count[level];
794         av_assert0(pic->prev->ref_count[level] >= 0);
795     }
796
797     pic->ref_removed[level] = 1;
798 }
799
800 static void vaapi_encode_set_b_pictures(AVCodecContext *avctx,
801                                         VAAPIEncodePicture *start,
802                                         VAAPIEncodePicture *end,
803                                         VAAPIEncodePicture *prev,
804                                         int current_depth,
805                                         VAAPIEncodePicture **last)
806 {
807     VAAPIEncodeContext *ctx = avctx->priv_data;
808     VAAPIEncodePicture *pic, *next, *ref;
809     int i, len;
810
811     av_assert0(start && end && start != end && start->next != end);
812
813     // If we are at the maximum depth then encode all pictures as
814     // non-referenced B-pictures.  Also do this if there is exactly one
815     // picture left, since there will be nothing to reference it.
816     if (current_depth == ctx->max_b_depth || start->next->next == end) {
817         for (pic = start->next; pic; pic = pic->next) {
818             if (pic == end)
819                 break;
820             pic->type    = PICTURE_TYPE_B;
821             pic->b_depth = current_depth;
822
823             vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
824             vaapi_encode_add_ref(avctx, pic, end,   1, 1, 0);
825             vaapi_encode_add_ref(avctx, pic, prev,  0, 0, 1);
826
827             for (ref = end->refs[1]; ref; ref = ref->refs[1])
828                 vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
829         }
830         *last = prev;
831
832     } else {
833         // Split the current list at the midpoint with a referenced
834         // B-picture, then descend into each side separately.
835         len = 0;
836         for (pic = start->next; pic != end; pic = pic->next)
837             ++len;
838         for (pic = start->next, i = 1; 2 * i < len; pic = pic->next, i++);
839
840         pic->type    = PICTURE_TYPE_B;
841         pic->b_depth = current_depth;
842
843         pic->is_reference = 1;
844
845         vaapi_encode_add_ref(avctx, pic, pic,   0, 1, 0);
846         vaapi_encode_add_ref(avctx, pic, start, 1, 1, 0);
847         vaapi_encode_add_ref(avctx, pic, end,   1, 1, 0);
848         vaapi_encode_add_ref(avctx, pic, prev,  0, 0, 1);
849
850         for (ref = end->refs[1]; ref; ref = ref->refs[1])
851             vaapi_encode_add_ref(avctx, pic, ref, 0, 1, 0);
852
853         if (i > 1)
854             vaapi_encode_set_b_pictures(avctx, start, pic, pic,
855                                         current_depth + 1, &next);
856         else
857             next = pic;
858
859         vaapi_encode_set_b_pictures(avctx, pic, end, next,
860                                     current_depth + 1, last);
861     }
862 }
863
864 static int vaapi_encode_pick_next(AVCodecContext *avctx,
865                                   VAAPIEncodePicture **pic_out)
866 {
867     VAAPIEncodeContext *ctx = avctx->priv_data;
868     VAAPIEncodePicture *pic = NULL, *next, *start;
869     int i, b_counter, closed_gop_end;
870
871     // If there are any B-frames already queued, the next one to encode
872     // is the earliest not-yet-issued frame for which all references are
873     // available.
874     for (pic = ctx->pic_start; pic; pic = pic->next) {
875         if (pic->encode_issued)
876             continue;
877         if (pic->type != PICTURE_TYPE_B)
878             continue;
879         for (i = 0; i < pic->nb_refs; i++) {
880             if (!pic->refs[i]->encode_issued)
881                 break;
882         }
883         if (i == pic->nb_refs)
884             break;
885     }
886
887     if (pic) {
888         av_log(avctx, AV_LOG_DEBUG, "Pick B-picture at depth %d to "
889                "encode next.\n", pic->b_depth);
890         *pic_out = pic;
891         return 0;
892     }
893
894     // Find the B-per-Pth available picture to become the next picture
895     // on the top layer.
896     start = NULL;
897     b_counter = 0;
898     closed_gop_end = ctx->closed_gop ||
899                      ctx->idr_counter == ctx->gop_per_idr;
900     for (pic = ctx->pic_start; pic; pic = next) {
901         next = pic->next;
902         if (pic->encode_issued) {
903             start = pic;
904             continue;
905         }
906         // If the next available picture is force-IDR, encode it to start
907         // a new GOP immediately.
908         if (pic->force_idr)
909             break;
910         if (b_counter == ctx->b_per_p)
911             break;
912         // If this picture ends a closed GOP or starts a new GOP then it
913         // needs to be in the top layer.
914         if (ctx->gop_counter + b_counter + closed_gop_end >= ctx->gop_size)
915             break;
916         // If the picture after this one is force-IDR, we need to encode
917         // this one in the top layer.
918         if (next && next->force_idr)
919             break;
920         ++b_counter;
921     }
922
923     // At the end of the stream the last picture must be in the top layer.
924     if (!pic && ctx->end_of_stream) {
925         --b_counter;
926         pic = ctx->pic_end;
927         if (pic->encode_issued)
928             return AVERROR_EOF;
929     }
930
931     if (!pic) {
932         av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
933                "need more input for reference pictures.\n");
934         return AVERROR(EAGAIN);
935     }
936     if (ctx->input_order <= ctx->decode_delay && !ctx->end_of_stream) {
937         av_log(avctx, AV_LOG_DEBUG, "Pick nothing to encode next - "
938                "need more input for timestamps.\n");
939         return AVERROR(EAGAIN);
940     }
941
942     if (pic->force_idr) {
943         av_log(avctx, AV_LOG_DEBUG, "Pick forced IDR-picture to "
944                "encode next.\n");
945         pic->type = PICTURE_TYPE_IDR;
946         ctx->idr_counter = 1;
947         ctx->gop_counter = 1;
948
949     } else if (ctx->gop_counter + b_counter >= ctx->gop_size) {
950         if (ctx->idr_counter == ctx->gop_per_idr) {
951             av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP IDR-picture to "
952                    "encode next.\n");
953             pic->type = PICTURE_TYPE_IDR;
954             ctx->idr_counter = 1;
955         } else {
956             av_log(avctx, AV_LOG_DEBUG, "Pick new-GOP I-picture to "
957                    "encode next.\n");
958             pic->type = PICTURE_TYPE_I;
959             ++ctx->idr_counter;
960         }
961         ctx->gop_counter = 1;
962
963     } else {
964         if (ctx->gop_counter + b_counter + closed_gop_end == ctx->gop_size) {
965             av_log(avctx, AV_LOG_DEBUG, "Pick group-end P-picture to "
966                    "encode next.\n");
967         } else {
968             av_log(avctx, AV_LOG_DEBUG, "Pick normal P-picture to "
969                    "encode next.\n");
970         }
971         pic->type = PICTURE_TYPE_P;
972         av_assert0(start);
973         ctx->gop_counter += 1 + b_counter;
974     }
975     pic->is_reference = 1;
976     *pic_out = pic;
977
978     vaapi_encode_add_ref(avctx, pic, pic, 0, 1, 0);
979     if (pic->type != PICTURE_TYPE_IDR) {
980         vaapi_encode_add_ref(avctx, pic, start,
981                              pic->type == PICTURE_TYPE_P,
982                              b_counter > 0, 0);
983         vaapi_encode_add_ref(avctx, pic, ctx->next_prev, 0, 0, 1);
984     }
985     if (ctx->next_prev)
986         --ctx->next_prev->ref_count[0];
987
988     if (b_counter > 0) {
989         vaapi_encode_set_b_pictures(avctx, start, pic, pic, 1,
990                                     &ctx->next_prev);
991     } else {
992         ctx->next_prev = pic;
993     }
994     ++ctx->next_prev->ref_count[0];
995     return 0;
996 }
997
998 static int vaapi_encode_clear_old(AVCodecContext *avctx)
999 {
1000     VAAPIEncodeContext *ctx = avctx->priv_data;
1001     VAAPIEncodePicture *pic, *prev, *next;
1002
1003     av_assert0(ctx->pic_start);
1004
1005     // Remove direct references once each picture is complete.
1006     for (pic = ctx->pic_start; pic; pic = pic->next) {
1007         if (pic->encode_complete && pic->next)
1008             vaapi_encode_remove_refs(avctx, pic, 0);
1009     }
1010
1011     // Remove indirect references once a picture has no direct references.
1012     for (pic = ctx->pic_start; pic; pic = pic->next) {
1013         if (pic->encode_complete && pic->ref_count[0] == 0)
1014             vaapi_encode_remove_refs(avctx, pic, 1);
1015     }
1016
1017     // Clear out all complete pictures with no remaining references.
1018     prev = NULL;
1019     for (pic = ctx->pic_start; pic; pic = next) {
1020         next = pic->next;
1021         if (pic->encode_complete && pic->ref_count[1] == 0) {
1022             av_assert0(pic->ref_removed[0] && pic->ref_removed[1]);
1023             if (prev)
1024                 prev->next = next;
1025             else
1026                 ctx->pic_start = next;
1027             vaapi_encode_free(avctx, pic);
1028         } else {
1029             prev = pic;
1030         }
1031     }
1032
1033     return 0;
1034 }
1035
1036 static int vaapi_encode_check_frame(AVCodecContext *avctx,
1037                                     const AVFrame *frame)
1038 {
1039     VAAPIEncodeContext *ctx = avctx->priv_data;
1040
1041     if ((frame->crop_top  || frame->crop_bottom ||
1042          frame->crop_left || frame->crop_right) && !ctx->crop_warned) {
1043         av_log(avctx, AV_LOG_WARNING, "Cropping information on input "
1044                "frames ignored due to lack of API support.\n");
1045         ctx->crop_warned = 1;
1046     }
1047
1048     if (!ctx->roi_allowed) {
1049         AVFrameSideData *sd =
1050             av_frame_get_side_data(frame, AV_FRAME_DATA_REGIONS_OF_INTEREST);
1051
1052         if (sd && !ctx->roi_warned) {
1053             av_log(avctx, AV_LOG_WARNING, "ROI side data on input "
1054                    "frames ignored due to lack of driver support.\n");
1055             ctx->roi_warned = 1;
1056         }
1057     }
1058
1059     return 0;
1060 }
1061
1062 static int vaapi_encode_send_frame(AVCodecContext *avctx, AVFrame *frame)
1063 {
1064     VAAPIEncodeContext *ctx = avctx->priv_data;
1065     VAAPIEncodePicture *pic;
1066     int err;
1067
1068     if (frame) {
1069         av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
1070                frame->width, frame->height, frame->pts);
1071
1072         err = vaapi_encode_check_frame(avctx, frame);
1073         if (err < 0)
1074             return err;
1075
1076         pic = vaapi_encode_alloc(avctx);
1077         if (!pic)
1078             return AVERROR(ENOMEM);
1079
1080         pic->input_image = av_frame_alloc();
1081         if (!pic->input_image) {
1082             err = AVERROR(ENOMEM);
1083             goto fail;
1084         }
1085
1086         if (ctx->input_order == 0 || frame->pict_type == AV_PICTURE_TYPE_I)
1087             pic->force_idr = 1;
1088
1089         pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
1090         pic->pts = frame->pts;
1091
1092         av_frame_move_ref(pic->input_image, frame);
1093
1094         if (ctx->input_order == 0)
1095             ctx->first_pts = pic->pts;
1096         if (ctx->input_order == ctx->decode_delay)
1097             ctx->dts_pts_diff = pic->pts - ctx->first_pts;
1098         if (ctx->output_delay > 0)
1099             ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
1100
1101         pic->display_order = ctx->input_order;
1102         ++ctx->input_order;
1103
1104         if (ctx->pic_start) {
1105             ctx->pic_end->next = pic;
1106             ctx->pic_end       = pic;
1107         } else {
1108             ctx->pic_start     = pic;
1109             ctx->pic_end       = pic;
1110         }
1111
1112     } else {
1113         ctx->end_of_stream = 1;
1114
1115         // Fix timestamps if we hit end-of-stream before the initial decode
1116         // delay has elapsed.
1117         if (ctx->input_order < ctx->decode_delay)
1118             ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
1119     }
1120
1121     return 0;
1122
1123 fail:
1124     vaapi_encode_free(avctx, pic);
1125     return err;
1126 }
1127
1128 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
1129 {
1130     VAAPIEncodeContext *ctx = avctx->priv_data;
1131     VAAPIEncodePicture *pic;
1132     AVFrame *frame = ctx->frame;
1133     int err;
1134
1135     err = ff_encode_get_frame(avctx, frame);
1136     if (err < 0 && err != AVERROR_EOF)
1137         return err;
1138
1139     if (err == AVERROR_EOF)
1140         frame = NULL;
1141
1142     err = vaapi_encode_send_frame(avctx, frame);
1143     if (err < 0)
1144         return err;
1145
1146     if (!ctx->pic_start) {
1147         if (ctx->end_of_stream)
1148             return AVERROR_EOF;
1149         else
1150             return AVERROR(EAGAIN);
1151     }
1152
1153     pic = NULL;
1154     err = vaapi_encode_pick_next(avctx, &pic);
1155     if (err < 0)
1156         return err;
1157     av_assert0(pic);
1158
1159     pic->encode_order = ctx->encode_order++;
1160
1161     err = vaapi_encode_issue(avctx, pic);
1162     if (err < 0) {
1163         av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1164         return err;
1165     }
1166
1167     err = vaapi_encode_output(avctx, pic, pkt);
1168     if (err < 0) {
1169         av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1170         return err;
1171     }
1172
1173     if (ctx->output_delay == 0) {
1174         pkt->dts = pkt->pts;
1175     } else if (pic->encode_order < ctx->decode_delay) {
1176         if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1177             pkt->dts = INT64_MIN;
1178         else
1179             pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1180     } else {
1181         pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1182                                 (3 * ctx->output_delay)];
1183     }
1184     av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1185            pkt->pts, pkt->dts);
1186
1187     ctx->output_order = pic->encode_order;
1188     vaapi_encode_clear_old(avctx);
1189
1190     return 0;
1191 }
1192
1193
1194 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
1195                                                   void *buffer, size_t size)
1196 {
1197     VAAPIEncodeContext *ctx = avctx->priv_data;
1198
1199     av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1200
1201     ctx->global_params_type[ctx->nb_global_params] = type;
1202     ctx->global_params     [ctx->nb_global_params] = buffer;
1203     ctx->global_params_size[ctx->nb_global_params] = size;
1204
1205     ++ctx->nb_global_params;
1206 }
1207
1208 typedef struct VAAPIEncodeRTFormat {
1209     const char *name;
1210     unsigned int value;
1211     int depth;
1212     int nb_components;
1213     int log2_chroma_w;
1214     int log2_chroma_h;
1215 } VAAPIEncodeRTFormat;
1216
1217 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1218     { "YUV400",    VA_RT_FORMAT_YUV400,        8, 1,      },
1219     { "YUV420",    VA_RT_FORMAT_YUV420,        8, 3, 1, 1 },
1220     { "YUV422",    VA_RT_FORMAT_YUV422,        8, 3, 1, 0 },
1221     { "YUV444",    VA_RT_FORMAT_YUV444,        8, 3, 0, 0 },
1222     { "YUV411",    VA_RT_FORMAT_YUV411,        8, 3, 2, 0 },
1223 #if VA_CHECK_VERSION(0, 38, 1)
1224     { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1225 #endif
1226 };
1227
1228 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1229     VAEntrypointEncSlice,
1230     VAEntrypointEncPicture,
1231 #if VA_CHECK_VERSION(0, 39, 2)
1232     VAEntrypointEncSliceLP,
1233 #endif
1234     0
1235 };
1236 #if VA_CHECK_VERSION(0, 39, 2)
1237 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1238     VAEntrypointEncSliceLP,
1239     0
1240 };
1241 #endif
1242
1243 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1244 {
1245     VAAPIEncodeContext      *ctx = avctx->priv_data;
1246     VAProfile    *va_profiles    = NULL;
1247     VAEntrypoint *va_entrypoints = NULL;
1248     VAStatus vas;
1249     const VAEntrypoint *usable_entrypoints;
1250     const VAAPIEncodeProfile *profile;
1251     const AVPixFmtDescriptor *desc;
1252     VAConfigAttrib rt_format_attr;
1253     const VAAPIEncodeRTFormat *rt_format;
1254     const char *profile_string, *entrypoint_string;
1255     int i, j, n, depth, err;
1256
1257
1258     if (ctx->low_power) {
1259 #if VA_CHECK_VERSION(0, 39, 2)
1260         usable_entrypoints = vaapi_encode_entrypoints_low_power;
1261 #else
1262         av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1263                "supported with this VAAPI version.\n");
1264         return AVERROR(EINVAL);
1265 #endif
1266     } else {
1267         usable_entrypoints = vaapi_encode_entrypoints_normal;
1268     }
1269
1270     desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1271     if (!desc) {
1272         av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1273                ctx->input_frames->sw_format);
1274         return AVERROR(EINVAL);
1275     }
1276     depth = desc->comp[0].depth;
1277     for (i = 1; i < desc->nb_components; i++) {
1278         if (desc->comp[i].depth != depth) {
1279             av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1280                    desc->name);
1281             return AVERROR(EINVAL);
1282         }
1283     }
1284     av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1285            desc->name);
1286
1287     n = vaMaxNumProfiles(ctx->hwctx->display);
1288     va_profiles = av_malloc_array(n, sizeof(VAProfile));
1289     if (!va_profiles) {
1290         err = AVERROR(ENOMEM);
1291         goto fail;
1292     }
1293     vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1294     if (vas != VA_STATUS_SUCCESS) {
1295         av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1296                vas, vaErrorStr(vas));
1297         err = AVERROR_EXTERNAL;
1298         goto fail;
1299     }
1300
1301     av_assert0(ctx->codec->profiles);
1302     for (i = 0; (ctx->codec->profiles[i].av_profile !=
1303                  FF_PROFILE_UNKNOWN); i++) {
1304         profile = &ctx->codec->profiles[i];
1305         if (depth               != profile->depth ||
1306             desc->nb_components != profile->nb_components)
1307             continue;
1308         if (desc->nb_components > 1 &&
1309             (desc->log2_chroma_w != profile->log2_chroma_w ||
1310              desc->log2_chroma_h != profile->log2_chroma_h))
1311             continue;
1312         if (avctx->profile != profile->av_profile &&
1313             avctx->profile != FF_PROFILE_UNKNOWN)
1314             continue;
1315
1316 #if VA_CHECK_VERSION(1, 0, 0)
1317         profile_string = vaProfileStr(profile->va_profile);
1318 #else
1319         profile_string = "(no profile names)";
1320 #endif
1321
1322         for (j = 0; j < n; j++) {
1323             if (va_profiles[j] == profile->va_profile)
1324                 break;
1325         }
1326         if (j >= n) {
1327             av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1328                    "is not supported by driver.\n", profile_string,
1329                    profile->va_profile);
1330             continue;
1331         }
1332
1333         ctx->profile = profile;
1334         break;
1335     }
1336     if (!ctx->profile) {
1337         av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1338         err = AVERROR(ENOSYS);
1339         goto fail;
1340     }
1341
1342     avctx->profile  = profile->av_profile;
1343     ctx->va_profile = profile->va_profile;
1344     av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1345            profile_string, ctx->va_profile);
1346
1347     n = vaMaxNumEntrypoints(ctx->hwctx->display);
1348     va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1349     if (!va_entrypoints) {
1350         err = AVERROR(ENOMEM);
1351         goto fail;
1352     }
1353     vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1354                                    va_entrypoints, &n);
1355     if (vas != VA_STATUS_SUCCESS) {
1356         av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1357                "profile %s (%d): %d (%s).\n", profile_string,
1358                ctx->va_profile, vas, vaErrorStr(vas));
1359         err = AVERROR_EXTERNAL;
1360         goto fail;
1361     }
1362
1363     for (i = 0; i < n; i++) {
1364         for (j = 0; usable_entrypoints[j]; j++) {
1365             if (va_entrypoints[i] == usable_entrypoints[j])
1366                 break;
1367         }
1368         if (usable_entrypoints[j])
1369             break;
1370     }
1371     if (i >= n) {
1372         av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1373                "for profile %s (%d).\n", profile_string, ctx->va_profile);
1374         err = AVERROR(ENOSYS);
1375         goto fail;
1376     }
1377
1378     ctx->va_entrypoint = va_entrypoints[i];
1379 #if VA_CHECK_VERSION(1, 0, 0)
1380     entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1381 #else
1382     entrypoint_string = "(no entrypoint names)";
1383 #endif
1384     av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1385            entrypoint_string, ctx->va_entrypoint);
1386
1387     for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1388         rt_format = &vaapi_encode_rt_formats[i];
1389         if (rt_format->depth         == depth &&
1390             rt_format->nb_components == profile->nb_components &&
1391             rt_format->log2_chroma_w == profile->log2_chroma_w &&
1392             rt_format->log2_chroma_h == profile->log2_chroma_h)
1393             break;
1394     }
1395     if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1396         av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1397                "found for profile %s (%d) entrypoint %s (%d).\n",
1398                profile_string, ctx->va_profile,
1399                entrypoint_string, ctx->va_entrypoint);
1400         err = AVERROR(ENOSYS);
1401         goto fail;
1402     }
1403
1404     rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1405     vas = vaGetConfigAttributes(ctx->hwctx->display,
1406                                 ctx->va_profile, ctx->va_entrypoint,
1407                                 &rt_format_attr, 1);
1408     if (vas != VA_STATUS_SUCCESS) {
1409         av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1410                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1411         err = AVERROR_EXTERNAL;
1412         goto fail;
1413     }
1414
1415     if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1416         av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1417                "supported by driver: assuming surface RT format %s "
1418                "is valid.\n", rt_format->name);
1419     } else if (!(rt_format_attr.value & rt_format->value)) {
1420         av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1421                "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1422                rt_format->name, profile_string, ctx->va_profile,
1423                entrypoint_string, ctx->va_entrypoint);
1424         err = AVERROR(ENOSYS);
1425         goto fail;
1426     } else {
1427         av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1428                "format %s (%#x).\n", rt_format->name, rt_format->value);
1429         ctx->config_attributes[ctx->nb_config_attributes++] =
1430             (VAConfigAttrib) {
1431             .type  = VAConfigAttribRTFormat,
1432             .value = rt_format->value,
1433         };
1434     }
1435
1436     err = 0;
1437 fail:
1438     av_freep(&va_profiles);
1439     av_freep(&va_entrypoints);
1440     return err;
1441 }
1442
1443 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1444     //                                  Bitrate   Quality
1445     //                                     | Maxrate | HRD/VBV
1446     { 0 }, //                              |    |    |    |
1447     { RC_MODE_CQP,  "CQP",  1, VA_RC_CQP,  0,   0,   1,   0 },
1448     { RC_MODE_CBR,  "CBR",  1, VA_RC_CBR,  1,   0,   0,   1 },
1449     { RC_MODE_VBR,  "VBR",  1, VA_RC_VBR,  1,   1,   0,   1 },
1450 #if VA_CHECK_VERSION(1, 1, 0)
1451     { RC_MODE_ICQ,  "ICQ",  1, VA_RC_ICQ,  0,   0,   1,   0 },
1452 #else
1453     { RC_MODE_ICQ,  "ICQ",  0 },
1454 #endif
1455 #if VA_CHECK_VERSION(1, 3, 0)
1456     { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1,   1,   1,   1 },
1457     { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1,   0,   0,   0 },
1458 #else
1459     { RC_MODE_QVBR, "QVBR", 0 },
1460     { RC_MODE_AVBR, "AVBR", 0 },
1461 #endif
1462 };
1463
1464 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1465 {
1466     VAAPIEncodeContext *ctx = avctx->priv_data;
1467     uint32_t supported_va_rc_modes;
1468     const VAAPIEncodeRCMode *rc_mode;
1469     int64_t rc_bits_per_second;
1470     int     rc_target_percentage;
1471     int     rc_window_size;
1472     int     rc_quality;
1473     int64_t hrd_buffer_size;
1474     int64_t hrd_initial_buffer_fullness;
1475     int fr_num, fr_den;
1476     VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1477     VAStatus vas;
1478     char supported_rc_modes_string[64];
1479
1480     vas = vaGetConfigAttributes(ctx->hwctx->display,
1481                                 ctx->va_profile, ctx->va_entrypoint,
1482                                 &rc_attr, 1);
1483     if (vas != VA_STATUS_SUCCESS) {
1484         av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1485                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1486         return AVERROR_EXTERNAL;
1487     }
1488     if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1489         av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1490                "supported rate control modes: assuming CQP only.\n");
1491         supported_va_rc_modes = VA_RC_CQP;
1492         strcpy(supported_rc_modes_string, "unknown");
1493     } else {
1494         char *str = supported_rc_modes_string;
1495         size_t len = sizeof(supported_rc_modes_string);
1496         int i, first = 1, res;
1497
1498         supported_va_rc_modes = rc_attr.value;
1499         for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1500             rc_mode = &vaapi_encode_rc_modes[i];
1501             if (supported_va_rc_modes & rc_mode->va_mode) {
1502                 res = snprintf(str, len, "%s%s",
1503                                first ? "" : ", ", rc_mode->name);
1504                 first = 0;
1505                 if (res < 0) {
1506                     *str = 0;
1507                     break;
1508                 }
1509                 len -= res;
1510                 str += res;
1511                 if (len == 0)
1512                     break;
1513             }
1514         }
1515
1516         av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1517                supported_rc_modes_string);
1518     }
1519
1520     // Rate control mode selection:
1521     // * If the user has set a mode explicitly with the rc_mode option,
1522     //   use it and fail if it is not available.
1523     // * If an explicit QP option has been set, use CQP.
1524     // * If the codec is CQ-only, use CQP.
1525     // * If the QSCALE avcodec option is set, use CQP.
1526     // * If bitrate and quality are both set, try QVBR.
1527     // * If quality is set, try ICQ, then CQP.
1528     // * If bitrate and maxrate are set and have the same value, try CBR.
1529     // * If a bitrate is set, try AVBR, then VBR, then CBR.
1530     // * If no bitrate is set, try ICQ, then CQP.
1531
1532 #define TRY_RC_MODE(mode, fail) do { \
1533         rc_mode = &vaapi_encode_rc_modes[mode]; \
1534         if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1535             if (fail) { \
1536                 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1537                        "RC mode (supported modes: %s).\n", rc_mode->name, \
1538                        supported_rc_modes_string); \
1539                 return AVERROR(EINVAL); \
1540             } \
1541             av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1542                    "RC mode.\n", rc_mode->name); \
1543             rc_mode = NULL; \
1544         } else { \
1545             goto rc_mode_found; \
1546         } \
1547     } while (0)
1548
1549     if (ctx->explicit_rc_mode)
1550         TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1551
1552     if (ctx->explicit_qp)
1553         TRY_RC_MODE(RC_MODE_CQP, 1);
1554
1555     if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1556         TRY_RC_MODE(RC_MODE_CQP, 1);
1557
1558     if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1559         TRY_RC_MODE(RC_MODE_CQP, 1);
1560
1561     if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1562         TRY_RC_MODE(RC_MODE_QVBR, 0);
1563
1564     if (avctx->global_quality > 0) {
1565         TRY_RC_MODE(RC_MODE_ICQ, 0);
1566         TRY_RC_MODE(RC_MODE_CQP, 0);
1567     }
1568
1569     if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1570         TRY_RC_MODE(RC_MODE_CBR, 0);
1571
1572     if (avctx->bit_rate > 0) {
1573         TRY_RC_MODE(RC_MODE_AVBR, 0);
1574         TRY_RC_MODE(RC_MODE_VBR, 0);
1575         TRY_RC_MODE(RC_MODE_CBR, 0);
1576     } else {
1577         TRY_RC_MODE(RC_MODE_ICQ, 0);
1578         TRY_RC_MODE(RC_MODE_CQP, 0);
1579     }
1580
1581     av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1582            "RC mode compatible with selected options "
1583            "(supported modes: %s).\n", supported_rc_modes_string);
1584     return AVERROR(EINVAL);
1585
1586 rc_mode_found:
1587     if (rc_mode->bitrate) {
1588         if (avctx->bit_rate <= 0) {
1589             av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1590                    "RC mode.\n", rc_mode->name);
1591             return AVERROR(EINVAL);
1592         }
1593
1594         if (rc_mode->mode == RC_MODE_AVBR) {
1595             // For maximum confusion AVBR is hacked into the existing API
1596             // by overloading some of the fields with completely different
1597             // meanings.
1598
1599             // Target percentage does not apply in AVBR mode.
1600             rc_bits_per_second = avctx->bit_rate;
1601
1602             // Accuracy tolerance range for meeting the specified target
1603             // bitrate.  It's very unclear how this is actually intended
1604             // to work - since we do want to get the specified bitrate,
1605             // set the accuracy to 100% for now.
1606             rc_target_percentage = 100;
1607
1608             // Convergence period in frames.  The GOP size reflects the
1609             // user's intended block size for cutting, so reusing that
1610             // as the convergence period seems a reasonable default.
1611             rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1612
1613         } else if (rc_mode->maxrate) {
1614             if (avctx->rc_max_rate > 0) {
1615                 if (avctx->rc_max_rate < avctx->bit_rate) {
1616                     av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1617                            "bitrate (%"PRId64") must not be greater than "
1618                            "maxrate (%"PRId64").\n", avctx->bit_rate,
1619                            avctx->rc_max_rate);
1620                     return AVERROR(EINVAL);
1621                 }
1622                 rc_bits_per_second   = avctx->rc_max_rate;
1623                 rc_target_percentage = (avctx->bit_rate * 100) /
1624                                        avctx->rc_max_rate;
1625             } else {
1626                 // We only have a target bitrate, but this mode requires
1627                 // that a maximum rate be supplied as well.  Since the
1628                 // user does not want this to be a constraint, arbitrarily
1629                 // pick a maximum rate of double the target rate.
1630                 rc_bits_per_second   = 2 * avctx->bit_rate;
1631                 rc_target_percentage = 50;
1632             }
1633         } else {
1634             if (avctx->rc_max_rate > avctx->bit_rate) {
1635                 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1636                        "in %s RC mode.\n", rc_mode->name);
1637             }
1638             rc_bits_per_second   = avctx->bit_rate;
1639             rc_target_percentage = 100;
1640         }
1641     } else {
1642         rc_bits_per_second   = 0;
1643         rc_target_percentage = 100;
1644     }
1645
1646     if (rc_mode->quality) {
1647         if (ctx->explicit_qp) {
1648             rc_quality = ctx->explicit_qp;
1649         } else if (avctx->global_quality > 0) {
1650             rc_quality = avctx->global_quality;
1651         } else {
1652             rc_quality = ctx->codec->default_quality;
1653             av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1654                    "using default (%d).\n", rc_quality);
1655         }
1656     } else {
1657         rc_quality = 0;
1658     }
1659
1660     if (rc_mode->hrd) {
1661         if (avctx->rc_buffer_size)
1662             hrd_buffer_size = avctx->rc_buffer_size;
1663         else if (avctx->rc_max_rate > 0)
1664             hrd_buffer_size = avctx->rc_max_rate;
1665         else
1666             hrd_buffer_size = avctx->bit_rate;
1667         if (avctx->rc_initial_buffer_occupancy) {
1668             if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1669                 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1670                        "must have initial buffer size (%d) <= "
1671                        "buffer size (%"PRId64").\n",
1672                        avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1673                 return AVERROR(EINVAL);
1674             }
1675             hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1676         } else {
1677             hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1678         }
1679
1680         rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1681     } else {
1682         if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1683             av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1684                    "in %s RC mode.\n", rc_mode->name);
1685         }
1686
1687         hrd_buffer_size             = 0;
1688         hrd_initial_buffer_fullness = 0;
1689
1690         if (rc_mode->mode != RC_MODE_AVBR) {
1691             // Already set (with completely different meaning) for AVBR.
1692             rc_window_size = 1000;
1693         }
1694     }
1695
1696     if (rc_bits_per_second          > UINT32_MAX ||
1697         hrd_buffer_size             > UINT32_MAX ||
1698         hrd_initial_buffer_fullness > UINT32_MAX) {
1699         av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1700                "greater are not supported by VAAPI.\n");
1701         return AVERROR(EINVAL);
1702     }
1703
1704     ctx->rc_mode     = rc_mode;
1705     ctx->rc_quality  = rc_quality;
1706     ctx->va_rc_mode  = rc_mode->va_mode;
1707     ctx->va_bit_rate = rc_bits_per_second;
1708
1709     av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1710     if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1711         // This driver does not want the RC mode attribute to be set.
1712     } else {
1713         ctx->config_attributes[ctx->nb_config_attributes++] =
1714             (VAConfigAttrib) {
1715             .type  = VAConfigAttribRateControl,
1716             .value = ctx->va_rc_mode,
1717         };
1718     }
1719
1720     if (rc_mode->quality)
1721         av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1722
1723     if (rc_mode->va_mode != VA_RC_CQP) {
1724         if (rc_mode->mode == RC_MODE_AVBR) {
1725             av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1726                    "converging in %d frames with %d%% accuracy.\n",
1727                    rc_bits_per_second, rc_window_size,
1728                    rc_target_percentage);
1729         } else if (rc_mode->bitrate) {
1730             av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1731                    "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1732                    rc_bits_per_second, rc_window_size);
1733         }
1734
1735         ctx->rc_params = (VAEncMiscParameterRateControl) {
1736             .bits_per_second    = rc_bits_per_second,
1737             .target_percentage  = rc_target_percentage,
1738             .window_size        = rc_window_size,
1739             .initial_qp         = 0,
1740             .min_qp             = (avctx->qmin > 0 ? avctx->qmin : 0),
1741             .basic_unit_size    = 0,
1742 #if VA_CHECK_VERSION(1, 1, 0)
1743             .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1744             .max_qp             = (avctx->qmax > 0 ? avctx->qmax : 0),
1745 #endif
1746 #if VA_CHECK_VERSION(1, 3, 0)
1747             .quality_factor     = rc_quality,
1748 #endif
1749         };
1750         vaapi_encode_add_global_param(avctx,
1751                                       VAEncMiscParameterTypeRateControl,
1752                                       &ctx->rc_params,
1753                                       sizeof(ctx->rc_params));
1754     }
1755
1756     if (rc_mode->hrd) {
1757         av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1758                "initial fullness %"PRId64" bits.\n",
1759                hrd_buffer_size, hrd_initial_buffer_fullness);
1760
1761         ctx->hrd_params = (VAEncMiscParameterHRD) {
1762             .initial_buffer_fullness = hrd_initial_buffer_fullness,
1763             .buffer_size             = hrd_buffer_size,
1764         };
1765         vaapi_encode_add_global_param(avctx,
1766                                       VAEncMiscParameterTypeHRD,
1767                                       &ctx->hrd_params,
1768                                       sizeof(ctx->hrd_params));
1769     }
1770
1771     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1772         av_reduce(&fr_num, &fr_den,
1773                   avctx->framerate.num, avctx->framerate.den, 65535);
1774     else
1775         av_reduce(&fr_num, &fr_den,
1776                   avctx->time_base.den, avctx->time_base.num, 65535);
1777
1778     av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1779            fr_num, fr_den, (double)fr_num / fr_den);
1780
1781     ctx->fr_params = (VAEncMiscParameterFrameRate) {
1782         .framerate = (unsigned int)fr_den << 16 | fr_num,
1783     };
1784 #if VA_CHECK_VERSION(0, 40, 0)
1785     vaapi_encode_add_global_param(avctx,
1786                                   VAEncMiscParameterTypeFrameRate,
1787                                   &ctx->fr_params,
1788                                   sizeof(ctx->fr_params));
1789 #endif
1790
1791     return 0;
1792 }
1793
1794 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1795 {
1796     VAAPIEncodeContext *ctx = avctx->priv_data;
1797     VAStatus vas;
1798     VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1799     uint32_t ref_l0, ref_l1;
1800
1801     vas = vaGetConfigAttributes(ctx->hwctx->display,
1802                                 ctx->va_profile,
1803                                 ctx->va_entrypoint,
1804                                 &attr, 1);
1805     if (vas != VA_STATUS_SUCCESS) {
1806         av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1807                "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1808         return AVERROR_EXTERNAL;
1809     }
1810
1811     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1812         ref_l0 = ref_l1 = 0;
1813     } else {
1814         ref_l0 = attr.value       & 0xffff;
1815         ref_l1 = attr.value >> 16 & 0xffff;
1816     }
1817
1818     if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1819         avctx->gop_size <= 1) {
1820         av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1821         ctx->gop_size = 1;
1822     } else if (ref_l0 < 1) {
1823         av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1824                "reference frames.\n");
1825         return AVERROR(EINVAL);
1826     } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1827                ref_l1 < 1 || avctx->max_b_frames < 1) {
1828         av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1829                "(supported references: %d / %d).\n", ref_l0, ref_l1);
1830         ctx->gop_size = avctx->gop_size;
1831         ctx->p_per_i  = INT_MAX;
1832         ctx->b_per_p  = 0;
1833     } else {
1834         av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1835                "(supported references: %d / %d).\n", ref_l0, ref_l1);
1836         ctx->gop_size = avctx->gop_size;
1837         ctx->p_per_i  = INT_MAX;
1838         ctx->b_per_p  = avctx->max_b_frames;
1839         if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1840             ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1841                                      av_log2(ctx->b_per_p) + 1);
1842         } else {
1843             ctx->max_b_depth = 1;
1844         }
1845     }
1846
1847     if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1848         ctx->closed_gop  = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1849         ctx->gop_per_idr = ctx->idr_interval + 1;
1850     } else {
1851         ctx->closed_gop  = 1;
1852         ctx->gop_per_idr = 1;
1853     }
1854
1855     return 0;
1856 }
1857
1858 static av_cold int vaapi_encode_init_row_slice_structure(AVCodecContext *avctx,
1859                                                          uint32_t slice_structure)
1860 {
1861     VAAPIEncodeContext *ctx = avctx->priv_data;
1862     int req_slices;
1863
1864     // For fixed-size slices currently we only support whole rows, making
1865     // rectangular slices.  This could be extended to arbitrary runs of
1866     // blocks, but since slices tend to be a conformance requirement and
1867     // most cases (such as broadcast or bluray) want rectangular slices
1868     // only it would need to be gated behind another option.
1869     if (avctx->slices > ctx->slice_block_rows) {
1870         av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1871                "configured number of slices (%d < %d); using "
1872                "maximum.\n", ctx->slice_block_rows, avctx->slices);
1873         req_slices = ctx->slice_block_rows;
1874     } else {
1875         req_slices = avctx->slices;
1876     }
1877     if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1878 #if VA_CHECK_VERSION(1, 8, 0)
1879         slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_MULTI_ROWS ||
1880 #endif
1881         slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1882         ctx->nb_slices  = req_slices;
1883         ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1884     } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1885         int k;
1886         for (k = 1;; k *= 2) {
1887             if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1888                 break;
1889         }
1890         ctx->nb_slices  = (ctx->slice_block_rows + k - 1) / k;
1891         ctx->slice_size = k;
1892 #if VA_CHECK_VERSION(1, 0, 0)
1893     } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1894         ctx->nb_slices  = ctx->slice_block_rows;
1895         ctx->slice_size = 1;
1896 #endif
1897     } else {
1898         av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1899                "slice structure modes (%#x).\n", slice_structure);
1900         return AVERROR(EINVAL);
1901     }
1902
1903     return 0;
1904 }
1905
1906 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1907 {
1908     VAAPIEncodeContext *ctx = avctx->priv_data;
1909     VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1910                                { VAConfigAttribEncSliceStructure } };
1911     VAStatus vas;
1912     uint32_t max_slices, slice_structure;
1913     int ret;
1914
1915     if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1916         if (avctx->slices > 0) {
1917             av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1918                    "but this codec does not support controlling slices.\n");
1919         }
1920         return 0;
1921     }
1922
1923     ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1924                              ctx->slice_block_height;
1925     ctx->slice_block_cols = (avctx->width  + ctx->slice_block_width  - 1) /
1926                              ctx->slice_block_width;
1927
1928     if (avctx->slices <= 1) {
1929         ctx->nb_slices  = 1;
1930         ctx->slice_size = ctx->slice_block_rows;
1931         return 0;
1932     }
1933
1934     vas = vaGetConfigAttributes(ctx->hwctx->display,
1935                                 ctx->va_profile,
1936                                 ctx->va_entrypoint,
1937                                 attr, FF_ARRAY_ELEMS(attr));
1938     if (vas != VA_STATUS_SUCCESS) {
1939         av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1940                "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1941         return AVERROR_EXTERNAL;
1942     }
1943     max_slices      = attr[0].value;
1944     slice_structure = attr[1].value;
1945     if (max_slices      == VA_ATTRIB_NOT_SUPPORTED ||
1946         slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1947         av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1948                "pictures as multiple slices.\n.");
1949         return AVERROR(EINVAL);
1950     }
1951
1952     ret = vaapi_encode_init_row_slice_structure(avctx, slice_structure);
1953     if (ret < 0)
1954         return ret;
1955
1956     if (ctx->nb_slices > avctx->slices) {
1957         av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1958                "%d (from %d) due to driver constraints on slice "
1959                "structure.\n", ctx->nb_slices, avctx->slices);
1960     }
1961     if (ctx->nb_slices > max_slices) {
1962         av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1963                "encoding with %d slices (max %"PRIu32").\n",
1964                ctx->nb_slices, max_slices);
1965         return AVERROR(EINVAL);
1966     }
1967
1968     av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1969            "(default size %d block rows).\n",
1970            ctx->nb_slices, ctx->slice_size);
1971     return 0;
1972 }
1973
1974 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1975 {
1976     VAAPIEncodeContext *ctx = avctx->priv_data;
1977     VAStatus vas;
1978     VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1979
1980     vas = vaGetConfigAttributes(ctx->hwctx->display,
1981                                 ctx->va_profile,
1982                                 ctx->va_entrypoint,
1983                                 &attr, 1);
1984     if (vas != VA_STATUS_SUCCESS) {
1985         av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1986                "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1987         return AVERROR_EXTERNAL;
1988     }
1989
1990     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1991         if (ctx->desired_packed_headers) {
1992             av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1993                    "packed headers (wanted %#x).\n",
1994                    ctx->desired_packed_headers);
1995         } else {
1996             av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1997                    "packed headers (none wanted).\n");
1998         }
1999         ctx->va_packed_headers = 0;
2000     } else {
2001         if (ctx->desired_packed_headers & ~attr.value) {
2002             av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
2003                    "wanted packed headers (wanted %#x, found %#x).\n",
2004                    ctx->desired_packed_headers, attr.value);
2005         } else {
2006             av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
2007                    "available (wanted %#x, found %#x).\n",
2008                    ctx->desired_packed_headers, attr.value);
2009         }
2010         ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
2011     }
2012
2013     if (ctx->va_packed_headers) {
2014         ctx->config_attributes[ctx->nb_config_attributes++] =
2015             (VAConfigAttrib) {
2016             .type  = VAConfigAttribEncPackedHeaders,
2017             .value = ctx->va_packed_headers,
2018         };
2019     }
2020
2021     if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
2022         !(ctx->va_packed_headers      & VA_ENC_PACKED_HEADER_SEQUENCE) &&
2023          (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
2024         av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
2025                "sequence headers, but a global header is requested.\n");
2026         av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
2027                "this may result in a stream which is not usable for some "
2028                "purposes (e.g. not muxable to some containers).\n");
2029     }
2030
2031     return 0;
2032 }
2033
2034 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
2035 {
2036 #if VA_CHECK_VERSION(0, 36, 0)
2037     VAAPIEncodeContext *ctx = avctx->priv_data;
2038     VAStatus vas;
2039     VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
2040     int quality = avctx->compression_level;
2041
2042     vas = vaGetConfigAttributes(ctx->hwctx->display,
2043                                 ctx->va_profile,
2044                                 ctx->va_entrypoint,
2045                                 &attr, 1);
2046     if (vas != VA_STATUS_SUCCESS) {
2047         av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
2048                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2049         return AVERROR_EXTERNAL;
2050     }
2051
2052     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2053         if (quality != 0) {
2054             av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
2055                    "supported: will use default quality level.\n");
2056         }
2057     } else {
2058         if (quality > attr.value) {
2059             av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
2060                    "valid range is 0-%d, using %d.\n",
2061                    attr.value, attr.value);
2062             quality = attr.value;
2063         }
2064
2065         ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
2066             .quality_level = quality,
2067         };
2068         vaapi_encode_add_global_param(avctx,
2069                                       VAEncMiscParameterTypeQualityLevel,
2070                                       &ctx->quality_params,
2071                                       sizeof(ctx->quality_params));
2072     }
2073 #else
2074     av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
2075            "not supported with this VAAPI version.\n");
2076 #endif
2077
2078     return 0;
2079 }
2080
2081 static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
2082 {
2083 #if VA_CHECK_VERSION(1, 0, 0)
2084     VAAPIEncodeContext *ctx = avctx->priv_data;
2085     VAStatus vas;
2086     VAConfigAttrib attr = { VAConfigAttribEncROI };
2087
2088     vas = vaGetConfigAttributes(ctx->hwctx->display,
2089                                 ctx->va_profile,
2090                                 ctx->va_entrypoint,
2091                                 &attr, 1);
2092     if (vas != VA_STATUS_SUCCESS) {
2093         av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
2094                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
2095         return AVERROR_EXTERNAL;
2096     }
2097
2098     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
2099         ctx->roi_allowed = 0;
2100     } else {
2101         VAConfigAttribValEncROI roi = {
2102             .value = attr.value,
2103         };
2104
2105         ctx->roi_max_regions = roi.bits.num_roi_regions;
2106         ctx->roi_allowed = ctx->roi_max_regions > 0 &&
2107             (ctx->va_rc_mode == VA_RC_CQP ||
2108              roi.bits.roi_rc_qp_delta_support);
2109     }
2110 #endif
2111     return 0;
2112 }
2113
2114 static void vaapi_encode_free_output_buffer(void *opaque,
2115                                             uint8_t *data)
2116 {
2117     AVCodecContext   *avctx = opaque;
2118     VAAPIEncodeContext *ctx = avctx->priv_data;
2119     VABufferID buffer_id;
2120
2121     buffer_id = (VABufferID)(uintptr_t)data;
2122
2123     vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2124
2125     av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
2126 }
2127
2128 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
2129                                                      int size)
2130 {
2131     AVCodecContext   *avctx = opaque;
2132     VAAPIEncodeContext *ctx = avctx->priv_data;
2133     VABufferID buffer_id;
2134     VAStatus vas;
2135     AVBufferRef *ref;
2136
2137     // The output buffer size is fixed, so it needs to be large enough
2138     // to hold the largest possible compressed frame.  We assume here
2139     // that the uncompressed frame plus some header data is an upper
2140     // bound on that.
2141     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
2142                          VAEncCodedBufferType,
2143                          3 * ctx->surface_width * ctx->surface_height +
2144                          (1 << 16), 1, 0, &buffer_id);
2145     if (vas != VA_STATUS_SUCCESS) {
2146         av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
2147                "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
2148         return NULL;
2149     }
2150
2151     av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
2152
2153     ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
2154                            sizeof(buffer_id),
2155                            &vaapi_encode_free_output_buffer,
2156                            avctx, AV_BUFFER_FLAG_READONLY);
2157     if (!ref) {
2158         vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2159         return NULL;
2160     }
2161
2162     return ref;
2163 }
2164
2165 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
2166 {
2167     VAAPIEncodeContext *ctx = avctx->priv_data;
2168     AVVAAPIHWConfig *hwconfig = NULL;
2169     AVHWFramesConstraints *constraints = NULL;
2170     enum AVPixelFormat recon_format;
2171     int err, i;
2172
2173     hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
2174     if (!hwconfig) {
2175         err = AVERROR(ENOMEM);
2176         goto fail;
2177     }
2178     hwconfig->config_id = ctx->va_config;
2179
2180     constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
2181                                                       hwconfig);
2182     if (!constraints) {
2183         err = AVERROR(ENOMEM);
2184         goto fail;
2185     }
2186
2187     // Probably we can use the input surface format as the surface format
2188     // of the reconstructed frames.  If not, we just pick the first (only?)
2189     // format in the valid list and hope that it all works.
2190     recon_format = AV_PIX_FMT_NONE;
2191     if (constraints->valid_sw_formats) {
2192         for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
2193             if (ctx->input_frames->sw_format ==
2194                 constraints->valid_sw_formats[i]) {
2195                 recon_format = ctx->input_frames->sw_format;
2196                 break;
2197             }
2198         }
2199         if (recon_format == AV_PIX_FMT_NONE) {
2200             // No match.  Just use the first in the supported list and
2201             // hope for the best.
2202             recon_format = constraints->valid_sw_formats[0];
2203         }
2204     } else {
2205         // No idea what to use; copy input format.
2206         recon_format = ctx->input_frames->sw_format;
2207     }
2208     av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
2209            "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
2210
2211     if (ctx->surface_width  < constraints->min_width  ||
2212         ctx->surface_height < constraints->min_height ||
2213         ctx->surface_width  > constraints->max_width ||
2214         ctx->surface_height > constraints->max_height) {
2215         av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2216                "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2217                ctx->surface_width, ctx->surface_height,
2218                constraints->min_width,  constraints->max_width,
2219                constraints->min_height, constraints->max_height);
2220         err = AVERROR(EINVAL);
2221         goto fail;
2222     }
2223
2224     av_freep(&hwconfig);
2225     av_hwframe_constraints_free(&constraints);
2226
2227     ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2228     if (!ctx->recon_frames_ref) {
2229         err = AVERROR(ENOMEM);
2230         goto fail;
2231     }
2232     ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2233
2234     ctx->recon_frames->format    = AV_PIX_FMT_VAAPI;
2235     ctx->recon_frames->sw_format = recon_format;
2236     ctx->recon_frames->width     = ctx->surface_width;
2237     ctx->recon_frames->height    = ctx->surface_height;
2238
2239     err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2240     if (err < 0) {
2241         av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2242                "frame context: %d.\n", err);
2243         goto fail;
2244     }
2245
2246     err = 0;
2247   fail:
2248     av_freep(&hwconfig);
2249     av_hwframe_constraints_free(&constraints);
2250     return err;
2251 }
2252
2253 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2254 {
2255     VAAPIEncodeContext *ctx = avctx->priv_data;
2256     AVVAAPIFramesContext *recon_hwctx = NULL;
2257     VAStatus vas;
2258     int err;
2259
2260     ctx->frame = av_frame_alloc();
2261     if (!ctx->frame) {
2262         return AVERROR(ENOMEM);
2263     }
2264
2265     if (!avctx->hw_frames_ctx) {
2266         av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2267                "required to associate the encoding device.\n");
2268         return AVERROR(EINVAL);
2269     }
2270
2271     ctx->va_config  = VA_INVALID_ID;
2272     ctx->va_context = VA_INVALID_ID;
2273
2274     ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2275     if (!ctx->input_frames_ref) {
2276         err = AVERROR(ENOMEM);
2277         goto fail;
2278     }
2279     ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2280
2281     ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2282     if (!ctx->device_ref) {
2283         err = AVERROR(ENOMEM);
2284         goto fail;
2285     }
2286     ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2287     ctx->hwctx = ctx->device->hwctx;
2288
2289     err = vaapi_encode_profile_entrypoint(avctx);
2290     if (err < 0)
2291         goto fail;
2292
2293     err = vaapi_encode_init_rate_control(avctx);
2294     if (err < 0)
2295         goto fail;
2296
2297     err = vaapi_encode_init_gop_structure(avctx);
2298     if (err < 0)
2299         goto fail;
2300
2301     err = vaapi_encode_init_slice_structure(avctx);
2302     if (err < 0)
2303         goto fail;
2304
2305     err = vaapi_encode_init_packed_headers(avctx);
2306     if (err < 0)
2307         goto fail;
2308
2309     err = vaapi_encode_init_roi(avctx);
2310     if (err < 0)
2311         goto fail;
2312
2313     if (avctx->compression_level >= 0) {
2314         err = vaapi_encode_init_quality(avctx);
2315         if (err < 0)
2316             goto fail;
2317     }
2318
2319     vas = vaCreateConfig(ctx->hwctx->display,
2320                          ctx->va_profile, ctx->va_entrypoint,
2321                          ctx->config_attributes, ctx->nb_config_attributes,
2322                          &ctx->va_config);
2323     if (vas != VA_STATUS_SUCCESS) {
2324         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2325                "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2326         err = AVERROR(EIO);
2327         goto fail;
2328     }
2329
2330     err = vaapi_encode_create_recon_frames(avctx);
2331     if (err < 0)
2332         goto fail;
2333
2334     recon_hwctx = ctx->recon_frames->hwctx;
2335     vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2336                           ctx->surface_width, ctx->surface_height,
2337                           VA_PROGRESSIVE,
2338                           recon_hwctx->surface_ids,
2339                           recon_hwctx->nb_surfaces,
2340                           &ctx->va_context);
2341     if (vas != VA_STATUS_SUCCESS) {
2342         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2343                "context: %d (%s).\n", vas, vaErrorStr(vas));
2344         err = AVERROR(EIO);
2345         goto fail;
2346     }
2347
2348     ctx->output_buffer_pool =
2349         av_buffer_pool_init2(sizeof(VABufferID), avctx,
2350                              &vaapi_encode_alloc_output_buffer, NULL);
2351     if (!ctx->output_buffer_pool) {
2352         err = AVERROR(ENOMEM);
2353         goto fail;
2354     }
2355
2356     if (ctx->codec->configure) {
2357         err = ctx->codec->configure(avctx);
2358         if (err < 0)
2359             goto fail;
2360     }
2361
2362     ctx->output_delay = ctx->b_per_p;
2363     ctx->decode_delay = ctx->max_b_depth;
2364
2365     if (ctx->codec->sequence_params_size > 0) {
2366         ctx->codec_sequence_params =
2367             av_mallocz(ctx->codec->sequence_params_size);
2368         if (!ctx->codec_sequence_params) {
2369             err = AVERROR(ENOMEM);
2370             goto fail;
2371         }
2372     }
2373     if (ctx->codec->picture_params_size > 0) {
2374         ctx->codec_picture_params =
2375             av_mallocz(ctx->codec->picture_params_size);
2376         if (!ctx->codec_picture_params) {
2377             err = AVERROR(ENOMEM);
2378             goto fail;
2379         }
2380     }
2381
2382     if (ctx->codec->init_sequence_params) {
2383         err = ctx->codec->init_sequence_params(avctx);
2384         if (err < 0) {
2385             av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2386                    "failed: %d.\n", err);
2387             goto fail;
2388         }
2389     }
2390
2391     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2392         ctx->codec->write_sequence_header &&
2393         avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2394         char data[MAX_PARAM_BUFFER_SIZE];
2395         size_t bit_len = 8 * sizeof(data);
2396
2397         err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2398         if (err < 0) {
2399             av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2400                    "for extradata: %d.\n", err);
2401             goto fail;
2402         } else {
2403             avctx->extradata_size = (bit_len + 7) / 8;
2404             avctx->extradata = av_mallocz(avctx->extradata_size +
2405                                           AV_INPUT_BUFFER_PADDING_SIZE);
2406             if (!avctx->extradata) {
2407                 err = AVERROR(ENOMEM);
2408                 goto fail;
2409             }
2410             memcpy(avctx->extradata, data, avctx->extradata_size);
2411         }
2412     }
2413
2414     return 0;
2415
2416 fail:
2417     return err;
2418 }
2419
2420 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2421 {
2422     VAAPIEncodeContext *ctx = avctx->priv_data;
2423     VAAPIEncodePicture *pic, *next;
2424
2425     for (pic = ctx->pic_start; pic; pic = next) {
2426         next = pic->next;
2427         vaapi_encode_free(avctx, pic);
2428     }
2429
2430     av_buffer_pool_uninit(&ctx->output_buffer_pool);
2431
2432     if (ctx->va_context != VA_INVALID_ID) {
2433         vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2434         ctx->va_context = VA_INVALID_ID;
2435     }
2436
2437     if (ctx->va_config != VA_INVALID_ID) {
2438         vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2439         ctx->va_config = VA_INVALID_ID;
2440     }
2441
2442     av_frame_free(&ctx->frame);
2443
2444     av_freep(&ctx->codec_sequence_params);
2445     av_freep(&ctx->codec_picture_params);
2446
2447     av_buffer_unref(&ctx->recon_frames_ref);
2448     av_buffer_unref(&ctx->input_frames_ref);
2449     av_buffer_unref(&ctx->device_ref);
2450
2451     return 0;
2452 }