]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_encode.c
Merge commit '49f9c4272c4029b57ff300d908ba03c6332fc9c4'
[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 int ff_vaapi_encode_send_frame(AVCodecContext *avctx, const AVFrame *frame)
917 {
918     VAAPIEncodeContext *ctx = avctx->priv_data;
919     VAAPIEncodePicture *pic;
920     int err;
921
922     if (frame) {
923         av_log(avctx, AV_LOG_DEBUG, "Input frame: %ux%u (%"PRId64").\n",
924                frame->width, frame->height, frame->pts);
925
926         pic = vaapi_encode_alloc(avctx);
927         if (!pic)
928             return AVERROR(ENOMEM);
929
930         pic->input_image = av_frame_alloc();
931         if (!pic->input_image) {
932             err = AVERROR(ENOMEM);
933             goto fail;
934         }
935         err = av_frame_ref(pic->input_image, frame);
936         if (err < 0)
937             goto fail;
938
939         if (ctx->input_order == 0)
940             pic->force_idr = 1;
941
942         pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
943         pic->pts = frame->pts;
944
945         if (ctx->input_order == 0)
946             ctx->first_pts = pic->pts;
947         if (ctx->input_order == ctx->decode_delay)
948             ctx->dts_pts_diff = pic->pts - ctx->first_pts;
949         if (ctx->output_delay > 0)
950             ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
951
952         pic->display_order = ctx->input_order;
953         ++ctx->input_order;
954
955         if (ctx->pic_start) {
956             ctx->pic_end->next = pic;
957             ctx->pic_end       = pic;
958         } else {
959             ctx->pic_start     = pic;
960             ctx->pic_end       = pic;
961         }
962
963     } else {
964         ctx->end_of_stream = 1;
965
966         // Fix timestamps if we hit end-of-stream before the initial decode
967         // delay has elapsed.
968         if (ctx->input_order < ctx->decode_delay)
969             ctx->dts_pts_diff = ctx->pic_end->pts - ctx->first_pts;
970     }
971
972     return 0;
973
974 fail:
975     return err;
976 }
977
978 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
979 {
980     VAAPIEncodeContext *ctx = avctx->priv_data;
981     VAAPIEncodePicture *pic;
982     int err;
983
984     if (!ctx->pic_start) {
985         if (ctx->end_of_stream)
986             return AVERROR_EOF;
987         else
988             return AVERROR(EAGAIN);
989     }
990
991     pic = NULL;
992     err = vaapi_encode_pick_next(avctx, &pic);
993     if (err < 0)
994         return err;
995     av_assert0(pic);
996
997     pic->encode_order = ctx->encode_order++;
998
999     err = vaapi_encode_issue(avctx, pic);
1000     if (err < 0) {
1001         av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
1002         return err;
1003     }
1004
1005     err = vaapi_encode_output(avctx, pic, pkt);
1006     if (err < 0) {
1007         av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
1008         return err;
1009     }
1010
1011     if (ctx->output_delay == 0) {
1012         pkt->dts = pkt->pts;
1013     } else if (pic->encode_order < ctx->decode_delay) {
1014         if (ctx->ts_ring[pic->encode_order] < INT64_MIN + ctx->dts_pts_diff)
1015             pkt->dts = INT64_MIN;
1016         else
1017             pkt->dts = ctx->ts_ring[pic->encode_order] - ctx->dts_pts_diff;
1018     } else {
1019         pkt->dts = ctx->ts_ring[(pic->encode_order - ctx->decode_delay) %
1020                                 (3 * ctx->output_delay)];
1021     }
1022     av_log(avctx, AV_LOG_DEBUG, "Output packet: pts %"PRId64" dts %"PRId64".\n",
1023            pkt->pts, pkt->dts);
1024
1025     ctx->output_order = pic->encode_order;
1026     vaapi_encode_clear_old(avctx);
1027
1028     return 0;
1029 }
1030
1031 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
1032                      const AVFrame *input_image, int *got_packet)
1033 {
1034     return AVERROR(ENOSYS);
1035 }
1036
1037 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx,
1038                                                   VAEncMiscParameterBuffer *buffer,
1039                                                   size_t size)
1040 {
1041     VAAPIEncodeContext *ctx = avctx->priv_data;
1042
1043     av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
1044
1045     ctx->global_params     [ctx->nb_global_params] = buffer;
1046     ctx->global_params_size[ctx->nb_global_params] = size;
1047
1048     ++ctx->nb_global_params;
1049 }
1050
1051 typedef struct VAAPIEncodeRTFormat {
1052     const char *name;
1053     unsigned int value;
1054     int depth;
1055     int nb_components;
1056     int log2_chroma_w;
1057     int log2_chroma_h;
1058 } VAAPIEncodeRTFormat;
1059
1060 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
1061     { "YUV400",    VA_RT_FORMAT_YUV400,        8, 1,      },
1062     { "YUV420",    VA_RT_FORMAT_YUV420,        8, 3, 1, 1 },
1063     { "YUV422",    VA_RT_FORMAT_YUV422,        8, 3, 1, 0 },
1064     { "YUV444",    VA_RT_FORMAT_YUV444,        8, 3, 0, 0 },
1065     { "YUV411",    VA_RT_FORMAT_YUV411,        8, 3, 2, 0 },
1066 #if VA_CHECK_VERSION(0, 38, 1)
1067     { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
1068 #endif
1069 };
1070
1071 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
1072     VAEntrypointEncSlice,
1073     VAEntrypointEncPicture,
1074 #if VA_CHECK_VERSION(0, 39, 2)
1075     VAEntrypointEncSliceLP,
1076 #endif
1077     0
1078 };
1079 #if VA_CHECK_VERSION(0, 39, 2)
1080 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1081     VAEntrypointEncSliceLP,
1082     0
1083 };
1084 #endif
1085
1086 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1087 {
1088     VAAPIEncodeContext      *ctx = avctx->priv_data;
1089     VAProfile    *va_profiles    = NULL;
1090     VAEntrypoint *va_entrypoints = NULL;
1091     VAStatus vas;
1092     const VAEntrypoint *usable_entrypoints;
1093     const VAAPIEncodeProfile *profile;
1094     const AVPixFmtDescriptor *desc;
1095     VAConfigAttrib rt_format_attr;
1096     const VAAPIEncodeRTFormat *rt_format;
1097     const char *profile_string, *entrypoint_string;
1098     int i, j, n, depth, err;
1099
1100
1101     if (ctx->low_power) {
1102 #if VA_CHECK_VERSION(0, 39, 2)
1103         usable_entrypoints = vaapi_encode_entrypoints_low_power;
1104 #else
1105         av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1106                "supported with this VAAPI version.\n");
1107         return AVERROR(EINVAL);
1108 #endif
1109     } else {
1110         usable_entrypoints = vaapi_encode_entrypoints_normal;
1111     }
1112
1113     desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1114     if (!desc) {
1115         av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1116                ctx->input_frames->sw_format);
1117         return AVERROR(EINVAL);
1118     }
1119     depth = desc->comp[0].depth;
1120     for (i = 1; i < desc->nb_components; i++) {
1121         if (desc->comp[i].depth != depth) {
1122             av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1123                    desc->name);
1124             return AVERROR(EINVAL);
1125         }
1126     }
1127     av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1128            desc->name);
1129
1130     n = vaMaxNumProfiles(ctx->hwctx->display);
1131     va_profiles = av_malloc_array(n, sizeof(VAProfile));
1132     if (!va_profiles) {
1133         err = AVERROR(ENOMEM);
1134         goto fail;
1135     }
1136     vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1137     if (vas != VA_STATUS_SUCCESS) {
1138         av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1139                vas, vaErrorStr(vas));
1140         err = AVERROR_EXTERNAL;
1141         goto fail;
1142     }
1143
1144     av_assert0(ctx->codec->profiles);
1145     for (i = 0; (ctx->codec->profiles[i].av_profile !=
1146                  FF_PROFILE_UNKNOWN); i++) {
1147         profile = &ctx->codec->profiles[i];
1148         if (depth               != profile->depth ||
1149             desc->nb_components != profile->nb_components)
1150             continue;
1151         if (desc->nb_components > 1 &&
1152             (desc->log2_chroma_w != profile->log2_chroma_w ||
1153              desc->log2_chroma_h != profile->log2_chroma_h))
1154             continue;
1155         if (avctx->profile != profile->av_profile &&
1156             avctx->profile != FF_PROFILE_UNKNOWN)
1157             continue;
1158
1159 #if VA_CHECK_VERSION(1, 0, 0)
1160         profile_string = vaProfileStr(profile->va_profile);
1161 #else
1162         profile_string = "(no profile names)";
1163 #endif
1164
1165         for (j = 0; j < n; j++) {
1166             if (va_profiles[j] == profile->va_profile)
1167                 break;
1168         }
1169         if (j >= n) {
1170             av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1171                    "is not supported by driver.\n", profile_string,
1172                    profile->va_profile);
1173             continue;
1174         }
1175
1176         ctx->profile = profile;
1177         break;
1178     }
1179     if (!ctx->profile) {
1180         av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1181         err = AVERROR(ENOSYS);
1182         goto fail;
1183     }
1184
1185     avctx->profile  = profile->av_profile;
1186     ctx->va_profile = profile->va_profile;
1187     av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1188            profile_string, ctx->va_profile);
1189
1190     n = vaMaxNumEntrypoints(ctx->hwctx->display);
1191     va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1192     if (!va_entrypoints) {
1193         err = AVERROR(ENOMEM);
1194         goto fail;
1195     }
1196     vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1197                                    va_entrypoints, &n);
1198     if (vas != VA_STATUS_SUCCESS) {
1199         av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1200                "profile %s (%d): %d (%s).\n", profile_string,
1201                ctx->va_profile, vas, vaErrorStr(vas));
1202         err = AVERROR_EXTERNAL;
1203         goto fail;
1204     }
1205
1206     for (i = 0; i < n; i++) {
1207         for (j = 0; usable_entrypoints[j]; j++) {
1208             if (va_entrypoints[i] == usable_entrypoints[j])
1209                 break;
1210         }
1211         if (usable_entrypoints[j])
1212             break;
1213     }
1214     if (i >= n) {
1215         av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1216                "for profile %s (%d).\n", profile_string, ctx->va_profile);
1217         err = AVERROR(ENOSYS);
1218         goto fail;
1219     }
1220
1221     ctx->va_entrypoint = va_entrypoints[i];
1222 #if VA_CHECK_VERSION(1, 0, 0)
1223     entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1224 #else
1225     entrypoint_string = "(no entrypoint names)";
1226 #endif
1227     av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1228            entrypoint_string, ctx->va_entrypoint);
1229
1230     for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1231         rt_format = &vaapi_encode_rt_formats[i];
1232         if (rt_format->depth         == depth &&
1233             rt_format->nb_components == profile->nb_components &&
1234             rt_format->log2_chroma_w == profile->log2_chroma_w &&
1235             rt_format->log2_chroma_h == profile->log2_chroma_h)
1236             break;
1237     }
1238     if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1239         av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1240                "found for profile %s (%d) entrypoint %s (%d).\n",
1241                profile_string, ctx->va_profile,
1242                entrypoint_string, ctx->va_entrypoint);
1243         err = AVERROR(ENOSYS);
1244         goto fail;
1245     }
1246
1247     rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1248     vas = vaGetConfigAttributes(ctx->hwctx->display,
1249                                 ctx->va_profile, ctx->va_entrypoint,
1250                                 &rt_format_attr, 1);
1251     if (vas != VA_STATUS_SUCCESS) {
1252         av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1253                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1254         err = AVERROR_EXTERNAL;
1255         goto fail;
1256     }
1257
1258     if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1259         av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1260                "supported by driver: assuming surface RT format %s "
1261                "is valid.\n", rt_format->name);
1262     } else if (!(rt_format_attr.value & rt_format->value)) {
1263         av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1264                "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1265                rt_format->name, profile_string, ctx->va_profile,
1266                entrypoint_string, ctx->va_entrypoint);
1267         err = AVERROR(ENOSYS);
1268         goto fail;
1269     } else {
1270         av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1271                "format %s (%#x).\n", rt_format->name, rt_format->value);
1272         ctx->config_attributes[ctx->nb_config_attributes++] =
1273             (VAConfigAttrib) {
1274             .type  = VAConfigAttribRTFormat,
1275             .value = rt_format->value,
1276         };
1277     }
1278
1279     err = 0;
1280 fail:
1281     av_freep(&va_profiles);
1282     av_freep(&va_entrypoints);
1283     return err;
1284 }
1285
1286 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1287     //                                  Bitrate   Quality
1288     //                                     | Maxrate | HRD/VBV
1289     { 0 }, //                              |    |    |    |
1290     { RC_MODE_CQP,  "CQP",  1, VA_RC_CQP,  0,   0,   1,   0 },
1291     { RC_MODE_CBR,  "CBR",  1, VA_RC_CBR,  1,   0,   0,   1 },
1292     { RC_MODE_VBR,  "VBR",  1, VA_RC_VBR,  1,   1,   0,   1 },
1293 #if VA_CHECK_VERSION(1, 1, 0)
1294     { RC_MODE_ICQ,  "ICQ",  1, VA_RC_ICQ,  0,   0,   1,   0 },
1295 #else
1296     { RC_MODE_ICQ,  "ICQ",  0 },
1297 #endif
1298 #if VA_CHECK_VERSION(1, 3, 0)
1299     { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1,   1,   1,   1 },
1300     { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1,   0,   0,   0 },
1301 #else
1302     { RC_MODE_QVBR, "QVBR", 0 },
1303     { RC_MODE_AVBR, "AVBR", 0 },
1304 #endif
1305 };
1306
1307 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1308 {
1309     VAAPIEncodeContext *ctx = avctx->priv_data;
1310     uint32_t supported_va_rc_modes;
1311     const VAAPIEncodeRCMode *rc_mode;
1312     int64_t rc_bits_per_second;
1313     int     rc_target_percentage;
1314     int     rc_window_size;
1315     int     rc_quality;
1316     int64_t hrd_buffer_size;
1317     int64_t hrd_initial_buffer_fullness;
1318     int fr_num, fr_den;
1319     VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1320     VAStatus vas;
1321     char supported_rc_modes_string[64];
1322
1323     vas = vaGetConfigAttributes(ctx->hwctx->display,
1324                                 ctx->va_profile, ctx->va_entrypoint,
1325                                 &rc_attr, 1);
1326     if (vas != VA_STATUS_SUCCESS) {
1327         av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1328                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1329         return AVERROR_EXTERNAL;
1330     }
1331     if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1332         av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1333                "supported rate control modes: assuming CQP only.\n");
1334         supported_va_rc_modes = VA_RC_CQP;
1335         strcpy(supported_rc_modes_string, "unknown");
1336     } else {
1337         char *str = supported_rc_modes_string;
1338         size_t len = sizeof(supported_rc_modes_string);
1339         int i, first = 1, res;
1340
1341         supported_va_rc_modes = rc_attr.value;
1342         for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1343             rc_mode = &vaapi_encode_rc_modes[i];
1344             if (supported_va_rc_modes & rc_mode->va_mode) {
1345                 res = snprintf(str, len, "%s%s",
1346                                first ? "" : ", ", rc_mode->name);
1347                 first = 0;
1348                 if (res < 0) {
1349                     *str = 0;
1350                     break;
1351                 }
1352                 len -= res;
1353                 str += res;
1354                 if (len == 0)
1355                     break;
1356             }
1357         }
1358
1359         av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1360                supported_rc_modes_string);
1361     }
1362
1363     // Rate control mode selection:
1364     // * If the user has set a mode explicitly with the rc_mode option,
1365     //   use it and fail if it is not available.
1366     // * If an explicit QP option has been set, use CQP.
1367     // * If the codec is CQ-only, use CQP.
1368     // * If the QSCALE avcodec option is set, use CQP.
1369     // * If bitrate and quality are both set, try QVBR.
1370     // * If quality is set, try ICQ, then CQP.
1371     // * If bitrate and maxrate are set and have the same value, try CBR.
1372     // * If a bitrate is set, try AVBR, then VBR, then CBR.
1373     // * If no bitrate is set, try ICQ, then CQP.
1374
1375 #define TRY_RC_MODE(mode, fail) do { \
1376         rc_mode = &vaapi_encode_rc_modes[mode]; \
1377         if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1378             if (fail) { \
1379                 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1380                        "RC mode (supported modes: %s).\n", rc_mode->name, \
1381                        supported_rc_modes_string); \
1382                 return AVERROR(EINVAL); \
1383             } \
1384             av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1385                    "RC mode.\n", rc_mode->name); \
1386             rc_mode = NULL; \
1387         } else { \
1388             goto rc_mode_found; \
1389         } \
1390     } while (0)
1391
1392     if (ctx->explicit_rc_mode)
1393         TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1394
1395     if (ctx->explicit_qp)
1396         TRY_RC_MODE(RC_MODE_CQP, 1);
1397
1398     if (ctx->codec->flags & FLAG_CONSTANT_QUALITY_ONLY)
1399         TRY_RC_MODE(RC_MODE_CQP, 1);
1400
1401     if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1402         TRY_RC_MODE(RC_MODE_CQP, 1);
1403
1404     if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1405         TRY_RC_MODE(RC_MODE_QVBR, 0);
1406
1407     if (avctx->global_quality > 0) {
1408         TRY_RC_MODE(RC_MODE_ICQ, 0);
1409         TRY_RC_MODE(RC_MODE_CQP, 0);
1410     }
1411
1412     if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1413         TRY_RC_MODE(RC_MODE_CBR, 0);
1414
1415     if (avctx->bit_rate > 0) {
1416         TRY_RC_MODE(RC_MODE_AVBR, 0);
1417         TRY_RC_MODE(RC_MODE_VBR, 0);
1418         TRY_RC_MODE(RC_MODE_CBR, 0);
1419     } else {
1420         TRY_RC_MODE(RC_MODE_ICQ, 0);
1421         TRY_RC_MODE(RC_MODE_CQP, 0);
1422     }
1423
1424     av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1425            "RC mode compatible with selected options "
1426            "(supported modes: %s).\n", supported_rc_modes_string);
1427     return AVERROR(EINVAL);
1428
1429 rc_mode_found:
1430     if (rc_mode->bitrate) {
1431         if (avctx->bit_rate <= 0) {
1432             av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1433                    "RC mode.\n", rc_mode->name);
1434             return AVERROR(EINVAL);
1435         }
1436
1437         if (rc_mode->mode == RC_MODE_AVBR) {
1438             // For maximum confusion AVBR is hacked into the existing API
1439             // by overloading some of the fields with completely different
1440             // meanings.
1441
1442             // Target percentage does not apply in AVBR mode.
1443             rc_bits_per_second = avctx->bit_rate;
1444
1445             // Accuracy tolerance range for meeting the specified target
1446             // bitrate.  It's very unclear how this is actually intended
1447             // to work - since we do want to get the specified bitrate,
1448             // set the accuracy to 100% for now.
1449             rc_target_percentage = 100;
1450
1451             // Convergence period in frames.  The GOP size reflects the
1452             // user's intended block size for cutting, so reusing that
1453             // as the convergence period seems a reasonable default.
1454             rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1455
1456         } else if (rc_mode->maxrate) {
1457             if (avctx->rc_max_rate > 0) {
1458                 if (avctx->rc_max_rate < avctx->bit_rate) {
1459                     av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1460                            "bitrate (%"PRId64") must not be greater than "
1461                            "maxrate (%"PRId64").\n", avctx->bit_rate,
1462                            avctx->rc_max_rate);
1463                     return AVERROR(EINVAL);
1464                 }
1465                 rc_bits_per_second   = avctx->rc_max_rate;
1466                 rc_target_percentage = (avctx->bit_rate * 100) /
1467                                        avctx->rc_max_rate;
1468             } else {
1469                 // We only have a target bitrate, but this mode requires
1470                 // that a maximum rate be supplied as well.  Since the
1471                 // user does not want this to be a constraint, arbitrarily
1472                 // pick a maximum rate of double the target rate.
1473                 rc_bits_per_second   = 2 * avctx->bit_rate;
1474                 rc_target_percentage = 50;
1475             }
1476         } else {
1477             if (avctx->rc_max_rate > avctx->bit_rate) {
1478                 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1479                        "in %s RC mode.\n", rc_mode->name);
1480             }
1481             rc_bits_per_second   = avctx->bit_rate;
1482             rc_target_percentage = 100;
1483         }
1484     } else {
1485         rc_bits_per_second   = 0;
1486         rc_target_percentage = 100;
1487     }
1488
1489     if (rc_mode->quality) {
1490         if (ctx->explicit_qp) {
1491             rc_quality = ctx->explicit_qp;
1492         } else if (avctx->global_quality > 0) {
1493             rc_quality = avctx->global_quality;
1494         } else {
1495             rc_quality = ctx->codec->default_quality;
1496             av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1497                    "using default (%d).\n", rc_quality);
1498         }
1499     } else {
1500         rc_quality = 0;
1501     }
1502
1503     if (rc_mode->hrd) {
1504         if (avctx->rc_buffer_size)
1505             hrd_buffer_size = avctx->rc_buffer_size;
1506         else if (avctx->rc_max_rate > 0)
1507             hrd_buffer_size = avctx->rc_max_rate;
1508         else
1509             hrd_buffer_size = avctx->bit_rate;
1510         if (avctx->rc_initial_buffer_occupancy) {
1511             if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1512                 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1513                        "must have initial buffer size (%d) <= "
1514                        "buffer size (%"PRId64").\n",
1515                        avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1516                 return AVERROR(EINVAL);
1517             }
1518             hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1519         } else {
1520             hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1521         }
1522
1523         rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1524     } else {
1525         if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1526             av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1527                    "in %s RC mode.\n", rc_mode->name);
1528         }
1529
1530         hrd_buffer_size             = 0;
1531         hrd_initial_buffer_fullness = 0;
1532
1533         if (rc_mode->mode != RC_MODE_AVBR) {
1534             // Already set (with completely different meaning) for AVBR.
1535             rc_window_size = 1000;
1536         }
1537     }
1538
1539     if (rc_bits_per_second          > UINT32_MAX ||
1540         hrd_buffer_size             > UINT32_MAX ||
1541         hrd_initial_buffer_fullness > UINT32_MAX) {
1542         av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1543                "greater are not supported by VAAPI.\n");
1544         return AVERROR(EINVAL);
1545     }
1546
1547     ctx->rc_mode     = rc_mode;
1548     ctx->rc_quality  = rc_quality;
1549     ctx->va_rc_mode  = rc_mode->va_mode;
1550     ctx->va_bit_rate = rc_bits_per_second;
1551
1552     av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1553     if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1554         // This driver does not want the RC mode attribute to be set.
1555     } else {
1556         ctx->config_attributes[ctx->nb_config_attributes++] =
1557             (VAConfigAttrib) {
1558             .type  = VAConfigAttribRateControl,
1559             .value = ctx->va_rc_mode,
1560         };
1561     }
1562
1563     if (rc_mode->quality)
1564         av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1565
1566     if (rc_mode->va_mode != VA_RC_CQP) {
1567         if (rc_mode->mode == RC_MODE_AVBR) {
1568             av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1569                    "converging in %d frames with %d%% accuracy.\n",
1570                    rc_bits_per_second, rc_window_size,
1571                    rc_target_percentage);
1572         } else if (rc_mode->bitrate) {
1573             av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1574                    "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1575                    rc_bits_per_second, rc_window_size);
1576         }
1577
1578         ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1579         ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1580             .bits_per_second    = rc_bits_per_second,
1581             .target_percentage  = rc_target_percentage,
1582             .window_size        = rc_window_size,
1583             .initial_qp         = 0,
1584             .min_qp             = (avctx->qmin > 0 ? avctx->qmin : 0),
1585             .basic_unit_size    = 0,
1586 #if VA_CHECK_VERSION(1, 1, 0)
1587             .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1588             .max_qp             = (avctx->qmax > 0 ? avctx->qmax : 0),
1589 #endif
1590 #if VA_CHECK_VERSION(1, 3, 0)
1591             .quality_factor     = rc_quality,
1592 #endif
1593         };
1594         vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
1595                                       sizeof(ctx->rc_params));
1596     }
1597
1598     if (rc_mode->hrd) {
1599         av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1600                "initial fullness %"PRId64" bits.\n",
1601                hrd_buffer_size, hrd_initial_buffer_fullness);
1602
1603         ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1604         ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1605             .initial_buffer_fullness = hrd_initial_buffer_fullness,
1606             .buffer_size             = hrd_buffer_size,
1607         };
1608         vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
1609                                       sizeof(ctx->hrd_params));
1610     }
1611
1612     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1613         av_reduce(&fr_num, &fr_den,
1614                   avctx->framerate.num, avctx->framerate.den, 65535);
1615     else
1616         av_reduce(&fr_num, &fr_den,
1617                   avctx->time_base.den, avctx->time_base.num, 65535);
1618
1619     av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1620            fr_num, fr_den, (double)fr_num / fr_den);
1621
1622     ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1623     ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1624
1625 #if VA_CHECK_VERSION(0, 40, 0)
1626     vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
1627                                   sizeof(ctx->fr_params));
1628 #endif
1629
1630     return 0;
1631 }
1632
1633 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1634 {
1635     VAAPIEncodeContext *ctx = avctx->priv_data;
1636     VAStatus vas;
1637     VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1638     uint32_t ref_l0, ref_l1;
1639
1640     vas = vaGetConfigAttributes(ctx->hwctx->display,
1641                                 ctx->va_profile,
1642                                 ctx->va_entrypoint,
1643                                 &attr, 1);
1644     if (vas != VA_STATUS_SUCCESS) {
1645         av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1646                "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1647         return AVERROR_EXTERNAL;
1648     }
1649
1650     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1651         ref_l0 = ref_l1 = 0;
1652     } else {
1653         ref_l0 = attr.value       & 0xffff;
1654         ref_l1 = attr.value >> 16 & 0xffff;
1655     }
1656
1657     if (ctx->codec->flags & FLAG_INTRA_ONLY ||
1658         avctx->gop_size <= 1) {
1659         av_log(avctx, AV_LOG_VERBOSE, "Using intra frames only.\n");
1660         ctx->gop_size = 1;
1661     } else if (ref_l0 < 1) {
1662         av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1663                "reference frames.\n");
1664         return AVERROR(EINVAL);
1665     } else if (!(ctx->codec->flags & FLAG_B_PICTURES) ||
1666                ref_l1 < 1 || avctx->max_b_frames < 1) {
1667         av_log(avctx, AV_LOG_VERBOSE, "Using intra and P-frames "
1668                "(supported references: %d / %d).\n", ref_l0, ref_l1);
1669         ctx->gop_size = avctx->gop_size;
1670         ctx->p_per_i  = INT_MAX;
1671         ctx->b_per_p  = 0;
1672     } else {
1673         av_log(avctx, AV_LOG_VERBOSE, "Using intra, P- and B-frames "
1674                "(supported references: %d / %d).\n", ref_l0, ref_l1);
1675         ctx->gop_size = avctx->gop_size;
1676         ctx->p_per_i  = INT_MAX;
1677         ctx->b_per_p  = avctx->max_b_frames;
1678         if (ctx->codec->flags & FLAG_B_PICTURE_REFERENCES) {
1679             ctx->max_b_depth = FFMIN(ctx->desired_b_depth,
1680                                      av_log2(ctx->b_per_p) + 1);
1681         } else {
1682             ctx->max_b_depth = 1;
1683         }
1684     }
1685
1686     if (ctx->codec->flags & FLAG_NON_IDR_KEY_PICTURES) {
1687         ctx->closed_gop  = !!(avctx->flags & AV_CODEC_FLAG_CLOSED_GOP);
1688         ctx->gop_per_idr = ctx->idr_interval + 1;
1689     } else {
1690         ctx->closed_gop  = 1;
1691         ctx->gop_per_idr = 1;
1692     }
1693
1694     return 0;
1695 }
1696
1697 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1698 {
1699     VAAPIEncodeContext *ctx = avctx->priv_data;
1700     VAConfigAttrib attr[2] = { { VAConfigAttribEncMaxSlices },
1701                                { VAConfigAttribEncSliceStructure } };
1702     VAStatus vas;
1703     uint32_t max_slices, slice_structure;
1704     int req_slices;
1705
1706     if (!(ctx->codec->flags & FLAG_SLICE_CONTROL)) {
1707         if (avctx->slices > 0) {
1708             av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1709                    "but this codec does not support controlling slices.\n");
1710         }
1711         return 0;
1712     }
1713
1714     ctx->slice_block_rows = (avctx->height + ctx->slice_block_height - 1) /
1715                              ctx->slice_block_height;
1716     ctx->slice_block_cols = (avctx->width  + ctx->slice_block_width  - 1) /
1717                              ctx->slice_block_width;
1718
1719     if (avctx->slices <= 1) {
1720         ctx->nb_slices  = 1;
1721         ctx->slice_size = ctx->slice_block_rows;
1722         return 0;
1723     }
1724
1725     vas = vaGetConfigAttributes(ctx->hwctx->display,
1726                                 ctx->va_profile,
1727                                 ctx->va_entrypoint,
1728                                 attr, FF_ARRAY_ELEMS(attr));
1729     if (vas != VA_STATUS_SUCCESS) {
1730         av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1731                "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1732         return AVERROR_EXTERNAL;
1733     }
1734     max_slices      = attr[0].value;
1735     slice_structure = attr[1].value;
1736     if (max_slices      == VA_ATTRIB_NOT_SUPPORTED ||
1737         slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1738         av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1739                "pictures as multiple slices.\n.");
1740         return AVERROR(EINVAL);
1741     }
1742
1743     // For fixed-size slices currently we only support whole rows, making
1744     // rectangular slices.  This could be extended to arbitrary runs of
1745     // blocks, but since slices tend to be a conformance requirement and
1746     // most cases (such as broadcast or bluray) want rectangular slices
1747     // only it would need to be gated behind another option.
1748     if (avctx->slices > ctx->slice_block_rows) {
1749         av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1750                "configured number of slices (%d < %d); using "
1751                "maximum.\n", ctx->slice_block_rows, avctx->slices);
1752         req_slices = ctx->slice_block_rows;
1753     } else {
1754         req_slices = avctx->slices;
1755     }
1756     if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1757         slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1758         ctx->nb_slices  = req_slices;
1759         ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1760     } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1761         int k;
1762         for (k = 1;; k *= 2) {
1763             if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1764                 break;
1765         }
1766         ctx->nb_slices  = (ctx->slice_block_rows + k - 1) / k;
1767         ctx->slice_size = k;
1768 #if VA_CHECK_VERSION(1, 0, 0)
1769     } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1770         ctx->nb_slices  = ctx->slice_block_rows;
1771         ctx->slice_size = 1;
1772 #endif
1773     } else {
1774         av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1775                "slice structure modes (%#x).\n", slice_structure);
1776         return AVERROR(EINVAL);
1777     }
1778
1779     if (ctx->nb_slices > avctx->slices) {
1780         av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1781                "%d (from %d) due to driver constraints on slice "
1782                "structure.\n", ctx->nb_slices, avctx->slices);
1783     }
1784     if (ctx->nb_slices > max_slices) {
1785         av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1786                "encoding with %d slices (max %"PRIu32").\n",
1787                ctx->nb_slices, max_slices);
1788         return AVERROR(EINVAL);
1789     }
1790
1791     av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices "
1792            "(default size %d block rows).\n",
1793            ctx->nb_slices, ctx->slice_size);
1794     return 0;
1795 }
1796
1797 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1798 {
1799     VAAPIEncodeContext *ctx = avctx->priv_data;
1800     VAStatus vas;
1801     VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1802
1803     vas = vaGetConfigAttributes(ctx->hwctx->display,
1804                                 ctx->va_profile,
1805                                 ctx->va_entrypoint,
1806                                 &attr, 1);
1807     if (vas != VA_STATUS_SUCCESS) {
1808         av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1809                "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1810         return AVERROR_EXTERNAL;
1811     }
1812
1813     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1814         if (ctx->desired_packed_headers) {
1815             av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1816                    "packed headers (wanted %#x).\n",
1817                    ctx->desired_packed_headers);
1818         } else {
1819             av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1820                    "packed headers (none wanted).\n");
1821         }
1822         ctx->va_packed_headers = 0;
1823     } else {
1824         if (ctx->desired_packed_headers & ~attr.value) {
1825             av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1826                    "wanted packed headers (wanted %#x, found %#x).\n",
1827                    ctx->desired_packed_headers, attr.value);
1828         } else {
1829             av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1830                    "available (wanted %#x, found %#x).\n",
1831                    ctx->desired_packed_headers, attr.value);
1832         }
1833         ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1834     }
1835
1836     if (ctx->va_packed_headers) {
1837         ctx->config_attributes[ctx->nb_config_attributes++] =
1838             (VAConfigAttrib) {
1839             .type  = VAConfigAttribEncPackedHeaders,
1840             .value = ctx->va_packed_headers,
1841         };
1842     }
1843
1844     if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1845         !(ctx->va_packed_headers      & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1846          (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1847         av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1848                "sequence headers, but a global header is requested.\n");
1849         av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1850                "this may result in a stream which is not usable for some "
1851                "purposes (e.g. not muxable to some containers).\n");
1852     }
1853
1854     return 0;
1855 }
1856
1857 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1858 {
1859 #if VA_CHECK_VERSION(0, 36, 0)
1860     VAAPIEncodeContext *ctx = avctx->priv_data;
1861     VAStatus vas;
1862     VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1863     int quality = avctx->compression_level;
1864
1865     vas = vaGetConfigAttributes(ctx->hwctx->display,
1866                                 ctx->va_profile,
1867                                 ctx->va_entrypoint,
1868                                 &attr, 1);
1869     if (vas != VA_STATUS_SUCCESS) {
1870         av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1871                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1872         return AVERROR_EXTERNAL;
1873     }
1874
1875     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1876         if (quality != 0) {
1877             av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1878                    "supported: will use default quality level.\n");
1879         }
1880     } else {
1881         if (quality > attr.value) {
1882             av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1883                    "valid range is 0-%d, using %d.\n",
1884                    attr.value, attr.value);
1885             quality = attr.value;
1886         }
1887
1888         ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
1889         ctx->quality_params.quality.quality_level = quality;
1890
1891         vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
1892                                       sizeof(ctx->quality_params));
1893     }
1894 #else
1895     av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1896            "not supported with this VAAPI version.\n");
1897 #endif
1898
1899     return 0;
1900 }
1901
1902 static void vaapi_encode_free_output_buffer(void *opaque,
1903                                             uint8_t *data)
1904 {
1905     AVCodecContext   *avctx = opaque;
1906     VAAPIEncodeContext *ctx = avctx->priv_data;
1907     VABufferID buffer_id;
1908
1909     buffer_id = (VABufferID)(uintptr_t)data;
1910
1911     vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1912
1913     av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1914 }
1915
1916 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1917                                                      int size)
1918 {
1919     AVCodecContext   *avctx = opaque;
1920     VAAPIEncodeContext *ctx = avctx->priv_data;
1921     VABufferID buffer_id;
1922     VAStatus vas;
1923     AVBufferRef *ref;
1924
1925     // The output buffer size is fixed, so it needs to be large enough
1926     // to hold the largest possible compressed frame.  We assume here
1927     // that the uncompressed frame plus some header data is an upper
1928     // bound on that.
1929     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1930                          VAEncCodedBufferType,
1931                          3 * ctx->surface_width * ctx->surface_height +
1932                          (1 << 16), 1, 0, &buffer_id);
1933     if (vas != VA_STATUS_SUCCESS) {
1934         av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1935                "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1936         return NULL;
1937     }
1938
1939     av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1940
1941     ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1942                            sizeof(buffer_id),
1943                            &vaapi_encode_free_output_buffer,
1944                            avctx, AV_BUFFER_FLAG_READONLY);
1945     if (!ref) {
1946         vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1947         return NULL;
1948     }
1949
1950     return ref;
1951 }
1952
1953 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1954 {
1955     VAAPIEncodeContext *ctx = avctx->priv_data;
1956     AVVAAPIHWConfig *hwconfig = NULL;
1957     AVHWFramesConstraints *constraints = NULL;
1958     enum AVPixelFormat recon_format;
1959     int err, i;
1960
1961     hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1962     if (!hwconfig) {
1963         err = AVERROR(ENOMEM);
1964         goto fail;
1965     }
1966     hwconfig->config_id = ctx->va_config;
1967
1968     constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1969                                                       hwconfig);
1970     if (!constraints) {
1971         err = AVERROR(ENOMEM);
1972         goto fail;
1973     }
1974
1975     // Probably we can use the input surface format as the surface format
1976     // of the reconstructed frames.  If not, we just pick the first (only?)
1977     // format in the valid list and hope that it all works.
1978     recon_format = AV_PIX_FMT_NONE;
1979     if (constraints->valid_sw_formats) {
1980         for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1981             if (ctx->input_frames->sw_format ==
1982                 constraints->valid_sw_formats[i]) {
1983                 recon_format = ctx->input_frames->sw_format;
1984                 break;
1985             }
1986         }
1987         if (recon_format == AV_PIX_FMT_NONE) {
1988             // No match.  Just use the first in the supported list and
1989             // hope for the best.
1990             recon_format = constraints->valid_sw_formats[0];
1991         }
1992     } else {
1993         // No idea what to use; copy input format.
1994         recon_format = ctx->input_frames->sw_format;
1995     }
1996     av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1997            "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1998
1999     if (ctx->surface_width  < constraints->min_width  ||
2000         ctx->surface_height < constraints->min_height ||
2001         ctx->surface_width  > constraints->max_width ||
2002         ctx->surface_height > constraints->max_height) {
2003         av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
2004                "size %dx%d (constraints: width %d-%d height %d-%d).\n",
2005                ctx->surface_width, ctx->surface_height,
2006                constraints->min_width,  constraints->max_width,
2007                constraints->min_height, constraints->max_height);
2008         err = AVERROR(EINVAL);
2009         goto fail;
2010     }
2011
2012     av_freep(&hwconfig);
2013     av_hwframe_constraints_free(&constraints);
2014
2015     ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
2016     if (!ctx->recon_frames_ref) {
2017         err = AVERROR(ENOMEM);
2018         goto fail;
2019     }
2020     ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
2021
2022     ctx->recon_frames->format    = AV_PIX_FMT_VAAPI;
2023     ctx->recon_frames->sw_format = recon_format;
2024     ctx->recon_frames->width     = ctx->surface_width;
2025     ctx->recon_frames->height    = ctx->surface_height;
2026
2027     err = av_hwframe_ctx_init(ctx->recon_frames_ref);
2028     if (err < 0) {
2029         av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2030                "frame context: %d.\n", err);
2031         goto fail;
2032     }
2033
2034     err = 0;
2035   fail:
2036     av_freep(&hwconfig);
2037     av_hwframe_constraints_free(&constraints);
2038     return err;
2039 }
2040
2041 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2042 {
2043     VAAPIEncodeContext *ctx = avctx->priv_data;
2044     AVVAAPIFramesContext *recon_hwctx = NULL;
2045     VAStatus vas;
2046     int err;
2047
2048     if (!avctx->hw_frames_ctx) {
2049         av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
2050                "required to associate the encoding device.\n");
2051         return AVERROR(EINVAL);
2052     }
2053
2054     ctx->va_config  = VA_INVALID_ID;
2055     ctx->va_context = VA_INVALID_ID;
2056
2057     ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
2058     if (!ctx->input_frames_ref) {
2059         err = AVERROR(ENOMEM);
2060         goto fail;
2061     }
2062     ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
2063
2064     ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
2065     if (!ctx->device_ref) {
2066         err = AVERROR(ENOMEM);
2067         goto fail;
2068     }
2069     ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
2070     ctx->hwctx = ctx->device->hwctx;
2071
2072     err = vaapi_encode_profile_entrypoint(avctx);
2073     if (err < 0)
2074         goto fail;
2075
2076     err = vaapi_encode_init_rate_control(avctx);
2077     if (err < 0)
2078         goto fail;
2079
2080     err = vaapi_encode_init_gop_structure(avctx);
2081     if (err < 0)
2082         goto fail;
2083
2084     err = vaapi_encode_init_slice_structure(avctx);
2085     if (err < 0)
2086         goto fail;
2087
2088     err = vaapi_encode_init_packed_headers(avctx);
2089     if (err < 0)
2090         goto fail;
2091
2092     if (avctx->compression_level >= 0) {
2093         err = vaapi_encode_init_quality(avctx);
2094         if (err < 0)
2095             goto fail;
2096     }
2097
2098     vas = vaCreateConfig(ctx->hwctx->display,
2099                          ctx->va_profile, ctx->va_entrypoint,
2100                          ctx->config_attributes, ctx->nb_config_attributes,
2101                          &ctx->va_config);
2102     if (vas != VA_STATUS_SUCCESS) {
2103         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2104                "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2105         err = AVERROR(EIO);
2106         goto fail;
2107     }
2108
2109     err = vaapi_encode_create_recon_frames(avctx);
2110     if (err < 0)
2111         goto fail;
2112
2113     recon_hwctx = ctx->recon_frames->hwctx;
2114     vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2115                           ctx->surface_width, ctx->surface_height,
2116                           VA_PROGRESSIVE,
2117                           recon_hwctx->surface_ids,
2118                           recon_hwctx->nb_surfaces,
2119                           &ctx->va_context);
2120     if (vas != VA_STATUS_SUCCESS) {
2121         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2122                "context: %d (%s).\n", vas, vaErrorStr(vas));
2123         err = AVERROR(EIO);
2124         goto fail;
2125     }
2126
2127     ctx->output_buffer_pool =
2128         av_buffer_pool_init2(sizeof(VABufferID), avctx,
2129                              &vaapi_encode_alloc_output_buffer, NULL);
2130     if (!ctx->output_buffer_pool) {
2131         err = AVERROR(ENOMEM);
2132         goto fail;
2133     }
2134
2135     if (ctx->codec->configure) {
2136         err = ctx->codec->configure(avctx);
2137         if (err < 0)
2138             goto fail;
2139     }
2140
2141     ctx->output_delay = ctx->b_per_p;
2142     ctx->decode_delay = ctx->max_b_depth;
2143
2144     if (ctx->codec->sequence_params_size > 0) {
2145         ctx->codec_sequence_params =
2146             av_mallocz(ctx->codec->sequence_params_size);
2147         if (!ctx->codec_sequence_params) {
2148             err = AVERROR(ENOMEM);
2149             goto fail;
2150         }
2151     }
2152     if (ctx->codec->picture_params_size > 0) {
2153         ctx->codec_picture_params =
2154             av_mallocz(ctx->codec->picture_params_size);
2155         if (!ctx->codec_picture_params) {
2156             err = AVERROR(ENOMEM);
2157             goto fail;
2158         }
2159     }
2160
2161     if (ctx->codec->init_sequence_params) {
2162         err = ctx->codec->init_sequence_params(avctx);
2163         if (err < 0) {
2164             av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2165                    "failed: %d.\n", err);
2166             goto fail;
2167         }
2168     }
2169
2170     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2171         ctx->codec->write_sequence_header &&
2172         avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2173         char data[MAX_PARAM_BUFFER_SIZE];
2174         size_t bit_len = 8 * sizeof(data);
2175
2176         err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2177         if (err < 0) {
2178             av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2179                    "for extradata: %d.\n", err);
2180             goto fail;
2181         } else {
2182             avctx->extradata_size = (bit_len + 7) / 8;
2183             avctx->extradata = av_mallocz(avctx->extradata_size +
2184                                           AV_INPUT_BUFFER_PADDING_SIZE);
2185             if (!avctx->extradata) {
2186                 err = AVERROR(ENOMEM);
2187                 goto fail;
2188             }
2189             memcpy(avctx->extradata, data, avctx->extradata_size);
2190         }
2191     }
2192
2193     return 0;
2194
2195 fail:
2196     ff_vaapi_encode_close(avctx);
2197     return err;
2198 }
2199
2200 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2201 {
2202     VAAPIEncodeContext *ctx = avctx->priv_data;
2203     VAAPIEncodePicture *pic, *next;
2204
2205     for (pic = ctx->pic_start; pic; pic = next) {
2206         next = pic->next;
2207         vaapi_encode_free(avctx, pic);
2208     }
2209
2210     av_buffer_pool_uninit(&ctx->output_buffer_pool);
2211
2212     if (ctx->va_context != VA_INVALID_ID) {
2213         vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2214         ctx->va_context = VA_INVALID_ID;
2215     }
2216
2217     if (ctx->va_config != VA_INVALID_ID) {
2218         vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2219         ctx->va_config = VA_INVALID_ID;
2220     }
2221
2222     av_freep(&ctx->codec_sequence_params);
2223     av_freep(&ctx->codec_picture_params);
2224
2225     av_buffer_unref(&ctx->recon_frames_ref);
2226     av_buffer_unref(&ctx->input_frames_ref);
2227     av_buffer_unref(&ctx->device_ref);
2228
2229     return 0;
2230 }