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