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