]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_encode.c
Merge commit '4024b566d664a4b161d677554be52f32e7ad4236'
[ffmpeg] / libavcodec / vaapi_encode.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <inttypes.h>
20 #include <string.h>
21
22 #include "libavutil/avassert.h"
23 #include "libavutil/log.h"
24 #include "libavutil/pixdesc.h"
25
26 #include "vaapi_encode.h"
27 #include "avcodec.h"
28
29 static const char *picture_type_name[] = { "IDR", "I", "P", "B" };
30
31 static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
32                                            VAAPIEncodePicture *pic,
33                                            int type, char *data, size_t bit_len)
34 {
35     VAAPIEncodeContext *ctx = avctx->priv_data;
36     VAStatus vas;
37     VABufferID param_buffer, data_buffer;
38     VAEncPackedHeaderParameterBuffer params = {
39         .type = type,
40         .bit_length = bit_len,
41         .has_emulation_bytes = 1,
42     };
43
44     av_assert0(pic->nb_param_buffers + 2 <= MAX_PARAM_BUFFERS);
45
46     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
47                          VAEncPackedHeaderParameterBufferType,
48                          sizeof(params), 1, &params, &param_buffer);
49     if (vas != VA_STATUS_SUCCESS) {
50         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
51                "for packed header (type %d): %d (%s).\n",
52                type, vas, vaErrorStr(vas));
53         return AVERROR(EIO);
54     }
55     pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
56
57     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
58                          VAEncPackedHeaderDataBufferType,
59                          (bit_len + 7) / 8, 1, data, &data_buffer);
60     if (vas != VA_STATUS_SUCCESS) {
61         av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
62                "for packed header (type %d): %d (%s).\n",
63                type, vas, vaErrorStr(vas));
64         return AVERROR(EIO);
65     }
66     pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
67
68     av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
69            "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
70     return 0;
71 }
72
73 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
74                                           VAAPIEncodePicture *pic,
75                                           int type, char *data, size_t len)
76 {
77     VAAPIEncodeContext *ctx = avctx->priv_data;
78     VAStatus vas;
79     VABufferID buffer;
80
81     av_assert0(pic->nb_param_buffers + 1 <= MAX_PARAM_BUFFERS);
82
83     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
84                          type, len, 1, data, &buffer);
85     if (vas != VA_STATUS_SUCCESS) {
86         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
87                "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
88         return AVERROR(EIO);
89     }
90     pic->param_buffers[pic->nb_param_buffers++] = buffer;
91
92     av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
93            type, buffer);
94     return 0;
95 }
96
97 static int vaapi_encode_wait(AVCodecContext *avctx,
98                              VAAPIEncodePicture *pic)
99 {
100     VAAPIEncodeContext *ctx = avctx->priv_data;
101     VAStatus vas;
102
103     av_assert0(pic->encode_issued);
104
105     if (pic->encode_complete) {
106         // Already waited for this picture.
107         return 0;
108     }
109
110     av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
111            "(recon surface %#x).\n", pic->display_order,
112            pic->encode_order, pic->recon_surface);
113
114     vas = vaSyncSurface(ctx->hwctx->display, pic->recon_surface);
115     if (vas != VA_STATUS_SUCCESS) {
116         av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
117                "%d (%s).\n", vas, vaErrorStr(vas));
118         return AVERROR(EIO);
119     }
120
121     // Input is definitely finished with now.
122     av_frame_free(&pic->input_image);
123
124     pic->encode_complete = 1;
125     return 0;
126 }
127
128 static int vaapi_encode_issue(AVCodecContext *avctx,
129                               VAAPIEncodePicture *pic)
130 {
131     VAAPIEncodeContext *ctx = avctx->priv_data;
132     VAAPIEncodeSlice *slice;
133     VAStatus vas;
134     int err, i;
135     char data[MAX_PARAM_BUFFER_SIZE];
136     size_t bit_len;
137
138     av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
139            "as type %s.\n", pic->display_order, pic->encode_order,
140            picture_type_name[pic->type]);
141     if (pic->nb_refs == 0) {
142         av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
143     } else {
144         av_log(avctx, AV_LOG_DEBUG, "Refers to:");
145         for (i = 0; i < pic->nb_refs; i++) {
146             av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
147                    pic->refs[i]->display_order, pic->refs[i]->encode_order);
148         }
149         av_log(avctx, AV_LOG_DEBUG, ".\n");
150     }
151
152     av_assert0(pic->input_available && !pic->encode_issued);
153     for (i = 0; i < pic->nb_refs; i++) {
154         av_assert0(pic->refs[i]);
155         // If we are serialised then the references must have already
156         // completed.  If not, they must have been issued but need not
157         // have completed yet.
158         if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
159             av_assert0(pic->refs[i]->encode_complete);
160         else
161             av_assert0(pic->refs[i]->encode_issued);
162     }
163
164     av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
165
166     pic->recon_image = av_frame_alloc();
167     if (!pic->recon_image) {
168         err = AVERROR(ENOMEM);
169         goto fail;
170     }
171
172     err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
173     if (err < 0) {
174         err = AVERROR(ENOMEM);
175         goto fail;
176     }
177     pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
178     av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
179
180     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
181                          VAEncCodedBufferType,
182                          MAX_OUTPUT_BUFFER_SIZE, 1, 0,
183                          &pic->output_buffer);
184     if (vas != VA_STATUS_SUCCESS) {
185         av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
186                "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
187         err = AVERROR(ENOMEM);
188         goto fail;
189     }
190     av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
191            pic->output_buffer);
192
193     if (ctx->codec->picture_params_size > 0) {
194         pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
195         if (!pic->codec_picture_params)
196             goto fail;
197         memcpy(pic->codec_picture_params, ctx->codec_picture_params,
198                ctx->codec->picture_params_size);
199     } else {
200         av_assert0(!ctx->codec_picture_params);
201     }
202
203     pic->nb_param_buffers = 0;
204
205     if (pic->encode_order == 0) {
206         // Global parameter buffers are set on the first picture only.
207
208         for (i = 0; i < ctx->nb_global_params; i++) {
209             err = vaapi_encode_make_param_buffer(avctx, pic,
210                                                  VAEncMiscParameterBufferType,
211                                                  (char*)ctx->global_params[i],
212                                                  ctx->global_params_size[i]);
213             if (err < 0)
214                 goto fail;
215         }
216     }
217
218     if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
219         err = vaapi_encode_make_param_buffer(avctx, pic,
220                                              VAEncSequenceParameterBufferType,
221                                              ctx->codec_sequence_params,
222                                              ctx->codec->sequence_params_size);
223         if (err < 0)
224             goto fail;
225     }
226
227     if (ctx->codec->init_picture_params) {
228         err = ctx->codec->init_picture_params(avctx, pic);
229         if (err < 0) {
230             av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
231                    "parameters: %d.\n", err);
232             goto fail;
233         }
234         err = vaapi_encode_make_param_buffer(avctx, pic,
235                                              VAEncPictureParameterBufferType,
236                                              pic->codec_picture_params,
237                                              ctx->codec->picture_params_size);
238         if (err < 0)
239             goto fail;
240     }
241
242     if (pic->type == PICTURE_TYPE_IDR) {
243         if (ctx->codec->write_sequence_header) {
244             bit_len = 8 * sizeof(data);
245             err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
246             if (err < 0) {
247                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
248                        "header: %d.\n", err);
249                 goto fail;
250             }
251             err = vaapi_encode_make_packed_header(avctx, pic,
252                                                   ctx->codec->sequence_header_type,
253                                                   data, bit_len);
254             if (err < 0)
255                 goto fail;
256         }
257     }
258
259     if (ctx->codec->write_picture_header) {
260         bit_len = 8 * sizeof(data);
261         err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
262         if (err < 0) {
263             av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
264                    "header: %d.\n", err);
265             goto fail;
266         }
267         err = vaapi_encode_make_packed_header(avctx, pic,
268                                               ctx->codec->picture_header_type,
269                                               data, bit_len);
270         if (err < 0)
271             goto fail;
272     }
273
274     if (ctx->codec->write_extra_buffer) {
275         for (i = 0;; i++) {
276             size_t len = sizeof(data);
277             int type;
278             err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
279                                                  data, &len);
280             if (err == AVERROR_EOF)
281                 break;
282             if (err < 0) {
283                 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
284                        "buffer %d: %d.\n", i, err);
285                 goto fail;
286             }
287
288             err = vaapi_encode_make_param_buffer(avctx, pic, type,
289                                                  data, len);
290             if (err < 0)
291                 goto fail;
292         }
293     }
294
295     av_assert0(pic->nb_slices <= MAX_PICTURE_SLICES);
296     for (i = 0; i < pic->nb_slices; i++) {
297         slice = av_mallocz(sizeof(*slice));
298         if (!slice) {
299             err = AVERROR(ENOMEM);
300             goto fail;
301         }
302         pic->slices[i] = slice;
303
304         if (ctx->codec->slice_params_size > 0) {
305             slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
306             if (!slice->codec_slice_params) {
307                 err = AVERROR(ENOMEM);
308                 goto fail;
309             }
310         }
311
312         if (ctx->codec->init_slice_params) {
313             err = ctx->codec->init_slice_params(avctx, pic, slice);
314             if (err < 0) {
315                 av_log(avctx, AV_LOG_ERROR, "Failed to initalise slice "
316                        "parameters: %d.\n", err);
317                 goto fail;
318             }
319         }
320
321         if (ctx->codec->write_slice_header) {
322             bit_len = 8 * sizeof(data);
323             err = ctx->codec->write_slice_header(avctx, pic, slice,
324                                                  data, &bit_len);
325             if (err < 0) {
326                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
327                        "header: %d.\n", err);
328                 goto fail;
329             }
330             err = vaapi_encode_make_packed_header(avctx, pic,
331                                                   ctx->codec->slice_header_type,
332                                                   data, bit_len);
333             if (err < 0)
334                 goto fail;
335         }
336
337         if (ctx->codec->init_slice_params) {
338             err = vaapi_encode_make_param_buffer(avctx, pic,
339                                                  VAEncSliceParameterBufferType,
340                                                  slice->codec_slice_params,
341                                                  ctx->codec->slice_params_size);
342             if (err < 0)
343                 goto fail;
344         }
345     }
346
347     vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
348                          pic->input_surface);
349     if (vas != VA_STATUS_SUCCESS) {
350         av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
351                "%d (%s).\n", vas, vaErrorStr(vas));
352         err = AVERROR(EIO);
353         goto fail_with_picture;
354     }
355
356     vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
357                           pic->param_buffers, pic->nb_param_buffers);
358     if (vas != VA_STATUS_SUCCESS) {
359         av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
360                "%d (%s).\n", vas, vaErrorStr(vas));
361         err = AVERROR(EIO);
362         goto fail_with_picture;
363     }
364
365     vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
366     if (vas != VA_STATUS_SUCCESS) {
367         av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
368                "%d (%s).\n", vas, vaErrorStr(vas));
369         err = AVERROR(EIO);
370         goto fail_at_end;
371     }
372
373     pic->encode_issued = 1;
374
375     if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
376         return vaapi_encode_wait(avctx, pic);
377     else
378         return 0;
379
380 fail_with_picture:
381     vaEndPicture(ctx->hwctx->display, ctx->va_context);
382 fail:
383     for(i = 0; i < pic->nb_param_buffers; i++)
384         vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
385 fail_at_end:
386     av_freep(&pic->codec_picture_params);
387     av_frame_free(&pic->recon_image);
388     return err;
389 }
390
391 static int vaapi_encode_output(AVCodecContext *avctx,
392                                VAAPIEncodePicture *pic, AVPacket *pkt)
393 {
394     VAAPIEncodeContext *ctx = avctx->priv_data;
395     VACodedBufferSegment *buf_list, *buf;
396     VAStatus vas;
397     int err;
398
399     err = vaapi_encode_wait(avctx, pic);
400     if (err < 0)
401         return err;
402
403     buf_list = NULL;
404     vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
405                       (void**)&buf_list);
406     if (vas != VA_STATUS_SUCCESS) {
407         av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
408                "%d (%s).\n", vas, vaErrorStr(vas));
409         err = AVERROR(EIO);
410         goto fail;
411     }
412
413     for (buf = buf_list; buf; buf = buf->next) {
414         av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
415                "(status %08x).\n", buf->size, buf->status);
416
417         err = av_new_packet(pkt, buf->size);
418         if (err < 0)
419             goto fail;
420
421         memcpy(pkt->data, buf->buf, buf->size);
422     }
423
424     if (pic->type == PICTURE_TYPE_IDR)
425         pkt->flags |= AV_PKT_FLAG_KEY;
426
427     pkt->pts = pic->pts;
428
429     vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
430     if (vas != VA_STATUS_SUCCESS) {
431         av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
432                "%d (%s).\n", vas, vaErrorStr(vas));
433         err = AVERROR(EIO);
434         goto fail;
435     }
436
437     vaDestroyBuffer(ctx->hwctx->display, pic->output_buffer);
438     pic->output_buffer = VA_INVALID_ID;
439
440     av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
441            pic->display_order, pic->encode_order);
442     return 0;
443
444 fail:
445     if (pic->output_buffer != VA_INVALID_ID) {
446         vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
447         vaDestroyBuffer(ctx->hwctx->display, pic->output_buffer);
448         pic->output_buffer = VA_INVALID_ID;
449     }
450     return err;
451 }
452
453 static int vaapi_encode_discard(AVCodecContext *avctx,
454                                 VAAPIEncodePicture *pic)
455 {
456     VAAPIEncodeContext *ctx = avctx->priv_data;
457
458     vaapi_encode_wait(avctx, pic);
459
460     if (pic->output_buffer != VA_INVALID_ID) {
461         av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
462                "%"PRId64"/%"PRId64".\n",
463                pic->display_order, pic->encode_order);
464
465         vaDestroyBuffer(ctx->hwctx->display, pic->output_buffer);
466         pic->output_buffer = VA_INVALID_ID;
467     }
468
469     return 0;
470 }
471
472 static VAAPIEncodePicture *vaapi_encode_alloc(void)
473 {
474     VAAPIEncodePicture *pic;
475
476     pic = av_mallocz(sizeof(*pic));
477     if (!pic)
478         return NULL;
479
480     pic->input_surface = VA_INVALID_ID;
481     pic->recon_surface = VA_INVALID_ID;
482     pic->output_buffer = VA_INVALID_ID;
483
484     return pic;
485 }
486
487 static int vaapi_encode_free(AVCodecContext *avctx,
488                              VAAPIEncodePicture *pic)
489 {
490     int i;
491
492     if (pic->encode_issued)
493         vaapi_encode_discard(avctx, pic);
494
495     for (i = 0; i < pic->nb_slices; i++) {
496         av_freep(&pic->slices[i]->priv_data);
497         av_freep(&pic->slices[i]->codec_slice_params);
498         av_freep(&pic->slices[i]);
499     }
500     av_freep(&pic->codec_picture_params);
501
502     av_frame_free(&pic->input_image);
503     av_frame_free(&pic->recon_image);
504
505     // Output buffer should already be destroyed.
506     av_assert0(pic->output_buffer == VA_INVALID_ID);
507
508     av_freep(&pic->priv_data);
509     av_freep(&pic->codec_picture_params);
510
511     av_free(pic);
512
513     return 0;
514 }
515
516 static int vaapi_encode_step(AVCodecContext *avctx,
517                              VAAPIEncodePicture *target)
518 {
519     VAAPIEncodeContext *ctx = avctx->priv_data;
520     VAAPIEncodePicture *pic;
521     int i, err;
522
523     if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
524         ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
525         // These two modes are equivalent, except that we wait for
526         // immediate completion on each operation if serialised.
527
528         if (!target) {
529             // No target, nothing to do yet.
530             return 0;
531         }
532
533         if (target->encode_complete) {
534             // Already done.
535             return 0;
536         }
537
538         pic = target;
539         for (i = 0; i < pic->nb_refs; i++) {
540             if (!pic->refs[i]->encode_complete) {
541                 err = vaapi_encode_step(avctx, pic->refs[i]);
542                 if (err < 0)
543                     return err;
544             }
545         }
546
547         err = vaapi_encode_issue(avctx, pic);
548         if (err < 0)
549             return err;
550
551     } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
552         int activity;
553
554         do {
555             activity = 0;
556             for (pic = ctx->pic_start; pic; pic = pic->next) {
557                 if (!pic->input_available || pic->encode_issued)
558                     continue;
559                 for (i = 0; i < pic->nb_refs; i++) {
560                     if (!pic->refs[i]->encode_issued)
561                         break;
562                 }
563                 if (i < pic->nb_refs)
564                     continue;
565                 err = vaapi_encode_issue(avctx, pic);
566                 if (err < 0)
567                     return err;
568                 activity = 1;
569             }
570         } while(activity);
571
572         if (target) {
573             av_assert0(target->encode_issued && "broken dependencies?");
574         }
575
576     } else {
577         av_assert0(0);
578     }
579
580     return 0;
581 }
582
583 static int vaapi_encode_get_next(AVCodecContext *avctx,
584                                  VAAPIEncodePicture **pic_out)
585 {
586     VAAPIEncodeContext *ctx = avctx->priv_data;
587     VAAPIEncodePicture *start, *end, *pic;
588     int i;
589
590     for (pic = ctx->pic_start; pic; pic = pic->next) {
591         if (pic->next)
592             av_assert0(pic->display_order + 1 == pic->next->display_order);
593         if (pic->display_order == ctx->input_order) {
594             *pic_out = pic;
595             return 0;
596         }
597     }
598
599     if (ctx->input_order == 0) {
600         // First frame is always an IDR frame.
601         av_assert0(!ctx->pic_start && !ctx->pic_end);
602
603         pic = vaapi_encode_alloc();
604         if (!pic)
605             return AVERROR(ENOMEM);
606
607         pic->type = PICTURE_TYPE_IDR;
608         pic->display_order = 0;
609         pic->encode_order  = 0;
610
611         ctx->pic_start = ctx->pic_end = pic;
612
613         *pic_out = pic;
614         return 0;
615     }
616
617     pic = vaapi_encode_alloc();
618     if (!pic)
619         return AVERROR(ENOMEM);
620
621     if (ctx->p_per_i == 0 || ctx->p_counter == ctx->p_per_i) {
622         if (ctx->i_per_idr == 0 || ctx->i_counter == ctx->i_per_idr) {
623             pic->type = PICTURE_TYPE_IDR;
624             ctx->i_counter = 0;
625         } else {
626             pic->type = PICTURE_TYPE_I;
627             ++ctx->i_counter;
628         }
629         ctx->p_counter = 0;
630     } else {
631         pic->type = PICTURE_TYPE_P;
632         pic->refs[0] = ctx->pic_end;
633         pic->nb_refs = 1;
634         ++ctx->p_counter;
635     }
636     start = end = pic;
637
638     if (pic->type != PICTURE_TYPE_IDR) {
639         // If that was not an IDR frame, add B-frames display-before and
640         // encode-after it.
641
642         for (i = 0; i < ctx->b_per_p; i++) {
643             pic = vaapi_encode_alloc();
644             if (!pic)
645                 goto fail;
646
647             pic->type = PICTURE_TYPE_B;
648             pic->refs[0] = ctx->pic_end;
649             pic->refs[1] = end;
650             pic->nb_refs = 2;
651
652             pic->next = start;
653             pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
654             pic->encode_order  = pic->display_order + 1;
655             start = pic;
656         }
657     }
658
659     for (i = 0, pic = start; pic; i++, pic = pic->next) {
660         pic->display_order = ctx->input_order + i;
661         if (end->type == PICTURE_TYPE_IDR)
662             pic->encode_order = ctx->input_order + i;
663         else if (pic == end)
664             pic->encode_order = ctx->input_order;
665         else
666             pic->encode_order = ctx->input_order + i + 1;
667     }
668
669     av_assert0(ctx->pic_end);
670     ctx->pic_end->next = start;
671     ctx->pic_end = end;
672
673     *pic_out = start;
674
675     av_log(avctx, AV_LOG_DEBUG, "Pictures:");
676     for (pic = ctx->pic_start; pic; pic = pic->next) {
677         av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
678                picture_type_name[pic->type],
679                pic->display_order, pic->encode_order);
680     }
681     av_log(avctx, AV_LOG_DEBUG, "\n");
682
683     return 0;
684
685 fail:
686     while (start) {
687         pic = start->next;
688         vaapi_encode_free(avctx, start);
689         start = pic;
690     }
691     return AVERROR(ENOMEM);
692 }
693
694 static int vaapi_encode_mangle_end(AVCodecContext *avctx)
695 {
696     VAAPIEncodeContext *ctx = avctx->priv_data;
697     VAAPIEncodePicture *pic, *last_pic, *next;
698
699     // Find the last picture we actually have input for.
700     for (pic = ctx->pic_start; pic; pic = pic->next) {
701         if (!pic->input_available)
702             break;
703         last_pic = pic;
704     }
705
706     if (pic) {
707         av_assert0(last_pic);
708
709         if (last_pic->type == PICTURE_TYPE_B) {
710             // Some fixing up is required.  Change the type of this
711             // picture to P, then modify preceding B references which
712             // point beyond it to point at it instead.
713
714             last_pic->type = PICTURE_TYPE_P;
715             last_pic->encode_order = last_pic->refs[1]->encode_order;
716
717             for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
718                 if (pic->type == PICTURE_TYPE_B &&
719                     pic->refs[1] == last_pic->refs[1])
720                     pic->refs[1] = last_pic;
721             }
722
723             last_pic->nb_refs = 1;
724             last_pic->refs[1] = NULL;
725         } else {
726             // We can use the current structure (no references point
727             // beyond the end), but there are unused pics to discard.
728         }
729
730         // Discard all following pics, they will never be used.
731         for (pic = last_pic->next; pic; pic = next) {
732             next = pic->next;
733             vaapi_encode_free(avctx, pic);
734         }
735
736         last_pic->next = NULL;
737         ctx->pic_end = last_pic;
738
739     } else {
740         // Input is available for all pictures, so we don't need to
741         // mangle anything.
742     }
743
744     av_log(avctx, AV_LOG_DEBUG, "Pictures at end of stream:");
745     for (pic = ctx->pic_start; pic; pic = pic->next) {
746         av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
747                picture_type_name[pic->type],
748                pic->display_order, pic->encode_order);
749     }
750     av_log(avctx, AV_LOG_DEBUG, "\n");
751
752     return 0;
753 }
754
755 static int vaapi_encode_clear_old(AVCodecContext *avctx)
756 {
757     VAAPIEncodeContext *ctx = avctx->priv_data;
758     VAAPIEncodePicture *pic, *old;
759     int i;
760
761     while (ctx->pic_start != ctx->pic_end) {
762         old = ctx->pic_start;
763         if (old->encode_order > ctx->output_order)
764             break;
765
766         for (pic = old->next; pic; pic = pic->next) {
767             if (pic->encode_complete)
768                 continue;
769             for (i = 0; i < pic->nb_refs; i++) {
770                 if (pic->refs[i] == old) {
771                     // We still need this picture because it's referred to
772                     // directly by a later one, so it and all following
773                     // pictures have to stay.
774                     return 0;
775                 }
776             }
777         }
778
779         pic = ctx->pic_start;
780         ctx->pic_start = pic->next;
781         vaapi_encode_free(avctx, pic);
782     }
783
784     return 0;
785 }
786
787 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
788                      const AVFrame *input_image, int *got_packet)
789 {
790     VAAPIEncodeContext *ctx = avctx->priv_data;
791     VAAPIEncodePicture *pic;
792     int err;
793
794     if (input_image) {
795         av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
796                input_image->width, input_image->height, input_image->pts);
797
798         err = vaapi_encode_get_next(avctx, &pic);
799         if (err) {
800             av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
801             return err;
802         }
803
804         pic->input_image = av_frame_alloc();
805         if (!pic->input_image) {
806             err = AVERROR(ENOMEM);
807             goto fail;
808         }
809         err = av_frame_ref(pic->input_image, input_image);
810         if (err < 0)
811             goto fail;
812         pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
813         pic->pts = input_image->pts;
814
815         if (ctx->input_order == 0)
816             ctx->first_pts = pic->pts;
817         if (ctx->input_order == ctx->decode_delay)
818             ctx->dts_pts_diff = pic->pts - ctx->first_pts;
819         if (ctx->output_delay > 0)
820             ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
821
822         pic->input_available = 1;
823
824     } else {
825         if (!ctx->end_of_stream) {
826             err = vaapi_encode_mangle_end(avctx);
827             if (err < 0)
828                 goto fail;
829             ctx->end_of_stream = 1;
830         }
831     }
832
833     ++ctx->input_order;
834     ++ctx->output_order;
835     av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
836
837     for (pic = ctx->pic_start; pic; pic = pic->next)
838         if (pic->encode_order == ctx->output_order)
839             break;
840
841     // pic can be null here if we don't have a specific target in this
842     // iteration.  We might still issue encodes if things can be overlapped,
843     // even though we don't intend to output anything.
844
845     err = vaapi_encode_step(avctx, pic);
846     if (err < 0) {
847         av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
848         goto fail;
849     }
850
851     if (!pic) {
852         *got_packet = 0;
853     } else {
854         err = vaapi_encode_output(avctx, pic, pkt);
855         if (err < 0) {
856             av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
857             goto fail;
858         }
859
860         if (ctx->output_delay == 0) {
861             pkt->dts = pkt->pts;
862         } else if (ctx->output_order < ctx->decode_delay) {
863             if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
864                 pkt->dts = INT64_MIN;
865             else
866                 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
867         } else {
868             pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
869                                     (3 * ctx->output_delay)];
870         }
871
872         *got_packet = 1;
873     }
874
875     err = vaapi_encode_clear_old(avctx);
876     if (err < 0) {
877         av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
878         goto fail;
879     }
880
881     return 0;
882
883 fail:
884     // Unclear what to clean up on failure.  There are probably some things we
885     // could do usefully clean up here, but for now just leave them for uninit()
886     // to do instead.
887     return err;
888 }
889
890 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx,
891                                  const VAAPIEncodeType *type)
892 {
893     VAAPIEncodeContext *ctx = avctx->priv_data;
894     AVVAAPIFramesContext *recon_hwctx = NULL;
895     AVVAAPIHWConfig *hwconfig = NULL;
896     AVHWFramesConstraints *constraints = NULL;
897     enum AVPixelFormat recon_format;
898     VAStatus vas;
899     int err, i;
900
901     if (!avctx->hw_frames_ctx) {
902         av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
903                "required to associate the encoding device.\n");
904         return AVERROR(EINVAL);
905     }
906
907     ctx->codec = type;
908     ctx->codec_options = ctx->codec_options_data;
909
910     ctx->priv_data = av_mallocz(type->priv_data_size);
911     if (!ctx->priv_data) {
912         err = AVERROR(ENOMEM);
913         goto fail;
914     }
915
916     ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
917     if (!ctx->input_frames_ref) {
918         err = AVERROR(ENOMEM);
919         goto fail;
920     }
921     ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
922
923     ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
924     if (!ctx->device_ref) {
925         err = AVERROR(ENOMEM);
926         goto fail;
927     }
928     ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
929     ctx->hwctx = ctx->device->hwctx;
930
931     err = ctx->codec->init(avctx);
932     if (err < 0)
933         goto fail;
934
935     vas = vaCreateConfig(ctx->hwctx->display,
936                          ctx->va_profile, ctx->va_entrypoint,
937                          ctx->config_attributes, ctx->nb_config_attributes,
938                          &ctx->va_config);
939     if (vas != VA_STATUS_SUCCESS) {
940         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
941                "configuration: %d (%s).\n", vas, vaErrorStr(vas));
942         err = AVERROR(EIO);
943         goto fail;
944     }
945
946     hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
947     if (!hwconfig) {
948         err = AVERROR(ENOMEM);
949         goto fail;
950     }
951     hwconfig->config_id = ctx->va_config;
952
953     constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
954                                                       hwconfig);
955     if (!constraints) {
956         err = AVERROR(ENOMEM);
957         goto fail;
958     }
959
960     // Probably we can use the input surface format as the surface format
961     // of the reconstructed frames.  If not, we just pick the first (only?)
962     // format in the valid list and hope that it all works.
963     recon_format = AV_PIX_FMT_NONE;
964     if (constraints->valid_sw_formats) {
965         for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
966             if (ctx->input_frames->sw_format ==
967                 constraints->valid_sw_formats[i]) {
968                 recon_format = ctx->input_frames->sw_format;
969                 break;
970             }
971         }
972         if (recon_format == AV_PIX_FMT_NONE)
973             recon_format = constraints->valid_sw_formats[i];
974     } else {
975         // No idea what to use; copy input format.
976         recon_format = ctx->input_frames->sw_format;
977     }
978     av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
979            "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
980
981     if (ctx->aligned_width  < constraints->min_width  ||
982         ctx->aligned_height < constraints->min_height ||
983         ctx->aligned_width  > constraints->max_width ||
984         ctx->aligned_height > constraints->max_height) {
985         av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
986                "size %dx%d (constraints: width %d-%d height %d-%d).\n",
987                ctx->aligned_width, ctx->aligned_height,
988                constraints->min_width,  constraints->max_width,
989                constraints->min_height, constraints->max_height);
990         err = AVERROR(EINVAL);
991         goto fail;
992     }
993
994     av_freep(&hwconfig);
995     av_hwframe_constraints_free(&constraints);
996
997     ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
998     if (!ctx->recon_frames_ref) {
999         err = AVERROR(ENOMEM);
1000         goto fail;
1001     }
1002     ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1003
1004     ctx->recon_frames->format    = AV_PIX_FMT_VAAPI;
1005     ctx->recon_frames->sw_format = recon_format;
1006     ctx->recon_frames->width     = ctx->aligned_width;
1007     ctx->recon_frames->height    = ctx->aligned_height;
1008     ctx->recon_frames->initial_pool_size = ctx->nb_recon_frames;
1009
1010     err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1011     if (err < 0) {
1012         av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1013                "frame context: %d.\n", err);
1014         goto fail;
1015     }
1016     recon_hwctx = ctx->recon_frames->hwctx;
1017
1018     vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1019                           ctx->aligned_width, ctx->aligned_height,
1020                           VA_PROGRESSIVE,
1021                           recon_hwctx->surface_ids,
1022                           recon_hwctx->nb_surfaces,
1023                           &ctx->va_context);
1024     if (vas != VA_STATUS_SUCCESS) {
1025         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1026                "context: %d (%s).\n", vas, vaErrorStr(vas));
1027         err = AVERROR(EIO);
1028         goto fail;
1029     }
1030
1031     ctx->input_order  = 0;
1032     ctx->output_delay = avctx->max_b_frames;
1033     ctx->decode_delay = 1;
1034     ctx->output_order = - ctx->output_delay - 1;
1035
1036     if (ctx->codec->sequence_params_size > 0) {
1037         ctx->codec_sequence_params =
1038             av_mallocz(ctx->codec->sequence_params_size);
1039         if (!ctx->codec_sequence_params) {
1040             err = AVERROR(ENOMEM);
1041             goto fail;
1042         }
1043     }
1044     if (ctx->codec->picture_params_size > 0) {
1045         ctx->codec_picture_params =
1046             av_mallocz(ctx->codec->picture_params_size);
1047         if (!ctx->codec_picture_params) {
1048             err = AVERROR(ENOMEM);
1049             goto fail;
1050         }
1051     }
1052
1053     if (ctx->codec->init_sequence_params) {
1054         err = ctx->codec->init_sequence_params(avctx);
1055         if (err < 0) {
1056             av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1057                    "failed: %d.\n", err);
1058             goto fail;
1059         }
1060     }
1061
1062     // All I are IDR for now.
1063     ctx->i_per_idr = 0;
1064     ctx->p_per_i = ((avctx->gop_size + avctx->max_b_frames) /
1065                     (avctx->max_b_frames + 1));
1066     ctx->b_per_p = avctx->max_b_frames;
1067
1068     // This should be configurable somehow.  (Needs testing on a machine
1069     // where it actually overlaps properly, though.)
1070     ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1071
1072     return 0;
1073
1074 fail:
1075     av_freep(&hwconfig);
1076     av_hwframe_constraints_free(&constraints);
1077     ff_vaapi_encode_close(avctx);
1078     return err;
1079 }
1080
1081 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
1082 {
1083     VAAPIEncodeContext *ctx = avctx->priv_data;
1084     VAAPIEncodePicture *pic, *next;
1085
1086     for (pic = ctx->pic_start; pic; pic = next) {
1087         next = pic->next;
1088         vaapi_encode_free(avctx, pic);
1089     }
1090
1091     if (ctx->va_context != VA_INVALID_ID)
1092         vaDestroyContext(ctx->hwctx->display, ctx->va_context);
1093
1094     if (ctx->va_config != VA_INVALID_ID)
1095         vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
1096
1097     if (ctx->codec->close)
1098         ctx->codec->close(avctx);
1099
1100     av_freep(&ctx->codec_sequence_params);
1101     av_freep(&ctx->codec_picture_params);
1102
1103     av_buffer_unref(&ctx->recon_frames_ref);
1104     av_buffer_unref(&ctx->input_frames_ref);
1105     av_buffer_unref(&ctx->device_ref);
1106
1107     av_freep(&ctx->priv_data);
1108
1109     return 0;
1110 }