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