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