]> git.sesse.net Git - ffmpeg/blob - libavcodec/vaapi_encode.c
vaapi_encode: Always reapply global parameters after the sequence header
[ffmpeg] / libavcodec / vaapi_encode.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 #include <inttypes.h>
20 #include <string.h>
21
22 #include "libavutil/avassert.h"
23 #include "libavutil/common.h"
24 #include "libavutil/log.h"
25 #include "libavutil/pixdesc.h"
26
27 #include "vaapi_encode.h"
28 #include "avcodec.h"
29
30 static const char * const picture_type_name[] = { "IDR", "I", "P", "B" };
31
32 static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
33                                            VAAPIEncodePicture *pic,
34                                            int type, char *data, size_t bit_len)
35 {
36     VAAPIEncodeContext *ctx = avctx->priv_data;
37     VAStatus vas;
38     VABufferID param_buffer, data_buffer;
39     VABufferID *tmp;
40     VAEncPackedHeaderParameterBuffer params = {
41         .type = type,
42         .bit_length = bit_len,
43         .has_emulation_bytes = 1,
44     };
45
46     tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 2);
47     if (!tmp)
48         return AVERROR(ENOMEM);
49     pic->param_buffers = tmp;
50
51     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
52                          VAEncPackedHeaderParameterBufferType,
53                          sizeof(params), 1, &params, &param_buffer);
54     if (vas != VA_STATUS_SUCCESS) {
55         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
56                "for packed header (type %d): %d (%s).\n",
57                type, vas, vaErrorStr(vas));
58         return AVERROR(EIO);
59     }
60     pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
61
62     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
63                          VAEncPackedHeaderDataBufferType,
64                          (bit_len + 7) / 8, 1, data, &data_buffer);
65     if (vas != VA_STATUS_SUCCESS) {
66         av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
67                "for packed header (type %d): %d (%s).\n",
68                type, vas, vaErrorStr(vas));
69         return AVERROR(EIO);
70     }
71     pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
72
73     av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
74            "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
75     return 0;
76 }
77
78 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
79                                           VAAPIEncodePicture *pic,
80                                           int type, char *data, size_t len)
81 {
82     VAAPIEncodeContext *ctx = avctx->priv_data;
83     VAStatus vas;
84     VABufferID *tmp;
85     VABufferID buffer;
86
87     tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 1);
88     if (!tmp)
89         return AVERROR(ENOMEM);
90     pic->param_buffers = tmp;
91
92     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
93                          type, len, 1, data, &buffer);
94     if (vas != VA_STATUS_SUCCESS) {
95         av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
96                "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
97         return AVERROR(EIO);
98     }
99     pic->param_buffers[pic->nb_param_buffers++] = buffer;
100
101     av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
102            type, buffer);
103     return 0;
104 }
105
106 static int vaapi_encode_wait(AVCodecContext *avctx,
107                              VAAPIEncodePicture *pic)
108 {
109     VAAPIEncodeContext *ctx = avctx->priv_data;
110     VAStatus vas;
111
112     av_assert0(pic->encode_issued);
113
114     if (pic->encode_complete) {
115         // Already waited for this picture.
116         return 0;
117     }
118
119     av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
120            "(input surface %#x).\n", pic->display_order,
121            pic->encode_order, pic->input_surface);
122
123     vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
124     if (vas != VA_STATUS_SUCCESS) {
125         av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
126                "%d (%s).\n", vas, vaErrorStr(vas));
127         return AVERROR(EIO);
128     }
129
130     // Input is definitely finished with now.
131     av_frame_free(&pic->input_image);
132
133     pic->encode_complete = 1;
134     return 0;
135 }
136
137 static int vaapi_encode_issue(AVCodecContext *avctx,
138                               VAAPIEncodePicture *pic)
139 {
140     VAAPIEncodeContext *ctx = avctx->priv_data;
141     VAAPIEncodeSlice *slice;
142     VAStatus vas;
143     int err, i;
144     char data[MAX_PARAM_BUFFER_SIZE];
145     size_t bit_len;
146
147     av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
148            "as type %s.\n", pic->display_order, pic->encode_order,
149            picture_type_name[pic->type]);
150     if (pic->nb_refs == 0) {
151         av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
152     } else {
153         av_log(avctx, AV_LOG_DEBUG, "Refers to:");
154         for (i = 0; i < pic->nb_refs; i++) {
155             av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
156                    pic->refs[i]->display_order, pic->refs[i]->encode_order);
157         }
158         av_log(avctx, AV_LOG_DEBUG, ".\n");
159     }
160
161     av_assert0(pic->input_available && !pic->encode_issued);
162     for (i = 0; i < pic->nb_refs; i++) {
163         av_assert0(pic->refs[i]);
164         // If we are serialised then the references must have already
165         // completed.  If not, they must have been issued but need not
166         // have completed yet.
167         if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
168             av_assert0(pic->refs[i]->encode_complete);
169         else
170             av_assert0(pic->refs[i]->encode_issued);
171     }
172
173     av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
174
175     pic->recon_image = av_frame_alloc();
176     if (!pic->recon_image) {
177         err = AVERROR(ENOMEM);
178         goto fail;
179     }
180
181     err = av_hwframe_get_buffer(ctx->recon_frames_ref, pic->recon_image, 0);
182     if (err < 0) {
183         err = AVERROR(ENOMEM);
184         goto fail;
185     }
186     pic->recon_surface = (VASurfaceID)(uintptr_t)pic->recon_image->data[3];
187     av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
188
189     pic->output_buffer_ref = av_buffer_pool_get(ctx->output_buffer_pool);
190     if (!pic->output_buffer_ref) {
191         err = AVERROR(ENOMEM);
192         goto fail;
193     }
194     pic->output_buffer = (VABufferID)(uintptr_t)pic->output_buffer_ref->data;
195     av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
196            pic->output_buffer);
197
198     if (ctx->codec->picture_params_size > 0) {
199         pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
200         if (!pic->codec_picture_params)
201             goto fail;
202         memcpy(pic->codec_picture_params, ctx->codec_picture_params,
203                ctx->codec->picture_params_size);
204     } else {
205         av_assert0(!ctx->codec_picture_params);
206     }
207
208     pic->nb_param_buffers = 0;
209
210     if (pic->type == PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
211         err = vaapi_encode_make_param_buffer(avctx, pic,
212                                              VAEncSequenceParameterBufferType,
213                                              ctx->codec_sequence_params,
214                                              ctx->codec->sequence_params_size);
215         if (err < 0)
216             goto fail;
217     }
218
219     if (pic->type == PICTURE_TYPE_IDR) {
220         for (i = 0; i < ctx->nb_global_params; i++) {
221             err = vaapi_encode_make_param_buffer(avctx, pic,
222                                                  VAEncMiscParameterBufferType,
223                                                  (char*)ctx->global_params[i],
224                                                  ctx->global_params_size[i]);
225             if (err < 0)
226                 goto fail;
227         }
228     }
229
230     if (ctx->codec->init_picture_params) {
231         err = ctx->codec->init_picture_params(avctx, pic);
232         if (err < 0) {
233             av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
234                    "parameters: %d.\n", err);
235             goto fail;
236         }
237         err = vaapi_encode_make_param_buffer(avctx, pic,
238                                              VAEncPictureParameterBufferType,
239                                              pic->codec_picture_params,
240                                              ctx->codec->picture_params_size);
241         if (err < 0)
242             goto fail;
243     }
244
245     if (pic->type == PICTURE_TYPE_IDR) {
246         if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
247             ctx->codec->write_sequence_header) {
248             bit_len = 8 * sizeof(data);
249             err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
250             if (err < 0) {
251                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
252                        "header: %d.\n", err);
253                 goto fail;
254             }
255             err = vaapi_encode_make_packed_header(avctx, pic,
256                                                   ctx->codec->sequence_header_type,
257                                                   data, bit_len);
258             if (err < 0)
259                 goto fail;
260         }
261     }
262
263     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
264         ctx->codec->write_picture_header) {
265         bit_len = 8 * sizeof(data);
266         err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
267         if (err < 0) {
268             av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
269                    "header: %d.\n", err);
270             goto fail;
271         }
272         err = vaapi_encode_make_packed_header(avctx, pic,
273                                               ctx->codec->picture_header_type,
274                                               data, bit_len);
275         if (err < 0)
276             goto fail;
277     }
278
279     if (ctx->codec->write_extra_buffer) {
280         for (i = 0;; i++) {
281             size_t len = sizeof(data);
282             int type;
283             err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
284                                                  data, &len);
285             if (err == AVERROR_EOF)
286                 break;
287             if (err < 0) {
288                 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
289                        "buffer %d: %d.\n", i, err);
290                 goto fail;
291             }
292
293             err = vaapi_encode_make_param_buffer(avctx, pic, type,
294                                                  data, len);
295             if (err < 0)
296                 goto fail;
297         }
298     }
299
300     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
301         ctx->codec->write_extra_header) {
302         for (i = 0;; i++) {
303             int type;
304             bit_len = 8 * sizeof(data);
305             err = ctx->codec->write_extra_header(avctx, pic, i, &type,
306                                                  data, &bit_len);
307             if (err == AVERROR_EOF)
308                 break;
309             if (err < 0) {
310                 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
311                        "header %d: %d.\n", i, err);
312                 goto fail;
313             }
314
315             err = vaapi_encode_make_packed_header(avctx, pic, type,
316                                                   data, bit_len);
317             if (err < 0)
318                 goto fail;
319         }
320     }
321
322     if (pic->nb_slices > 0) {
323         pic->slices = av_mallocz_array(pic->nb_slices, sizeof(*pic->slices));
324         if (!pic->slices) {
325             err = AVERROR(ENOMEM);
326             goto fail;
327         }
328     }
329     for (i = 0; i < pic->nb_slices; i++) {
330         slice = &pic->slices[i];
331         slice->index = i;
332
333         if (ctx->codec->slice_params_size > 0) {
334             slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
335             if (!slice->codec_slice_params) {
336                 err = AVERROR(ENOMEM);
337                 goto fail;
338             }
339         }
340
341         if (ctx->codec->init_slice_params) {
342             err = ctx->codec->init_slice_params(avctx, pic, slice);
343             if (err < 0) {
344                 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
345                        "parameters: %d.\n", err);
346                 goto fail;
347             }
348         }
349
350         if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
351             ctx->codec->write_slice_header) {
352             bit_len = 8 * sizeof(data);
353             err = ctx->codec->write_slice_header(avctx, pic, slice,
354                                                  data, &bit_len);
355             if (err < 0) {
356                 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
357                        "header: %d.\n", err);
358                 goto fail;
359             }
360             err = vaapi_encode_make_packed_header(avctx, pic,
361                                                   ctx->codec->slice_header_type,
362                                                   data, bit_len);
363             if (err < 0)
364                 goto fail;
365         }
366
367         if (ctx->codec->init_slice_params) {
368             err = vaapi_encode_make_param_buffer(avctx, pic,
369                                                  VAEncSliceParameterBufferType,
370                                                  slice->codec_slice_params,
371                                                  ctx->codec->slice_params_size);
372             if (err < 0)
373                 goto fail;
374         }
375     }
376
377     vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
378                          pic->input_surface);
379     if (vas != VA_STATUS_SUCCESS) {
380         av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
381                "%d (%s).\n", vas, vaErrorStr(vas));
382         err = AVERROR(EIO);
383         goto fail_with_picture;
384     }
385
386     vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
387                           pic->param_buffers, pic->nb_param_buffers);
388     if (vas != VA_STATUS_SUCCESS) {
389         av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
390                "%d (%s).\n", vas, vaErrorStr(vas));
391         err = AVERROR(EIO);
392         goto fail_with_picture;
393     }
394
395     vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
396     if (vas != VA_STATUS_SUCCESS) {
397         av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
398                "%d (%s).\n", vas, vaErrorStr(vas));
399         err = AVERROR(EIO);
400         // vaRenderPicture() has been called here, so we should not destroy
401         // the parameter buffers unless separate destruction is required.
402         if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
403             AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
404             goto fail;
405         else
406             goto fail_at_end;
407     }
408
409     if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
410         AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
411         for (i = 0; i < pic->nb_param_buffers; i++) {
412             vas = vaDestroyBuffer(ctx->hwctx->display,
413                                   pic->param_buffers[i]);
414             if (vas != VA_STATUS_SUCCESS) {
415                 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
416                        "param buffer %#x: %d (%s).\n",
417                        pic->param_buffers[i], vas, vaErrorStr(vas));
418                 // And ignore.
419             }
420         }
421     }
422
423     pic->encode_issued = 1;
424
425     if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING)
426         return vaapi_encode_wait(avctx, pic);
427     else
428         return 0;
429
430 fail_with_picture:
431     vaEndPicture(ctx->hwctx->display, ctx->va_context);
432 fail:
433     for(i = 0; i < pic->nb_param_buffers; i++)
434         vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
435     for (i = 0; i < pic->nb_slices; i++) {
436         if (pic->slices) {
437             av_freep(&pic->slices[i].priv_data);
438             av_freep(&pic->slices[i].codec_slice_params);
439         }
440     }
441 fail_at_end:
442     av_freep(&pic->codec_picture_params);
443     av_freep(&pic->param_buffers);
444     av_freep(&pic->slices);
445     av_frame_free(&pic->recon_image);
446     av_buffer_unref(&pic->output_buffer_ref);
447     pic->output_buffer = VA_INVALID_ID;
448     return err;
449 }
450
451 static int vaapi_encode_output(AVCodecContext *avctx,
452                                VAAPIEncodePicture *pic, AVPacket *pkt)
453 {
454     VAAPIEncodeContext *ctx = avctx->priv_data;
455     VACodedBufferSegment *buf_list, *buf;
456     VAStatus vas;
457     int err;
458
459     err = vaapi_encode_wait(avctx, pic);
460     if (err < 0)
461         return err;
462
463     buf_list = NULL;
464     vas = vaMapBuffer(ctx->hwctx->display, pic->output_buffer,
465                       (void**)&buf_list);
466     if (vas != VA_STATUS_SUCCESS) {
467         av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
468                "%d (%s).\n", vas, vaErrorStr(vas));
469         err = AVERROR(EIO);
470         goto fail;
471     }
472
473     for (buf = buf_list; buf; buf = buf->next) {
474         av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
475                "(status %08x).\n", buf->size, buf->status);
476
477         err = av_new_packet(pkt, buf->size);
478         if (err < 0)
479             goto fail_mapped;
480
481         memcpy(pkt->data, buf->buf, buf->size);
482     }
483
484     if (pic->type == PICTURE_TYPE_IDR)
485         pkt->flags |= AV_PKT_FLAG_KEY;
486
487     pkt->pts = pic->pts;
488
489     vas = vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
490     if (vas != VA_STATUS_SUCCESS) {
491         av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
492                "%d (%s).\n", vas, vaErrorStr(vas));
493         err = AVERROR(EIO);
494         goto fail;
495     }
496
497     av_buffer_unref(&pic->output_buffer_ref);
498     pic->output_buffer = VA_INVALID_ID;
499
500     av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
501            pic->display_order, pic->encode_order);
502     return 0;
503
504 fail_mapped:
505     vaUnmapBuffer(ctx->hwctx->display, pic->output_buffer);
506 fail:
507     av_buffer_unref(&pic->output_buffer_ref);
508     pic->output_buffer = VA_INVALID_ID;
509     return err;
510 }
511
512 static int vaapi_encode_discard(AVCodecContext *avctx,
513                                 VAAPIEncodePicture *pic)
514 {
515     vaapi_encode_wait(avctx, pic);
516
517     if (pic->output_buffer_ref) {
518         av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
519                "%"PRId64"/%"PRId64".\n",
520                pic->display_order, pic->encode_order);
521
522         av_buffer_unref(&pic->output_buffer_ref);
523         pic->output_buffer = VA_INVALID_ID;
524     }
525
526     return 0;
527 }
528
529 static VAAPIEncodePicture *vaapi_encode_alloc(void)
530 {
531     VAAPIEncodePicture *pic;
532
533     pic = av_mallocz(sizeof(*pic));
534     if (!pic)
535         return NULL;
536
537     pic->input_surface = VA_INVALID_ID;
538     pic->recon_surface = VA_INVALID_ID;
539     pic->output_buffer = VA_INVALID_ID;
540
541     return pic;
542 }
543
544 static int vaapi_encode_free(AVCodecContext *avctx,
545                              VAAPIEncodePicture *pic)
546 {
547     int i;
548
549     if (pic->encode_issued)
550         vaapi_encode_discard(avctx, pic);
551
552     for (i = 0; i < pic->nb_slices; i++) {
553         if (pic->slices) {
554             av_freep(&pic->slices[i].priv_data);
555             av_freep(&pic->slices[i].codec_slice_params);
556         }
557     }
558     av_freep(&pic->codec_picture_params);
559
560     av_frame_free(&pic->input_image);
561     av_frame_free(&pic->recon_image);
562
563     av_freep(&pic->param_buffers);
564     av_freep(&pic->slices);
565     // Output buffer should already be destroyed.
566     av_assert0(pic->output_buffer == VA_INVALID_ID);
567
568     av_freep(&pic->priv_data);
569     av_freep(&pic->codec_picture_params);
570
571     av_free(pic);
572
573     return 0;
574 }
575
576 static int vaapi_encode_step(AVCodecContext *avctx,
577                              VAAPIEncodePicture *target)
578 {
579     VAAPIEncodeContext *ctx = avctx->priv_data;
580     VAAPIEncodePicture *pic;
581     int i, err;
582
583     if (ctx->issue_mode == ISSUE_MODE_SERIALISE_EVERYTHING ||
584         ctx->issue_mode == ISSUE_MODE_MINIMISE_LATENCY) {
585         // These two modes are equivalent, except that we wait for
586         // immediate completion on each operation if serialised.
587
588         if (!target) {
589             // No target, nothing to do yet.
590             return 0;
591         }
592
593         if (target->encode_complete) {
594             // Already done.
595             return 0;
596         }
597
598         pic = target;
599         for (i = 0; i < pic->nb_refs; i++) {
600             if (!pic->refs[i]->encode_complete) {
601                 err = vaapi_encode_step(avctx, pic->refs[i]);
602                 if (err < 0)
603                     return err;
604             }
605         }
606
607         err = vaapi_encode_issue(avctx, pic);
608         if (err < 0)
609             return err;
610
611     } else if (ctx->issue_mode == ISSUE_MODE_MAXIMISE_THROUGHPUT) {
612         int activity;
613
614         // Run through the list of all available pictures repeatedly
615         // and issue the first one found which has all dependencies
616         // available (including previously-issued but not necessarily
617         // completed pictures).
618         do {
619             activity = 0;
620             for (pic = ctx->pic_start; pic; pic = pic->next) {
621                 if (!pic->input_available || pic->encode_issued)
622                     continue;
623                 for (i = 0; i < pic->nb_refs; i++) {
624                     if (!pic->refs[i]->encode_issued)
625                         break;
626                 }
627                 if (i < pic->nb_refs)
628                     continue;
629                 err = vaapi_encode_issue(avctx, pic);
630                 if (err < 0)
631                     return err;
632                 activity = 1;
633                 // Start again from the beginning of the list,
634                 // because issuing this picture may have satisfied
635                 // forward dependencies of earlier ones.
636                 break;
637             }
638         } while(activity);
639
640         // If we had a defined target for this step then it will
641         // always have been issued by now.
642         if (target) {
643             av_assert0(target->encode_issued && "broken dependencies?");
644         }
645
646     } else {
647         av_assert0(0);
648     }
649
650     return 0;
651 }
652
653 static int vaapi_encode_get_next(AVCodecContext *avctx,
654                                  VAAPIEncodePicture **pic_out)
655 {
656     VAAPIEncodeContext *ctx = avctx->priv_data;
657     VAAPIEncodePicture *start, *end, *pic;
658     int i;
659
660     for (pic = ctx->pic_start; pic; pic = pic->next) {
661         if (pic->next)
662             av_assert0(pic->display_order + 1 == pic->next->display_order);
663         if (pic->display_order == ctx->input_order) {
664             *pic_out = pic;
665             return 0;
666         }
667     }
668
669     pic = vaapi_encode_alloc();
670     if (!pic)
671         return AVERROR(ENOMEM);
672
673     if (ctx->input_order == 0 || ctx->force_idr ||
674         ctx->gop_counter >= avctx->gop_size) {
675         pic->type = PICTURE_TYPE_IDR;
676         ctx->force_idr = 0;
677         ctx->gop_counter = 1;
678         ctx->p_counter = 0;
679     } else if (ctx->p_counter >= ctx->p_per_i) {
680         pic->type = PICTURE_TYPE_I;
681         ++ctx->gop_counter;
682         ctx->p_counter = 0;
683     } else {
684         pic->type = PICTURE_TYPE_P;
685         pic->refs[0] = ctx->pic_end;
686         pic->nb_refs = 1;
687         ++ctx->gop_counter;
688         ++ctx->p_counter;
689     }
690     start = end = pic;
691
692     if (pic->type != PICTURE_TYPE_IDR) {
693         // If that was not an IDR frame, add B-frames display-before and
694         // encode-after it, but not exceeding the GOP size.
695
696         for (i = 0; i < ctx->b_per_p &&
697              ctx->gop_counter < avctx->gop_size; i++) {
698             pic = vaapi_encode_alloc();
699             if (!pic)
700                 goto fail;
701
702             pic->type = PICTURE_TYPE_B;
703             pic->refs[0] = ctx->pic_end;
704             pic->refs[1] = end;
705             pic->nb_refs = 2;
706
707             pic->next = start;
708             pic->display_order = ctx->input_order + ctx->b_per_p - i - 1;
709             pic->encode_order  = pic->display_order + 1;
710             start = pic;
711
712             ++ctx->gop_counter;
713         }
714     }
715
716     if (ctx->input_order == 0) {
717         pic->display_order = 0;
718         pic->encode_order  = 0;
719
720         ctx->pic_start = ctx->pic_end = pic;
721
722     } else {
723         for (i = 0, pic = start; pic; i++, pic = pic->next) {
724             pic->display_order = ctx->input_order + i;
725             if (end->type == PICTURE_TYPE_IDR)
726                 pic->encode_order = ctx->input_order + i;
727             else if (pic == end)
728                 pic->encode_order = ctx->input_order;
729             else
730                 pic->encode_order = ctx->input_order + i + 1;
731         }
732
733         av_assert0(ctx->pic_end);
734         ctx->pic_end->next = start;
735         ctx->pic_end = end;
736     }
737     *pic_out = start;
738
739     av_log(avctx, AV_LOG_DEBUG, "Pictures:");
740     for (pic = ctx->pic_start; pic; pic = pic->next) {
741         av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
742                picture_type_name[pic->type],
743                pic->display_order, pic->encode_order);
744     }
745     av_log(avctx, AV_LOG_DEBUG, "\n");
746
747     return 0;
748
749 fail:
750     while (start) {
751         pic = start->next;
752         vaapi_encode_free(avctx, start);
753         start = pic;
754     }
755     return AVERROR(ENOMEM);
756 }
757
758 static int vaapi_encode_truncate_gop(AVCodecContext *avctx)
759 {
760     VAAPIEncodeContext *ctx = avctx->priv_data;
761     VAAPIEncodePicture *pic, *last_pic, *next;
762
763     av_assert0(!ctx->pic_start || ctx->pic_start->input_available);
764
765     // Find the last picture we actually have input for.
766     for (pic = ctx->pic_start; pic; pic = pic->next) {
767         if (!pic->input_available)
768             break;
769         last_pic = pic;
770     }
771
772     if (pic) {
773         if (last_pic->type == PICTURE_TYPE_B) {
774             // Some fixing up is required.  Change the type of this
775             // picture to P, then modify preceding B references which
776             // point beyond it to point at it instead.
777
778             last_pic->type = PICTURE_TYPE_P;
779             last_pic->encode_order = last_pic->refs[1]->encode_order;
780
781             for (pic = ctx->pic_start; pic != last_pic; pic = pic->next) {
782                 if (pic->type == PICTURE_TYPE_B &&
783                     pic->refs[1] == last_pic->refs[1])
784                     pic->refs[1] = last_pic;
785             }
786
787             last_pic->nb_refs = 1;
788             last_pic->refs[1] = NULL;
789         } else {
790             // We can use the current structure (no references point
791             // beyond the end), but there are unused pics to discard.
792         }
793
794         // Discard all following pics, they will never be used.
795         for (pic = last_pic->next; pic; pic = next) {
796             next = pic->next;
797             vaapi_encode_free(avctx, pic);
798         }
799
800         last_pic->next = NULL;
801         ctx->pic_end = last_pic;
802
803     } else {
804         // Input is available for all pictures, so we don't need to
805         // mangle anything.
806     }
807
808     av_log(avctx, AV_LOG_DEBUG, "Pictures ending truncated GOP:");
809     for (pic = ctx->pic_start; pic; pic = pic->next) {
810         av_log(avctx, AV_LOG_DEBUG, " %s (%"PRId64"/%"PRId64")",
811                picture_type_name[pic->type],
812                pic->display_order, pic->encode_order);
813     }
814     av_log(avctx, AV_LOG_DEBUG, "\n");
815
816     return 0;
817 }
818
819 static int vaapi_encode_clear_old(AVCodecContext *avctx)
820 {
821     VAAPIEncodeContext *ctx = avctx->priv_data;
822     VAAPIEncodePicture *pic, *old;
823     int i;
824
825     while (ctx->pic_start != ctx->pic_end) {
826         old = ctx->pic_start;
827         if (old->encode_order > ctx->output_order)
828             break;
829
830         for (pic = old->next; pic; pic = pic->next) {
831             if (pic->encode_complete)
832                 continue;
833             for (i = 0; i < pic->nb_refs; i++) {
834                 if (pic->refs[i] == old) {
835                     // We still need this picture because it's referred to
836                     // directly by a later one, so it and all following
837                     // pictures have to stay.
838                     return 0;
839                 }
840             }
841         }
842
843         pic = ctx->pic_start;
844         ctx->pic_start = pic->next;
845         vaapi_encode_free(avctx, pic);
846     }
847
848     return 0;
849 }
850
851 int ff_vaapi_encode2(AVCodecContext *avctx, AVPacket *pkt,
852                      const AVFrame *input_image, int *got_packet)
853 {
854     VAAPIEncodeContext *ctx = avctx->priv_data;
855     VAAPIEncodePicture *pic;
856     int err;
857
858     if (input_image) {
859         av_log(avctx, AV_LOG_DEBUG, "Encode frame: %ux%u (%"PRId64").\n",
860                input_image->width, input_image->height, input_image->pts);
861
862         if (input_image->pict_type == AV_PICTURE_TYPE_I) {
863             err = vaapi_encode_truncate_gop(avctx);
864             if (err < 0)
865                 goto fail;
866             ctx->force_idr = 1;
867         }
868
869         err = vaapi_encode_get_next(avctx, &pic);
870         if (err) {
871             av_log(avctx, AV_LOG_ERROR, "Input setup failed: %d.\n", err);
872             return err;
873         }
874
875         pic->input_image = av_frame_alloc();
876         if (!pic->input_image) {
877             err = AVERROR(ENOMEM);
878             goto fail;
879         }
880         err = av_frame_ref(pic->input_image, input_image);
881         if (err < 0)
882             goto fail;
883         pic->input_surface = (VASurfaceID)(uintptr_t)input_image->data[3];
884         pic->pts = input_image->pts;
885
886         if (ctx->input_order == 0)
887             ctx->first_pts = pic->pts;
888         if (ctx->input_order == ctx->decode_delay)
889             ctx->dts_pts_diff = pic->pts - ctx->first_pts;
890         if (ctx->output_delay > 0)
891             ctx->ts_ring[ctx->input_order % (3 * ctx->output_delay)] = pic->pts;
892
893         pic->input_available = 1;
894
895     } else {
896         if (!ctx->end_of_stream) {
897             err = vaapi_encode_truncate_gop(avctx);
898             if (err < 0)
899                 goto fail;
900             ctx->end_of_stream = 1;
901         }
902     }
903
904     ++ctx->input_order;
905     ++ctx->output_order;
906     av_assert0(ctx->output_order + ctx->output_delay + 1 == ctx->input_order);
907
908     for (pic = ctx->pic_start; pic; pic = pic->next)
909         if (pic->encode_order == ctx->output_order)
910             break;
911
912     // pic can be null here if we don't have a specific target in this
913     // iteration.  We might still issue encodes if things can be overlapped,
914     // even though we don't intend to output anything.
915
916     err = vaapi_encode_step(avctx, pic);
917     if (err < 0) {
918         av_log(avctx, AV_LOG_ERROR, "Encode failed: %d.\n", err);
919         goto fail;
920     }
921
922     if (!pic) {
923         *got_packet = 0;
924     } else {
925         err = vaapi_encode_output(avctx, pic, pkt);
926         if (err < 0) {
927             av_log(avctx, AV_LOG_ERROR, "Output failed: %d.\n", err);
928             goto fail;
929         }
930
931         if (ctx->output_delay == 0) {
932             pkt->dts = pkt->pts;
933         } else if (ctx->output_order < ctx->decode_delay) {
934             if (ctx->ts_ring[ctx->output_order] < INT64_MIN + ctx->dts_pts_diff)
935                 pkt->dts = INT64_MIN;
936             else
937                 pkt->dts = ctx->ts_ring[ctx->output_order] - ctx->dts_pts_diff;
938         } else {
939             pkt->dts = ctx->ts_ring[(ctx->output_order - ctx->decode_delay) %
940                                     (3 * ctx->output_delay)];
941         }
942
943         *got_packet = 1;
944     }
945
946     err = vaapi_encode_clear_old(avctx);
947     if (err < 0) {
948         av_log(avctx, AV_LOG_ERROR, "List clearing failed: %d.\n", err);
949         goto fail;
950     }
951
952     return 0;
953
954 fail:
955     // Unclear what to clean up on failure.  There are probably some things we
956     // could do usefully clean up here, but for now just leave them for uninit()
957     // to do instead.
958     return err;
959 }
960
961 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx,
962                                                   VAEncMiscParameterBuffer *buffer,
963                                                   size_t size)
964 {
965     VAAPIEncodeContext *ctx = avctx->priv_data;
966
967     av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
968
969     ctx->global_params     [ctx->nb_global_params] = buffer;
970     ctx->global_params_size[ctx->nb_global_params] = size;
971
972     ++ctx->nb_global_params;
973 }
974
975 typedef struct VAAPIEncodeRTFormat {
976     const char *name;
977     unsigned int value;
978     int depth;
979     int nb_components;
980     int log2_chroma_w;
981     int log2_chroma_h;
982 } VAAPIEncodeRTFormat;
983
984 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
985     { "YUV400",    VA_RT_FORMAT_YUV400,        8, 1,      },
986     { "YUV420",    VA_RT_FORMAT_YUV420,        8, 3, 1, 1 },
987     { "YUV422",    VA_RT_FORMAT_YUV422,        8, 3, 1, 0 },
988     { "YUV444",    VA_RT_FORMAT_YUV444,        8, 3, 0, 0 },
989     { "YUV411",    VA_RT_FORMAT_YUV411,        8, 3, 2, 0 },
990 #if VA_CHECK_VERSION(0, 38, 1)
991     { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
992 #endif
993 };
994
995 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
996     VAEntrypointEncSlice,
997     VAEntrypointEncPicture,
998 #if VA_CHECK_VERSION(0, 39, 2)
999     VAEntrypointEncSliceLP,
1000 #endif
1001     0
1002 };
1003 #if VA_CHECK_VERSION(0, 39, 2)
1004 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
1005     VAEntrypointEncSliceLP,
1006     0
1007 };
1008 #endif
1009
1010 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
1011 {
1012     VAAPIEncodeContext      *ctx = avctx->priv_data;
1013     VAProfile    *va_profiles    = NULL;
1014     VAEntrypoint *va_entrypoints = NULL;
1015     VAStatus vas;
1016     const VAEntrypoint *usable_entrypoints;
1017     const VAAPIEncodeProfile *profile;
1018     const AVPixFmtDescriptor *desc;
1019     VAConfigAttrib rt_format_attr;
1020     const VAAPIEncodeRTFormat *rt_format;
1021     const char *profile_string, *entrypoint_string;
1022     int i, j, n, depth, err;
1023
1024
1025     if (ctx->low_power) {
1026 #if VA_CHECK_VERSION(0, 39, 2)
1027         usable_entrypoints = vaapi_encode_entrypoints_low_power;
1028 #else
1029         av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
1030                "supported with this VAAPI version.\n");
1031         return AVERROR(EINVAL);
1032 #endif
1033     } else {
1034         usable_entrypoints = vaapi_encode_entrypoints_normal;
1035     }
1036
1037     desc = av_pix_fmt_desc_get(ctx->input_frames->sw_format);
1038     if (!desc) {
1039         av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
1040                ctx->input_frames->sw_format);
1041         return AVERROR(EINVAL);
1042     }
1043     depth = desc->comp[0].depth;
1044     for (i = 1; i < desc->nb_components; i++) {
1045         if (desc->comp[i].depth != depth) {
1046             av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
1047                    desc->name);
1048             return AVERROR(EINVAL);
1049         }
1050     }
1051     av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
1052            desc->name);
1053
1054     n = vaMaxNumProfiles(ctx->hwctx->display);
1055     va_profiles = av_malloc_array(n, sizeof(VAProfile));
1056     if (!va_profiles) {
1057         err = AVERROR(ENOMEM);
1058         goto fail;
1059     }
1060     vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1061     if (vas != VA_STATUS_SUCCESS) {
1062         av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1063                vas, vaErrorStr(vas));
1064         err = AVERROR_EXTERNAL;
1065         goto fail;
1066     }
1067
1068     av_assert0(ctx->codec->profiles);
1069     for (i = 0; (ctx->codec->profiles[i].av_profile !=
1070                  FF_PROFILE_UNKNOWN); i++) {
1071         profile = &ctx->codec->profiles[i];
1072         if (depth               != profile->depth ||
1073             desc->nb_components != profile->nb_components)
1074             continue;
1075         if (desc->nb_components > 1 &&
1076             (desc->log2_chroma_w != profile->log2_chroma_w ||
1077              desc->log2_chroma_h != profile->log2_chroma_h))
1078             continue;
1079         if (avctx->profile != profile->av_profile &&
1080             avctx->profile != FF_PROFILE_UNKNOWN)
1081             continue;
1082
1083 #if VA_CHECK_VERSION(1, 0, 0)
1084         profile_string = vaProfileStr(profile->va_profile);
1085 #else
1086         profile_string = "(no profile names)";
1087 #endif
1088
1089         for (j = 0; j < n; j++) {
1090             if (va_profiles[j] == profile->va_profile)
1091                 break;
1092         }
1093         if (j >= n) {
1094             av_log(avctx, AV_LOG_VERBOSE, "Matching profile %d is "
1095                    "not supported by driver.\n", profile->va_profile);
1096             continue;
1097         }
1098
1099         ctx->profile = profile;
1100         break;
1101     }
1102     if (!ctx->profile) {
1103         av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1104         err = AVERROR(ENOSYS);
1105         goto fail;
1106     }
1107
1108     avctx->profile  = profile->av_profile;
1109     ctx->va_profile = profile->va_profile;
1110     av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1111            profile_string, ctx->va_profile);
1112
1113     n = vaMaxNumEntrypoints(ctx->hwctx->display);
1114     va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1115     if (!va_entrypoints) {
1116         err = AVERROR(ENOMEM);
1117         goto fail;
1118     }
1119     vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1120                                    va_entrypoints, &n);
1121     if (vas != VA_STATUS_SUCCESS) {
1122         av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1123                "profile %s (%d): %d (%s).\n", profile_string,
1124                ctx->va_profile, vas, vaErrorStr(vas));
1125         err = AVERROR_EXTERNAL;
1126         goto fail;
1127     }
1128
1129     for (i = 0; i < n; i++) {
1130         for (j = 0; usable_entrypoints[j]; j++) {
1131             if (va_entrypoints[i] == usable_entrypoints[j])
1132                 break;
1133         }
1134         if (usable_entrypoints[j])
1135             break;
1136     }
1137     if (i >= n) {
1138         av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1139                "for profile %s (%d).\n", profile_string, ctx->va_profile);
1140         err = AVERROR(ENOSYS);
1141         goto fail;
1142     }
1143
1144     ctx->va_entrypoint = va_entrypoints[i];
1145 #if VA_CHECK_VERSION(1, 0, 0)
1146     entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1147 #else
1148     entrypoint_string = "(no entrypoint names)";
1149 #endif
1150     av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1151            entrypoint_string, ctx->va_entrypoint);
1152
1153     for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1154         rt_format = &vaapi_encode_rt_formats[i];
1155         if (rt_format->depth         == depth &&
1156             rt_format->nb_components == profile->nb_components &&
1157             rt_format->log2_chroma_w == profile->log2_chroma_w &&
1158             rt_format->log2_chroma_h == profile->log2_chroma_h)
1159             break;
1160     }
1161     if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1162         av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1163                "found for profile %s (%d) entrypoint %s (%d).\n",
1164                profile_string, ctx->va_profile,
1165                entrypoint_string, ctx->va_entrypoint);
1166         err = AVERROR(ENOSYS);
1167         goto fail;
1168     }
1169
1170     rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1171     vas = vaGetConfigAttributes(ctx->hwctx->display,
1172                                 ctx->va_profile, ctx->va_entrypoint,
1173                                 &rt_format_attr, 1);
1174     if (vas != VA_STATUS_SUCCESS) {
1175         av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1176                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1177         err = AVERROR_EXTERNAL;
1178         goto fail;
1179     }
1180
1181     if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1182         av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1183                "supported by driver: assuming surface RT format %s "
1184                "is valid.\n", rt_format->name);
1185     } else if (!(rt_format_attr.value & rt_format->value)) {
1186         av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1187                "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1188                rt_format->name, profile_string, ctx->va_profile,
1189                entrypoint_string, ctx->va_entrypoint);
1190         err = AVERROR(ENOSYS);
1191         goto fail;
1192     } else {
1193         av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1194                "format %s (%#x).\n", rt_format->name, rt_format->value);
1195         ctx->config_attributes[ctx->nb_config_attributes++] =
1196             (VAConfigAttrib) {
1197             .type  = VAConfigAttribRTFormat,
1198             .value = rt_format->value,
1199         };
1200     }
1201
1202     err = 0;
1203 fail:
1204     av_freep(&va_profiles);
1205     av_freep(&va_entrypoints);
1206     return err;
1207 }
1208
1209 static av_cold int vaapi_encode_config_attributes(AVCodecContext *avctx)
1210 {
1211     VAAPIEncodeContext *ctx = avctx->priv_data;
1212     VAStatus vas;
1213     int i;
1214
1215     VAConfigAttrib attr[] = {
1216         { VAConfigAttribRateControl      },
1217         { VAConfigAttribEncMaxRefFrames  },
1218         { VAConfigAttribEncPackedHeaders },
1219     };
1220
1221     vas = vaGetConfigAttributes(ctx->hwctx->display,
1222                                 ctx->va_profile, ctx->va_entrypoint,
1223                                 attr, FF_ARRAY_ELEMS(attr));
1224     if (vas != VA_STATUS_SUCCESS) {
1225         av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "
1226                "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1227         return AVERROR(EINVAL);
1228     }
1229
1230     for (i = 0; i < FF_ARRAY_ELEMS(attr); i++) {
1231         if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {
1232             // Unfortunately we have to treat this as "don't know" and hope
1233             // for the best, because the Intel MJPEG encoder returns this
1234             // for all the interesting attributes.
1235             av_log(avctx, AV_LOG_DEBUG, "Attribute (%d) is not supported.\n",
1236                    attr[i].type);
1237             continue;
1238         }
1239         switch (attr[i].type) {
1240         case VAConfigAttribRateControl:
1241             // Hack for backward compatibility: CBR was the only
1242             // usable RC mode for a long time, so old drivers will
1243             // only have it.  Normal default options may now choose
1244             // VBR and then fail, however, so override it here with
1245             // CBR if that is the only supported mode.
1246             if (ctx->va_rc_mode == VA_RC_VBR &&
1247                 !(attr[i].value & VA_RC_VBR) &&
1248                 (attr[i].value & VA_RC_CBR)) {
1249                 av_log(avctx, AV_LOG_WARNING, "VBR rate control is "
1250                        "not supported with this driver version; "
1251                        "using CBR instead.\n");
1252                 ctx->va_rc_mode = VA_RC_CBR;
1253             }
1254             if (!(ctx->va_rc_mode & attr[i].value)) {
1255                 av_log(avctx, AV_LOG_ERROR, "Rate control mode %#x "
1256                        "is not supported (mask: %#x).\n",
1257                        ctx->va_rc_mode, attr[i].value);
1258                 return AVERROR(EINVAL);
1259             }
1260             ctx->config_attributes[ctx->nb_config_attributes++] =
1261                 (VAConfigAttrib) {
1262                 .type  = VAConfigAttribRateControl,
1263                 .value = ctx->va_rc_mode,
1264             };
1265             break;
1266         case VAConfigAttribEncMaxRefFrames:
1267         {
1268             unsigned int ref_l0 = attr[i].value & 0xffff;
1269             unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;
1270
1271             if (avctx->gop_size > 1 && ref_l0 < 1) {
1272                 av_log(avctx, AV_LOG_ERROR, "P frames are not "
1273                        "supported (%#x).\n", attr[i].value);
1274                 return AVERROR(EINVAL);
1275             }
1276             if (avctx->max_b_frames > 0 && ref_l1 < 1) {
1277                 av_log(avctx, AV_LOG_WARNING, "B frames are not "
1278                        "supported (%#x) by the underlying driver.\n",
1279                        attr[i].value);
1280                 avctx->max_b_frames = 0;
1281             }
1282         }
1283         break;
1284         case VAConfigAttribEncPackedHeaders:
1285             if (ctx->va_packed_headers & ~attr[i].value) {
1286                 // This isn't fatal, but packed headers are always
1287                 // preferable because they are under our control.
1288                 // When absent, the driver is generating them and some
1289                 // features may not work (e.g. VUI or SEI in H.264).
1290                 av_log(avctx, AV_LOG_WARNING, "Warning: some packed "
1291                        "headers are not supported (want %#x, got %#x).\n",
1292                        ctx->va_packed_headers, attr[i].value);
1293                 ctx->va_packed_headers &= attr[i].value;
1294             }
1295             ctx->config_attributes[ctx->nb_config_attributes++] =
1296                 (VAConfigAttrib) {
1297                 .type  = VAConfigAttribEncPackedHeaders,
1298                 .value = ctx->va_packed_headers,
1299             };
1300             break;
1301         default:
1302             av_assert0(0 && "Unexpected config attribute.");
1303         }
1304     }
1305
1306     return 0;
1307 }
1308
1309 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1310 {
1311     VAAPIEncodeContext *ctx = avctx->priv_data;
1312     int rc_bits_per_second;
1313     int rc_target_percentage;
1314     int rc_window_size;
1315     int hrd_buffer_size;
1316     int hrd_initial_buffer_fullness;
1317     int fr_num, fr_den;
1318
1319     if (avctx->bit_rate > INT32_MAX) {
1320         av_log(avctx, AV_LOG_ERROR, "Target bitrate of 2^31 bps or "
1321                "higher is not supported.\n");
1322         return AVERROR(EINVAL);
1323     }
1324
1325     if (avctx->rc_buffer_size)
1326         hrd_buffer_size = avctx->rc_buffer_size;
1327     else
1328         hrd_buffer_size = avctx->bit_rate;
1329     if (avctx->rc_initial_buffer_occupancy)
1330         hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1331     else
1332         hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1333
1334     if (ctx->va_rc_mode == VA_RC_CBR) {
1335         rc_bits_per_second   = avctx->bit_rate;
1336         rc_target_percentage = 100;
1337         rc_window_size       = 1000;
1338     } else {
1339         if (avctx->rc_max_rate < avctx->bit_rate) {
1340             // Max rate is unset or invalid, just use the normal bitrate.
1341             rc_bits_per_second   = avctx->bit_rate;
1342             rc_target_percentage = 100;
1343         } else {
1344             rc_bits_per_second   = avctx->rc_max_rate;
1345             rc_target_percentage = (avctx->bit_rate * 100) / rc_bits_per_second;
1346         }
1347         rc_window_size = (hrd_buffer_size * 1000) / avctx->bit_rate;
1348     }
1349
1350     ctx->rc_params.misc.type = VAEncMiscParameterTypeRateControl;
1351     ctx->rc_params.rc = (VAEncMiscParameterRateControl) {
1352         .bits_per_second   = rc_bits_per_second,
1353         .target_percentage = rc_target_percentage,
1354         .window_size       = rc_window_size,
1355         .initial_qp        = 0,
1356         .min_qp            = (avctx->qmin > 0 ? avctx->qmin : 0),
1357         .basic_unit_size   = 0,
1358     };
1359     vaapi_encode_add_global_param(avctx, &ctx->rc_params.misc,
1360                                   sizeof(ctx->rc_params));
1361
1362     ctx->hrd_params.misc.type = VAEncMiscParameterTypeHRD;
1363     ctx->hrd_params.hrd = (VAEncMiscParameterHRD) {
1364         .initial_buffer_fullness = hrd_initial_buffer_fullness,
1365         .buffer_size             = hrd_buffer_size,
1366     };
1367     vaapi_encode_add_global_param(avctx, &ctx->hrd_params.misc,
1368                                   sizeof(ctx->hrd_params));
1369
1370     if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1371         av_reduce(&fr_num, &fr_den,
1372                   avctx->framerate.num, avctx->framerate.den, 65535);
1373     else
1374         av_reduce(&fr_num, &fr_den,
1375                   avctx->time_base.den, avctx->time_base.num, 65535);
1376
1377     ctx->fr_params.misc.type = VAEncMiscParameterTypeFrameRate;
1378     ctx->fr_params.fr.framerate = (unsigned int)fr_den << 16 | fr_num;
1379
1380 #if VA_CHECK_VERSION(0, 40, 0)
1381     vaapi_encode_add_global_param(avctx, &ctx->fr_params.misc,
1382                                   sizeof(ctx->fr_params));
1383 #endif
1384
1385     return 0;
1386 }
1387
1388 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1389 {
1390 #if VA_CHECK_VERSION(0, 36, 0)
1391     VAAPIEncodeContext *ctx = avctx->priv_data;
1392     VAStatus vas;
1393     VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1394     int quality = avctx->compression_level;
1395
1396     vas = vaGetConfigAttributes(ctx->hwctx->display,
1397                                 ctx->va_profile,
1398                                 ctx->va_entrypoint,
1399                                 &attr, 1);
1400     if (vas != VA_STATUS_SUCCESS) {
1401         av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1402                "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1403         return AVERROR_EXTERNAL;
1404     }
1405
1406     if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1407         if (quality != 0) {
1408             av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1409                    "supported: will use default quality level.\n");
1410         }
1411     } else {
1412         if (quality > attr.value) {
1413             av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1414                    "valid range is 0-%d, using %d.\n",
1415                    attr.value, attr.value);
1416             quality = attr.value;
1417         }
1418
1419         ctx->quality_params.misc.type = VAEncMiscParameterTypeQualityLevel;
1420         ctx->quality_params.quality.quality_level = quality;
1421
1422         vaapi_encode_add_global_param(avctx, &ctx->quality_params.misc,
1423                                       sizeof(ctx->quality_params));
1424     }
1425 #else
1426     av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1427            "not supported with this VAAPI version.\n");
1428 #endif
1429
1430     return 0;
1431 }
1432
1433 static void vaapi_encode_free_output_buffer(void *opaque,
1434                                             uint8_t *data)
1435 {
1436     AVCodecContext   *avctx = opaque;
1437     VAAPIEncodeContext *ctx = avctx->priv_data;
1438     VABufferID buffer_id;
1439
1440     buffer_id = (VABufferID)(uintptr_t)data;
1441
1442     vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1443
1444     av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
1445 }
1446
1447 static AVBufferRef *vaapi_encode_alloc_output_buffer(void *opaque,
1448                                                      int size)
1449 {
1450     AVCodecContext   *avctx = opaque;
1451     VAAPIEncodeContext *ctx = avctx->priv_data;
1452     VABufferID buffer_id;
1453     VAStatus vas;
1454     AVBufferRef *ref;
1455
1456     // The output buffer size is fixed, so it needs to be large enough
1457     // to hold the largest possible compressed frame.  We assume here
1458     // that the uncompressed frame plus some header data is an upper
1459     // bound on that.
1460     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
1461                          VAEncCodedBufferType,
1462                          3 * ctx->surface_width * ctx->surface_height +
1463                          (1 << 16), 1, 0, &buffer_id);
1464     if (vas != VA_STATUS_SUCCESS) {
1465         av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
1466                "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
1467         return NULL;
1468     }
1469
1470     av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", buffer_id);
1471
1472     ref = av_buffer_create((uint8_t*)(uintptr_t)buffer_id,
1473                            sizeof(buffer_id),
1474                            &vaapi_encode_free_output_buffer,
1475                            avctx, AV_BUFFER_FLAG_READONLY);
1476     if (!ref) {
1477         vaDestroyBuffer(ctx->hwctx->display, buffer_id);
1478         return NULL;
1479     }
1480
1481     return ref;
1482 }
1483
1484 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
1485 {
1486     VAAPIEncodeContext *ctx = avctx->priv_data;
1487     AVVAAPIHWConfig *hwconfig = NULL;
1488     AVHWFramesConstraints *constraints = NULL;
1489     enum AVPixelFormat recon_format;
1490     int err, i;
1491
1492     hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
1493     if (!hwconfig) {
1494         err = AVERROR(ENOMEM);
1495         goto fail;
1496     }
1497     hwconfig->config_id = ctx->va_config;
1498
1499     constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
1500                                                       hwconfig);
1501     if (!constraints) {
1502         err = AVERROR(ENOMEM);
1503         goto fail;
1504     }
1505
1506     // Probably we can use the input surface format as the surface format
1507     // of the reconstructed frames.  If not, we just pick the first (only?)
1508     // format in the valid list and hope that it all works.
1509     recon_format = AV_PIX_FMT_NONE;
1510     if (constraints->valid_sw_formats) {
1511         for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
1512             if (ctx->input_frames->sw_format ==
1513                 constraints->valid_sw_formats[i]) {
1514                 recon_format = ctx->input_frames->sw_format;
1515                 break;
1516             }
1517         }
1518         if (recon_format == AV_PIX_FMT_NONE) {
1519             // No match.  Just use the first in the supported list and
1520             // hope for the best.
1521             recon_format = constraints->valid_sw_formats[0];
1522         }
1523     } else {
1524         // No idea what to use; copy input format.
1525         recon_format = ctx->input_frames->sw_format;
1526     }
1527     av_log(avctx, AV_LOG_DEBUG, "Using %s as format of "
1528            "reconstructed frames.\n", av_get_pix_fmt_name(recon_format));
1529
1530     if (ctx->surface_width  < constraints->min_width  ||
1531         ctx->surface_height < constraints->min_height ||
1532         ctx->surface_width  > constraints->max_width ||
1533         ctx->surface_height > constraints->max_height) {
1534         av_log(avctx, AV_LOG_ERROR, "Hardware does not support encoding at "
1535                "size %dx%d (constraints: width %d-%d height %d-%d).\n",
1536                ctx->surface_width, ctx->surface_height,
1537                constraints->min_width,  constraints->max_width,
1538                constraints->min_height, constraints->max_height);
1539         err = AVERROR(EINVAL);
1540         goto fail;
1541     }
1542
1543     av_freep(&hwconfig);
1544     av_hwframe_constraints_free(&constraints);
1545
1546     ctx->recon_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
1547     if (!ctx->recon_frames_ref) {
1548         err = AVERROR(ENOMEM);
1549         goto fail;
1550     }
1551     ctx->recon_frames = (AVHWFramesContext*)ctx->recon_frames_ref->data;
1552
1553     ctx->recon_frames->format    = AV_PIX_FMT_VAAPI;
1554     ctx->recon_frames->sw_format = recon_format;
1555     ctx->recon_frames->width     = ctx->surface_width;
1556     ctx->recon_frames->height    = ctx->surface_height;
1557     // At most three IDR/I/P frames and two runs of B frames can be in
1558     // flight at any one time.
1559     ctx->recon_frames->initial_pool_size = 3 + 2 * avctx->max_b_frames;
1560
1561     err = av_hwframe_ctx_init(ctx->recon_frames_ref);
1562     if (err < 0) {
1563         av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
1564                "frame context: %d.\n", err);
1565         goto fail;
1566     }
1567
1568     err = 0;
1569   fail:
1570     av_freep(&hwconfig);
1571     av_hwframe_constraints_free(&constraints);
1572     return err;
1573 }
1574
1575 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
1576 {
1577     VAAPIEncodeContext *ctx = avctx->priv_data;
1578     AVVAAPIFramesContext *recon_hwctx = NULL;
1579     VAStatus vas;
1580     int err;
1581
1582     if (!avctx->hw_frames_ctx) {
1583         av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
1584                "required to associate the encoding device.\n");
1585         return AVERROR(EINVAL);
1586     }
1587
1588     ctx->va_config  = VA_INVALID_ID;
1589     ctx->va_context = VA_INVALID_ID;
1590
1591     ctx->input_frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
1592     if (!ctx->input_frames_ref) {
1593         err = AVERROR(ENOMEM);
1594         goto fail;
1595     }
1596     ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
1597
1598     ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
1599     if (!ctx->device_ref) {
1600         err = AVERROR(ENOMEM);
1601         goto fail;
1602     }
1603     ctx->device = (AVHWDeviceContext*)ctx->device_ref->data;
1604     ctx->hwctx = ctx->device->hwctx;
1605
1606     err = vaapi_encode_profile_entrypoint(avctx);
1607     if (err < 0)
1608         goto fail;
1609
1610     err = vaapi_encode_config_attributes(avctx);
1611     if (err < 0)
1612         goto fail;
1613
1614     if (avctx->compression_level >= 0) {
1615         err = vaapi_encode_init_quality(avctx);
1616         if (err < 0)
1617             goto fail;
1618     }
1619
1620     vas = vaCreateConfig(ctx->hwctx->display,
1621                          ctx->va_profile, ctx->va_entrypoint,
1622                          ctx->config_attributes, ctx->nb_config_attributes,
1623                          &ctx->va_config);
1624     if (vas != VA_STATUS_SUCCESS) {
1625         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1626                "configuration: %d (%s).\n", vas, vaErrorStr(vas));
1627         err = AVERROR(EIO);
1628         goto fail;
1629     }
1630
1631     err = vaapi_encode_create_recon_frames(avctx);
1632     if (err < 0)
1633         goto fail;
1634
1635     recon_hwctx = ctx->recon_frames->hwctx;
1636     vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
1637                           ctx->surface_width, ctx->surface_height,
1638                           VA_PROGRESSIVE,
1639                           recon_hwctx->surface_ids,
1640                           recon_hwctx->nb_surfaces,
1641                           &ctx->va_context);
1642     if (vas != VA_STATUS_SUCCESS) {
1643         av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
1644                "context: %d (%s).\n", vas, vaErrorStr(vas));
1645         err = AVERROR(EIO);
1646         goto fail;
1647     }
1648
1649     ctx->output_buffer_pool =
1650         av_buffer_pool_init2(sizeof(VABufferID), avctx,
1651                              &vaapi_encode_alloc_output_buffer, NULL);
1652     if (!ctx->output_buffer_pool) {
1653         err = AVERROR(ENOMEM);
1654         goto fail;
1655     }
1656
1657     if (ctx->va_rc_mode & ~VA_RC_CQP) {
1658         err = vaapi_encode_init_rate_control(avctx);
1659         if (err < 0)
1660             goto fail;
1661     }
1662
1663     if (ctx->codec->configure) {
1664         err = ctx->codec->configure(avctx);
1665         if (err < 0)
1666             goto fail;
1667     }
1668
1669     ctx->input_order  = 0;
1670     ctx->output_delay = avctx->max_b_frames;
1671     ctx->decode_delay = 1;
1672     ctx->output_order = - ctx->output_delay - 1;
1673
1674     // Currently we never generate I frames, only IDR.
1675     ctx->p_per_i = INT_MAX;
1676     ctx->b_per_p = avctx->max_b_frames;
1677
1678     if (ctx->codec->sequence_params_size > 0) {
1679         ctx->codec_sequence_params =
1680             av_mallocz(ctx->codec->sequence_params_size);
1681         if (!ctx->codec_sequence_params) {
1682             err = AVERROR(ENOMEM);
1683             goto fail;
1684         }
1685     }
1686     if (ctx->codec->picture_params_size > 0) {
1687         ctx->codec_picture_params =
1688             av_mallocz(ctx->codec->picture_params_size);
1689         if (!ctx->codec_picture_params) {
1690             err = AVERROR(ENOMEM);
1691             goto fail;
1692         }
1693     }
1694
1695     if (ctx->codec->init_sequence_params) {
1696         err = ctx->codec->init_sequence_params(avctx);
1697         if (err < 0) {
1698             av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
1699                    "failed: %d.\n", err);
1700             goto fail;
1701         }
1702     }
1703
1704     // This should be configurable somehow.  (Needs testing on a machine
1705     // where it actually overlaps properly, though.)
1706     ctx->issue_mode = ISSUE_MODE_MAXIMISE_THROUGHPUT;
1707
1708     if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
1709         ctx->codec->write_sequence_header) {
1710         char data[MAX_PARAM_BUFFER_SIZE];
1711         size_t bit_len = 8 * sizeof(data);
1712
1713         err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
1714         if (err < 0) {
1715             av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
1716                    "for extradata: %d.\n", err);
1717             goto fail;
1718         } else {
1719             avctx->extradata_size = (bit_len + 7) / 8;
1720             avctx->extradata = av_mallocz(avctx->extradata_size +
1721                                           AV_INPUT_BUFFER_PADDING_SIZE);
1722             if (!avctx->extradata) {
1723                 err = AVERROR(ENOMEM);
1724                 goto fail;
1725             }
1726             memcpy(avctx->extradata, data, avctx->extradata_size);
1727         }
1728     }
1729
1730     return 0;
1731
1732 fail:
1733     ff_vaapi_encode_close(avctx);
1734     return err;
1735 }
1736
1737 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
1738 {
1739     VAAPIEncodeContext *ctx = avctx->priv_data;
1740     VAAPIEncodePicture *pic, *next;
1741
1742     for (pic = ctx->pic_start; pic; pic = next) {
1743         next = pic->next;
1744         vaapi_encode_free(avctx, pic);
1745     }
1746
1747     av_buffer_pool_uninit(&ctx->output_buffer_pool);
1748
1749     if (ctx->va_context != VA_INVALID_ID) {
1750         vaDestroyContext(ctx->hwctx->display, ctx->va_context);
1751         ctx->va_context = VA_INVALID_ID;
1752     }
1753
1754     if (ctx->va_config != VA_INVALID_ID) {
1755         vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
1756         ctx->va_config = VA_INVALID_ID;
1757     }
1758
1759     av_freep(&ctx->codec_sequence_params);
1760     av_freep(&ctx->codec_picture_params);
1761
1762     av_buffer_unref(&ctx->recon_frames_ref);
1763     av_buffer_unref(&ctx->input_frames_ref);
1764     av_buffer_unref(&ctx->device_ref);
1765
1766     return 0;
1767 }