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