]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_encode.c
vaapi_encode: Allocate picture-private data in generic code
[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 "avcodec.h"
29
30 static const char * const picture_type_name[] = { "IDR", "I", "P", "B" };
31
32 static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
33                                            VAAPIEncodePicture *pic,
34                                            int type, char *data, size_t bit_len)
35 {
36     VAAPIEncodeContext *ctx = avctx->priv_data;
37     VAStatus vas;
38     VABufferID param_buffer, data_buffer;
39     VABufferID *tmp;
40     VAEncPackedHeaderParameterBuffer params = {
41         .type = type,
42         .bit_length = bit_len,
43         .has_emulation_bytes = 1,
44     };
45
46     tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 2);
47     if (!tmp)
48         return AVERROR(ENOMEM);
49     pic->param_buffers = tmp;
50
51     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
52                          VAEncPackedHeaderParameterBufferType,
53                          sizeof(params), 1, &params, &param_buffer);
54     if (vas != VA_STATUS_SUCCESS) {
55         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
56                "for packed header (type %d): %d (%s).\n",
57                type, vas, vaErrorStr(vas));
58         return AVERROR(EIO);
59     }
60     pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
61
62     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
63                          VAEncPackedHeaderDataBufferType,
64                          (bit_len + 7) / 8, 1, data, &data_buffer);
65     if (vas != VA_STATUS_SUCCESS) {
66         av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
67                "for packed header (type %d): %d (%s).\n",
68                type, vas, vaErrorStr(vas));
69         return AVERROR(EIO);
70     }
71     pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
72
73     av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
74            "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
75     return 0;
76 }
77
78 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
79                                           VAAPIEncodePicture *pic,
80                                           int type, char *data, size_t len)
81 {
82     VAAPIEncodeContext *ctx = avctx->priv_data;
83     VAStatus vas;
84     VABufferID *tmp;
85     VABufferID buffer;
86
87     tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 1);
88     if (!tmp)
89         return AVERROR(ENOMEM);
90     pic->param_buffers = tmp;
91
92     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
93                          type, len, 1, data, &buffer);
94     if (vas != VA_STATUS_SUCCESS) {
95         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
96                "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
97         return AVERROR(EIO);
98     }
99     pic->param_buffers[pic->nb_param_buffers++] = buffer;
100
101     av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
102            type, buffer);
103     return 0;
104 }
105
106 static int vaapi_encode_wait(AVCodecContext *avctx,
107                              VAAPIEncodePicture *pic)
108 {
109     VAAPIEncodeContext *ctx = avctx->priv_data;
110     VAStatus vas;
111
112     av_assert0(pic->encode_issued);
113
114     if (pic->encode_complete) {
115         // Already waited for this picture.
116         return 0;
117     }
118
119     av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
120            "(input surface %#x).\n", pic->display_order,
121            pic->encode_order, pic->input_surface);
122
123     vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
124     if (vas != VA_STATUS_SUCCESS) {
125         av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
126                "%d (%s).\n", vas, vaErrorStr(vas));
127         return AVERROR(EIO);
128     }
129
130     // Input is definitely finished with now.
131     av_frame_free(&pic->input_image);
132
133     pic->encode_complete = 1;
134     return 0;
135 }
136
137 static int vaapi_encode_issue(AVCodecContext *avctx,
138                               VAAPIEncodePicture *pic)
139 {
140     VAAPIEncodeContext *ctx = avctx->priv_data;
141     VAAPIEncodeSlice *slice;
142     VAStatus vas;
143     int err, i;
144     char data[MAX_PARAM_BUFFER_SIZE];
145     size_t bit_len;
146
147     av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
148            "as type %s.\n", pic->display_order, pic->encode_order,
149            picture_type_name[pic->type]);
150     if (pic->nb_refs == 0) {
151         av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
152     } else {
153         av_log(avctx, AV_LOG_DEBUG, "Refers to:");
154         for (i = 0; i < pic->nb_refs; i++) {
155             av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
156                    pic->refs[i]->display_order, pic->refs[i]->encode_order);
157         }
158         av_log(avctx, AV_LOG_DEBUG, ".\n");
159     }
160
161     av_assert0(pic->input_available && !pic->encode_issued);
162     for (i = 0; i < pic->nb_refs; i++) {
163         av_assert0(pic->refs[i]);
164         // If we are serialised then the references must have already
165         // completed.  If not, they must have been issued but need not
166         // have completed yet.
167         if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
168             av_assert0(pic->refs[i]->encode_complete);
169         else
170             av_assert0(pic->refs[i]->encode_issued);
171     }
172
173     av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
174
175     pic->recon_image = av_frame_alloc();
176     if (!pic->recon_image) {
177         err = AVERROR(ENOMEM);
178         goto fail;
179     }
180
181     err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
182     if (err < 0) {
183         err = AVERROR(ENOMEM);
184         goto fail;
185     }
186     pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
187     av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
188
189     pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
190     if (!pic->output_buffer_ref) {
191         err = AVERROR(ENOMEM);
192         goto fail;
193     }
194     pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
195     av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
196            pic->output_buffer);
197
198     if (ctx->codec->picture_params_size > 0) {
199         pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
200         if (!pic->codec_picture_params)
201             goto fail;
202         memcpy(pic->codec_picture_params, ctx->codec_picture_params,
203                ctx->codec->picture_params_size);
204     } else {
205         av_assert0(!ctx->codec_picture_params);
206     }
207
208     pic->nb_param_buffers = 0;
209
210     if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
211         err = vaapi_encode_make_param_buffer(avctx, pic,
212                                              VAEncSequenceParameterBufferType,
213                                              ctx->codec_sequence_params,
214                                              ctx->codec->sequence_params_size);
215         if (err < 0)
216             goto fail;
217     }
218
219     if (pic->type == PICTURE_TYPE_IDR) {
220         for (i = 0; i < ctx->nb_global_params; i++) {
221             err = vaapi_encode_make_param_buffer(avctx, pic,
222                                                  VAEncMiscParameterBufferType,
223                                                  (char*)ctx->global_params[i],
224                                                  ctx->global_params_size[i]);
225             if (err < 0)
226                 goto fail;
227         }
228     }
229
230     if (ctx->codec->init_picture_params) {
231         err = ctx->codec->init_picture_params(avctx, pic);
232         if (err < 0) {
233             av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
234                    "parameters: %d.\n", err);
235             goto fail;
236         }
237         err = vaapi_encode_make_param_buffer(avctx, pic,
238                                              VAEncPictureParameterBufferType,
239                                              pic->codec_picture_params,
240                                              ctx->codec->picture_params_size);
241         if (err < 0)
242             goto fail;
243     }
244
245     if (pic->type == PICTURE_TYPE_IDR) {
246         if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
247             ctx->codec->write_sequence_header) {
248             bit_len = 8 * sizeof(data);
249             err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
250             if (err < 0) {
251                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
252                        "header: %d.\n", err);
253                 goto fail;
254             }
255             err = vaapi_encode_make_packed_header(avctx, pic,
256                                                   ctx->codec->sequence_header_type,
257                                                   data, bit_len);
258             if (err < 0)
259                 goto fail;
260         }
261     }
262
263     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
264         ctx->codec->write_picture_header) {
265         bit_len = 8 * sizeof(data);
266         err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
267         if (err < 0) {
268             av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
269                    "header: %d.\n", err);
270             goto fail;
271         }
272         err = vaapi_encode_make_packed_header(avctx, pic,
273                                               ctx->codec->picture_header_type,
274                                               data, bit_len);
275         if (err < 0)
276             goto fail;
277     }
278
279     if (ctx->codec->write_extra_buffer) {
280         for (i = 0;; i++) {
281             size_t len = sizeof(data);
282             int type;
283             err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
284                                                  data, &len);
285             if (err == AVERROR_EOF)
286                 break;
287             if (err < 0) {
288                 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
289                        "buffer %d: %d.\n", i, err);
290                 goto fail;
291             }
292
293             err = vaapi_encode_make_param_buffer(avctx, pic, type,
294                                                  data, len);
295             if (err < 0)
296                 goto fail;
297         }
298     }
299
300     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
301         ctx->codec->write_extra_header) {
302         for (i = 0;; i++) {
303             int type;
304             bit_len = 8 * sizeof(data);
305             err = ctx->codec->write_extra_header(avctx, pic, i, &type,
306                                                  data, &bit_len);
307             if (err == AVERROR_EOF)
308                 break;
309             if (err < 0) {
310                 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
311                        "header %d: %d.\n", i, err);
312                 goto fail;
313             }
314
315             err = vaapi_encode_make_packed_header(avctx, pic, type,
316                                                   data, bit_len);
317             if (err < 0)
318                 goto fail;
319         }
320     }
321
322     if (pic->nb_slices == 0)
323         pic->nb_slices = ctx->nb_slices;
324     if (pic->nb_slices > 0) {
325         int rounding;
326
327         pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
328         if (!pic->slices) {
329             err = AVERROR(ENOMEM);
330             goto fail;
331         }
332
333         for (i = 0; i < pic->nb_slices; i++)
334             pic->slices[i].row_size = ctx->slice_size;
335
336         rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
337         if (rounding > 0) {
338             // Place rounding error at top and bottom of frame.
339             av_assert0(rounding < pic->nb_slices);
340             // Some Intel drivers contain a bug where the encoder will fail
341             // if the last slice is smaller than the one before it.  Since
342             // that's straightforward to avoid here, just do so.
343             if (rounding <= 2) {
344                 for (i = 0; i < rounding; i++)
345                     ++pic->slices[i].row_size;
346             } else {
347                 for (i = 0; i < (rounding + 1) / 2; i++)
348                     ++pic->slices[pic->nb_slices - i - 1].row_size;
349                 for (i = 0; i < rounding / 2; i++)
350                     ++pic->slices[i].row_size;
351             }
352         } else if (rounding < 0) {
353             // Remove rounding error from last slice only.
354             av_assert0(rounding < ctx->slice_size);
355             pic->slices[pic->nb_slices - 1].row_size += rounding;
356         }
357     }
358     for (i = 0; i < pic->nb_slices; i++) {
359         slice = &pic->slices[i];
360         slice->index = i;
361         if (i == 0) {
362             slice->row_start   = 0;
363             slice->block_start = 0;
364         } else {
365             const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
366             slice->row_start   = prev->row_start   + prev->row_size;
367             slice->block_start = prev->block_start + prev->block_size;
368         }
369         slice->block_size  = slice->row_size * ctx->slice_block_cols;
370
371         av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
372                "%d-%d (%d blocks).\n", i, slice->row_start,
373                slice->row_start + slice->row_size - 1, slice->row_size,
374                slice->block_start, slice->block_start + slice->block_size - 1,
375                slice->block_size);
376
377         if (ctx->codec->slice_params_size > 0) {
378             slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
379             if (!slice->codec_slice_params) {
380                 err = AVERROR(ENOMEM);
381                 goto fail;
382             }
383         }
384
385         if (ctx->codec->init_slice_params) {
386             err = ctx->codec->init_slice_params(avctx, pic, slice);
387             if (err < 0) {
388                 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
389                        "parameters: %d.\n", err);
390                 goto fail;
391             }
392         }
393
394         if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
395             ctx->codec->write_slice_header) {
396             bit_len = 8 * sizeof(data);
397             err = ctx->codec->write_slice_header(avctx, pic, slice,
398                                                  data, &bit_len);
399             if (err < 0) {
400                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
401                        "header: %d.\n", err);
402                 goto fail;
403             }
404             err = vaapi_encode_make_packed_header(avctx, pic,
405                                                   ctx->codec->slice_header_type,
406                                                   data, bit_len);
407             if (err < 0)
408                 goto fail;
409         }
410
411         if (ctx->codec->init_slice_params) {
412             err = vaapi_encode_make_param_buffer(avctx, pic,
413                                                  VAEncSliceParameterBufferType,
414                                                  slice->codec_slice_params,
415                                                  ctx->codec->slice_params_size);
416             if (err < 0)
417                 goto fail;
418         }
419     }
420
421     vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
422                          pic->input_surface);
423     if (vas != VA_STATUS_SUCCESS) {
424         av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
425                "%d (%s).\n", vas, vaErrorStr(vas));
426         err = AVERROR(EIO);
427         goto fail_with_picture;
428     }
429
430     vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
431                           pic->param_buffers, pic->nb_param_buffers);
432     if (vas != VA_STATUS_SUCCESS) {
433         av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
434                "%d (%s).\n", vas, vaErrorStr(vas));
435         err = AVERROR(EIO);
436         goto fail_with_picture;
437     }
438
439     vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
440     if (vas != VA_STATUS_SUCCESS) {
441         av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
442                "%d (%s).\n", vas, vaErrorStr(vas));
443         err = AVERROR(EIO);
444         // vaRenderPicture() has been called here, so we should not destroy
445         // the parameter buffers unless separate destruction is required.
446         if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
447             AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
448             goto fail;
449         else
450             goto fail_at_end;
451     }
452
453     if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
454         AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
455         for (i = 0; i < pic->nb_param_buffers; i++) {
456             vas = vaDestroyBuffer(ctx->hwctx->display,
457                                   pic->param_buffers[i]);
458             if (vas != VA_STATUS_SUCCESS) {
459                 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
460                        "param buffer %#x: %d (%s).\n",
461                        pic->param_buffers[i], vas, vaErrorStr(vas));
462                 // And ignore.
463             }
464         }
465     }
466
467     pic->encode_issued = 1;
468
469     if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
470         return vaapi_encode_wait(avctx, pic);
471     else
472         return 0;
473
474 fail_with_picture:
475     vaEndPicture(ctx->hwctx->display, ctx->va_context);
476 fail:
477     for(i = 0; i < pic->nb_param_buffers; i++)
478         vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
479     for (i = 0; i < pic->nb_slices; i++) {
480         if (pic->slices) {
481             av_freep(&pic->slices[i].priv_data);
482             av_freep(&pic->slices[i].codec_slice_params);
483         }
484     }
485 fail_at_end:
486     av_freep(&pic->codec_picture_params);
487     av_freep(&pic->param_buffers);
488     av_freep(&pic->slices);
489     av_frame_free(&pic->recon_image);
490     av_buffer_unref(&pic->output_buffer_ref);
491     pic->output_buffer = VA_INVALID_ID;
492     return err;
493 }
494
495 static int vaapi_encode_output(AVCodecContext *avctx,
496                                VAAPIEncodePicture *pic, AVPacket *pkt)
497 {
498     VAAPIEncodeContext *ctx = avctx->priv_data;
499     VACodedBufferSegment *buf_list, *buf;
500     VAStatus vas;
501     int err;
502
503     err = vaapi_encode_wait(avctx, pic);
504     if (err < 0)
505         return err;
506
507     buf_list = NULL;
508     vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
509                       (void**)&buf_list);
510     if (vas != VA_STATUS_SUCCESS) {
511         av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
512                "%d (%s).\n", vas, vaErrorStr(vas));
513         err = AVERROR(EIO);
514         goto fail;
515     }
516
517     for (buf = buf_list; buf; buf = buf->next) {
518         av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
519                "(status %08x).\n", buf->size, buf->status);
520
521         err = av_new_packet(pkt, buf->size);
522         if (err < 0)
523             goto fail_mapped;
524
525         memcpy(pkt->data, buf->buf, buf->size);
526     }
527
528     if (pic->type == PICTURE_TYPE_IDR)
529         pkt->flags |= AV_PKT_FLAG_KEY;
530
531     pkt->pts = pic->pts;
532
533     vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
534     if (vas != VA_STATUS_SUCCESS) {
535         av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
536                "%d (%s).\n", vas, vaErrorStr(vas));
537         err = AVERROR(EIO);
538         goto fail;
539     }
540
541     av_buffer_unref(&pic->output_buffer_ref);
542     pic->output_buffer = VA_INVALID_ID;
543
544     av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
545            pic->display_order, pic->encode_order);
546     return 0;
547
548 fail_mapped:
549     vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
550 fail:
551     av_buffer_unref(&pic->output_buffer_ref);
552     pic->output_buffer = VA_INVALID_ID;
553     return err;
554 }
555
556 static int vaapi_encode_discard(AVCodecContext *avctx,
557                                 VAAPIEncodePicture *pic)
558 {
559     vaapi_encode_wait(avctx, pic);
560
561     if (pic->output_buffer_ref) {
562         av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
563                "%"PRId64"/%"PRId64".\n",
564                pic->display_order, pic->encode_order);
565
566         av_buffer_unref(&pic->output_buffer_ref);
567         pic->output_buffer = VA_INVALID_ID;
568     }
569
570     return 0;
571 }
572
573 static VAAPIEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx)
574 {
575     VAAPIEncodeContext *ctx = avctx->priv_data;
576     VAAPIEncodePicture *pic;
577
578     pic = av_mallocz(sizeof(*pic));
579     if (!pic)
580         return NULL;
581
582     if (ctx->codec->picture_priv_data_size > 0) {
583         pic->priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
584         if (!pic->priv_data) {
585             av_freep(&pic);
586             return NULL;
587         }
588     }
589
590     pic->input_surface = VA_INVALID_ID;
591     pic->recon_surface = VA_INVALID_ID;
592     pic->output_buffer = VA_INVALID_ID;
593
594     return pic;
595 }
596
597 static int vaapi_encode_free(AVCodecContext *avctx,
598                              VAAPIEncodePicture *pic)
599 {
600     int i;
601
602     if (pic->encode_issued)
603         vaapi_encode_discard(avctx, pic);
604
605     for (i = 0; i < pic->nb_slices; i++) {
606         if (pic->slices) {
607             av_freep(&pic->slices[i].priv_data);
608             av_freep(&pic->slices[i].codec_slice_params);
609         }
610     }
611     av_freep(&pic->codec_picture_params);
612
613     av_frame_free(&pic->input_image);
614     av_frame_free(&pic->recon_image);
615
616     av_freep(&pic->param_buffers);
617     av_freep(&pic->slices);
618     // Output buffer should already be destroyed.
619     av_assert0(pic->output_buffer == VA_INVALID_ID);
620
621     av_freep(&pic->priv_data);
622     av_freep(&pic->codec_picture_params);
623
624     av_free(pic);
625
626     return 0;
627 }
628
629 static int vaapi_encode_step(AVCodecContext *avctx,
630                              VAAPIEncodePicture *target)
631 {
632     VAAPIEncodeContext *ctx = avctx->priv_data;
633     VAAPIEncodePicture *pic;
634     int i, err;
635
636     if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
637         ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
638         // These two modes are equivalent, except that we wait for
639         // immediate completion on each operation if serialised.
640
641         if (!target) {
642             // No target, nothing to do yet.
643             return 0;
644         }
645
646         if (target->encode_complete) {
647             // Already done.
648             return 0;
649         }
650
651         pic = target;
652         for (i = 0; i < pic->nb_refs; i++) {
653             if (!pic->refs[i]->encode_complete) {
654                 err = vaapi_encode_step(avctx, pic->refs[i]);
655                 if (err < 0)
656                     return err;
657             }
658         }
659
660         err = vaapi_encode_issue(avctx, pic);
661         if (err < 0)
662             return err;
663
664     } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
665         int activity;
666
667         // Run through the list of all available pictures repeatedly
668         // and issue the first one found which has all dependencies
669         // available (including previously-issued but not necessarily
670         // completed pictures).
671         do {
672             activity = 0;
673             for (pic = ctx->pic_start; pic; pic = pic->next) {
674                 if (!pic->input_available || pic->encode_issued)
675                     continue;
676                 for (i = 0; i < pic->nb_refs; i++) {
677                     if (!pic->refs[i]->encode_issued)
678                         break;
679                 }
680                 if (i < pic->nb_refs)
681                     continue;
682                 err = vaapi_encode_issue(avctx, pic);
683                 if (err < 0)
684                     return err;
685                 activity = 1;
686                 // Start again from the beginning of the list,
687                 // because issuing this picture may have satisfied
688                 // forward dependencies of earlier ones.
689                 break;
690             }
691         } while(activity);
692
693         // If we had a defined target for this step then it will
694         // always have been issued by now.
695         if (target) {
696             av_assert0(target->encode_issued && "broken dependencies?");
697         }
698
699     } else {
700         av_assert0(0);
701     }
702
703     return 0;
704 }
705
706 static int vaapi_encode_get_next(AVCodecContext *avctx,
707                                  VAAPIEncodePicture **pic_out)
708 {
709     VAAPIEncodeContext *ctx = avctx->priv_data;
710     VAAPIEncodePicture *start, *end, *pic;
711     int i;
712
713     for (pic = ctx->pic_start; pic; pic = pic->next) {
714         if (pic->next)
715             av_assert0(pic->display_order + 1 == pic->next->display_order);
716         if (pic->display_order == ctx->input_order) {
717             *pic_out = pic;
718             return 0;
719         }
720     }
721
722     pic = vaapi_encode_alloc(avctx);
723     if (!pic)
724         return AVERROR(ENOMEM);
725
726     if (ctx->input_order == 0 || ctx->force_idr ||
727         ctx->gop_counter >= ctx->gop_size) {
728         pic->type = PICTURE_TYPE_IDR;
729         ctx->force_idr = 0;
730         ctx->gop_counter = 1;
731         ctx->p_counter = 0;
732     } else if (ctx->p_counter >= ctx->p_per_i) {
733         pic->type = PICTURE_TYPE_I;
734         ++ctx->gop_counter;
735         ctx->p_counter = 0;
736     } else {
737         pic->type = PICTURE_TYPE_P;
738         pic->refs[0] = ctx->pic_end;
739         pic->nb_refs = 1;
740         ++ctx->gop_counter;
741         ++ctx->p_counter;
742     }
743     start = end = pic;
744
745     if (pic->type != PICTURE_TYPE_IDR) {
746         // If that was not an IDR frame, add B-frames display-before and
747         // encode-after it, but not exceeding the GOP size.
748
749         for (i = 0; i < ctx->b_per_p &&
750              ctx->gop_counter < ctx->gop_size; i++) {
751             pic = vaapi_encode_alloc(avctx);
752             if (!pic)
753                 goto fail;
754
755             pic->type = PICTURE_TYPE_B;
756             pic->refs[0] = ctx->pic_end;
757             pic->refs[1] = end;
758             pic->nb_refs = 2;
759
760             pic->next = start;
761             pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
762             pic->encode_order  = pic->display_order + 1;
763             start = pic;
764
765             ++ctx->gop_counter;
766         }
767     }
768
769     if (ctx->input_order == 0) {
770         pic->display_order = 0;
771         pic->encode_order  = 0;
772
773         ctx->pic_start = ctx->pic_end = pic;
774
775     } else {
776         for (i = 0, pic = start; pic; i++, pic = pic->next) {
777             pic->display_order = ctx->input_order + i;
778             if (end->type == PICTURE_TYPE_IDR)
779                 pic->encode_order = ctx->input_order + i;
780             else if (pic == end)
781                 pic->encode_order = ctx->input_order;
782             else
783                 pic->encode_order = ctx->input_order + i + 1;
784         }
785
786         av_assert0(ctx->pic_end);
787         ctx->pic_end->next = start;
788         ctx->pic_end = end;
789     }
790     *pic_out = start;
791
792     av_log(avctx, AV_LOG_DEBUG, "Pictures:");
793     for (pic = ctx->pic_start; pic; pic = pic->next) {
794         av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
795                picture_type_name[pic->type],
796                pic->display_order, pic->encode_order);
797     }
798     av_log(avctx, AV_LOG_DEBUG, "\n");
799
800     return 0;
801
802 fail:
803     while (start) {
804         pic = start->next;
805         vaapi_encode_free(avctx, start);
806         start = pic;
807     }
808     return AVERROR(ENOMEM);
809 }
810
811 static int vaapi_encode_truncate_gop(AVCodecContext *avctx)
812 {
813     VAAPIEncodeContext *ctx = avctx->priv_data;
814     VAAPIEncodePicture *pic, *last_pic, *next;
815
816     av_assert0(!ctx->pic_start || ctx->pic_start->input_available);
817
818     // Find the last picture we actually have input for.
819     for (pic = ctx->pic_start; pic; pic = pic->next) {
820         if (!pic->input_available)
821             break;
822         last_pic = pic;
823     }
824
825     if (pic) {
826         if (last_pic->type == PICTURE_TYPE_B) {
827             // Some fixing up is required.  Change the type of this
828             // picture to P, then modify preceding B references which
829             // point beyond it to point at it instead.
830
831             last_pic->type = PICTURE_TYPE_P;
832             last_pic->encode_order = last_pic->refs[1]->encode_order;
833
834             for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
835                 if (pic->type == PICTURE_TYPE_B &&
836                     pic->refs[1] == last_pic->refs[1])
837                     pic->refs[1] = last_pic;
838             }
839
840             last_pic->nb_refs = 1;
841             last_pic->refs[1] = NULL;
842         } else {
843             // We can use the current structure (no references point
844             // beyond the end), but there are unused pics to discard.
845         }
846
847         // Discard all following pics, they will never be used.
848         for (pic = last_pic->next; pic; pic = next) {
849             next = pic->next;
850             vaapi_encode_free(avctx, pic);
851         }
852
853         last_pic->next = NULL;
854         ctx->pic_end = last_pic;
855
856     } else {
857         // Input is available for all pictures, so we don't need to
858         // mangle anything.
859     }
860
861     av_log(avctx, AV_LOG_DEBUG, "Pictures ending truncated GOP:");
862     for (pic = ctx->pic_start; pic; pic = pic->next) {
863         av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
864                picture_type_name[pic->type],
865                pic->display_order, pic->encode_order);
866     }
867     av_log(avctx, AV_LOG_DEBUG, "\n");
868
869     return 0;
870 }
871
872 static int vaapi_encode_clear_old(AVCodecContext *avctx)
873 {
874     VAAPIEncodeContext *ctx = avctx->priv_data;
875     VAAPIEncodePicture *pic, *old;
876     int i;
877
878     while (ctx->pic_start != ctx->pic_end) {
879         old = ctx->pic_start;
880         if (old->encode_order > ctx->output_order)
881             break;
882
883         for (pic = old->next; pic; pic = pic->next) {
884             if (pic->encode_complete)
885                 continue;
886             for (i = 0; i < pic->nb_refs; i++) {
887                 if (pic->refs[i] == old) {
888                     // We still need this picture because it's referred to
889                     // directly by a later one, so it and all following
890                     // pictures have to stay.
891                     return 0;
892                 }
893             }
894         }
895
896         pic = ctx->pic_start;
897         ctx->pic_start = pic->next;
898         vaapi_encode_free(avctx, pic);
899     }
900
901     return 0;
902 }
903
904 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
905                      const AVFrame *input_image, int *got_packet)
906 {
907     VAAPIEncodeContext *ctx = avctx->priv_data;
908     VAAPIEncodePicture *pic;
909     int err;
910
911     if (input_image) {
912         av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
913                input_image->width, input_image->height, input_image->pts);
914
915         if (input_image->pict_type == AV_PICTURE_TYPE_I) {
916             err = vaapi_encode_truncate_gop(avctx);
917             if (err < 0)
918                 goto fail;
919             ctx->force_idr = 1;
920         }
921
922         err = vaapi_encode_get_next(avctx, &pic);
923         if (err) {
924             av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
925             return err;
926         }
927
928         pic->input_image = av_frame_alloc();
929         if (!pic->input_image) {
930             err = AVERROR(ENOMEM);
931             goto fail;
932         }
933         err = av_frame_ref(pic->input_image, input_image);
934         if (err < 0)
935             goto fail;
936         pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
937         pic->pts = input_image->pts;
938
939         if (ctx->input_order == 0)
940             ctx->first_pts = pic->pts;
941         if (ctx->input_order == ctx->decode_delay)
942             ctx->dts_pts_diff = pic->pts - ctx->first_pts;
943         if (ctx->output_delay > 0)
944             ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
945
946         pic->input_available = 1;
947
948     } else {
949         if (!ctx->end_of_stream) {
950             err = vaapi_encode_truncate_gop(avctx);
951             if (err < 0)
952                 goto fail;
953             ctx->end_of_stream = 1;
954         }
955     }
956
957     ++ctx->input_order;
958     ++ctx->output_order;
959     av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
960
961     for (pic = ctx->pic_start; pic; pic = pic->next)
962         if (pic->encode_order == ctx->output_order)
963             break;
964
965     // pic can be null here if we don't have a specific target in this
966     // iteration.  We might still issue encodes if things can be overlapped,
967     // even though we don't intend to output anything.
968
969     err = vaapi_encode_step(avctx, pic);
970     if (err < 0) {
971         av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
972         goto fail;
973     }
974
975     if (!pic) {
976         *got_packet = 0;
977     } else {
978         err = vaapi_encode_output(avctx, pic, pkt);
979         if (err < 0) {
980             av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
981             goto fail;
982         }
983
984         if (ctx->output_delay == 0) {
985             pkt->dts = pkt->pts;
986         } else if (ctx->output_order < ctx->decode_delay) {
987             if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
988                 pkt->dts = INT64_MIN;
989             else
990                 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
991         } else {
992             pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
993                                     (3 * ctx->output_delay)];
994         }
995
996         *got_packet = 1;
997     }
998
999     err = vaapi_encode_clear_old(avctx);
1000     if (err < 0) {
1001         av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
1002         goto fail;
1003     }
1004
1005     return 0;
1006
1007 fail:
1008     // Unclear what to clean up on failure.  There are probably some things we
1009     // could do usefully clean up here, but for now just leave them for uninit()
1010     // to do instead.
1011     return err;
1012 }
1013
1014 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx,
1015                                                   VAEncMiscParameterBuffer *buffer,
1016                                                   size_t size)
1017 {
1018     VAAPIEncodeContext *ctx = avctx->priv_data;
1019
1020     av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1021
1022     ctx->global_params     [ctx->nb_global_params] = buffer;
1023     ctx->global_params_size[ctx->nb_global_params] = size;
1024
1025     ++ctx->nb_global_params;
1026 }
1027
1028 typedef struct VAAPIEncodeRTFormat {
1029     const char *name;
1030     unsigned int value;
1031     int depth;
1032     int nb_components;
1033     int log2_chroma_w;
1034     int log2_chroma_h;
1035 } VAAPIEncodeRTFormat;
1036
1037 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1038     { "YUV400",    VA_RT_FORMAT_YUV400,        8, 1,      },
1039     { "YUV420",    VA_RT_FORMAT_YUV420,        8, 3, 1, 1 },
1040     { "YUV422",    VA_RT_FORMAT_YUV422,        8, 3, 1, 0 },
1041     { "YUV444",    VA_RT_FORMAT_YUV444,        8, 3, 0, 0 },
1042     { "YUV411",    VA_RT_FORMAT_YUV411,        8, 3, 2, 0 },
1043 #if VA_CHECK_VERSION(0, 38, 1)
1044     { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1045 #endif
1046 };
1047
1048 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1049     VAEntrypointEncSlice,
1050     VAEntrypointEncPicture,
1051 #if VA_CHECK_VERSION(0, 39, 2)
1052     VAEntrypointEncSliceLP,
1053 #endif
1054     0
1055 };
1056 #if VA_CHECK_VERSION(0, 39, 2)
1057 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1058     VAEntrypointEncSliceLP,
1059     0
1060 };
1061 #endif
1062
1063 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1064 {
1065     VAAPIEncodeContext      *ctx = avctx->priv_data;
1066     VAProfile    *va_profiles    = NULL;
1067     VAEntrypoint *va_entrypoints = NULL;
1068     VAStatus vas;
1069     const VAEntrypoint *usable_entrypoints;
1070     const VAAPIEncodeProfile *profile;
1071     const AVPixFmtDescriptor *desc;
1072     VAConfigAttrib rt_format_attr;
1073     const VAAPIEncodeRTFormat *rt_format;
1074     const char *profile_string, *entrypoint_string;
1075     int i, j, n, depth, err;
1076
1077
1078     if (ctx->low_power) {
1079 #if VA_CHECK_VERSION(0, 39, 2)
1080         usable_entrypoints = vaapi_encode_entrypoints_low_power;
1081 #else
1082         av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1083                "supported with this VAAPI version.\n");
1084         return AVERROR(EINVAL);
1085 #endif
1086     } else {
1087         usable_entrypoints = vaapi_encode_entrypoints_normal;
1088     }
1089
1090     desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1091     if (!desc) {
1092         av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1093                ctx->input_frames->sw_format);
1094         return AVERROR(EINVAL);
1095     }
1096     depth = desc->comp[0].depth;
1097     for (i = 1; i < desc->nb_components; i++) {
1098         if (desc->comp[i].depth != depth) {
1099             av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1100                    desc->name);
1101             return AVERROR(EINVAL);
1102         }
1103     }
1104     av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1105            desc->name);
1106
1107     n = vaMaxNumProfiles(ctx->hwctx->display);
1108     va_profiles = av_malloc_array(n, sizeof(VAProfile));
1109     if (!va_profiles) {
1110         err = AVERROR(ENOMEM);
1111         goto fail;
1112     }
1113     vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1114     if (vas != VA_STATUS_SUCCESS) {
1115         av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1116                vas, vaErrorStr(vas));
1117         err = AVERROR_EXTERNAL;
1118         goto fail;
1119     }
1120
1121     av_assert0(ctx->codec->profiles);
1122     for (i = 0; (ctx->codec->profiles[i].av_profile !=
1123                  FF_PROFILE_UNKNOWN); i++) {
1124         profile = &ctx->codec->profiles[i];
1125         if (depth               != profile->depth ||
1126             desc->nb_components != profile->nb_components)
1127             continue;
1128         if (desc->nb_components > 1 &&
1129             (desc->log2_chroma_w != profile->log2_chroma_w ||
1130              desc->log2_chroma_h != profile->log2_chroma_h))
1131             continue;
1132         if (avctx->profile != profile->av_profile &&
1133             avctx->profile != FF_PROFILE_UNKNOWN)
1134             continue;
1135
1136 #if VA_CHECK_VERSION(1, 0, 0)
1137         profile_string = vaProfileStr(profile->va_profile);
1138 #else
1139         profile_string = "(no profile names)";
1140 #endif
1141
1142         for (j = 0; j < n; j++) {
1143             if (va_profiles[j] == profile->va_profile)
1144                 break;
1145         }
1146         if (j >= n) {
1147             av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1148                    "is not supported by driver.\n", profile_string,
1149                    profile->va_profile);
1150             continue;
1151         }
1152
1153         ctx->profile = profile;
1154         break;
1155     }
1156     if (!ctx->profile) {
1157         av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1158         err = AVERROR(ENOSYS);
1159         goto fail;
1160     }
1161
1162     avctx->profile  = profile->av_profile;
1163     ctx->va_profile = profile->va_profile;
1164     av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1165            profile_string, ctx->va_profile);
1166
1167     n = vaMaxNumEntrypoints(ctx->hwctx->display);
1168     va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1169     if (!va_entrypoints) {
1170         err = AVERROR(ENOMEM);
1171         goto fail;
1172     }
1173     vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1174                                    va_entrypoints, &n);
1175     if (vas != VA_STATUS_SUCCESS) {
1176         av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1177                "profile %s (%d): %d (%s).\n", profile_string,
1178                ctx->va_profile, vas, vaErrorStr(vas));
1179         err = AVERROR_EXTERNAL;
1180         goto fail;
1181     }
1182
1183     for (i = 0; i < n; i++) {
1184         for (j = 0; usable_entrypoints[j]; j++) {
1185             if (va_entrypoints[i] == usable_entrypoints[j])
1186                 break;
1187         }
1188         if (usable_entrypoints[j])
1189             break;
1190     }
1191     if (i >= n) {
1192         av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1193                "for profile %s (%d).\n", profile_string, ctx->va_profile);
1194         err = AVERROR(ENOSYS);
1195         goto fail;
1196     }
1197
1198     ctx->va_entrypoint = va_entrypoints[i];
1199 #if VA_CHECK_VERSION(1, 0, 0)
1200     entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1201 #else
1202     entrypoint_string = "(no entrypoint names)";
1203 #endif
1204     av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1205            entrypoint_string, ctx->va_entrypoint);
1206
1207     for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1208         rt_format = &vaapi_encode_rt_formats[i];
1209         if (rt_format->depth         == depth &&
1210             rt_format->nb_components == profile->nb_components &&
1211             rt_format->log2_chroma_w == profile->log2_chroma_w &&
1212             rt_format->log2_chroma_h == profile->log2_chroma_h)
1213             break;
1214     }
1215     if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1216         av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1217                "found for profile %s (%d) entrypoint %s (%d).\n",
1218                profile_string, ctx->va_profile,
1219                entrypoint_string, ctx->va_entrypoint);
1220         err = AVERROR(ENOSYS);
1221         goto fail;
1222     }
1223
1224     rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1225     vas = vaGetConfigAttributes(ctx->hwctx->display,
1226                                 ctx->va_profile, ctx->va_entrypoint,
1227                                 &rt_format_attr, 1);
1228     if (vas != VA_STATUS_SUCCESS) {
1229         av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1230                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1231         err = AVERROR_EXTERNAL;
1232         goto fail;
1233     }
1234
1235     if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1236         av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1237                "supported by driver: assuming surface RT format %s "
1238                "is valid.\n", rt_format->name);
1239     } else if (!(rt_format_attr.value & rt_format->value)) {
1240         av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1241                "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1242                rt_format->name, profile_string, ctx->va_profile,
1243                entrypoint_string, ctx->va_entrypoint);
1244         err = AVERROR(ENOSYS);
1245         goto fail;
1246     } else {
1247         av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1248                "format %s (%#x).\n", rt_format->name, rt_format->value);
1249         ctx->config_attributes[ctx->nb_config_attributes++] =
1250             (VAConfigAttrib) {
1251             .type  = VAConfigAttribRTFormat,
1252             .value = rt_format->value,
1253         };
1254     }
1255
1256     err = 0;
1257 fail:
1258     av_freep(&va_profiles);
1259     av_freep(&va_entrypoints);
1260     return err;
1261 }
1262
1263 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1264 {
1265     VAAPIEncodeContext *ctx = avctx->priv_data;
1266     int64_t rc_bits_per_second;
1267     int     rc_target_percentage;
1268     int     rc_window_size;
1269     int64_t hrd_buffer_size;
1270     int64_t hrd_initial_buffer_fullness;
1271     int fr_num, fr_den;
1272     VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1273     VAStatus vas;
1274
1275     vas = vaGetConfigAttributes(ctx->hwctx->display,
1276                                 ctx->va_profile, ctx->va_entrypoint,
1277                                 &rc_attr, 1);
1278     if (vas != VA_STATUS_SUCCESS) {
1279         av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1280                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1281         return AVERROR_EXTERNAL;
1282     }
1283
1284     if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1285         av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1286                "supported rate control modes: assuming constant-quality.\n");
1287         ctx->va_rc_mode = VA_RC_CQP;
1288         return 0;
1289     }
1290     if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY ||
1291         avctx->flags & AV_CODEC_FLAG_QSCALE ||
1292         avctx->bit_rate <= 0) {
1293         if (rc_attr.value & VA_RC_CQP) {
1294             av_log(avctx, AV_LOG_VERBOSE, "Using constant-quality mode.\n");
1295             ctx->va_rc_mode = VA_RC_CQP;
1296             if (avctx->bit_rate > 0 || avctx->rc_max_rate > 0) {
1297                 av_log(avctx, AV_LOG_WARNING, "Bitrate target parameters "
1298                        "ignored in constant-quality mode.\n");
1299             }
1300             return 0;
1301         } else {
1302             av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1303                    "constant-quality mode (%#x).\n", rc_attr.value);
1304             return AVERROR(EINVAL);
1305         }
1306     }
1307
1308     if (!(rc_attr.value & (VA_RC_CBR | VA_RC_VBR))) {
1309         av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1310                "bitrate-targetted rate control modes.\n");
1311         return AVERROR(EINVAL);
1312     }
1313
1314     if (avctx->rc_buffer_size)
1315         hrd_buffer_size = avctx->rc_buffer_size;
1316     else if (avctx->rc_max_rate > 0)
1317         hrd_buffer_size = avctx->rc_max_rate;
1318     else
1319         hrd_buffer_size = avctx->bit_rate;
1320     if (avctx->rc_initial_buffer_occupancy) {
1321         if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1322             av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1323                    "must have initial buffer size (%d) < "
1324                    "buffer size (%"PRId64").\n",
1325                    avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1326             return AVERROR(EINVAL);
1327         }
1328         hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1329     } else {
1330         hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1331     }
1332
1333     if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {
1334         av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: must have "
1335                "bitrate (%"PRId64") <= maxrate (%"PRId64").\n",
1336                avctx->bit_rate, avctx->rc_max_rate);
1337         return AVERROR(EINVAL);
1338     }
1339
1340     if (avctx->rc_max_rate > avctx->bit_rate) {
1341         if (!(rc_attr.value & VA_RC_VBR)) {
1342             av_log(avctx, AV_LOG_WARNING, "Driver does not support "
1343                    "VBR mode (%#x), using CBR mode instead.\n",
1344                    rc_attr.value);
1345             ctx->va_rc_mode = VA_RC_CBR;
1346
1347             rc_bits_per_second   = avctx->bit_rate;
1348             rc_target_percentage = 100;
1349         } else {
1350             ctx->va_rc_mode = VA_RC_VBR;
1351
1352             rc_bits_per_second   = avctx->rc_max_rate;
1353             rc_target_percentage = (avctx->bit_rate * 100) /
1354                                    avctx->rc_max_rate;
1355         }
1356
1357     } else if (avctx->rc_max_rate == avctx->bit_rate) {
1358         if (!(rc_attr.value & VA_RC_CBR)) {
1359             av_log(avctx, AV_LOG_WARNING, "Driver does not support "
1360                    "CBR mode (%#x), using VBR mode instead.\n",
1361                    rc_attr.value);
1362             ctx->va_rc_mode = VA_RC_VBR;
1363         } else {
1364             ctx->va_rc_mode = VA_RC_CBR;
1365         }
1366
1367         rc_bits_per_second   = avctx->bit_rate;
1368         rc_target_percentage = 100;
1369
1370     } else {
1371         if (rc_attr.value & VA_RC_VBR) {
1372             ctx->va_rc_mode = VA_RC_VBR;
1373
1374             // We only have a target bitrate, but VAAPI requires that a
1375             // maximum rate be supplied as well.  Since the user has
1376             // offered no particular constraint, arbitrarily pick a
1377             // maximum rate of double the target rate.
1378             rc_bits_per_second   = 2 * avctx->bit_rate;
1379             rc_target_percentage = 50;
1380         } else {
1381             ctx->va_rc_mode = VA_RC_CBR;
1382
1383             rc_bits_per_second   = avctx->bit_rate;
1384             rc_target_percentage = 100;
1385         }
1386     }
1387
1388     rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1389
1390     av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s, %d%% of %"PRId64" bps "
1391            "over %d ms.\n", ctx->va_rc_mode == VA_RC_VBR ? "VBR" : "CBR",
1392            rc_target_percentage, rc_bits_per_second, rc_window_size);
1393     av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1394            "initial fullness %"PRId64" bits.\n",
1395            hrd_buffer_size, hrd_initial_buffer_fullness);
1396
1397     if (rc_bits_per_second          > UINT32_MAX ||
1398         hrd_buffer_size             > UINT32_MAX ||
1399         hrd_initial_buffer_fullness > UINT32_MAX) {
1400         av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1401                "greater are not supported by VAAPI.\n");
1402         return AVERROR(EINVAL);
1403     }
1404
1405     ctx->va_bit_rate = rc_bits_per_second;
1406
1407     ctx->config_attributes[ctx->nb_config_attributes++] =
1408         (VAConfigAttrib) {
1409         .type  = VAConfigAttribRateControl,
1410         .value = ctx->va_rc_mode,
1411     };
1412
1413     ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1414     ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1415         .bits_per_second   = rc_bits_per_second,
1416         .target_percentage = rc_target_percentage,
1417         .window_size       = rc_window_size,
1418         .initial_qp        = 0,
1419         .min_qp            = (avctx->qmin > 0 ? avctx->qmin : 0),
1420         .basic_unit_size   = 0,
1421 #if VA_CHECK_VERSION(1, 1, 0)
1422         .max_qp            = (avctx->qmax > 0 ? avctx->qmax : 0),
1423 #endif
1424     };
1425     vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
1426                                   sizeof(ctx->rc_params));
1427
1428     ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1429     ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1430         .initial_buffer_fullness = hrd_initial_buffer_fullness,
1431         .buffer_size             = hrd_buffer_size,
1432     };
1433     vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
1434                                   sizeof(ctx->hrd_params));
1435
1436     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1437         av_reduce(&fr_num, &fr_den,
1438                   avctx->framerate.num, avctx->framerate.den, 65535);
1439     else
1440         av_reduce(&fr_num, &fr_den,
1441                   avctx->time_base.den, avctx->time_base.num, 65535);
1442
1443     ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1444     ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1445
1446 #if VA_CHECK_VERSION(0, 40, 0)
1447     vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
1448                                   sizeof(ctx->fr_params));
1449 #endif
1450
1451     return 0;
1452 }
1453
1454 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1455 {
1456     VAAPIEncodeContext *ctx = avctx->priv_data;
1457     VAStatus vas;
1458     VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1459     uint32_t ref_l0, ref_l1;
1460
1461     vas = vaGetConfigAttributes(ctx->hwctx->display,
1462                                 ctx->va_profile,
1463                                 ctx->va_entrypoint,
1464                                 &attr, 1);
1465     if (vas != VA_STATUS_SUCCESS) {
1466         av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1467                "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1468         return AVERROR_EXTERNAL;
1469     }
1470
1471     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1472         ref_l0 = ref_l1 = 0;
1473     } else {
1474         ref_l0 = attr.value       & 0xffff;
1475         ref_l1 = attr.value >> 16 & 0xffff;
1476     }
1477
1478     if (avctx->gop_size <= 1) {
1479         av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1480         ctx->gop_size = 1;
1481     } else if (ref_l0 < 1) {
1482         av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1483                "reference frames.\n");
1484         return AVERROR(EINVAL);
1485     } else if (ref_l1 < 1 || avctx->max_b_frames < 1) {
1486         av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1487                "(supported references: %d / %d).\n", ref_l0, ref_l1);
1488         ctx->gop_size = avctx->gop_size;
1489         ctx->p_per_i  = INT_MAX;
1490         ctx->b_per_p  = 0;
1491     } else {
1492         av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1493                "(supported references: %d / %d).\n", ref_l0, ref_l1);
1494         ctx->gop_size = avctx->gop_size;
1495         ctx->p_per_i  = INT_MAX;
1496         ctx->b_per_p  = avctx->max_b_frames;
1497     }
1498
1499     return 0;
1500 }
1501
1502 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1503 {
1504     VAAPIEncodeContext *ctx = avctx->priv_data;
1505     VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1506                                { VAConfigAttribEncSliceStructure } };
1507     VAStatus vas;
1508     uint32_t max_slices, slice_structure;
1509     int req_slices;
1510
1511     if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1512         if (avctx->slices > 0) {
1513             av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1514                    "but this codec does not support controlling slices.\n");
1515         }
1516         return 0;
1517     }
1518
1519     ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1520                              ctx->slice_block_height;
1521     ctx->slice_block_cols = (avctx->width  + ctx->slice_block_width  - 1) /
1522                              ctx->slice_block_width;
1523
1524     if (avctx->slices <= 1) {
1525         ctx->nb_slices  = 1;
1526         ctx->slice_size = ctx->slice_block_rows;
1527         return 0;
1528     }
1529
1530     vas = vaGetConfigAttributes(ctx->hwctx->display,
1531                                 ctx->va_profile,
1532                                 ctx->va_entrypoint,
1533                                 attr, FF_ARRAY_ELEMS(attr));
1534     if (vas != VA_STATUS_SUCCESS) {
1535         av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1536                "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1537         return AVERROR_EXTERNAL;
1538     }
1539     max_slices      = attr[0].value;
1540     slice_structure = attr[1].value;
1541     if (max_slices      == VA_ATTRIB_NOT_SUPPORTED ||
1542         slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1543         av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1544                "pictures as multiple slices.\n.");
1545         return AVERROR(EINVAL);
1546     }
1547
1548     // For fixed-size slices currently we only support whole rows, making
1549     // rectangular slices.  This could be extended to arbitrary runs of
1550     // blocks, but since slices tend to be a conformance requirement and
1551     // most cases (such as broadcast or bluray) want rectangular slices
1552     // only it would need to be gated behind another option.
1553     if (avctx->slices > ctx->slice_block_rows) {
1554         av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1555                "configured number of slices (%d < %d); using "
1556                "maximum.\n", ctx->slice_block_rows, avctx->slices);
1557         req_slices = ctx->slice_block_rows;
1558     } else {
1559         req_slices = avctx->slices;
1560     }
1561     if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1562         slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1563         ctx->nb_slices  = req_slices;
1564         ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1565     } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1566         int k;
1567         for (k = 1;; k *= 2) {
1568             if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1569                 break;
1570         }
1571         ctx->nb_slices  = (ctx->slice_block_rows + k - 1) / k;
1572         ctx->slice_size = k;
1573 #if VA_CHECK_VERSION(1, 0, 0)
1574     } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1575         ctx->nb_slices  = ctx->slice_block_rows;
1576         ctx->slice_size = 1;
1577 #endif
1578     } else {
1579         av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1580                "slice structure modes (%#x).\n", slice_structure);
1581         return AVERROR(EINVAL);
1582     }
1583
1584     if (ctx->nb_slices > avctx->slices) {
1585         av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1586                "%d (from %d) due to driver constraints on slice "
1587                "structure.\n", ctx->nb_slices, avctx->slices);
1588     }
1589     if (ctx->nb_slices > max_slices) {
1590         av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1591                "encoding with %d slices (max %"PRIu32").\n",
1592                ctx->nb_slices, max_slices);
1593         return AVERROR(EINVAL);
1594     }
1595
1596     av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1597            "(default size %d block rows).\n",
1598            ctx->nb_slices, ctx->slice_size);
1599     return 0;
1600 }
1601
1602 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1603 {
1604     VAAPIEncodeContext *ctx = avctx->priv_data;
1605     VAStatus vas;
1606     VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1607
1608     vas = vaGetConfigAttributes(ctx->hwctx->display,
1609                                 ctx->va_profile,
1610                                 ctx->va_entrypoint,
1611                                 &attr, 1);
1612     if (vas != VA_STATUS_SUCCESS) {
1613         av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1614                "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1615         return AVERROR_EXTERNAL;
1616     }
1617
1618     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1619         if (ctx->desired_packed_headers) {
1620             av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1621                    "packed headers (wanted %#x).\n",
1622                    ctx->desired_packed_headers);
1623         } else {
1624             av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1625                    "packed headers (none wanted).\n");
1626         }
1627         ctx->va_packed_headers = 0;
1628     } else {
1629         if (ctx->desired_packed_headers & ~attr.value) {
1630             av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1631                    "wanted packed headers (wanted %#x, found %#x).\n",
1632                    ctx->desired_packed_headers, attr.value);
1633         } else {
1634             av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1635                    "available (wanted %#x, found %#x).\n",
1636                    ctx->desired_packed_headers, attr.value);
1637         }
1638         ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1639     }
1640
1641     if (ctx->va_packed_headers) {
1642         ctx->config_attributes[ctx->nb_config_attributes++] =
1643             (VAConfigAttrib) {
1644             .type  = VAConfigAttribEncPackedHeaders,
1645             .value = ctx->va_packed_headers,
1646         };
1647     }
1648
1649     if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1650         !(ctx->va_packed_headers      & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1651          (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1652         av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1653                "sequence headers, but a global header is requested.\n");
1654         av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1655                "this may result in a stream which is not usable for some "
1656                "purposes (e.g. not muxable to some containers).\n");
1657     }
1658
1659     return 0;
1660 }
1661
1662 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1663 {
1664 #if VA_CHECK_VERSION(0, 36, 0)
1665     VAAPIEncodeContext *ctx = avctx->priv_data;
1666     VAStatus vas;
1667     VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1668     int quality = avctx->compression_level;
1669
1670     vas = vaGetConfigAttributes(ctx->hwctx->display,
1671                                 ctx->va_profile,
1672                                 ctx->va_entrypoint,
1673                                 &attr, 1);
1674     if (vas != VA_STATUS_SUCCESS) {
1675         av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1676                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1677         return AVERROR_EXTERNAL;
1678     }
1679
1680     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1681         if (quality != 0) {
1682             av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1683                    "supported: will use default quality level.\n");
1684         }
1685     } else {
1686         if (quality > attr.value) {
1687             av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1688                    "valid range is 0-%d, using %d.\n",
1689                    attr.value, attr.value);
1690             quality = attr.value;
1691         }
1692
1693         ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
1694         ctx->quality_params.quality.quality_level = quality;
1695
1696         vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
1697                                       sizeof(ctx->quality_params));
1698     }
1699 #else
1700     av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1701            "not supported with this VAAPI version.\n");
1702 #endif
1703
1704     return 0;
1705 }
1706
1707 static void vaapi_encode_free_output_buffer(void *opaque,
1708                                             uint8_t *data)
1709 {
1710     AVCodecContext   *avctx = opaque;
1711     VAAPIEncodeContext *ctx = avctx->priv_data;
1712     VABufferID buffer_id;
1713
1714     buffer_id = (VABufferID)(uintptr_t)data;
1715
1716     vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1717
1718     av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1719 }
1720
1721 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1722                                                      int size)
1723 {
1724     AVCodecContext   *avctx = opaque;
1725     VAAPIEncodeContext *ctx = avctx->priv_data;
1726     VABufferID buffer_id;
1727     VAStatus vas;
1728     AVBufferRef *ref;
1729
1730     // The output buffer size is fixed, so it needs to be large enough
1731     // to hold the largest possible compressed frame.  We assume here
1732     // that the uncompressed frame plus some header data is an upper
1733     // bound on that.
1734     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1735                          VAEncCodedBufferType,
1736                          3 * ctx->surface_width * ctx->surface_height +
1737                          (1 << 16), 1, 0, &buffer_id);
1738     if (vas != VA_STATUS_SUCCESS) {
1739         av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1740                "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1741         return NULL;
1742     }
1743
1744     av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1745
1746     ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1747                            sizeof(buffer_id),
1748                            &vaapi_encode_free_output_buffer,
1749                            avctx, AV_BUFFER_FLAG_READONLY);
1750     if (!ref) {
1751         vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1752         return NULL;
1753     }
1754
1755     return ref;
1756 }
1757
1758 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1759 {
1760     VAAPIEncodeContext *ctx = avctx->priv_data;
1761     AVVAAPIHWConfig *hwconfig = NULL;
1762     AVHWFramesConstraints *constraints = NULL;
1763     enum AVPixelFormat recon_format;
1764     int err, i;
1765
1766     hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1767     if (!hwconfig) {
1768         err = AVERROR(ENOMEM);
1769         goto fail;
1770     }
1771     hwconfig->config_id = ctx->va_config;
1772
1773     constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1774                                                       hwconfig);
1775     if (!constraints) {
1776         err = AVERROR(ENOMEM);
1777         goto fail;
1778     }
1779
1780     // Probably we can use the input surface format as the surface format
1781     // of the reconstructed frames.  If not, we just pick the first (only?)
1782     // format in the valid list and hope that it all works.
1783     recon_format = AV_PIX_FMT_NONE;
1784     if (constraints->valid_sw_formats) {
1785         for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1786             if (ctx->input_frames->sw_format ==
1787                 constraints->valid_sw_formats[i]) {
1788                 recon_format = ctx->input_frames->sw_format;
1789                 break;
1790             }
1791         }
1792         if (recon_format == AV_PIX_FMT_NONE) {
1793             // No match.  Just use the first in the supported list and
1794             // hope for the best.
1795             recon_format = constraints->valid_sw_formats[0];
1796         }
1797     } else {
1798         // No idea what to use; copy input format.
1799         recon_format = ctx->input_frames->sw_format;
1800     }
1801     av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1802            "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1803
1804     if (ctx->surface_width  < constraints->min_width  ||
1805         ctx->surface_height < constraints->min_height ||
1806         ctx->surface_width  > constraints->max_width ||
1807         ctx->surface_height > constraints->max_height) {
1808         av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1809                "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1810                ctx->surface_width, ctx->surface_height,
1811                constraints->min_width,  constraints->max_width,
1812                constraints->min_height, constraints->max_height);
1813         err = AVERROR(EINVAL);
1814         goto fail;
1815     }
1816
1817     av_freep(&hwconfig);
1818     av_hwframe_constraints_free(&constraints);
1819
1820     ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1821     if (!ctx->recon_frames_ref) {
1822         err = AVERROR(ENOMEM);
1823         goto fail;
1824     }
1825     ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1826
1827     ctx->recon_frames->format    = AV_PIX_FMT_VAAPI;
1828     ctx->recon_frames->sw_format = recon_format;
1829     ctx->recon_frames->width     = ctx->surface_width;
1830     ctx->recon_frames->height    = ctx->surface_height;
1831     // At most three IDR/I/P frames and two runs of B frames can be in
1832     // flight at any one time.
1833     ctx->recon_frames->initial_pool_size = 3 + 2 * ctx->b_per_p;
1834
1835     err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1836     if (err < 0) {
1837         av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1838                "frame context: %d.\n", err);
1839         goto fail;
1840     }
1841
1842     err = 0;
1843   fail:
1844     av_freep(&hwconfig);
1845     av_hwframe_constraints_free(&constraints);
1846     return err;
1847 }
1848
1849 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
1850 {
1851     VAAPIEncodeContext *ctx = avctx->priv_data;
1852     AVVAAPIFramesContext *recon_hwctx = NULL;
1853     VAStatus vas;
1854     int err;
1855
1856     if (!avctx->hw_frames_ctx) {
1857         av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1858                "required to associate the encoding device.\n");
1859         return AVERROR(EINVAL);
1860     }
1861
1862     ctx->va_config  = VA_INVALID_ID;
1863     ctx->va_context = VA_INVALID_ID;
1864
1865     ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1866     if (!ctx->input_frames_ref) {
1867         err = AVERROR(ENOMEM);
1868         goto fail;
1869     }
1870     ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1871
1872     ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1873     if (!ctx->device_ref) {
1874         err = AVERROR(ENOMEM);
1875         goto fail;
1876     }
1877     ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1878     ctx->hwctx = ctx->device->hwctx;
1879
1880     err = vaapi_encode_profile_entrypoint(avctx);
1881     if (err < 0)
1882         goto fail;
1883
1884     err = vaapi_encode_init_rate_control(avctx);
1885     if (err < 0)
1886         goto fail;
1887
1888     err = vaapi_encode_init_gop_structure(avctx);
1889     if (err < 0)
1890         goto fail;
1891
1892     err = vaapi_encode_init_slice_structure(avctx);
1893     if (err < 0)
1894         goto fail;
1895
1896     err = vaapi_encode_init_packed_headers(avctx);
1897     if (err < 0)
1898         goto fail;
1899
1900     if (avctx->compression_level >= 0) {
1901         err = vaapi_encode_init_quality(avctx);
1902         if (err < 0)
1903             goto fail;
1904     }
1905
1906     vas = vaCreateConfig(ctx->hwctx->display,
1907                          ctx->va_profile, ctx->va_entrypoint,
1908                          ctx->config_attributes, ctx->nb_config_attributes,
1909                          &ctx->va_config);
1910     if (vas != VA_STATUS_SUCCESS) {
1911         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1912                "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1913         err = AVERROR(EIO);
1914         goto fail;
1915     }
1916
1917     err = vaapi_encode_create_recon_frames(avctx);
1918     if (err < 0)
1919         goto fail;
1920
1921     recon_hwctx = ctx->recon_frames->hwctx;
1922     vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1923                           ctx->surface_width, ctx->surface_height,
1924                           VA_PROGRESSIVE,
1925                           recon_hwctx->surface_ids,
1926                           recon_hwctx->nb_surfaces,
1927                           &ctx->va_context);
1928     if (vas != VA_STATUS_SUCCESS) {
1929         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1930                "context: %d (%s).\n", vas, vaErrorStr(vas));
1931         err = AVERROR(EIO);
1932         goto fail;
1933     }
1934
1935     ctx->output_buffer_pool =
1936         av_buffer_pool_init2(sizeof(VABufferID), avctx,
1937                              &vaapi_encode_alloc_output_buffer, NULL);
1938     if (!ctx->output_buffer_pool) {
1939         err = AVERROR(ENOMEM);
1940         goto fail;
1941     }
1942
1943     if (ctx->codec->configure) {
1944         err = ctx->codec->configure(avctx);
1945         if (err < 0)
1946             goto fail;
1947     }
1948
1949     ctx->input_order  = 0;
1950     ctx->output_delay = ctx->b_per_p;
1951     ctx->decode_delay = 1;
1952     ctx->output_order = - ctx->output_delay - 1;
1953
1954     if (ctx->codec->sequence_params_size > 0) {
1955         ctx->codec_sequence_params =
1956             av_mallocz(ctx->codec->sequence_params_size);
1957         if (!ctx->codec_sequence_params) {
1958             err = AVERROR(ENOMEM);
1959             goto fail;
1960         }
1961     }
1962     if (ctx->codec->picture_params_size > 0) {
1963         ctx->codec_picture_params =
1964             av_mallocz(ctx->codec->picture_params_size);
1965         if (!ctx->codec_picture_params) {
1966             err = AVERROR(ENOMEM);
1967             goto fail;
1968         }
1969     }
1970
1971     if (ctx->codec->init_sequence_params) {
1972         err = ctx->codec->init_sequence_params(avctx);
1973         if (err < 0) {
1974             av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1975                    "failed: %d.\n", err);
1976             goto fail;
1977         }
1978     }
1979
1980     // This should be configurable somehow.  (Needs testing on a machine
1981     // where it actually overlaps properly, though.)
1982     ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1983
1984     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
1985         ctx->codec->write_sequence_header &&
1986         avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1987         char data[MAX_PARAM_BUFFER_SIZE];
1988         size_t bit_len = 8 * sizeof(data);
1989
1990         err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
1991         if (err < 0) {
1992             av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
1993                    "for extradata: %d.\n", err);
1994             goto fail;
1995         } else {
1996             avctx->extradata_size = (bit_len + 7) / 8;
1997             avctx->extradata = av_mallocz(avctx->extradata_size +
1998                                           AV_INPUT_BUFFER_PADDING_SIZE);
1999             if (!avctx->extradata) {
2000                 err = AVERROR(ENOMEM);
2001                 goto fail;
2002             }
2003             memcpy(avctx->extradata, data, avctx->extradata_size);
2004         }
2005     }
2006
2007     return 0;
2008
2009 fail:
2010     ff_vaapi_encode_close(avctx);
2011     return err;
2012 }
2013
2014 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2015 {
2016     VAAPIEncodeContext *ctx = avctx->priv_data;
2017     VAAPIEncodePicture *pic, *next;
2018
2019     for (pic = ctx->pic_start; pic; pic = next) {
2020         next = pic->next;
2021         vaapi_encode_free(avctx, pic);
2022     }
2023
2024     av_buffer_pool_uninit(&ctx->output_buffer_pool);
2025
2026     if (ctx->va_context != VA_INVALID_ID) {
2027         vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2028         ctx->va_context = VA_INVALID_ID;
2029     }
2030
2031     if (ctx->va_config != VA_INVALID_ID) {
2032         vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2033         ctx->va_config = VA_INVALID_ID;
2034     }
2035
2036     av_freep(&ctx->codec_sequence_params);
2037     av_freep(&ctx->codec_picture_params);
2038
2039     av_buffer_unref(&ctx->recon_frames_ref);
2040     av_buffer_unref(&ctx->input_frames_ref);
2041     av_buffer_unref(&ctx->device_ref);
2042
2043     return 0;
2044 }