]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_encode.c
nvenc: Allow different const qps for I, P and B frames
[ffmpeg] / libavcodec / vaapi_encode.c
1 /*
2  * This file is part of Libav.
3  *
4  * Libav 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  * Libav 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 Libav; 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     VAEncPackedHeaderParameterBuffer params = {
40         .type = type,
41         .bit_length = bit_len,
42         .has_emulation_bytes = 1,
43     };
44
45     av_assert0(pic->nb_param_buffers + 2 <= MAX_PARAM_BUFFERS);
46
47     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
48                          VAEncPackedHeaderParameterBufferType,
49                          sizeof(params), 1, &params, &param_buffer);
50     if (vas != VA_STATUS_SUCCESS) {
51         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
52                "for packed header (type %d): %d (%s).\n",
53                type, vas, vaErrorStr(vas));
54         return AVERROR(EIO);
55     }
56     pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
57
58     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
59                          VAEncPackedHeaderDataBufferType,
60                          (bit_len + 7) / 8, 1, data, &data_buffer);
61     if (vas != VA_STATUS_SUCCESS) {
62         av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
63                "for packed header (type %d): %d (%s).\n",
64                type, vas, vaErrorStr(vas));
65         return AVERROR(EIO);
66     }
67     pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
68
69     av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
70            "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
71     return 0;
72 }
73
74 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
75                                           VAAPIEncodePicture *pic,
76                                           int type, char *data, size_t len)
77 {
78     VAAPIEncodeContext *ctx = avctx->priv_data;
79     VAStatus vas;
80     VABufferID buffer;
81
82     av_assert0(pic->nb_param_buffers + 1 <= MAX_PARAM_BUFFERS);
83
84     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
85                          type, len, 1, data, &buffer);
86     if (vas != VA_STATUS_SUCCESS) {
87         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
88                "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
89         return AVERROR(EIO);
90     }
91     pic->param_buffers[pic->nb_param_buffers++] = buffer;
92
93     av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
94            type, buffer);
95     return 0;
96 }
97
98 static int vaapi_encode_wait(AVCodecContext *avctx,
99                              VAAPIEncodePicture *pic)
100 {
101     VAAPIEncodeContext *ctx = avctx->priv_data;
102     VAStatus vas;
103
104     av_assert0(pic->encode_issued);
105
106     if (pic->encode_complete) {
107         // Already waited for this picture.
108         return 0;
109     }
110
111     av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
112            "(input surface %#x).\n", pic->display_order,
113            pic->encode_order, pic->input_surface);
114
115     vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
116     if (vas != VA_STATUS_SUCCESS) {
117         av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
118                "%d (%s).\n", vas, vaErrorStr(vas));
119         return AVERROR(EIO);
120     }
121
122     // Input is definitely finished with now.
123     av_frame_free(&pic->input_image);
124
125     pic->encode_complete = 1;
126     return 0;
127 }
128
129 static int vaapi_encode_issue(AVCodecContext *avctx,
130                               VAAPIEncodePicture *pic)
131 {
132     VAAPIEncodeContext *ctx = avctx->priv_data;
133     VAAPIEncodeSlice *slice;
134     VAStatus vas;
135     int err, i;
136     char data[MAX_PARAM_BUFFER_SIZE];
137     size_t bit_len;
138
139     av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
140            "as type %s.\n", pic->display_order, pic->encode_order,
141            picture_type_name[pic->type]);
142     if (pic->nb_refs == 0) {
143         av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
144     } else {
145         av_log(avctx, AV_LOG_DEBUG, "Refers to:");
146         for (i = 0; i < pic->nb_refs; i++) {
147             av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
148                    pic->refs[i]->display_order, pic->refs[i]->encode_order);
149         }
150         av_log(avctx, AV_LOG_DEBUG, ".\n");
151     }
152
153     av_assert0(pic->input_available && !pic->encode_issued);
154     for (i = 0; i < pic->nb_refs; i++) {
155         av_assert0(pic->refs[i]);
156         // If we are serialised then the references must have already
157         // completed.  If not, they must have been issued but need not
158         // have completed yet.
159         if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
160             av_assert0(pic->refs[i]->encode_complete);
161         else
162             av_assert0(pic->refs[i]->encode_issued);
163     }
164
165     av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
166
167     pic->recon_image = av_frame_alloc();
168     if (!pic->recon_image) {
169         err = AVERROR(ENOMEM);
170         goto fail;
171     }
172
173     err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
174     if (err < 0) {
175         err = AVERROR(ENOMEM);
176         goto fail;
177     }
178     pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
179     av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
180
181     pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
182     if (!pic->output_buffer_ref) {
183         err = AVERROR(ENOMEM);
184         goto fail;
185     }
186     pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
187     av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
188            pic->output_buffer);
189
190     if (ctx->codec->picture_params_size > 0) {
191         pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
192         if (!pic->codec_picture_params)
193             goto fail;
194         memcpy(pic->codec_picture_params, ctx->codec_picture_params,
195                ctx->codec->picture_params_size);
196     } else {
197         av_assert0(!ctx->codec_picture_params);
198     }
199
200     pic->nb_param_buffers = 0;
201
202     if (pic->encode_order == 0) {
203         // Global parameter buffers are set on the first picture only.
204
205         for (i = 0; i < ctx->nb_global_params; i++) {
206             err = vaapi_encode_make_param_buffer(avctx, pic,
207                                                  VAEncMiscParameterBufferType,
208                                                  (char*)ctx->global_params[i],
209                                                  ctx->global_params_size[i]);
210             if (err < 0)
211                 goto fail;
212         }
213     }
214
215     if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
216         err = vaapi_encode_make_param_buffer(avctx, pic,
217                                              VAEncSequenceParameterBufferType,
218                                              ctx->codec_sequence_params,
219                                              ctx->codec->sequence_params_size);
220         if (err < 0)
221             goto fail;
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     av_assert0(pic->nb_slices <= MAX_PICTURE_SLICES);
317     for (i = 0; i < pic->nb_slices; i++) {
318         slice = av_mallocz(sizeof(*slice));
319         if (!slice) {
320             err = AVERROR(ENOMEM);
321             goto fail;
322         }
323         slice->index = i;
324         pic->slices[i] = slice;
325
326         if (ctx->codec->slice_params_size > 0) {
327             slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
328             if (!slice->codec_slice_params) {
329                 err = AVERROR(ENOMEM);
330                 goto fail;
331             }
332         }
333
334         if (ctx->codec->init_slice_params) {
335             err = ctx->codec->init_slice_params(avctx, pic, slice);
336             if (err < 0) {
337                 av_log(avctx, AV_LOG_ERROR, "Failed to initalise slice "
338                        "parameters: %d.\n", err);
339                 goto fail;
340             }
341         }
342
343         if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
344             ctx->codec->write_slice_header) {
345             bit_len = 8 * sizeof(data);
346             err = ctx->codec->write_slice_header(avctx, pic, slice,
347                                                  data, &bit_len);
348             if (err < 0) {
349                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
350                        "header: %d.\n", err);
351                 goto fail;
352             }
353             err = vaapi_encode_make_packed_header(avctx, pic,
354                                                   ctx->codec->slice_header_type,
355                                                   data, bit_len);
356             if (err < 0)
357                 goto fail;
358         }
359
360         if (ctx->codec->init_slice_params) {
361             err = vaapi_encode_make_param_buffer(avctx, pic,
362                                                  VAEncSliceParameterBufferType,
363                                                  slice->codec_slice_params,
364                                                  ctx->codec->slice_params_size);
365             if (err < 0)
366                 goto fail;
367         }
368     }
369
370     vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
371                          pic->input_surface);
372     if (vas != VA_STATUS_SUCCESS) {
373         av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
374                "%d (%s).\n", vas, vaErrorStr(vas));
375         err = AVERROR(EIO);
376         goto fail_with_picture;
377     }
378
379     vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
380                           pic->param_buffers, pic->nb_param_buffers);
381     if (vas != VA_STATUS_SUCCESS) {
382         av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
383                "%d (%s).\n", vas, vaErrorStr(vas));
384         err = AVERROR(EIO);
385         goto fail_with_picture;
386     }
387
388     vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
389     if (vas != VA_STATUS_SUCCESS) {
390         av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
391                "%d (%s).\n", vas, vaErrorStr(vas));
392         err = AVERROR(EIO);
393         // vaRenderPicture() has been called here, so we should not destroy
394         // the parameter buffers unless separate destruction is required.
395         if (ctx->hwctx->driver_quirks &
396             AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
397             goto fail;
398         else
399             goto fail_at_end;
400     }
401
402     if (ctx->hwctx->driver_quirks &
403         AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
404         for (i = 0; i < pic->nb_param_buffers; i++) {
405             vas = vaDestroyBuffer(ctx->hwctx->display,
406                                   pic->param_buffers[i]);
407             if (vas != VA_STATUS_SUCCESS) {
408                 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
409                        "param buffer %#x: %d (%s).\n",
410                        pic->param_buffers[i], vas, vaErrorStr(vas));
411                 // And ignore.
412             }
413         }
414     }
415
416     pic->encode_issued = 1;
417
418     if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
419         return vaapi_encode_wait(avctx, pic);
420     else
421         return 0;
422
423 fail_with_picture:
424     vaEndPicture(ctx->hwctx->display, ctx->va_context);
425 fail:
426     for(i = 0; i < pic->nb_param_buffers; i++)
427         vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
428 fail_at_end:
429     av_freep(&pic->codec_picture_params);
430     av_frame_free(&pic->recon_image);
431     av_buffer_unref(&pic->output_buffer_ref);
432     pic->output_buffer = VA_INVALID_ID;
433     return err;
434 }
435
436 static int vaapi_encode_output(AVCodecContext *avctx,
437                                VAAPIEncodePicture *pic, AVPacket *pkt)
438 {
439     VAAPIEncodeContext *ctx = avctx->priv_data;
440     VACodedBufferSegment *buf_list, *buf;
441     VAStatus vas;
442     int err;
443
444     err = vaapi_encode_wait(avctx, pic);
445     if (err < 0)
446         return err;
447
448     buf_list = NULL;
449     vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
450                       (void**)&buf_list);
451     if (vas != VA_STATUS_SUCCESS) {
452         av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
453                "%d (%s).\n", vas, vaErrorStr(vas));
454         err = AVERROR(EIO);
455         goto fail;
456     }
457
458     for (buf = buf_list; buf; buf = buf->next) {
459         av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
460                "(status %08x).\n", buf->size, buf->status);
461
462         err = av_new_packet(pkt, buf->size);
463         if (err < 0)
464             goto fail_mapped;
465
466         memcpy(pkt->data, buf->buf, buf->size);
467     }
468
469     if (pic->type == PICTURE_TYPE_IDR)
470         pkt->flags |= AV_PKT_FLAG_KEY;
471
472     pkt->pts = pic->pts;
473
474     vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
475     if (vas != VA_STATUS_SUCCESS) {
476         av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
477                "%d (%s).\n", vas, vaErrorStr(vas));
478         err = AVERROR(EIO);
479         goto fail;
480     }
481
482     av_buffer_unref(&pic->output_buffer_ref);
483     pic->output_buffer = VA_INVALID_ID;
484
485     av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
486            pic->display_order, pic->encode_order);
487     return 0;
488
489 fail_mapped:
490     vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
491 fail:
492     av_buffer_unref(&pic->output_buffer_ref);
493     pic->output_buffer = VA_INVALID_ID;
494     return err;
495 }
496
497 static int vaapi_encode_discard(AVCodecContext *avctx,
498                                 VAAPIEncodePicture *pic)
499 {
500     vaapi_encode_wait(avctx, pic);
501
502     if (pic->output_buffer_ref) {
503         av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
504                "%"PRId64"/%"PRId64".\n",
505                pic->display_order, pic->encode_order);
506
507         av_buffer_unref(&pic->output_buffer_ref);
508         pic->output_buffer = VA_INVALID_ID;
509     }
510
511     return 0;
512 }
513
514 static VAAPIEncodePicture *vaapi_encode_alloc(void)
515 {
516     VAAPIEncodePicture *pic;
517
518     pic = av_mallocz(sizeof(*pic));
519     if (!pic)
520         return NULL;
521
522     pic->input_surface = VA_INVALID_ID;
523     pic->recon_surface = VA_INVALID_ID;
524     pic->output_buffer = VA_INVALID_ID;
525
526     return pic;
527 }
528
529 static int vaapi_encode_free(AVCodecContext *avctx,
530                              VAAPIEncodePicture *pic)
531 {
532     int i;
533
534     if (pic->encode_issued)
535         vaapi_encode_discard(avctx, pic);
536
537     for (i = 0; i < pic->nb_slices; i++) {
538         av_freep(&pic->slices[i]->priv_data);
539         av_freep(&pic->slices[i]->codec_slice_params);
540         av_freep(&pic->slices[i]);
541     }
542     av_freep(&pic->codec_picture_params);
543
544     av_frame_free(&pic->input_image);
545     av_frame_free(&pic->recon_image);
546
547     // Output buffer should already be destroyed.
548     av_assert0(pic->output_buffer == VA_INVALID_ID);
549
550     av_freep(&pic->priv_data);
551     av_freep(&pic->codec_picture_params);
552
553     av_free(pic);
554
555     return 0;
556 }
557
558 static int vaapi_encode_step(AVCodecContext *avctx,
559                              VAAPIEncodePicture *target)
560 {
561     VAAPIEncodeContext *ctx = avctx->priv_data;
562     VAAPIEncodePicture *pic;
563     int i, err;
564
565     if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
566         ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
567         // These two modes are equivalent, except that we wait for
568         // immediate completion on each operation if serialised.
569
570         if (!target) {
571             // No target, nothing to do yet.
572             return 0;
573         }
574
575         if (target->encode_complete) {
576             // Already done.
577             return 0;
578         }
579
580         pic = target;
581         for (i = 0; i < pic->nb_refs; i++) {
582             if (!pic->refs[i]->encode_complete) {
583                 err = vaapi_encode_step(avctx, pic->refs[i]);
584                 if (err < 0)
585                     return err;
586             }
587         }
588
589         err = vaapi_encode_issue(avctx, pic);
590         if (err < 0)
591             return err;
592
593     } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
594         int activity;
595
596         // Run through the list of all available pictures repeatedly
597         // and issue the first one found which has all dependencies
598         // available (including previously-issued but not necessarily
599         // completed pictures).
600         do {
601             activity = 0;
602             for (pic = ctx->pic_start; pic; pic = pic->next) {
603                 if (!pic->input_available || pic->encode_issued)
604                     continue;
605                 for (i = 0; i < pic->nb_refs; i++) {
606                     if (!pic->refs[i]->encode_issued)
607                         break;
608                 }
609                 if (i < pic->nb_refs)
610                     continue;
611                 err = vaapi_encode_issue(avctx, pic);
612                 if (err < 0)
613                     return err;
614                 activity = 1;
615                 // Start again from the beginning of the list,
616                 // because issuing this picture may have satisfied
617                 // forward dependencies of earlier ones.
618                 break;
619             }
620         } while(activity);
621
622         // If we had a defined target for this step then it will
623         // always have been issued by now.
624         if (target) {
625             av_assert0(target->encode_issued && "broken dependencies?");
626         }
627
628     } else {
629         av_assert0(0);
630     }
631
632     return 0;
633 }
634
635 static int vaapi_encode_get_next(AVCodecContext *avctx,
636                                  VAAPIEncodePicture **pic_out)
637 {
638     VAAPIEncodeContext *ctx = avctx->priv_data;
639     VAAPIEncodePicture *start, *end, *pic;
640     int i;
641
642     for (pic = ctx->pic_start; pic; pic = pic->next) {
643         if (pic->next)
644             av_assert0(pic->display_order + 1 == pic->next->display_order);
645         if (pic->display_order == ctx->input_order) {
646             *pic_out = pic;
647             return 0;
648         }
649     }
650
651     pic = vaapi_encode_alloc();
652     if (!pic)
653         return AVERROR(ENOMEM);
654
655     if (ctx->input_order == 0 || ctx->force_idr ||
656         ctx->gop_counter >= avctx->gop_size) {
657         pic->type = PICTURE_TYPE_IDR;
658         ctx->force_idr = 0;
659         ctx->gop_counter = 1;
660         ctx->p_counter = 0;
661     } else if (ctx->p_counter >= ctx->p_per_i) {
662         pic->type = PICTURE_TYPE_I;
663         ++ctx->gop_counter;
664         ctx->p_counter = 0;
665     } else {
666         pic->type = PICTURE_TYPE_P;
667         pic->refs[0] = ctx->pic_end;
668         pic->nb_refs = 1;
669         ++ctx->gop_counter;
670         ++ctx->p_counter;
671     }
672     start = end = pic;
673
674     if (pic->type != PICTURE_TYPE_IDR) {
675         // If that was not an IDR frame, add B-frames display-before and
676         // encode-after it, but not exceeding the GOP size.
677
678         for (i = 0; i < ctx->b_per_p &&
679              ctx->gop_counter < avctx->gop_size; i++) {
680             pic = vaapi_encode_alloc();
681             if (!pic)
682                 goto fail;
683
684             pic->type = PICTURE_TYPE_B;
685             pic->refs[0] = ctx->pic_end;
686             pic->refs[1] = end;
687             pic->nb_refs = 2;
688
689             pic->next = start;
690             pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
691             pic->encode_order  = pic->display_order + 1;
692             start = pic;
693
694             ++ctx->gop_counter;
695         }
696     }
697
698     if (ctx->input_order == 0) {
699         pic->display_order = 0;
700         pic->encode_order  = 0;
701
702         ctx->pic_start = ctx->pic_end = pic;
703
704     } else {
705         for (i = 0, pic = start; pic; i++, pic = pic->next) {
706             pic->display_order = ctx->input_order + i;
707             if (end->type == PICTURE_TYPE_IDR)
708                 pic->encode_order = ctx->input_order + i;
709             else if (pic == end)
710                 pic->encode_order = ctx->input_order;
711             else
712                 pic->encode_order = ctx->input_order + i + 1;
713         }
714
715         av_assert0(ctx->pic_end);
716         ctx->pic_end->next = start;
717         ctx->pic_end = end;
718     }
719     *pic_out = start;
720
721     av_log(avctx, AV_LOG_DEBUG, "Pictures:");
722     for (pic = ctx->pic_start; pic; pic = pic->next) {
723         av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
724                picture_type_name[pic->type],
725                pic->display_order, pic->encode_order);
726     }
727     av_log(avctx, AV_LOG_DEBUG, "\n");
728
729     return 0;
730
731 fail:
732     while (start) {
733         pic = start->next;
734         vaapi_encode_free(avctx, start);
735         start = pic;
736     }
737     return AVERROR(ENOMEM);
738 }
739
740 static int vaapi_encode_truncate_gop(AVCodecContext *avctx)
741 {
742     VAAPIEncodeContext *ctx = avctx->priv_data;
743     VAAPIEncodePicture *pic, *last_pic, *next;
744
745     // Find the last picture we actually have input for.
746     for (pic = ctx->pic_start; pic; pic = pic->next) {
747         if (!pic->input_available)
748             break;
749         last_pic = pic;
750     }
751
752     if (pic) {
753         av_assert0(last_pic);
754
755         if (last_pic->type == PICTURE_TYPE_B) {
756             // Some fixing up is required.  Change the type of this
757             // picture to P, then modify preceding B references which
758             // point beyond it to point at it instead.
759
760             last_pic->type = PICTURE_TYPE_P;
761             last_pic->encode_order = last_pic->refs[1]->encode_order;
762
763             for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
764                 if (pic->type == PICTURE_TYPE_B &&
765                     pic->refs[1] == last_pic->refs[1])
766                     pic->refs[1] = last_pic;
767             }
768
769             last_pic->nb_refs = 1;
770             last_pic->refs[1] = NULL;
771         } else {
772             // We can use the current structure (no references point
773             // beyond the end), but there are unused pics to discard.
774         }
775
776         // Discard all following pics, they will never be used.
777         for (pic = last_pic->next; pic; pic = next) {
778             next = pic->next;
779             vaapi_encode_free(avctx, pic);
780         }
781
782         last_pic->next = NULL;
783         ctx->pic_end = last_pic;
784
785     } else {
786         // Input is available for all pictures, so we don't need to
787         // mangle anything.
788     }
789
790     av_log(avctx, AV_LOG_DEBUG, "Pictures ending truncated GOP:");
791     for (pic = ctx->pic_start; pic; pic = pic->next) {
792         av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
793                picture_type_name[pic->type],
794                pic->display_order, pic->encode_order);
795     }
796     av_log(avctx, AV_LOG_DEBUG, "\n");
797
798     return 0;
799 }
800
801 static int vaapi_encode_clear_old(AVCodecContext *avctx)
802 {
803     VAAPIEncodeContext *ctx = avctx->priv_data;
804     VAAPIEncodePicture *pic, *old;
805     int i;
806
807     while (ctx->pic_start != ctx->pic_end) {
808         old = ctx->pic_start;
809         if (old->encode_order > ctx->output_order)
810             break;
811
812         for (pic = old->next; pic; pic = pic->next) {
813             if (pic->encode_complete)
814                 continue;
815             for (i = 0; i < pic->nb_refs; i++) {
816                 if (pic->refs[i] == old) {
817                     // We still need this picture because it's referred to
818                     // directly by a later one, so it and all following
819                     // pictures have to stay.
820                     return 0;
821                 }
822             }
823         }
824
825         pic = ctx->pic_start;
826         ctx->pic_start = pic->next;
827         vaapi_encode_free(avctx, pic);
828     }
829
830     return 0;
831 }
832
833 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
834                      const AVFrame *input_image, int *got_packet)
835 {
836     VAAPIEncodeContext *ctx = avctx->priv_data;
837     VAAPIEncodePicture *pic;
838     int err;
839
840     if (input_image) {
841         av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
842                input_image->width, input_image->height, input_image->pts);
843
844         if (input_image->pict_type == AV_PICTURE_TYPE_I) {
845             err = vaapi_encode_truncate_gop(avctx);
846             if (err < 0)
847                 goto fail;
848             ctx->force_idr = 1;
849         }
850
851         err = vaapi_encode_get_next(avctx, &pic);
852         if (err) {
853             av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
854             return err;
855         }
856
857         pic->input_image = av_frame_alloc();
858         if (!pic->input_image) {
859             err = AVERROR(ENOMEM);
860             goto fail;
861         }
862         err = av_frame_ref(pic->input_image, input_image);
863         if (err < 0)
864             goto fail;
865         pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
866         pic->pts = input_image->pts;
867
868         if (ctx->input_order == 0)
869             ctx->first_pts = pic->pts;
870         if (ctx->input_order == ctx->decode_delay)
871             ctx->dts_pts_diff = pic->pts - ctx->first_pts;
872         if (ctx->output_delay > 0)
873             ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
874
875         pic->input_available = 1;
876
877     } else {
878         if (!ctx->end_of_stream) {
879             err = vaapi_encode_truncate_gop(avctx);
880             if (err < 0)
881                 goto fail;
882             ctx->end_of_stream = 1;
883         }
884     }
885
886     ++ctx->input_order;
887     ++ctx->output_order;
888     av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
889
890     for (pic = ctx->pic_start; pic; pic = pic->next)
891         if (pic->encode_order == ctx->output_order)
892             break;
893
894     // pic can be null here if we don't have a specific target in this
895     // iteration.  We might still issue encodes if things can be overlapped,
896     // even though we don't intend to output anything.
897
898     err = vaapi_encode_step(avctx, pic);
899     if (err < 0) {
900         av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
901         goto fail;
902     }
903
904     if (!pic) {
905         *got_packet = 0;
906     } else {
907         err = vaapi_encode_output(avctx, pic, pkt);
908         if (err < 0) {
909             av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
910             goto fail;
911         }
912
913         if (ctx->output_delay == 0) {
914             pkt->dts = pkt->pts;
915         } else if (ctx->output_order < ctx->decode_delay) {
916             if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
917                 pkt->dts = INT64_MIN;
918             else
919                 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
920         } else {
921             pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
922                                     (3 * ctx->output_delay)];
923         }
924
925         *got_packet = 1;
926     }
927
928     err = vaapi_encode_clear_old(avctx);
929     if (err < 0) {
930         av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
931         goto fail;
932     }
933
934     return 0;
935
936 fail:
937     // Unclear what to clean up on failure.  There are probably some things we
938     // could do usefully clean up here, but for now just leave them for uninit()
939     // to do instead.
940     return err;
941 }
942
943 static av_cold int vaapi_encode_config_attributes(AVCodecContext *avctx)
944 {
945     VAAPIEncodeContext *ctx = avctx->priv_data;
946     VAStatus vas;
947     int i, n, err;
948     VAProfile    *profiles    = NULL;
949     VAEntrypoint *entrypoints = NULL;
950     VAConfigAttrib attr[] = {
951         { VAConfigAttribRTFormat         },
952         { VAConfigAttribRateControl      },
953         { VAConfigAttribEncMaxRefFrames  },
954         { VAConfigAttribEncPackedHeaders },
955     };
956
957     n = vaMaxNumProfiles(ctx->hwctx->display);
958     profiles = av_malloc_array(n, sizeof(VAProfile));
959     if (!profiles) {
960         err = AVERROR(ENOMEM);
961         goto fail;
962     }
963     vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);
964     if (vas != VA_STATUS_SUCCESS) {
965         av_log(ctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
966                vas, vaErrorStr(vas));
967         err = AVERROR(ENOSYS);
968         goto fail;
969     }
970     for (i = 0; i < n; i++) {
971         if (profiles[i] == ctx->va_profile)
972             break;
973     }
974     if (i >= n) {
975         av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",
976                ctx->va_profile);
977         err = AVERROR(ENOSYS);
978         goto fail;
979     }
980
981     n = vaMaxNumEntrypoints(ctx->hwctx->display);
982     entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
983     if (!entrypoints) {
984         err = AVERROR(ENOMEM);
985         goto fail;
986     }
987     vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
988                                    entrypoints, &n);
989     if (vas != VA_STATUS_SUCCESS) {
990         av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "
991                "profile %u: %d (%s).\n", ctx->va_profile,
992                vas, vaErrorStr(vas));
993         err = AVERROR(ENOSYS);
994         goto fail;
995     }
996     for (i = 0; i < n; i++) {
997         if (entrypoints[i] == ctx->va_entrypoint)
998             break;
999     }
1000     if (i >= n) {
1001         av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "
1002                "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);
1003         err = AVERROR(ENOSYS);
1004         goto fail;
1005     }
1006
1007     vas = vaGetConfigAttributes(ctx->hwctx->display,
1008                                 ctx->va_profile, ctx->va_entrypoint,
1009                                 attr, FF_ARRAY_ELEMS(attr));
1010     if (vas != VA_STATUS_SUCCESS) {
1011         av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "
1012                "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1013         return AVERROR(EINVAL);
1014     }
1015
1016     for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {
1017         if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {
1018             // Unfortunately we have to treat this as "don't know" and hope
1019             // for the best, because the Intel MJPEG encoder returns this
1020             // for all the interesting attributes.
1021             continue;
1022         }
1023         switch (attr[i].type) {
1024         case VAConfigAttribRTFormat:
1025             if (!(ctx->va_rt_format & attr[i].value)) {
1026                 av_log(avctx, AV_LOG_ERROR, "Surface RT format %#x "
1027                        "is not supported (mask %#x).\n",
1028                        ctx->va_rt_format, attr[i].value);
1029                 err = AVERROR(EINVAL);
1030                 goto fail;
1031             }
1032             ctx->config_attributes[ctx->nb_config_attributes++] =
1033                 (VAConfigAttrib) {
1034                 .type  = VAConfigAttribRTFormat,
1035                 .value = ctx->va_rt_format,
1036             };
1037             break;
1038         case VAConfigAttribRateControl:
1039             // Hack for backward compatibility: CBR was the only
1040             // usable RC mode for a long time, so old drivers will
1041             // only have it.  Normal default options may now choose
1042             // VBR and then fail, however, so override it here with
1043             // CBR if that is the only supported mode.
1044             if (ctx->va_rc_mode == VA_RC_VBR &&
1045                 !(attr[i].value & VA_RC_VBR) &&
1046                 (attr[i].value & VA_RC_CBR)) {
1047                 av_log(avctx, AV_LOG_WARNING, "VBR rate control is "
1048                        "not supported with this driver version; "
1049                        "using CBR instead.\n");
1050                 ctx->va_rc_mode = VA_RC_CBR;
1051             }
1052             if (!(ctx->va_rc_mode & attr[i].value)) {
1053                 av_log(avctx, AV_LOG_ERROR, "Rate control mode %#x "
1054                        "is not supported (mask: %#x).\n",
1055                        ctx->va_rc_mode, attr[i].value);
1056                 err = AVERROR(EINVAL);
1057                 goto fail;
1058             }
1059             ctx->config_attributes[ctx->nb_config_attributes++] =
1060                 (VAConfigAttrib) {
1061                 .type  = VAConfigAttribRateControl,
1062                 .value = ctx->va_rc_mode,
1063             };
1064             break;
1065         case VAConfigAttribEncMaxRefFrames:
1066         {
1067             unsigned int ref_l0 = attr[i].value & 0xffff;
1068             unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;
1069
1070             if (avctx->gop_size > 1 && ref_l0 < 1) {
1071                 av_log(avctx, AV_LOG_ERROR, "P frames are not "
1072                        "supported (%#x).\n", attr[i].value);
1073                 err = AVERROR(EINVAL);
1074                 goto fail;
1075             }
1076             if (avctx->max_b_frames > 0 && ref_l1 < 1) {
1077                 av_log(avctx, AV_LOG_ERROR, "B frames are not "
1078                        "supported (%#x).\n", attr[i].value);
1079                 err = AVERROR(EINVAL);
1080                 goto fail;
1081             }
1082         }
1083         break;
1084         case VAConfigAttribEncPackedHeaders:
1085             if (ctx->va_packed_headers & ~attr[i].value) {
1086                 // This isn't fatal, but packed headers are always
1087                 // preferable because they are under our control.
1088                 // When absent, the driver is generating them and some
1089                 // features may not work (e.g. VUI or SEI in H.264).
1090                 av_log(avctx, AV_LOG_WARNING, "Warning: some packed "
1091                        "headers are not supported (want %#x, got %#x).\n",
1092                        ctx->va_packed_headers, attr[i].value);
1093                 ctx->va_packed_headers &= attr[i].value;
1094             }
1095             ctx->config_attributes[ctx->nb_config_attributes++] =
1096                 (VAConfigAttrib) {
1097                 .type  = VAConfigAttribEncPackedHeaders,
1098                 .value = ctx->va_packed_headers,
1099             };
1100             break;
1101         default:
1102             av_assert0(0 && "Unexpected config attribute.");
1103         }
1104     }
1105
1106     err = 0;
1107 fail:
1108     av_freep(&profiles);
1109     av_freep(&entrypoints);
1110     return err;
1111 }
1112
1113 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1114 {
1115     VAAPIEncodeContext *ctx = avctx->priv_data;
1116     int rc_bits_per_second;
1117     int rc_target_percentage;
1118     int rc_window_size;
1119     int hrd_buffer_size;
1120     int hrd_initial_buffer_fullness;
1121     int fr_num, fr_den;
1122
1123     if (avctx->rc_buffer_size)
1124         hrd_buffer_size = avctx->rc_buffer_size;
1125     else
1126         hrd_buffer_size = avctx->bit_rate;
1127     if (avctx->rc_initial_buffer_occupancy)
1128         hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1129     else
1130         hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1131
1132     if (ctx->va_rc_mode == VA_RC_CBR) {
1133         rc_bits_per_second   = avctx->bit_rate;
1134         rc_target_percentage = 100;
1135         rc_window_size       = 1000;
1136     } else {
1137         if (avctx->rc_max_rate < avctx->bit_rate) {
1138             // Max rate is unset or invalid, just use the normal bitrate.
1139             rc_bits_per_second   = avctx->bit_rate;
1140             rc_target_percentage = 100;
1141         } else {
1142             rc_bits_per_second   = avctx->rc_max_rate;
1143             rc_target_percentage = (avctx->bit_rate * 100) / rc_bits_per_second;
1144         }
1145         rc_window_size = (hrd_buffer_size * 1000) / avctx->bit_rate;
1146     }
1147
1148     ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1149     ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1150         .bits_per_second   = rc_bits_per_second,
1151         .target_percentage = rc_target_percentage,
1152         .window_size       = rc_window_size,
1153         .initial_qp        = 0,
1154         .min_qp            = (avctx->qmin > 0 ? avctx->qmin : 0),
1155         .basic_unit_size   = 0,
1156     };
1157     ctx->global_params[ctx->nb_global_params] =
1158         &ctx->rc_params.misc;
1159     ctx->global_params_size[ctx->nb_global_params++] =
1160         sizeof(ctx->rc_params);
1161
1162     ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1163     ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1164         .initial_buffer_fullness = hrd_initial_buffer_fullness,
1165         .buffer_size             = hrd_buffer_size,
1166     };
1167     ctx->global_params[ctx->nb_global_params] =
1168         &ctx->hrd_params.misc;
1169     ctx->global_params_size[ctx->nb_global_params++] =
1170         sizeof(ctx->hrd_params);
1171
1172     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1173         av_reduce(&fr_num, &fr_den,
1174                   avctx->framerate.num, avctx->framerate.den, 65535);
1175     else
1176         av_reduce(&fr_num, &fr_den,
1177                   avctx->time_base.den, avctx->time_base.num, 65535);
1178
1179     ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1180     ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1181
1182 #if VA_CHECK_VERSION(0, 40, 0)
1183     ctx->global_params[ctx->nb_global_params] =
1184         &ctx->fr_params.misc;
1185     ctx->global_params_size[ctx->nb_global_params++] =
1186         sizeof(ctx->fr_params);
1187 #endif
1188
1189     return 0;
1190 }
1191
1192 static void vaapi_encode_free_output_buffer(void *opaque,
1193                                             uint8_t *data)
1194 {
1195     AVCodecContext   *avctx = opaque;
1196     VAAPIEncodeContext *ctx = avctx->priv_data;
1197     VABufferID buffer_id;
1198
1199     buffer_id = (VABufferID)(uintptr_t)data;
1200
1201     vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1202
1203     av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1204 }
1205
1206 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1207                                                      int size)
1208 {
1209     AVCodecContext   *avctx = opaque;
1210     VAAPIEncodeContext *ctx = avctx->priv_data;
1211     VABufferID buffer_id;
1212     VAStatus vas;
1213     AVBufferRef *ref;
1214
1215     // The output buffer size is fixed, so it needs to be large enough
1216     // to hold the largest possible compressed frame.  We assume here
1217     // that the uncompressed frame plus some header data is an upper
1218     // bound on that.
1219     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1220                          VAEncCodedBufferType,
1221                          3 * ctx->surface_width * ctx->surface_height +
1222                          (1 << 16), 1, 0, &buffer_id);
1223     if (vas != VA_STATUS_SUCCESS) {
1224         av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1225                "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1226         return NULL;
1227     }
1228
1229     av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1230
1231     ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1232                            sizeof(buffer_id),
1233                            &vaapi_encode_free_output_buffer,
1234                            avctx, AV_BUFFER_FLAG_READONLY);
1235     if (!ref) {
1236         vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1237         return NULL;
1238     }
1239
1240     return ref;
1241 }
1242
1243 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1244 {
1245     VAAPIEncodeContext *ctx = avctx->priv_data;
1246     AVVAAPIHWConfig *hwconfig = NULL;
1247     AVHWFramesConstraints *constraints = NULL;
1248     enum AVPixelFormat recon_format;
1249     int err, i;
1250
1251     hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1252     if (!hwconfig) {
1253         err = AVERROR(ENOMEM);
1254         goto fail;
1255     }
1256     hwconfig->config_id = ctx->va_config;
1257
1258     constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1259                                                       hwconfig);
1260     if (!constraints) {
1261         err = AVERROR(ENOMEM);
1262         goto fail;
1263     }
1264
1265     // Probably we can use the input surface format as the surface format
1266     // of the reconstructed frames.  If not, we just pick the first (only?)
1267     // format in the valid list and hope that it all works.
1268     recon_format = AV_PIX_FMT_NONE;
1269     if (constraints->valid_sw_formats) {
1270         for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1271             if (ctx->input_frames->sw_format ==
1272                 constraints->valid_sw_formats[i]) {
1273                 recon_format = ctx->input_frames->sw_format;
1274                 break;
1275             }
1276         }
1277         if (recon_format == AV_PIX_FMT_NONE) {
1278             // No match.  Just use the first in the supported list and
1279             // hope for the best.
1280             recon_format = constraints->valid_sw_formats[0];
1281         }
1282     } else {
1283         // No idea what to use; copy input format.
1284         recon_format = ctx->input_frames->sw_format;
1285     }
1286     av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1287            "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1288
1289     if (ctx->surface_width  < constraints->min_width  ||
1290         ctx->surface_height < constraints->min_height ||
1291         ctx->surface_width  > constraints->max_width ||
1292         ctx->surface_height > constraints->max_height) {
1293         av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1294                "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1295                ctx->surface_width, ctx->surface_height,
1296                constraints->min_width,  constraints->max_width,
1297                constraints->min_height, constraints->max_height);
1298         err = AVERROR(EINVAL);
1299         goto fail;
1300     }
1301
1302     av_freep(&hwconfig);
1303     av_hwframe_constraints_free(&constraints);
1304
1305     ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1306     if (!ctx->recon_frames_ref) {
1307         err = AVERROR(ENOMEM);
1308         goto fail;
1309     }
1310     ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1311
1312     ctx->recon_frames->format    = AV_PIX_FMT_VAAPI;
1313     ctx->recon_frames->sw_format = recon_format;
1314     ctx->recon_frames->width     = ctx->surface_width;
1315     ctx->recon_frames->height    = ctx->surface_height;
1316     // At most three IDR/I/P frames and two runs of B frames can be in
1317     // flight at any one time.
1318     ctx->recon_frames->initial_pool_size = 3 + 2 * avctx->max_b_frames;
1319
1320     err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1321     if (err < 0) {
1322         av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1323                "frame context: %d.\n", err);
1324         goto fail;
1325     }
1326
1327     err = 0;
1328   fail:
1329     av_freep(&hwconfig);
1330     av_hwframe_constraints_free(&constraints);
1331     return err;
1332 }
1333
1334 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
1335 {
1336     VAAPIEncodeContext *ctx = avctx->priv_data;
1337     AVVAAPIFramesContext *recon_hwctx = NULL;
1338     VAStatus vas;
1339     int err;
1340
1341     if (!avctx->hw_frames_ctx) {
1342         av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1343                "required to associate the encoding device.\n");
1344         return AVERROR(EINVAL);
1345     }
1346
1347     ctx->codec_options = ctx->codec_options_data;
1348
1349     ctx->va_config  = VA_INVALID_ID;
1350     ctx->va_context = VA_INVALID_ID;
1351
1352     ctx->priv_data = av_mallocz(ctx->codec->priv_data_size);
1353     if (!ctx->priv_data) {
1354         err = AVERROR(ENOMEM);
1355         goto fail;
1356     }
1357
1358     ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1359     if (!ctx->input_frames_ref) {
1360         err = AVERROR(ENOMEM);
1361         goto fail;
1362     }
1363     ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1364
1365     ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1366     if (!ctx->device_ref) {
1367         err = AVERROR(ENOMEM);
1368         goto fail;
1369     }
1370     ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1371     ctx->hwctx = ctx->device->hwctx;
1372
1373     err = vaapi_encode_config_attributes(avctx);
1374     if (err < 0)
1375         goto fail;
1376
1377     vas = vaCreateConfig(ctx->hwctx->display,
1378                          ctx->va_profile, ctx->va_entrypoint,
1379                          ctx->config_attributes, ctx->nb_config_attributes,
1380                          &ctx->va_config);
1381     if (vas != VA_STATUS_SUCCESS) {
1382         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1383                "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1384         err = AVERROR(EIO);
1385         goto fail;
1386     }
1387
1388     err = vaapi_encode_create_recon_frames(avctx);
1389     if (err < 0)
1390         goto fail;
1391
1392     recon_hwctx = ctx->recon_frames->hwctx;
1393     vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1394                           ctx->surface_width, ctx->surface_height,
1395                           VA_PROGRESSIVE,
1396                           recon_hwctx->surface_ids,
1397                           recon_hwctx->nb_surfaces,
1398                           &ctx->va_context);
1399     if (vas != VA_STATUS_SUCCESS) {
1400         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1401                "context: %d (%s).\n", vas, vaErrorStr(vas));
1402         err = AVERROR(EIO);
1403         goto fail;
1404     }
1405
1406     ctx->output_buffer_pool =
1407         av_buffer_pool_init2(sizeof(VABufferID), avctx,
1408                              &vaapi_encode_alloc_output_buffer, NULL);
1409     if (!ctx->output_buffer_pool) {
1410         err = AVERROR(ENOMEM);
1411         goto fail;
1412     }
1413
1414     if (ctx->va_rc_mode & ~VA_RC_CQP) {
1415         err = vaapi_encode_init_rate_control(avctx);
1416         if (err < 0)
1417             goto fail;
1418     }
1419
1420     if (ctx->codec->configure) {
1421         err = ctx->codec->configure(avctx);
1422         if (err < 0)
1423             goto fail;
1424     }
1425
1426     ctx->input_order  = 0;
1427     ctx->output_delay = avctx->max_b_frames;
1428     ctx->decode_delay = 1;
1429     ctx->output_order = - ctx->output_delay - 1;
1430
1431     // Currently we never generate I frames, only IDR.
1432     ctx->p_per_i = ((avctx->gop_size + avctx->max_b_frames) /
1433                     (avctx->max_b_frames + 1));
1434     ctx->b_per_p = avctx->max_b_frames;
1435
1436     if (ctx->codec->sequence_params_size > 0) {
1437         ctx->codec_sequence_params =
1438             av_mallocz(ctx->codec->sequence_params_size);
1439         if (!ctx->codec_sequence_params) {
1440             err = AVERROR(ENOMEM);
1441             goto fail;
1442         }
1443     }
1444     if (ctx->codec->picture_params_size > 0) {
1445         ctx->codec_picture_params =
1446             av_mallocz(ctx->codec->picture_params_size);
1447         if (!ctx->codec_picture_params) {
1448             err = AVERROR(ENOMEM);
1449             goto fail;
1450         }
1451     }
1452
1453     if (ctx->codec->init_sequence_params) {
1454         err = ctx->codec->init_sequence_params(avctx);
1455         if (err < 0) {
1456             av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1457                    "failed: %d.\n", err);
1458             goto fail;
1459         }
1460     }
1461
1462     // This should be configurable somehow.  (Needs testing on a machine
1463     // where it actually overlaps properly, though.)
1464     ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1465
1466     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
1467         ctx->codec->write_sequence_header) {
1468         char data[MAX_PARAM_BUFFER_SIZE];
1469         size_t bit_len = 8 * sizeof(data);
1470
1471         err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
1472         if (err < 0) {
1473             av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
1474                    "for extradata: %d.\n", err);
1475             goto fail;
1476         } else {
1477             avctx->extradata_size = (bit_len + 7) / 8;
1478             avctx->extradata = av_mallocz(avctx->extradata_size +
1479                                           AV_INPUT_BUFFER_PADDING_SIZE);
1480             if (!avctx->extradata) {
1481                 err = AVERROR(ENOMEM);
1482                 goto fail;
1483             }
1484             memcpy(avctx->extradata, data, avctx->extradata_size);
1485         }
1486     }
1487
1488     return 0;
1489
1490 fail:
1491     ff_vaapi_encode_close(avctx);
1492     return err;
1493 }
1494
1495 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
1496 {
1497     VAAPIEncodeContext *ctx = avctx->priv_data;
1498     VAAPIEncodePicture *pic, *next;
1499
1500     for (pic = ctx->pic_start; pic; pic = next) {
1501         next = pic->next;
1502         vaapi_encode_free(avctx, pic);
1503     }
1504
1505     if (ctx->va_context != VA_INVALID_ID) {
1506         vaDestroyContext(ctx->hwctx->display, ctx->va_context);
1507         ctx->va_context = VA_INVALID_ID;
1508     }
1509
1510     if (ctx->va_config != VA_INVALID_ID) {
1511         vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
1512         ctx->va_config = VA_INVALID_ID;
1513     }
1514
1515     av_buffer_pool_uninit(&ctx->output_buffer_pool);
1516
1517     av_freep(&ctx->codec_sequence_params);
1518     av_freep(&ctx->codec_picture_params);
1519
1520     av_buffer_unref(&ctx->recon_frames_ref);
1521     av_buffer_unref(&ctx->input_frames_ref);
1522     av_buffer_unref(&ctx->device_ref);
1523
1524     av_freep(&ctx->priv_data);
1525
1526     return 0;
1527 }