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