FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavcodec/vaapi_encode.c
Date: 2024-07-26 21:54:09
Exec Total Coverage
Lines: 0 1159 0.0%
Functions: 0 31 0.0%
Branches: 0 704 0.0%

Line Branch Exec Source
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 "config.h"
23
24 #include "libavutil/avassert.h"
25 #include "libavutil/common.h"
26 #include "libavutil/internal.h"
27 #include "libavutil/log.h"
28 #include "libavutil/mem.h"
29 #include "libavutil/pixdesc.h"
30
31 #include "vaapi_encode.h"
32 #include "encode.h"
33 #include "avcodec.h"
34 #include "refstruct.h"
35
36 const AVCodecHWConfigInternal *const ff_vaapi_encode_hw_configs[] = {
37 HW_CONFIG_ENCODER_FRAMES(VAAPI, VAAPI),
38 NULL,
39 };
40
41 static int vaapi_encode_make_packed_header(AVCodecContext *avctx,
42 VAAPIEncodePicture *pic,
43 int type, char *data, size_t bit_len)
44 {
45 VAAPIEncodeContext *ctx = avctx->priv_data;
46 VAStatus vas;
47 VABufferID param_buffer, data_buffer;
48 VABufferID *tmp;
49 VAEncPackedHeaderParameterBuffer params = {
50 .type = type,
51 .bit_length = bit_len,
52 .has_emulation_bytes = 1,
53 };
54
55 tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 2);
56 if (!tmp)
57 return AVERROR(ENOMEM);
58 pic->param_buffers = tmp;
59
60 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
61 VAEncPackedHeaderParameterBufferType,
62 sizeof(params), 1, &params, &param_buffer);
63 if (vas != VA_STATUS_SUCCESS) {
64 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
65 "for packed header (type %d): %d (%s).\n",
66 type, vas, vaErrorStr(vas));
67 return AVERROR(EIO);
68 }
69 pic->param_buffers[pic->nb_param_buffers++] = param_buffer;
70
71 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
72 VAEncPackedHeaderDataBufferType,
73 (bit_len + 7) / 8, 1, data, &data_buffer);
74 if (vas != VA_STATUS_SUCCESS) {
75 av_log(avctx, AV_LOG_ERROR, "Failed to create data buffer "
76 "for packed header (type %d): %d (%s).\n",
77 type, vas, vaErrorStr(vas));
78 return AVERROR(EIO);
79 }
80 pic->param_buffers[pic->nb_param_buffers++] = data_buffer;
81
82 av_log(avctx, AV_LOG_DEBUG, "Packed header buffer (%d) is %#x/%#x "
83 "(%zu bits).\n", type, param_buffer, data_buffer, bit_len);
84 return 0;
85 }
86
87 static int vaapi_encode_make_param_buffer(AVCodecContext *avctx,
88 VAAPIEncodePicture *pic,
89 int type, char *data, size_t len)
90 {
91 VAAPIEncodeContext *ctx = avctx->priv_data;
92 VAStatus vas;
93 VABufferID *tmp;
94 VABufferID buffer;
95
96 tmp = av_realloc_array(pic->param_buffers, sizeof(*tmp), pic->nb_param_buffers + 1);
97 if (!tmp)
98 return AVERROR(ENOMEM);
99 pic->param_buffers = tmp;
100
101 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
102 type, len, 1, data, &buffer);
103 if (vas != VA_STATUS_SUCCESS) {
104 av_log(avctx, AV_LOG_ERROR, "Failed to create parameter buffer "
105 "(type %d): %d (%s).\n", type, vas, vaErrorStr(vas));
106 return AVERROR(EIO);
107 }
108 pic->param_buffers[pic->nb_param_buffers++] = buffer;
109
110 av_log(avctx, AV_LOG_DEBUG, "Param buffer (%d) is %#x.\n",
111 type, buffer);
112 return 0;
113 }
114
115 static int vaapi_encode_make_misc_param_buffer(AVCodecContext *avctx,
116 VAAPIEncodePicture *pic,
117 int type,
118 const void *data, size_t len)
119 {
120 // Construct the buffer on the stack - 1KB is much larger than any
121 // current misc parameter buffer type (the largest is EncQuality at
122 // 224 bytes).
123 uint8_t buffer[1024];
124 VAEncMiscParameterBuffer header = {
125 .type = type,
126 };
127 size_t buffer_size = sizeof(header) + len;
128 av_assert0(buffer_size <= sizeof(buffer));
129
130 memcpy(buffer, &header, sizeof(header));
131 memcpy(buffer + sizeof(header), data, len);
132
133 return vaapi_encode_make_param_buffer(avctx, pic,
134 VAEncMiscParameterBufferType,
135 buffer, buffer_size);
136 }
137
138 static int vaapi_encode_wait(AVCodecContext *avctx,
139 VAAPIEncodePicture *pic)
140 {
141 #if VA_CHECK_VERSION(1, 9, 0)
142 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
143 #endif
144 VAAPIEncodeContext *ctx = avctx->priv_data;
145 FFHWBaseEncodePicture *base_pic = &pic->base;
146 VAStatus vas;
147
148 av_assert0(base_pic->encode_issued);
149
150 if (base_pic->encode_complete) {
151 // Already waited for this picture.
152 return 0;
153 }
154
155 av_log(avctx, AV_LOG_DEBUG, "Sync to pic %"PRId64"/%"PRId64" "
156 "(input surface %#x).\n", base_pic->display_order,
157 base_pic->encode_order, pic->input_surface);
158
159 #if VA_CHECK_VERSION(1, 9, 0)
160 if (base_ctx->async_encode) {
161 vas = vaSyncBuffer(ctx->hwctx->display,
162 pic->output_buffer,
163 VA_TIMEOUT_INFINITE);
164 if (vas != VA_STATUS_SUCCESS) {
165 av_log(avctx, AV_LOG_ERROR, "Failed to sync to output buffer completion: "
166 "%d (%s).\n", vas, vaErrorStr(vas));
167 return AVERROR(EIO);
168 }
169 } else
170 #endif
171 { // If vaSyncBuffer is not implemented, try old version API.
172 vas = vaSyncSurface(ctx->hwctx->display, pic->input_surface);
173 if (vas != VA_STATUS_SUCCESS) {
174 av_log(avctx, AV_LOG_ERROR, "Failed to sync to picture completion: "
175 "%d (%s).\n", vas, vaErrorStr(vas));
176 return AVERROR(EIO);
177 }
178 }
179
180 // Input is definitely finished with now.
181 av_frame_free(&base_pic->input_image);
182
183 base_pic->encode_complete = 1;
184 return 0;
185 }
186
187 static int vaapi_encode_make_row_slice(AVCodecContext *avctx,
188 VAAPIEncodePicture *pic)
189 {
190 VAAPIEncodeContext *ctx = avctx->priv_data;
191 VAAPIEncodeSlice *slice;
192 int i, rounding;
193
194 for (i = 0; i < pic->nb_slices; i++)
195 pic->slices[i].row_size = ctx->slice_size;
196
197 rounding = ctx->slice_block_rows - ctx->nb_slices * ctx->slice_size;
198 if (rounding > 0) {
199 // Place rounding error at top and bottom of frame.
200 av_assert0(rounding < pic->nb_slices);
201 // Some Intel drivers contain a bug where the encoder will fail
202 // if the last slice is smaller than the one before it. Since
203 // that's straightforward to avoid here, just do so.
204 if (rounding <= 2) {
205 for (i = 0; i < rounding; i++)
206 ++pic->slices[i].row_size;
207 } else {
208 for (i = 0; i < (rounding + 1) / 2; i++)
209 ++pic->slices[pic->nb_slices - i - 1].row_size;
210 for (i = 0; i < rounding / 2; i++)
211 ++pic->slices[i].row_size;
212 }
213 } else if (rounding < 0) {
214 // Remove rounding error from last slice only.
215 av_assert0(rounding < ctx->slice_size);
216 pic->slices[pic->nb_slices - 1].row_size += rounding;
217 }
218
219 for (i = 0; i < pic->nb_slices; i++) {
220 slice = &pic->slices[i];
221 slice->index = i;
222 if (i == 0) {
223 slice->row_start = 0;
224 slice->block_start = 0;
225 } else {
226 const VAAPIEncodeSlice *prev = &pic->slices[i - 1];
227 slice->row_start = prev->row_start + prev->row_size;
228 slice->block_start = prev->block_start + prev->block_size;
229 }
230 slice->block_size = slice->row_size * ctx->slice_block_cols;
231
232 av_log(avctx, AV_LOG_DEBUG, "Slice %d: %d-%d (%d rows), "
233 "%d-%d (%d blocks).\n", i, slice->row_start,
234 slice->row_start + slice->row_size - 1, slice->row_size,
235 slice->block_start, slice->block_start + slice->block_size - 1,
236 slice->block_size);
237 }
238
239 return 0;
240 }
241
242 static int vaapi_encode_make_tile_slice(AVCodecContext *avctx,
243 VAAPIEncodePicture *pic)
244 {
245 VAAPIEncodeContext *ctx = avctx->priv_data;
246 VAAPIEncodeSlice *slice;
247 int i, j, index;
248
249 for (i = 0; i < ctx->tile_cols; i++) {
250 for (j = 0; j < ctx->tile_rows; j++) {
251 index = j * ctx->tile_cols + i;
252 slice = &pic->slices[index];
253 slice->index = index;
254
255 pic->slices[index].block_start = ctx->col_bd[i] +
256 ctx->row_bd[j] * ctx->slice_block_cols;
257 pic->slices[index].block_size = ctx->row_height[j] * ctx->col_width[i];
258
259 av_log(avctx, AV_LOG_DEBUG, "Slice %2d: (%2d, %2d) start at: %4d "
260 "width:%2d height:%2d (%d blocks).\n", index, ctx->col_bd[i],
261 ctx->row_bd[j], slice->block_start, ctx->col_width[i],
262 ctx->row_height[j], slice->block_size);
263 }
264 }
265
266 return 0;
267 }
268
269 static int vaapi_encode_issue(AVCodecContext *avctx,
270 const FFHWBaseEncodePicture *base_pic)
271 {
272 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
273 VAAPIEncodeContext *ctx = avctx->priv_data;
274 VAAPIEncodePicture *pic = (VAAPIEncodePicture*)base_pic;
275 VAAPIEncodeSlice *slice;
276 VAStatus vas;
277 int err, i;
278 char data[MAX_PARAM_BUFFER_SIZE];
279 size_t bit_len;
280 av_unused AVFrameSideData *sd;
281
282 av_log(avctx, AV_LOG_DEBUG, "Issuing encode for pic %"PRId64"/%"PRId64" "
283 "as type %s.\n", base_pic->display_order, base_pic->encode_order,
284 ff_hw_base_encode_get_pictype_name(base_pic->type));
285 if (base_pic->nb_refs[0] == 0 && base_pic->nb_refs[1] == 0) {
286 av_log(avctx, AV_LOG_DEBUG, "No reference pictures.\n");
287 } else {
288 av_log(avctx, AV_LOG_DEBUG, "L0 refers to");
289 for (i = 0; i < base_pic->nb_refs[0]; i++) {
290 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
291 base_pic->refs[0][i]->display_order, base_pic->refs[0][i]->encode_order);
292 }
293 av_log(avctx, AV_LOG_DEBUG, ".\n");
294
295 if (base_pic->nb_refs[1]) {
296 av_log(avctx, AV_LOG_DEBUG, "L1 refers to");
297 for (i = 0; i < base_pic->nb_refs[1]; i++) {
298 av_log(avctx, AV_LOG_DEBUG, " %"PRId64"/%"PRId64,
299 base_pic->refs[1][i]->display_order, base_pic->refs[1][i]->encode_order);
300 }
301 av_log(avctx, AV_LOG_DEBUG, ".\n");
302 }
303 }
304
305 av_assert0(!base_pic->encode_issued);
306 for (i = 0; i < base_pic->nb_refs[0]; i++) {
307 av_assert0(base_pic->refs[0][i]);
308 av_assert0(base_pic->refs[0][i]->encode_issued);
309 }
310 for (i = 0; i < base_pic->nb_refs[1]; i++) {
311 av_assert0(base_pic->refs[1][i]);
312 av_assert0(base_pic->refs[1][i]->encode_issued);
313 }
314
315 av_log(avctx, AV_LOG_DEBUG, "Input surface is %#x.\n", pic->input_surface);
316
317 err = av_hwframe_get_buffer(base_ctx->recon_frames_ref, base_pic->recon_image, 0);
318 if (err < 0) {
319 err = AVERROR(ENOMEM);
320 goto fail;
321 }
322 pic->recon_surface = (VASurfaceID)(uintptr_t)base_pic->recon_image->data[3];
323 av_log(avctx, AV_LOG_DEBUG, "Recon surface is %#x.\n", pic->recon_surface);
324
325 pic->output_buffer_ref = ff_refstruct_pool_get(ctx->output_buffer_pool);
326 if (!pic->output_buffer_ref) {
327 err = AVERROR(ENOMEM);
328 goto fail;
329 }
330 pic->output_buffer = *pic->output_buffer_ref;
331 av_log(avctx, AV_LOG_DEBUG, "Output buffer is %#x.\n",
332 pic->output_buffer);
333
334 if (ctx->codec->picture_params_size > 0) {
335 pic->codec_picture_params = av_malloc(ctx->codec->picture_params_size);
336 if (!pic->codec_picture_params)
337 goto fail;
338 memcpy(pic->codec_picture_params, ctx->codec_picture_params,
339 ctx->codec->picture_params_size);
340 } else {
341 av_assert0(!ctx->codec_picture_params);
342 }
343
344 pic->nb_param_buffers = 0;
345
346 if (base_pic->type == FF_HW_PICTURE_TYPE_IDR && ctx->codec->init_sequence_params) {
347 err = vaapi_encode_make_param_buffer(avctx, pic,
348 VAEncSequenceParameterBufferType,
349 ctx->codec_sequence_params,
350 ctx->codec->sequence_params_size);
351 if (err < 0)
352 goto fail;
353 }
354
355 if (base_pic->type == FF_HW_PICTURE_TYPE_IDR) {
356 for (i = 0; i < ctx->nb_global_params; i++) {
357 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
358 ctx->global_params_type[i],
359 ctx->global_params[i],
360 ctx->global_params_size[i]);
361 if (err < 0)
362 goto fail;
363 }
364 }
365
366 if (ctx->codec->init_picture_params) {
367 err = ctx->codec->init_picture_params(avctx, pic);
368 if (err < 0) {
369 av_log(avctx, AV_LOG_ERROR, "Failed to initialise picture "
370 "parameters: %d.\n", err);
371 goto fail;
372 }
373 err = vaapi_encode_make_param_buffer(avctx, pic,
374 VAEncPictureParameterBufferType,
375 pic->codec_picture_params,
376 ctx->codec->picture_params_size);
377 if (err < 0)
378 goto fail;
379 }
380
381 #if VA_CHECK_VERSION(1, 5, 0)
382 if (ctx->max_frame_size) {
383 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
384 VAEncMiscParameterTypeMaxFrameSize,
385 &ctx->mfs_params,
386 sizeof(ctx->mfs_params));
387 if (err < 0)
388 goto fail;
389 }
390 #endif
391
392 if (base_pic->type == FF_HW_PICTURE_TYPE_IDR) {
393 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
394 ctx->codec->write_sequence_header) {
395 bit_len = 8 * sizeof(data);
396 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
397 if (err < 0) {
398 av_log(avctx, AV_LOG_ERROR, "Failed to write per-sequence "
399 "header: %d.\n", err);
400 goto fail;
401 }
402 err = vaapi_encode_make_packed_header(avctx, pic,
403 ctx->codec->sequence_header_type,
404 data, bit_len);
405 if (err < 0)
406 goto fail;
407 }
408 }
409
410 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_PICTURE &&
411 ctx->codec->write_picture_header) {
412 bit_len = 8 * sizeof(data);
413 err = ctx->codec->write_picture_header(avctx, pic, data, &bit_len);
414 if (err < 0) {
415 av_log(avctx, AV_LOG_ERROR, "Failed to write per-picture "
416 "header: %d.\n", err);
417 goto fail;
418 }
419 err = vaapi_encode_make_packed_header(avctx, pic,
420 ctx->codec->picture_header_type,
421 data, bit_len);
422 if (err < 0)
423 goto fail;
424 }
425
426 if (ctx->codec->write_extra_buffer) {
427 for (i = 0;; i++) {
428 size_t len = sizeof(data);
429 int type;
430 err = ctx->codec->write_extra_buffer(avctx, pic, i, &type,
431 data, &len);
432 if (err == AVERROR_EOF)
433 break;
434 if (err < 0) {
435 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
436 "buffer %d: %d.\n", i, err);
437 goto fail;
438 }
439
440 err = vaapi_encode_make_param_buffer(avctx, pic, type,
441 data, len);
442 if (err < 0)
443 goto fail;
444 }
445 }
446
447 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_MISC &&
448 ctx->codec->write_extra_header) {
449 for (i = 0;; i++) {
450 int type;
451 bit_len = 8 * sizeof(data);
452 err = ctx->codec->write_extra_header(avctx, pic, i, &type,
453 data, &bit_len);
454 if (err == AVERROR_EOF)
455 break;
456 if (err < 0) {
457 av_log(avctx, AV_LOG_ERROR, "Failed to write extra "
458 "header %d: %d.\n", i, err);
459 goto fail;
460 }
461
462 err = vaapi_encode_make_packed_header(avctx, pic, type,
463 data, bit_len);
464 if (err < 0)
465 goto fail;
466 }
467 }
468
469 if (pic->nb_slices == 0)
470 pic->nb_slices = ctx->nb_slices;
471 if (pic->nb_slices > 0) {
472 pic->slices = av_calloc(pic->nb_slices, sizeof(*pic->slices));
473 if (!pic->slices) {
474 err = AVERROR(ENOMEM);
475 goto fail;
476 }
477
478 if (ctx->tile_rows && ctx->tile_cols)
479 vaapi_encode_make_tile_slice(avctx, pic);
480 else
481 vaapi_encode_make_row_slice(avctx, pic);
482 }
483
484 for (i = 0; i < pic->nb_slices; i++) {
485 slice = &pic->slices[i];
486
487 if (ctx->codec->slice_params_size > 0) {
488 slice->codec_slice_params = av_mallocz(ctx->codec->slice_params_size);
489 if (!slice->codec_slice_params) {
490 err = AVERROR(ENOMEM);
491 goto fail;
492 }
493 }
494
495 if (ctx->codec->init_slice_params) {
496 err = ctx->codec->init_slice_params(avctx, pic, slice);
497 if (err < 0) {
498 av_log(avctx, AV_LOG_ERROR, "Failed to initialise slice "
499 "parameters: %d.\n", err);
500 goto fail;
501 }
502 }
503
504 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SLICE &&
505 ctx->codec->write_slice_header) {
506 bit_len = 8 * sizeof(data);
507 err = ctx->codec->write_slice_header(avctx, pic, slice,
508 data, &bit_len);
509 if (err < 0) {
510 av_log(avctx, AV_LOG_ERROR, "Failed to write per-slice "
511 "header: %d.\n", err);
512 goto fail;
513 }
514 err = vaapi_encode_make_packed_header(avctx, pic,
515 ctx->codec->slice_header_type,
516 data, bit_len);
517 if (err < 0)
518 goto fail;
519 }
520
521 if (ctx->codec->init_slice_params) {
522 err = vaapi_encode_make_param_buffer(avctx, pic,
523 VAEncSliceParameterBufferType,
524 slice->codec_slice_params,
525 ctx->codec->slice_params_size);
526 if (err < 0)
527 goto fail;
528 }
529 }
530
531 #if VA_CHECK_VERSION(1, 0, 0)
532 sd = av_frame_get_side_data(base_pic->input_image,
533 AV_FRAME_DATA_REGIONS_OF_INTEREST);
534 if (sd && base_ctx->roi_allowed) {
535 const AVRegionOfInterest *roi;
536 uint32_t roi_size;
537 VAEncMiscParameterBufferROI param_roi;
538 int nb_roi, i, v;
539
540 roi = (const AVRegionOfInterest*)sd->data;
541 roi_size = roi->self_size;
542 av_assert0(roi_size && sd->size % roi_size == 0);
543 nb_roi = sd->size / roi_size;
544 if (nb_roi > ctx->roi_max_regions) {
545 if (!base_ctx->roi_warned) {
546 av_log(avctx, AV_LOG_WARNING, "More ROIs set than "
547 "supported by driver (%d > %d).\n",
548 nb_roi, ctx->roi_max_regions);
549 base_ctx->roi_warned = 1;
550 }
551 nb_roi = ctx->roi_max_regions;
552 }
553
554 pic->roi = av_calloc(nb_roi, sizeof(*pic->roi));
555 if (!pic->roi) {
556 err = AVERROR(ENOMEM);
557 goto fail;
558 }
559 // For overlapping regions, the first in the array takes priority.
560 for (i = 0; i < nb_roi; i++) {
561 roi = (const AVRegionOfInterest*)(sd->data + roi_size * i);
562
563 av_assert0(roi->qoffset.den != 0);
564 v = roi->qoffset.num * ctx->roi_quant_range / roi->qoffset.den;
565 av_log(avctx, AV_LOG_DEBUG, "ROI: (%d,%d)-(%d,%d) -> %+d.\n",
566 roi->top, roi->left, roi->bottom, roi->right, v);
567
568 pic->roi[i] = (VAEncROI) {
569 .roi_rectangle = {
570 .x = roi->left,
571 .y = roi->top,
572 .width = roi->right - roi->left,
573 .height = roi->bottom - roi->top,
574 },
575 .roi_value = av_clip_int8(v),
576 };
577 }
578
579 param_roi = (VAEncMiscParameterBufferROI) {
580 .num_roi = nb_roi,
581 .max_delta_qp = INT8_MAX,
582 .min_delta_qp = INT8_MIN,
583 .roi = pic->roi,
584 .roi_flags.bits.roi_value_is_qp_delta = 1,
585 };
586
587 err = vaapi_encode_make_misc_param_buffer(avctx, pic,
588 VAEncMiscParameterTypeROI,
589 &param_roi,
590 sizeof(param_roi));
591 if (err < 0)
592 goto fail;
593 }
594 #endif
595
596 vas = vaBeginPicture(ctx->hwctx->display, ctx->va_context,
597 pic->input_surface);
598 if (vas != VA_STATUS_SUCCESS) {
599 av_log(avctx, AV_LOG_ERROR, "Failed to begin picture encode issue: "
600 "%d (%s).\n", vas, vaErrorStr(vas));
601 err = AVERROR(EIO);
602 goto fail_with_picture;
603 }
604
605 vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
606 pic->param_buffers, pic->nb_param_buffers);
607 if (vas != VA_STATUS_SUCCESS) {
608 av_log(avctx, AV_LOG_ERROR, "Failed to upload encode parameters: "
609 "%d (%s).\n", vas, vaErrorStr(vas));
610 err = AVERROR(EIO);
611 goto fail_with_picture;
612 }
613
614 vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
615 if (vas != VA_STATUS_SUCCESS) {
616 av_log(avctx, AV_LOG_ERROR, "Failed to end picture encode issue: "
617 "%d (%s).\n", vas, vaErrorStr(vas));
618 err = AVERROR(EIO);
619 // vaRenderPicture() has been called here, so we should not destroy
620 // the parameter buffers unless separate destruction is required.
621 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
622 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS)
623 goto fail;
624 else
625 goto fail_at_end;
626 }
627
628 if (CONFIG_VAAPI_1 || ctx->hwctx->driver_quirks &
629 AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
630 for (i = 0; i < pic->nb_param_buffers; i++) {
631 vas = vaDestroyBuffer(ctx->hwctx->display,
632 pic->param_buffers[i]);
633 if (vas != VA_STATUS_SUCCESS) {
634 av_log(avctx, AV_LOG_ERROR, "Failed to destroy "
635 "param buffer %#x: %d (%s).\n",
636 pic->param_buffers[i], vas, vaErrorStr(vas));
637 // And ignore.
638 }
639 }
640 }
641
642 return 0;
643
644 fail_with_picture:
645 vaEndPicture(ctx->hwctx->display, ctx->va_context);
646 fail:
647 for(i = 0; i < pic->nb_param_buffers; i++)
648 vaDestroyBuffer(ctx->hwctx->display, pic->param_buffers[i]);
649 if (pic->slices) {
650 for (i = 0; i < pic->nb_slices; i++)
651 av_freep(&pic->slices[i].codec_slice_params);
652 }
653 fail_at_end:
654 av_freep(&pic->codec_picture_params);
655 av_freep(&pic->param_buffers);
656 av_freep(&pic->slices);
657 av_freep(&pic->roi);
658 ff_refstruct_unref(&pic->output_buffer_ref);
659 pic->output_buffer = VA_INVALID_ID;
660 return err;
661 }
662
663 static int vaapi_encode_get_coded_buffer_size(AVCodecContext *avctx, VABufferID buf_id)
664 {
665 VAAPIEncodeContext *ctx = avctx->priv_data;
666 VACodedBufferSegment *buf_list, *buf;
667 int size = 0;
668 VAStatus vas;
669 int err;
670
671 vas = vaMapBuffer(ctx->hwctx->display, buf_id,
672 (void**)&buf_list);
673 if (vas != VA_STATUS_SUCCESS) {
674 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
675 "%d (%s).\n", vas, vaErrorStr(vas));
676 err = AVERROR(EIO);
677 return err;
678 }
679
680 for (buf = buf_list; buf; buf = buf->next)
681 size += buf->size;
682
683 vas = vaUnmapBuffer(ctx->hwctx->display, buf_id);
684 if (vas != VA_STATUS_SUCCESS) {
685 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
686 "%d (%s).\n", vas, vaErrorStr(vas));
687 err = AVERROR(EIO);
688 return err;
689 }
690
691 return size;
692 }
693
694 static int vaapi_encode_get_coded_buffer_data(AVCodecContext *avctx,
695 VABufferID buf_id, uint8_t **dst)
696 {
697 VAAPIEncodeContext *ctx = avctx->priv_data;
698 VACodedBufferSegment *buf_list, *buf;
699 VAStatus vas;
700 int err;
701
702 vas = vaMapBuffer(ctx->hwctx->display, buf_id,
703 (void**)&buf_list);
704 if (vas != VA_STATUS_SUCCESS) {
705 av_log(avctx, AV_LOG_ERROR, "Failed to map output buffers: "
706 "%d (%s).\n", vas, vaErrorStr(vas));
707 err = AVERROR(EIO);
708 return err;
709 }
710
711 for (buf = buf_list; buf; buf = buf->next) {
712 av_log(avctx, AV_LOG_DEBUG, "Output buffer: %u bytes "
713 "(status %08x).\n", buf->size, buf->status);
714
715 memcpy(*dst, buf->buf, buf->size);
716 *dst += buf->size;
717 }
718
719 vas = vaUnmapBuffer(ctx->hwctx->display, buf_id);
720 if (vas != VA_STATUS_SUCCESS) {
721 av_log(avctx, AV_LOG_ERROR, "Failed to unmap output buffers: "
722 "%d (%s).\n", vas, vaErrorStr(vas));
723 err = AVERROR(EIO);
724 return err;
725 }
726
727 return 0;
728 }
729
730 static int vaapi_encode_get_coded_data(AVCodecContext *avctx,
731 VAAPIEncodePicture *pic, AVPacket *pkt)
732 {
733 VAAPIEncodeContext *ctx = avctx->priv_data;
734 VABufferID output_buffer_prev;
735 int total_size = 0;
736 uint8_t *ptr;
737 int ret;
738
739 if (ctx->coded_buffer_ref) {
740 output_buffer_prev = *ctx->coded_buffer_ref;
741 ret = vaapi_encode_get_coded_buffer_size(avctx, output_buffer_prev);
742 if (ret < 0)
743 goto end;
744 total_size += ret;
745 }
746
747 ret = vaapi_encode_get_coded_buffer_size(avctx, pic->output_buffer);
748 if (ret < 0)
749 goto end;
750 total_size += ret;
751
752 ret = ff_get_encode_buffer(avctx, pkt, total_size, 0);
753 if (ret < 0)
754 goto end;
755 ptr = pkt->data;
756
757 if (ctx->coded_buffer_ref) {
758 ret = vaapi_encode_get_coded_buffer_data(avctx, output_buffer_prev, &ptr);
759 if (ret < 0)
760 goto end;
761 }
762
763 ret = vaapi_encode_get_coded_buffer_data(avctx, pic->output_buffer, &ptr);
764 if (ret < 0)
765 goto end;
766
767 end:
768 ff_refstruct_unref(&ctx->coded_buffer_ref);
769 ff_refstruct_unref(&pic->output_buffer_ref);
770 pic->output_buffer = VA_INVALID_ID;
771
772 return ret;
773 }
774
775 static int vaapi_encode_output(AVCodecContext *avctx,
776 const FFHWBaseEncodePicture *base_pic, AVPacket *pkt)
777 {
778 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
779 VAAPIEncodeContext *ctx = avctx->priv_data;
780 VAAPIEncodePicture *pic = (VAAPIEncodePicture*)base_pic;
781 AVPacket *pkt_ptr = pkt;
782 int err;
783
784 err = vaapi_encode_wait(avctx, pic);
785 if (err < 0)
786 return err;
787
788 if (pic->non_independent_frame) {
789 av_assert0(!ctx->coded_buffer_ref);
790 ctx->coded_buffer_ref = ff_refstruct_ref(pic->output_buffer_ref);
791
792 if (pic->tail_size) {
793 if (base_ctx->tail_pkt->size) {
794 err = AVERROR_BUG;
795 goto end;
796 }
797
798 err = ff_get_encode_buffer(avctx, base_ctx->tail_pkt, pic->tail_size, 0);
799 if (err < 0)
800 goto end;
801
802 memcpy(base_ctx->tail_pkt->data, pic->tail_data, pic->tail_size);
803 pkt_ptr = base_ctx->tail_pkt;
804 }
805 } else {
806 err = vaapi_encode_get_coded_data(avctx, pic, pkt);
807 if (err < 0)
808 goto end;
809 }
810
811 av_log(avctx, AV_LOG_DEBUG, "Output read for pic %"PRId64"/%"PRId64".\n",
812 base_pic->display_order, base_pic->encode_order);
813
814 ff_hw_base_encode_set_output_property(base_ctx, avctx, (FFHWBaseEncodePicture*)base_pic, pkt_ptr,
815 ctx->codec->flags & FLAG_TIMESTAMP_NO_DELAY);
816
817 end:
818 ff_refstruct_unref(&pic->output_buffer_ref);
819 pic->output_buffer = VA_INVALID_ID;
820 return err;
821 }
822
823 static int vaapi_encode_discard(AVCodecContext *avctx,
824 VAAPIEncodePicture *pic)
825 {
826 FFHWBaseEncodePicture *base_pic = &pic->base;
827
828 vaapi_encode_wait(avctx, pic);
829
830 if (pic->output_buffer_ref) {
831 av_log(avctx, AV_LOG_DEBUG, "Discard output for pic "
832 "%"PRId64"/%"PRId64".\n",
833 base_pic->display_order, base_pic->encode_order);
834
835 ff_refstruct_unref(&pic->output_buffer_ref);
836 pic->output_buffer = VA_INVALID_ID;
837 }
838
839 return 0;
840 }
841
842 static FFHWBaseEncodePicture *vaapi_encode_alloc(AVCodecContext *avctx,
843 const AVFrame *frame)
844 {
845 VAAPIEncodeContext *ctx = avctx->priv_data;
846 VAAPIEncodePicture *pic;
847
848 pic = av_mallocz(sizeof(*pic));
849 if (!pic)
850 return NULL;
851
852 if (ctx->codec->picture_priv_data_size > 0) {
853 pic->base.priv_data = av_mallocz(ctx->codec->picture_priv_data_size);
854 if (!pic->base.priv_data) {
855 av_freep(&pic);
856 return NULL;
857 }
858 }
859
860 pic->input_surface = (VASurfaceID)(uintptr_t)frame->data[3];
861 pic->recon_surface = VA_INVALID_ID;
862 pic->output_buffer = VA_INVALID_ID;
863
864 return &pic->base;
865 }
866
867 static int vaapi_encode_free(AVCodecContext *avctx,
868 FFHWBaseEncodePicture *base_pic)
869 {
870 VAAPIEncodePicture *pic = (VAAPIEncodePicture*)base_pic;
871 int i;
872
873 if (base_pic->encode_issued)
874 vaapi_encode_discard(avctx, pic);
875
876 if (pic->slices) {
877 for (i = 0; i < pic->nb_slices; i++)
878 av_freep(&pic->slices[i].codec_slice_params);
879 }
880
881 ff_hw_base_encode_free(base_pic);
882
883 av_freep(&pic->param_buffers);
884 av_freep(&pic->slices);
885 // Output buffer should already be destroyed.
886 av_assert0(pic->output_buffer == VA_INVALID_ID);
887
888 av_freep(&pic->codec_picture_params);
889 av_freep(&pic->roi);
890
891 av_free(pic);
892
893 return 0;
894 }
895
896 static av_cold void vaapi_encode_add_global_param(AVCodecContext *avctx, int type,
897 void *buffer, size_t size)
898 {
899 VAAPIEncodeContext *ctx = avctx->priv_data;
900
901 av_assert0(ctx->nb_global_params < MAX_GLOBAL_PARAMS);
902
903 ctx->global_params_type[ctx->nb_global_params] = type;
904 ctx->global_params [ctx->nb_global_params] = buffer;
905 ctx->global_params_size[ctx->nb_global_params] = size;
906
907 ++ctx->nb_global_params;
908 }
909
910 typedef struct VAAPIEncodeRTFormat {
911 const char *name;
912 unsigned int value;
913 int depth;
914 int nb_components;
915 int log2_chroma_w;
916 int log2_chroma_h;
917 } VAAPIEncodeRTFormat;
918
919 static const VAAPIEncodeRTFormat vaapi_encode_rt_formats[] = {
920 { "YUV400", VA_RT_FORMAT_YUV400, 8, 1, },
921 { "YUV420", VA_RT_FORMAT_YUV420, 8, 3, 1, 1 },
922 { "YUV422", VA_RT_FORMAT_YUV422, 8, 3, 1, 0 },
923 #if VA_CHECK_VERSION(1, 2, 0)
924 { "YUV420_12", VA_RT_FORMAT_YUV420_12, 12, 3, 1, 1 },
925 { "YUV422_10", VA_RT_FORMAT_YUV422_10, 10, 3, 1, 0 },
926 { "YUV422_12", VA_RT_FORMAT_YUV422_12, 12, 3, 1, 0 },
927 { "YUV444_10", VA_RT_FORMAT_YUV444_10, 10, 3, 0, 0 },
928 { "YUV444_12", VA_RT_FORMAT_YUV444_12, 12, 3, 0, 0 },
929 #endif
930 { "YUV444", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
931 { "XYUV", VA_RT_FORMAT_YUV444, 8, 3, 0, 0 },
932 { "YUV411", VA_RT_FORMAT_YUV411, 8, 3, 2, 0 },
933 #if VA_CHECK_VERSION(0, 38, 1)
934 { "YUV420_10", VA_RT_FORMAT_YUV420_10BPP, 10, 3, 1, 1 },
935 #endif
936 };
937
938 static const VAEntrypoint vaapi_encode_entrypoints_normal[] = {
939 VAEntrypointEncSlice,
940 VAEntrypointEncPicture,
941 #if VA_CHECK_VERSION(0, 39, 2)
942 VAEntrypointEncSliceLP,
943 #endif
944 0
945 };
946 #if VA_CHECK_VERSION(0, 39, 2)
947 static const VAEntrypoint vaapi_encode_entrypoints_low_power[] = {
948 VAEntrypointEncSliceLP,
949 0
950 };
951 #endif
952
953 static av_cold int vaapi_encode_profile_entrypoint(AVCodecContext *avctx)
954 {
955 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
956 VAAPIEncodeContext *ctx = avctx->priv_data;
957 VAProfile *va_profiles = NULL;
958 VAEntrypoint *va_entrypoints = NULL;
959 VAStatus vas;
960 const VAEntrypoint *usable_entrypoints;
961 const VAAPIEncodeProfile *profile;
962 const AVPixFmtDescriptor *desc;
963 VAConfigAttrib rt_format_attr;
964 const VAAPIEncodeRTFormat *rt_format;
965 const char *profile_string, *entrypoint_string;
966 int i, j, n, depth, err;
967
968
969 if (ctx->low_power) {
970 #if VA_CHECK_VERSION(0, 39, 2)
971 usable_entrypoints = vaapi_encode_entrypoints_low_power;
972 #else
973 av_log(avctx, AV_LOG_ERROR, "Low-power encoding is not "
974 "supported with this VAAPI version.\n");
975 return AVERROR(EINVAL);
976 #endif
977 } else {
978 usable_entrypoints = vaapi_encode_entrypoints_normal;
979 }
980
981 desc = av_pix_fmt_desc_get(base_ctx->input_frames->sw_format);
982 if (!desc) {
983 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%d).\n",
984 base_ctx->input_frames->sw_format);
985 return AVERROR(EINVAL);
986 }
987 depth = desc->comp[0].depth;
988 for (i = 1; i < desc->nb_components; i++) {
989 if (desc->comp[i].depth != depth) {
990 av_log(avctx, AV_LOG_ERROR, "Invalid input pixfmt (%s).\n",
991 desc->name);
992 return AVERROR(EINVAL);
993 }
994 }
995 av_log(avctx, AV_LOG_VERBOSE, "Input surface format is %s.\n",
996 desc->name);
997
998 n = vaMaxNumProfiles(ctx->hwctx->display);
999 va_profiles = av_malloc_array(n, sizeof(VAProfile));
1000 if (!va_profiles) {
1001 err = AVERROR(ENOMEM);
1002 goto fail;
1003 }
1004 vas = vaQueryConfigProfiles(ctx->hwctx->display, va_profiles, &n);
1005 if (vas != VA_STATUS_SUCCESS) {
1006 av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: %d (%s).\n",
1007 vas, vaErrorStr(vas));
1008 err = AVERROR_EXTERNAL;
1009 goto fail;
1010 }
1011
1012 av_assert0(ctx->codec->profiles);
1013 for (i = 0; (ctx->codec->profiles[i].av_profile !=
1014 AV_PROFILE_UNKNOWN); i++) {
1015 profile = &ctx->codec->profiles[i];
1016 if (depth != profile->depth ||
1017 desc->nb_components != profile->nb_components)
1018 continue;
1019 if (desc->nb_components > 1 &&
1020 (desc->log2_chroma_w != profile->log2_chroma_w ||
1021 desc->log2_chroma_h != profile->log2_chroma_h))
1022 continue;
1023 if (avctx->profile != profile->av_profile &&
1024 avctx->profile != AV_PROFILE_UNKNOWN)
1025 continue;
1026
1027 #if VA_CHECK_VERSION(1, 0, 0)
1028 profile_string = vaProfileStr(profile->va_profile);
1029 #else
1030 profile_string = "(no profile names)";
1031 #endif
1032
1033 for (j = 0; j < n; j++) {
1034 if (va_profiles[j] == profile->va_profile)
1035 break;
1036 }
1037 if (j >= n) {
1038 av_log(avctx, AV_LOG_VERBOSE, "Compatible profile %s (%d) "
1039 "is not supported by driver.\n", profile_string,
1040 profile->va_profile);
1041 continue;
1042 }
1043
1044 ctx->profile = profile;
1045 break;
1046 }
1047 if (!ctx->profile) {
1048 av_log(avctx, AV_LOG_ERROR, "No usable encoding profile found.\n");
1049 err = AVERROR(ENOSYS);
1050 goto fail;
1051 }
1052
1053 avctx->profile = profile->av_profile;
1054 ctx->va_profile = profile->va_profile;
1055 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI profile %s (%d).\n",
1056 profile_string, ctx->va_profile);
1057
1058 n = vaMaxNumEntrypoints(ctx->hwctx->display);
1059 va_entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));
1060 if (!va_entrypoints) {
1061 err = AVERROR(ENOMEM);
1062 goto fail;
1063 }
1064 vas = vaQueryConfigEntrypoints(ctx->hwctx->display, ctx->va_profile,
1065 va_entrypoints, &n);
1066 if (vas != VA_STATUS_SUCCESS) {
1067 av_log(avctx, AV_LOG_ERROR, "Failed to query entrypoints for "
1068 "profile %s (%d): %d (%s).\n", profile_string,
1069 ctx->va_profile, vas, vaErrorStr(vas));
1070 err = AVERROR_EXTERNAL;
1071 goto fail;
1072 }
1073
1074 for (i = 0; i < n; i++) {
1075 for (j = 0; usable_entrypoints[j]; j++) {
1076 if (va_entrypoints[i] == usable_entrypoints[j])
1077 break;
1078 }
1079 if (usable_entrypoints[j])
1080 break;
1081 }
1082 if (i >= n) {
1083 av_log(avctx, AV_LOG_ERROR, "No usable encoding entrypoint found "
1084 "for profile %s (%d).\n", profile_string, ctx->va_profile);
1085 err = AVERROR(ENOSYS);
1086 goto fail;
1087 }
1088
1089 ctx->va_entrypoint = va_entrypoints[i];
1090 #if VA_CHECK_VERSION(1, 0, 0)
1091 entrypoint_string = vaEntrypointStr(ctx->va_entrypoint);
1092 #else
1093 entrypoint_string = "(no entrypoint names)";
1094 #endif
1095 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI entrypoint %s (%d).\n",
1096 entrypoint_string, ctx->va_entrypoint);
1097
1098 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rt_formats); i++) {
1099 rt_format = &vaapi_encode_rt_formats[i];
1100 if (rt_format->depth == depth &&
1101 rt_format->nb_components == profile->nb_components &&
1102 rt_format->log2_chroma_w == profile->log2_chroma_w &&
1103 rt_format->log2_chroma_h == profile->log2_chroma_h)
1104 break;
1105 }
1106 if (i >= FF_ARRAY_ELEMS(vaapi_encode_rt_formats)) {
1107 av_log(avctx, AV_LOG_ERROR, "No usable render target format "
1108 "found for profile %s (%d) entrypoint %s (%d).\n",
1109 profile_string, ctx->va_profile,
1110 entrypoint_string, ctx->va_entrypoint);
1111 err = AVERROR(ENOSYS);
1112 goto fail;
1113 }
1114
1115 rt_format_attr = (VAConfigAttrib) { VAConfigAttribRTFormat };
1116 vas = vaGetConfigAttributes(ctx->hwctx->display,
1117 ctx->va_profile, ctx->va_entrypoint,
1118 &rt_format_attr, 1);
1119 if (vas != VA_STATUS_SUCCESS) {
1120 av_log(avctx, AV_LOG_ERROR, "Failed to query RT format "
1121 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1122 err = AVERROR_EXTERNAL;
1123 goto fail;
1124 }
1125
1126 if (rt_format_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1127 av_log(avctx, AV_LOG_VERBOSE, "RT format config attribute not "
1128 "supported by driver: assuming surface RT format %s "
1129 "is valid.\n", rt_format->name);
1130 } else if (!(rt_format_attr.value & rt_format->value)) {
1131 av_log(avctx, AV_LOG_ERROR, "Surface RT format %s not supported "
1132 "by driver for encoding profile %s (%d) entrypoint %s (%d).\n",
1133 rt_format->name, profile_string, ctx->va_profile,
1134 entrypoint_string, ctx->va_entrypoint);
1135 err = AVERROR(ENOSYS);
1136 goto fail;
1137 } else {
1138 av_log(avctx, AV_LOG_VERBOSE, "Using VAAPI render target "
1139 "format %s (%#x).\n", rt_format->name, rt_format->value);
1140 ctx->config_attributes[ctx->nb_config_attributes++] =
1141 (VAConfigAttrib) {
1142 .type = VAConfigAttribRTFormat,
1143 .value = rt_format->value,
1144 };
1145 }
1146
1147 err = 0;
1148 fail:
1149 av_freep(&va_profiles);
1150 av_freep(&va_entrypoints);
1151 return err;
1152 }
1153
1154 static const VAAPIEncodeRCMode vaapi_encode_rc_modes[] = {
1155 // Bitrate Quality
1156 // | Maxrate | HRD/VBV
1157 { 0 }, // | | | |
1158 { RC_MODE_CQP, "CQP", 1, VA_RC_CQP, 0, 0, 1, 0 },
1159 { RC_MODE_CBR, "CBR", 1, VA_RC_CBR, 1, 0, 0, 1 },
1160 { RC_MODE_VBR, "VBR", 1, VA_RC_VBR, 1, 1, 0, 1 },
1161 #if VA_CHECK_VERSION(1, 1, 0)
1162 { RC_MODE_ICQ, "ICQ", 1, VA_RC_ICQ, 0, 0, 1, 0 },
1163 #else
1164 { RC_MODE_ICQ, "ICQ", 0 },
1165 #endif
1166 #if VA_CHECK_VERSION(1, 3, 0)
1167 { RC_MODE_QVBR, "QVBR", 1, VA_RC_QVBR, 1, 1, 1, 1 },
1168 { RC_MODE_AVBR, "AVBR", 0, VA_RC_AVBR, 1, 0, 0, 0 },
1169 #else
1170 { RC_MODE_QVBR, "QVBR", 0 },
1171 { RC_MODE_AVBR, "AVBR", 0 },
1172 #endif
1173 };
1174
1175 static av_cold int vaapi_encode_init_rate_control(AVCodecContext *avctx)
1176 {
1177 VAAPIEncodeContext *ctx = avctx->priv_data;
1178 uint32_t supported_va_rc_modes;
1179 const VAAPIEncodeRCMode *rc_mode;
1180 int64_t rc_bits_per_second;
1181 int rc_target_percentage;
1182 int rc_window_size;
1183 int rc_quality;
1184 int64_t hrd_buffer_size;
1185 int64_t hrd_initial_buffer_fullness;
1186 int fr_num, fr_den;
1187 VAConfigAttrib rc_attr = { VAConfigAttribRateControl };
1188 VAStatus vas;
1189 char supported_rc_modes_string[64];
1190
1191 vas = vaGetConfigAttributes(ctx->hwctx->display,
1192 ctx->va_profile, ctx->va_entrypoint,
1193 &rc_attr, 1);
1194 if (vas != VA_STATUS_SUCCESS) {
1195 av_log(avctx, AV_LOG_ERROR, "Failed to query rate control "
1196 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1197 return AVERROR_EXTERNAL;
1198 }
1199 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1200 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any "
1201 "supported rate control modes: assuming CQP only.\n");
1202 supported_va_rc_modes = VA_RC_CQP;
1203 strcpy(supported_rc_modes_string, "unknown");
1204 } else {
1205 char *str = supported_rc_modes_string;
1206 size_t len = sizeof(supported_rc_modes_string);
1207 int i, first = 1, res;
1208
1209 supported_va_rc_modes = rc_attr.value;
1210 if (ctx->blbrc) {
1211 #if VA_CHECK_VERSION(0, 39, 2)
1212 if (!(supported_va_rc_modes & VA_RC_MB)) {
1213 ctx->blbrc = 0;
1214 av_log(avctx, AV_LOG_WARNING, "Driver does not support BLBRC.\n");
1215 }
1216 #else
1217 ctx->blbrc = 0;
1218 av_log(avctx, AV_LOG_WARNING, "Please consider to update to VAAPI 0.39.2 "
1219 "or above, which can support BLBRC.\n");
1220 #endif
1221 }
1222
1223 for (i = 0; i < FF_ARRAY_ELEMS(vaapi_encode_rc_modes); i++) {
1224 rc_mode = &vaapi_encode_rc_modes[i];
1225 if (supported_va_rc_modes & rc_mode->va_mode) {
1226 res = snprintf(str, len, "%s%s",
1227 first ? "" : ", ", rc_mode->name);
1228 first = 0;
1229 if (res < 0) {
1230 *str = 0;
1231 break;
1232 }
1233 len -= res;
1234 str += res;
1235 if (len == 0)
1236 break;
1237 }
1238 }
1239
1240 av_log(avctx, AV_LOG_DEBUG, "Driver supports RC modes %s.\n",
1241 supported_rc_modes_string);
1242 }
1243
1244 // Rate control mode selection:
1245 // * If the user has set a mode explicitly with the rc_mode option,
1246 // use it and fail if it is not available.
1247 // * If an explicit QP option has been set, use CQP.
1248 // * If the codec is CQ-only, use CQP.
1249 // * If the QSCALE avcodec option is set, use CQP.
1250 // * If bitrate and quality are both set, try QVBR.
1251 // * If quality is set, try ICQ, then CQP.
1252 // * If bitrate and maxrate are set and have the same value, try CBR.
1253 // * If a bitrate is set, try AVBR, then VBR, then CBR.
1254 // * If no bitrate is set, try ICQ, then CQP.
1255
1256 #define TRY_RC_MODE(mode, fail) do { \
1257 rc_mode = &vaapi_encode_rc_modes[mode]; \
1258 if (!(rc_mode->va_mode & supported_va_rc_modes)) { \
1259 if (fail) { \
1260 av_log(avctx, AV_LOG_ERROR, "Driver does not support %s " \
1261 "RC mode (supported modes: %s).\n", rc_mode->name, \
1262 supported_rc_modes_string); \
1263 return AVERROR(EINVAL); \
1264 } \
1265 av_log(avctx, AV_LOG_DEBUG, "Driver does not support %s " \
1266 "RC mode.\n", rc_mode->name); \
1267 rc_mode = NULL; \
1268 } else { \
1269 goto rc_mode_found; \
1270 } \
1271 } while (0)
1272
1273 if (ctx->explicit_rc_mode)
1274 TRY_RC_MODE(ctx->explicit_rc_mode, 1);
1275
1276 if (ctx->explicit_qp)
1277 TRY_RC_MODE(RC_MODE_CQP, 1);
1278
1279 if (ctx->codec->flags & FF_HW_FLAG_CONSTANT_QUALITY_ONLY)
1280 TRY_RC_MODE(RC_MODE_CQP, 1);
1281
1282 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1283 TRY_RC_MODE(RC_MODE_CQP, 1);
1284
1285 if (avctx->bit_rate > 0 && avctx->global_quality > 0)
1286 TRY_RC_MODE(RC_MODE_QVBR, 0);
1287
1288 if (avctx->global_quality > 0) {
1289 TRY_RC_MODE(RC_MODE_ICQ, 0);
1290 TRY_RC_MODE(RC_MODE_CQP, 0);
1291 }
1292
1293 if (avctx->bit_rate > 0 && avctx->rc_max_rate == avctx->bit_rate)
1294 TRY_RC_MODE(RC_MODE_CBR, 0);
1295
1296 if (avctx->bit_rate > 0) {
1297 TRY_RC_MODE(RC_MODE_AVBR, 0);
1298 TRY_RC_MODE(RC_MODE_VBR, 0);
1299 TRY_RC_MODE(RC_MODE_CBR, 0);
1300 } else {
1301 TRY_RC_MODE(RC_MODE_ICQ, 0);
1302 TRY_RC_MODE(RC_MODE_CQP, 0);
1303 }
1304
1305 av_log(avctx, AV_LOG_ERROR, "Driver does not support any "
1306 "RC mode compatible with selected options "
1307 "(supported modes: %s).\n", supported_rc_modes_string);
1308 return AVERROR(EINVAL);
1309
1310 rc_mode_found:
1311 if (rc_mode->bitrate) {
1312 if (avctx->bit_rate <= 0) {
1313 av_log(avctx, AV_LOG_ERROR, "Bitrate must be set for %s "
1314 "RC mode.\n", rc_mode->name);
1315 return AVERROR(EINVAL);
1316 }
1317
1318 if (rc_mode->mode == RC_MODE_AVBR) {
1319 // For maximum confusion AVBR is hacked into the existing API
1320 // by overloading some of the fields with completely different
1321 // meanings.
1322
1323 // Target percentage does not apply in AVBR mode.
1324 rc_bits_per_second = avctx->bit_rate;
1325
1326 // Accuracy tolerance range for meeting the specified target
1327 // bitrate. It's very unclear how this is actually intended
1328 // to work - since we do want to get the specified bitrate,
1329 // set the accuracy to 100% for now.
1330 rc_target_percentage = 100;
1331
1332 // Convergence period in frames. The GOP size reflects the
1333 // user's intended block size for cutting, so reusing that
1334 // as the convergence period seems a reasonable default.
1335 rc_window_size = avctx->gop_size > 0 ? avctx->gop_size : 60;
1336
1337 } else if (rc_mode->maxrate) {
1338 if (avctx->rc_max_rate > 0) {
1339 if (avctx->rc_max_rate < avctx->bit_rate) {
1340 av_log(avctx, AV_LOG_ERROR, "Invalid bitrate settings: "
1341 "bitrate (%"PRId64") must not be greater than "
1342 "maxrate (%"PRId64").\n", avctx->bit_rate,
1343 avctx->rc_max_rate);
1344 return AVERROR(EINVAL);
1345 }
1346 rc_bits_per_second = avctx->rc_max_rate;
1347 rc_target_percentage = (avctx->bit_rate * 100) /
1348 avctx->rc_max_rate;
1349 } else {
1350 // We only have a target bitrate, but this mode requires
1351 // that a maximum rate be supplied as well. Since the
1352 // user does not want this to be a constraint, arbitrarily
1353 // pick a maximum rate of double the target rate.
1354 rc_bits_per_second = 2 * avctx->bit_rate;
1355 rc_target_percentage = 50;
1356 }
1357 } else {
1358 if (avctx->rc_max_rate > avctx->bit_rate) {
1359 av_log(avctx, AV_LOG_WARNING, "Max bitrate is ignored "
1360 "in %s RC mode.\n", rc_mode->name);
1361 }
1362 rc_bits_per_second = avctx->bit_rate;
1363 rc_target_percentage = 100;
1364 }
1365 } else {
1366 rc_bits_per_second = 0;
1367 rc_target_percentage = 100;
1368 }
1369
1370 if (rc_mode->quality) {
1371 if (ctx->explicit_qp) {
1372 rc_quality = ctx->explicit_qp;
1373 } else if (avctx->global_quality > 0) {
1374 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
1375 rc_quality = avctx->global_quality / FF_QP2LAMBDA;
1376 else
1377 rc_quality = avctx->global_quality;
1378 } else {
1379 rc_quality = ctx->codec->default_quality;
1380 av_log(avctx, AV_LOG_WARNING, "No quality level set; "
1381 "using default (%d).\n", rc_quality);
1382 }
1383 } else {
1384 rc_quality = 0;
1385 }
1386
1387 if (rc_mode->hrd) {
1388 if (avctx->rc_buffer_size)
1389 hrd_buffer_size = avctx->rc_buffer_size;
1390 else if (avctx->rc_max_rate > 0)
1391 hrd_buffer_size = avctx->rc_max_rate;
1392 else
1393 hrd_buffer_size = avctx->bit_rate;
1394 if (avctx->rc_initial_buffer_occupancy) {
1395 if (avctx->rc_initial_buffer_occupancy > hrd_buffer_size) {
1396 av_log(avctx, AV_LOG_ERROR, "Invalid RC buffer settings: "
1397 "must have initial buffer size (%d) <= "
1398 "buffer size (%"PRId64").\n",
1399 avctx->rc_initial_buffer_occupancy, hrd_buffer_size);
1400 return AVERROR(EINVAL);
1401 }
1402 hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;
1403 } else {
1404 hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;
1405 }
1406
1407 rc_window_size = (hrd_buffer_size * 1000) / rc_bits_per_second;
1408 } else {
1409 if (avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1410 av_log(avctx, AV_LOG_WARNING, "Buffering settings are ignored "
1411 "in %s RC mode.\n", rc_mode->name);
1412 }
1413
1414 hrd_buffer_size = 0;
1415 hrd_initial_buffer_fullness = 0;
1416
1417 if (rc_mode->mode != RC_MODE_AVBR) {
1418 // Already set (with completely different meaning) for AVBR.
1419 rc_window_size = 1000;
1420 }
1421 }
1422
1423 if (rc_bits_per_second > UINT32_MAX ||
1424 hrd_buffer_size > UINT32_MAX ||
1425 hrd_initial_buffer_fullness > UINT32_MAX) {
1426 av_log(avctx, AV_LOG_ERROR, "RC parameters of 2^32 or "
1427 "greater are not supported by VAAPI.\n");
1428 return AVERROR(EINVAL);
1429 }
1430
1431 ctx->rc_mode = rc_mode;
1432 ctx->rc_quality = rc_quality;
1433 ctx->va_rc_mode = rc_mode->va_mode;
1434 ctx->va_bit_rate = rc_bits_per_second;
1435
1436 av_log(avctx, AV_LOG_VERBOSE, "RC mode: %s.\n", rc_mode->name);
1437
1438 if (ctx->blbrc && ctx->va_rc_mode == VA_RC_CQP)
1439 ctx->blbrc = 0;
1440 av_log(avctx, AV_LOG_VERBOSE, "Block Level bitrate control: %s.\n", ctx->blbrc ? "ON" : "OFF");
1441
1442 if (rc_attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1443 // This driver does not want the RC mode attribute to be set.
1444 } else {
1445 ctx->config_attributes[ctx->nb_config_attributes++] =
1446 (VAConfigAttrib) {
1447 .type = VAConfigAttribRateControl,
1448 #if VA_CHECK_VERSION(0, 39, 2)
1449 .value = ctx->blbrc ? ctx->va_rc_mode | VA_RC_MB : ctx->va_rc_mode,
1450 #else
1451 .value = ctx->va_rc_mode,
1452 #endif
1453 };
1454 }
1455
1456 if (rc_mode->quality)
1457 av_log(avctx, AV_LOG_VERBOSE, "RC quality: %d.\n", rc_quality);
1458
1459 if (rc_mode->va_mode != VA_RC_CQP) {
1460 if (rc_mode->mode == RC_MODE_AVBR) {
1461 av_log(avctx, AV_LOG_VERBOSE, "RC target: %"PRId64" bps "
1462 "converging in %d frames with %d%% accuracy.\n",
1463 rc_bits_per_second, rc_window_size,
1464 rc_target_percentage);
1465 } else if (rc_mode->bitrate) {
1466 av_log(avctx, AV_LOG_VERBOSE, "RC target: %d%% of "
1467 "%"PRId64" bps over %d ms.\n", rc_target_percentage,
1468 rc_bits_per_second, rc_window_size);
1469 }
1470
1471 ctx->rc_params = (VAEncMiscParameterRateControl) {
1472 .bits_per_second = rc_bits_per_second,
1473 .target_percentage = rc_target_percentage,
1474 .window_size = rc_window_size,
1475 .initial_qp = 0,
1476 .min_qp = (avctx->qmin > 0 ? avctx->qmin : 0),
1477 .basic_unit_size = 0,
1478 #if VA_CHECK_VERSION(1, 1, 0)
1479 .ICQ_quality_factor = av_clip(rc_quality, 1, 51),
1480 .max_qp = (avctx->qmax > 0 ? avctx->qmax : 0),
1481 #endif
1482 #if VA_CHECK_VERSION(1, 3, 0)
1483 .quality_factor = rc_quality,
1484 #endif
1485 #if VA_CHECK_VERSION(0, 39, 2)
1486 .rc_flags.bits.mb_rate_control = ctx->blbrc ? 1 : 2,
1487 #endif
1488 };
1489 vaapi_encode_add_global_param(avctx,
1490 VAEncMiscParameterTypeRateControl,
1491 &ctx->rc_params,
1492 sizeof(ctx->rc_params));
1493 }
1494
1495 if (rc_mode->hrd) {
1496 av_log(avctx, AV_LOG_VERBOSE, "RC buffer: %"PRId64" bits, "
1497 "initial fullness %"PRId64" bits.\n",
1498 hrd_buffer_size, hrd_initial_buffer_fullness);
1499
1500 ctx->hrd_params = (VAEncMiscParameterHRD) {
1501 .initial_buffer_fullness = hrd_initial_buffer_fullness,
1502 .buffer_size = hrd_buffer_size,
1503 };
1504 vaapi_encode_add_global_param(avctx,
1505 VAEncMiscParameterTypeHRD,
1506 &ctx->hrd_params,
1507 sizeof(ctx->hrd_params));
1508 }
1509
1510 if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1511 av_reduce(&fr_num, &fr_den,
1512 avctx->framerate.num, avctx->framerate.den, 65535);
1513 else
1514 av_reduce(&fr_num, &fr_den,
1515 avctx->time_base.den, avctx->time_base.num, 65535);
1516
1517 av_log(avctx, AV_LOG_VERBOSE, "RC framerate: %d/%d (%.2f fps).\n",
1518 fr_num, fr_den, (double)fr_num / fr_den);
1519
1520 ctx->fr_params = (VAEncMiscParameterFrameRate) {
1521 .framerate = (unsigned int)fr_den << 16 | fr_num,
1522 };
1523 #if VA_CHECK_VERSION(0, 40, 0)
1524 vaapi_encode_add_global_param(avctx,
1525 VAEncMiscParameterTypeFrameRate,
1526 &ctx->fr_params,
1527 sizeof(ctx->fr_params));
1528 #endif
1529
1530 return 0;
1531 }
1532
1533 static av_cold int vaapi_encode_init_max_frame_size(AVCodecContext *avctx)
1534 {
1535 #if VA_CHECK_VERSION(1, 5, 0)
1536 VAAPIEncodeContext *ctx = avctx->priv_data;
1537 VAConfigAttrib attr = { VAConfigAttribMaxFrameSize };
1538 VAStatus vas;
1539
1540 if (ctx->va_rc_mode == VA_RC_CQP) {
1541 ctx->max_frame_size = 0;
1542 av_log(avctx, AV_LOG_ERROR, "Max frame size is invalid in CQP rate "
1543 "control mode.\n");
1544 return AVERROR(EINVAL);
1545 }
1546
1547 vas = vaGetConfigAttributes(ctx->hwctx->display,
1548 ctx->va_profile,
1549 ctx->va_entrypoint,
1550 &attr, 1);
1551 if (vas != VA_STATUS_SUCCESS) {
1552 ctx->max_frame_size = 0;
1553 av_log(avctx, AV_LOG_ERROR, "Failed to query max frame size "
1554 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1555 return AVERROR_EXTERNAL;
1556 }
1557
1558 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1559 ctx->max_frame_size = 0;
1560 av_log(avctx, AV_LOG_ERROR, "Max frame size attribute "
1561 "is not supported.\n");
1562 return AVERROR(EINVAL);
1563 } else {
1564 VAConfigAttribValMaxFrameSize attr_mfs;
1565 attr_mfs.value = attr.value;
1566 // Prefer to use VAEncMiscParameterTypeMaxFrameSize for max frame size.
1567 if (!attr_mfs.bits.max_frame_size && attr_mfs.bits.multiple_pass) {
1568 ctx->max_frame_size = 0;
1569 av_log(avctx, AV_LOG_ERROR, "Driver only supports multiple pass "
1570 "max frame size which has not been implemented in FFmpeg.\n");
1571 return AVERROR(EINVAL);
1572 }
1573
1574 ctx->mfs_params = (VAEncMiscParameterBufferMaxFrameSize){
1575 .max_frame_size = ctx->max_frame_size * 8,
1576 };
1577
1578 av_log(avctx, AV_LOG_VERBOSE, "Set max frame size: %d bytes.\n",
1579 ctx->max_frame_size);
1580 }
1581 #else
1582 av_log(avctx, AV_LOG_ERROR, "The max frame size option is not supported with "
1583 "this VAAPI version.\n");
1584 return AVERROR(EINVAL);
1585 #endif
1586
1587 return 0;
1588 }
1589
1590 static av_cold int vaapi_encode_init_gop_structure(AVCodecContext *avctx)
1591 {
1592 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
1593 VAAPIEncodeContext *ctx = avctx->priv_data;
1594 VAStatus vas;
1595 VAConfigAttrib attr = { VAConfigAttribEncMaxRefFrames };
1596 uint32_t ref_l0, ref_l1;
1597 int prediction_pre_only, err;
1598
1599 vas = vaGetConfigAttributes(ctx->hwctx->display,
1600 ctx->va_profile,
1601 ctx->va_entrypoint,
1602 &attr, 1);
1603 if (vas != VA_STATUS_SUCCESS) {
1604 av_log(avctx, AV_LOG_ERROR, "Failed to query reference frames "
1605 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1606 return AVERROR_EXTERNAL;
1607 }
1608
1609 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1610 ref_l0 = ref_l1 = 0;
1611 } else {
1612 ref_l0 = attr.value & 0xffff;
1613 ref_l1 = attr.value >> 16 & 0xffff;
1614 }
1615
1616 base_ctx->p_to_gpb = 0;
1617 prediction_pre_only = 0;
1618
1619 #if VA_CHECK_VERSION(1, 9, 0)
1620 if (!(ctx->codec->flags & FF_HW_FLAG_INTRA_ONLY ||
1621 avctx->gop_size <= 1)) {
1622 attr = (VAConfigAttrib) { VAConfigAttribPredictionDirection };
1623 vas = vaGetConfigAttributes(ctx->hwctx->display,
1624 ctx->va_profile,
1625 ctx->va_entrypoint,
1626 &attr, 1);
1627 if (vas != VA_STATUS_SUCCESS) {
1628 av_log(avctx, AV_LOG_WARNING, "Failed to query prediction direction "
1629 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1630 return AVERROR_EXTERNAL;
1631 } else if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1632 av_log(avctx, AV_LOG_VERBOSE, "Driver does not report any additional "
1633 "prediction constraints.\n");
1634 } else {
1635 if (((ref_l0 > 0 || ref_l1 > 0) && !(attr.value & VA_PREDICTION_DIRECTION_PREVIOUS)) ||
1636 ((ref_l1 == 0) && (attr.value & (VA_PREDICTION_DIRECTION_FUTURE | VA_PREDICTION_DIRECTION_BI_NOT_EMPTY)))) {
1637 av_log(avctx, AV_LOG_ERROR, "Driver report incorrect prediction "
1638 "direction attribute.\n");
1639 return AVERROR_EXTERNAL;
1640 }
1641
1642 if (!(attr.value & VA_PREDICTION_DIRECTION_FUTURE)) {
1643 if (ref_l0 > 0 && ref_l1 > 0) {
1644 prediction_pre_only = 1;
1645 av_log(avctx, AV_LOG_VERBOSE, "Driver only support same reference "
1646 "lists for B-frames.\n");
1647 }
1648 }
1649
1650 if (attr.value & VA_PREDICTION_DIRECTION_BI_NOT_EMPTY) {
1651 if (ref_l0 > 0 && ref_l1 > 0) {
1652 base_ctx->p_to_gpb = 1;
1653 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support P-frames, "
1654 "replacing them with B-frames.\n");
1655 }
1656 }
1657 }
1658 }
1659 #endif
1660
1661 err = ff_hw_base_init_gop_structure(base_ctx, avctx, ref_l0, ref_l1,
1662 ctx->codec->flags, prediction_pre_only);
1663 if (err < 0)
1664 return err;
1665
1666 return 0;
1667 }
1668
1669 static av_cold int vaapi_encode_init_row_slice_structure(AVCodecContext *avctx,
1670 uint32_t slice_structure)
1671 {
1672 VAAPIEncodeContext *ctx = avctx->priv_data;
1673 int req_slices;
1674
1675 // For fixed-size slices currently we only support whole rows, making
1676 // rectangular slices. This could be extended to arbitrary runs of
1677 // blocks, but since slices tend to be a conformance requirement and
1678 // most cases (such as broadcast or bluray) want rectangular slices
1679 // only it would need to be gated behind another option.
1680 if (avctx->slices > ctx->slice_block_rows) {
1681 av_log(avctx, AV_LOG_WARNING, "Not enough rows to use "
1682 "configured number of slices (%d < %d); using "
1683 "maximum.\n", ctx->slice_block_rows, avctx->slices);
1684 req_slices = ctx->slice_block_rows;
1685 } else {
1686 req_slices = avctx->slices;
1687 }
1688 if (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS ||
1689 slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS) {
1690 ctx->nb_slices = req_slices;
1691 ctx->slice_size = ctx->slice_block_rows / ctx->nb_slices;
1692 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_POWER_OF_TWO_ROWS) {
1693 int k;
1694 for (k = 1;; k *= 2) {
1695 if (2 * k * (req_slices - 1) + 1 >= ctx->slice_block_rows)
1696 break;
1697 }
1698 ctx->nb_slices = (ctx->slice_block_rows + k - 1) / k;
1699 ctx->slice_size = k;
1700 #if VA_CHECK_VERSION(1, 0, 0)
1701 } else if (slice_structure & VA_ENC_SLICE_STRUCTURE_EQUAL_ROWS) {
1702 ctx->nb_slices = ctx->slice_block_rows;
1703 ctx->slice_size = 1;
1704 #endif
1705 } else {
1706 av_log(avctx, AV_LOG_ERROR, "Driver does not support any usable "
1707 "slice structure modes (%#x).\n", slice_structure);
1708 return AVERROR(EINVAL);
1709 }
1710
1711 return 0;
1712 }
1713
1714 static av_cold int vaapi_encode_init_tile_slice_structure(AVCodecContext *avctx,
1715 uint32_t slice_structure)
1716 {
1717 VAAPIEncodeContext *ctx = avctx->priv_data;
1718 int i, req_tiles;
1719
1720 if (!(slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_MACROBLOCKS ||
1721 (slice_structure & VA_ENC_SLICE_STRUCTURE_ARBITRARY_ROWS &&
1722 ctx->tile_cols == 1))) {
1723 av_log(avctx, AV_LOG_ERROR, "Supported slice structure (%#x) doesn't work for "
1724 "current tile requirement.\n", slice_structure);
1725 return AVERROR(EINVAL);
1726 }
1727
1728 if (ctx->tile_rows > ctx->slice_block_rows ||
1729 ctx->tile_cols > ctx->slice_block_cols) {
1730 av_log(avctx, AV_LOG_WARNING, "Not enough block rows/cols (%d x %d) "
1731 "for configured number of tile (%d x %d); ",
1732 ctx->slice_block_rows, ctx->slice_block_cols,
1733 ctx->tile_rows, ctx->tile_cols);
1734 ctx->tile_rows = ctx->tile_rows > ctx->slice_block_rows ?
1735 ctx->slice_block_rows : ctx->tile_rows;
1736 ctx->tile_cols = ctx->tile_cols > ctx->slice_block_cols ?
1737 ctx->slice_block_cols : ctx->tile_cols;
1738 av_log(avctx, AV_LOG_WARNING, "using allowed maximum (%d x %d).\n",
1739 ctx->tile_rows, ctx->tile_cols);
1740 }
1741
1742 req_tiles = ctx->tile_rows * ctx->tile_cols;
1743
1744 // Tile slice is not allowed to cross the boundary of a tile due to
1745 // the constraints of media-driver. Currently we support one slice
1746 // per tile. This could be extended to multiple slices per tile.
1747 if (avctx->slices != req_tiles)
1748 av_log(avctx, AV_LOG_WARNING, "The number of requested slices "
1749 "mismatches with configured number of tile (%d != %d); "
1750 "using requested tile number for slice.\n",
1751 avctx->slices, req_tiles);
1752
1753 ctx->nb_slices = req_tiles;
1754
1755 // Default in uniform spacing
1756 // 6-3, 6-5
1757 for (i = 0; i < ctx->tile_cols; i++) {
1758 ctx->col_width[i] = ( i + 1 ) * ctx->slice_block_cols / ctx->tile_cols -
1759 i * ctx->slice_block_cols / ctx->tile_cols;
1760 ctx->col_bd[i + 1] = ctx->col_bd[i] + ctx->col_width[i];
1761 }
1762 // 6-4, 6-6
1763 for (i = 0; i < ctx->tile_rows; i++) {
1764 ctx->row_height[i] = ( i + 1 ) * ctx->slice_block_rows / ctx->tile_rows -
1765 i * ctx->slice_block_rows / ctx->tile_rows;
1766 ctx->row_bd[i + 1] = ctx->row_bd[i] + ctx->row_height[i];
1767 }
1768
1769 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d x %d tile.\n",
1770 ctx->tile_rows, ctx->tile_cols);
1771
1772 return 0;
1773 }
1774
1775 static av_cold int vaapi_encode_init_slice_structure(AVCodecContext *avctx)
1776 {
1777 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
1778 VAAPIEncodeContext *ctx = avctx->priv_data;
1779 VAConfigAttrib attr[3] = { { VAConfigAttribEncMaxSlices },
1780 { VAConfigAttribEncSliceStructure },
1781 #if VA_CHECK_VERSION(1, 1, 0)
1782 { VAConfigAttribEncTileSupport },
1783 #endif
1784 };
1785 VAStatus vas;
1786 uint32_t max_slices, slice_structure;
1787 int ret;
1788
1789 if (!(ctx->codec->flags & FF_HW_FLAG_SLICE_CONTROL)) {
1790 if (avctx->slices > 0) {
1791 av_log(avctx, AV_LOG_WARNING, "Multiple slices were requested "
1792 "but this codec does not support controlling slices.\n");
1793 }
1794 return 0;
1795 }
1796
1797 av_assert0(base_ctx->slice_block_height > 0 && base_ctx->slice_block_width > 0);
1798
1799 ctx->slice_block_rows = (avctx->height + base_ctx->slice_block_height - 1) /
1800 base_ctx->slice_block_height;
1801 ctx->slice_block_cols = (avctx->width + base_ctx->slice_block_width - 1) /
1802 base_ctx->slice_block_width;
1803
1804 if (avctx->slices <= 1 && !ctx->tile_rows && !ctx->tile_cols) {
1805 ctx->nb_slices = 1;
1806 ctx->slice_size = ctx->slice_block_rows;
1807 return 0;
1808 }
1809
1810 vas = vaGetConfigAttributes(ctx->hwctx->display,
1811 ctx->va_profile,
1812 ctx->va_entrypoint,
1813 attr, FF_ARRAY_ELEMS(attr));
1814 if (vas != VA_STATUS_SUCCESS) {
1815 av_log(avctx, AV_LOG_ERROR, "Failed to query slice "
1816 "attributes: %d (%s).\n", vas, vaErrorStr(vas));
1817 return AVERROR_EXTERNAL;
1818 }
1819 max_slices = attr[0].value;
1820 slice_structure = attr[1].value;
1821 if (max_slices == VA_ATTRIB_NOT_SUPPORTED ||
1822 slice_structure == VA_ATTRIB_NOT_SUPPORTED) {
1823 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1824 "pictures as multiple slices.\n.");
1825 return AVERROR(EINVAL);
1826 }
1827
1828 if (ctx->tile_rows && ctx->tile_cols) {
1829 #if VA_CHECK_VERSION(1, 1, 0)
1830 uint32_t tile_support = attr[2].value;
1831 if (tile_support == VA_ATTRIB_NOT_SUPPORTED) {
1832 av_log(avctx, AV_LOG_ERROR, "Driver does not support encoding "
1833 "pictures as multiple tiles.\n.");
1834 return AVERROR(EINVAL);
1835 }
1836 #else
1837 av_log(avctx, AV_LOG_ERROR, "Tile encoding option is "
1838 "not supported with this VAAPI version.\n");
1839 return AVERROR(EINVAL);
1840 #endif
1841 }
1842
1843 if (ctx->tile_rows && ctx->tile_cols)
1844 ret = vaapi_encode_init_tile_slice_structure(avctx, slice_structure);
1845 else
1846 ret = vaapi_encode_init_row_slice_structure(avctx, slice_structure);
1847 if (ret < 0)
1848 return ret;
1849
1850 if (ctx->nb_slices > avctx->slices) {
1851 av_log(avctx, AV_LOG_WARNING, "Slice count rounded up to "
1852 "%d (from %d) due to driver constraints on slice "
1853 "structure.\n", ctx->nb_slices, avctx->slices);
1854 }
1855 if (ctx->nb_slices > max_slices) {
1856 av_log(avctx, AV_LOG_ERROR, "Driver does not support "
1857 "encoding with %d slices (max %"PRIu32").\n",
1858 ctx->nb_slices, max_slices);
1859 return AVERROR(EINVAL);
1860 }
1861
1862 av_log(avctx, AV_LOG_VERBOSE, "Encoding pictures with %d slices.\n",
1863 ctx->nb_slices);
1864 return 0;
1865 }
1866
1867 static av_cold int vaapi_encode_init_packed_headers(AVCodecContext *avctx)
1868 {
1869 VAAPIEncodeContext *ctx = avctx->priv_data;
1870 VAStatus vas;
1871 VAConfigAttrib attr = { VAConfigAttribEncPackedHeaders };
1872
1873 vas = vaGetConfigAttributes(ctx->hwctx->display,
1874 ctx->va_profile,
1875 ctx->va_entrypoint,
1876 &attr, 1);
1877 if (vas != VA_STATUS_SUCCESS) {
1878 av_log(avctx, AV_LOG_ERROR, "Failed to query packed headers "
1879 "attribute: %d (%s).\n", vas, vaErrorStr(vas));
1880 return AVERROR_EXTERNAL;
1881 }
1882
1883 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1884 if (ctx->desired_packed_headers) {
1885 av_log(avctx, AV_LOG_WARNING, "Driver does not support any "
1886 "packed headers (wanted %#x).\n",
1887 ctx->desired_packed_headers);
1888 } else {
1889 av_log(avctx, AV_LOG_VERBOSE, "Driver does not support any "
1890 "packed headers (none wanted).\n");
1891 }
1892 ctx->va_packed_headers = 0;
1893 } else {
1894 if (ctx->desired_packed_headers & ~attr.value) {
1895 av_log(avctx, AV_LOG_WARNING, "Driver does not support some "
1896 "wanted packed headers (wanted %#x, found %#x).\n",
1897 ctx->desired_packed_headers, attr.value);
1898 } else {
1899 av_log(avctx, AV_LOG_VERBOSE, "All wanted packed headers "
1900 "available (wanted %#x, found %#x).\n",
1901 ctx->desired_packed_headers, attr.value);
1902 }
1903 ctx->va_packed_headers = ctx->desired_packed_headers & attr.value;
1904 }
1905
1906 if (ctx->va_packed_headers) {
1907 ctx->config_attributes[ctx->nb_config_attributes++] =
1908 (VAConfigAttrib) {
1909 .type = VAConfigAttribEncPackedHeaders,
1910 .value = ctx->va_packed_headers,
1911 };
1912 }
1913
1914 if ( (ctx->desired_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1915 !(ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE) &&
1916 (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER)) {
1917 av_log(avctx, AV_LOG_WARNING, "Driver does not support packed "
1918 "sequence headers, but a global header is requested.\n");
1919 av_log(avctx, AV_LOG_WARNING, "No global header will be written: "
1920 "this may result in a stream which is not usable for some "
1921 "purposes (e.g. not muxable to some containers).\n");
1922 }
1923
1924 return 0;
1925 }
1926
1927 static av_cold int vaapi_encode_init_quality(AVCodecContext *avctx)
1928 {
1929 #if VA_CHECK_VERSION(0, 36, 0)
1930 VAAPIEncodeContext *ctx = avctx->priv_data;
1931 VAStatus vas;
1932 VAConfigAttrib attr = { VAConfigAttribEncQualityRange };
1933 int quality = avctx->compression_level;
1934
1935 vas = vaGetConfigAttributes(ctx->hwctx->display,
1936 ctx->va_profile,
1937 ctx->va_entrypoint,
1938 &attr, 1);
1939 if (vas != VA_STATUS_SUCCESS) {
1940 av_log(avctx, AV_LOG_ERROR, "Failed to query quality "
1941 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1942 return AVERROR_EXTERNAL;
1943 }
1944
1945 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1946 if (quality != 0) {
1947 av_log(avctx, AV_LOG_WARNING, "Quality attribute is not "
1948 "supported: will use default quality level.\n");
1949 }
1950 } else {
1951 if (quality > attr.value) {
1952 av_log(avctx, AV_LOG_WARNING, "Invalid quality level: "
1953 "valid range is 0-%d, using %d.\n",
1954 attr.value, attr.value);
1955 quality = attr.value;
1956 }
1957
1958 ctx->quality_params = (VAEncMiscParameterBufferQualityLevel) {
1959 .quality_level = quality,
1960 };
1961 vaapi_encode_add_global_param(avctx,
1962 VAEncMiscParameterTypeQualityLevel,
1963 &ctx->quality_params,
1964 sizeof(ctx->quality_params));
1965 }
1966 #else
1967 av_log(avctx, AV_LOG_WARNING, "The encode quality option is "
1968 "not supported with this VAAPI version.\n");
1969 #endif
1970
1971 return 0;
1972 }
1973
1974 static av_cold int vaapi_encode_init_roi(AVCodecContext *avctx)
1975 {
1976 #if VA_CHECK_VERSION(1, 0, 0)
1977 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
1978 VAAPIEncodeContext *ctx = avctx->priv_data;
1979 VAStatus vas;
1980 VAConfigAttrib attr = { VAConfigAttribEncROI };
1981
1982 vas = vaGetConfigAttributes(ctx->hwctx->display,
1983 ctx->va_profile,
1984 ctx->va_entrypoint,
1985 &attr, 1);
1986 if (vas != VA_STATUS_SUCCESS) {
1987 av_log(avctx, AV_LOG_ERROR, "Failed to query ROI "
1988 "config attribute: %d (%s).\n", vas, vaErrorStr(vas));
1989 return AVERROR_EXTERNAL;
1990 }
1991
1992 if (attr.value == VA_ATTRIB_NOT_SUPPORTED) {
1993 base_ctx->roi_allowed = 0;
1994 } else {
1995 VAConfigAttribValEncROI roi = {
1996 .value = attr.value,
1997 };
1998
1999 ctx->roi_max_regions = roi.bits.num_roi_regions;
2000 base_ctx->roi_allowed = ctx->roi_max_regions > 0 &&
2001 (ctx->va_rc_mode == VA_RC_CQP ||
2002 roi.bits.roi_rc_qp_delta_support);
2003 }
2004 #endif
2005 return 0;
2006 }
2007
2008 static void vaapi_encode_free_output_buffer(FFRefStructOpaque opaque,
2009 void *obj)
2010 {
2011 AVCodecContext *avctx = opaque.nc;
2012 VAAPIEncodeContext *ctx = avctx->priv_data;
2013 VABufferID *buffer_id_ref = obj;
2014 VABufferID buffer_id = *buffer_id_ref;
2015
2016 vaDestroyBuffer(ctx->hwctx->display, buffer_id);
2017
2018 av_log(avctx, AV_LOG_DEBUG, "Freed output buffer %#x\n", buffer_id);
2019 }
2020
2021 static int vaapi_encode_alloc_output_buffer(FFRefStructOpaque opaque, void *obj)
2022 {
2023 AVCodecContext *avctx = opaque.nc;
2024 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
2025 VAAPIEncodeContext *ctx = avctx->priv_data;
2026 VABufferID *buffer_id = obj;
2027 VAStatus vas;
2028
2029 // The output buffer size is fixed, so it needs to be large enough
2030 // to hold the largest possible compressed frame. We assume here
2031 // that the uncompressed frame plus some header data is an upper
2032 // bound on that.
2033 vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
2034 VAEncCodedBufferType,
2035 3 * base_ctx->surface_width * base_ctx->surface_height +
2036 (1 << 16), 1, 0, buffer_id);
2037 if (vas != VA_STATUS_SUCCESS) {
2038 av_log(avctx, AV_LOG_ERROR, "Failed to create bitstream "
2039 "output buffer: %d (%s).\n", vas, vaErrorStr(vas));
2040 return AVERROR(ENOMEM);
2041 }
2042
2043 av_log(avctx, AV_LOG_DEBUG, "Allocated output buffer %#x\n", *buffer_id);
2044
2045 return 0;
2046 }
2047
2048 static av_cold int vaapi_encode_create_recon_frames(AVCodecContext *avctx)
2049 {
2050 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
2051 VAAPIEncodeContext *ctx = avctx->priv_data;
2052 AVVAAPIHWConfig *hwconfig = NULL;
2053 enum AVPixelFormat recon_format;
2054 int err;
2055
2056 hwconfig = av_hwdevice_hwconfig_alloc(base_ctx->device_ref);
2057 if (!hwconfig) {
2058 err = AVERROR(ENOMEM);
2059 goto fail;
2060 }
2061 hwconfig->config_id = ctx->va_config;
2062
2063 err = ff_hw_base_get_recon_format(base_ctx, (const void*)hwconfig, &recon_format);
2064 if (err < 0)
2065 goto fail;
2066
2067 base_ctx->recon_frames_ref = av_hwframe_ctx_alloc(base_ctx->device_ref);
2068 if (!base_ctx->recon_frames_ref) {
2069 err = AVERROR(ENOMEM);
2070 goto fail;
2071 }
2072 base_ctx->recon_frames = (AVHWFramesContext*)base_ctx->recon_frames_ref->data;
2073
2074 base_ctx->recon_frames->format = AV_PIX_FMT_VAAPI;
2075 base_ctx->recon_frames->sw_format = recon_format;
2076 base_ctx->recon_frames->width = base_ctx->surface_width;
2077 base_ctx->recon_frames->height = base_ctx->surface_height;
2078
2079 err = av_hwframe_ctx_init(base_ctx->recon_frames_ref);
2080 if (err < 0) {
2081 av_log(avctx, AV_LOG_ERROR, "Failed to initialise reconstructed "
2082 "frame context: %d.\n", err);
2083 goto fail;
2084 }
2085
2086 err = 0;
2087 fail:
2088 av_freep(&hwconfig);
2089 return err;
2090 }
2091
2092 static const FFHWEncodePictureOperation vaapi_op = {
2093 .alloc = &vaapi_encode_alloc,
2094
2095 .issue = &vaapi_encode_issue,
2096
2097 .output = &vaapi_encode_output,
2098
2099 .free = &vaapi_encode_free,
2100 };
2101
2102 int ff_vaapi_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2103 {
2104 return ff_hw_base_encode_receive_packet(avctx->priv_data, avctx, pkt);
2105 }
2106
2107 av_cold int ff_vaapi_encode_init(AVCodecContext *avctx)
2108 {
2109 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
2110 VAAPIEncodeContext *ctx = avctx->priv_data;
2111 AVVAAPIFramesContext *recon_hwctx = NULL;
2112 VAStatus vas;
2113 int err;
2114
2115 err = ff_hw_base_encode_init(avctx, base_ctx);
2116 if (err < 0)
2117 goto fail;
2118
2119 ctx->va_config = VA_INVALID_ID;
2120 ctx->va_context = VA_INVALID_ID;
2121
2122 base_ctx->op = &vaapi_op;
2123
2124 ctx->hwctx = base_ctx->device->hwctx;
2125
2126 err = vaapi_encode_profile_entrypoint(avctx);
2127 if (err < 0)
2128 goto fail;
2129
2130 if (ctx->codec->get_encoder_caps) {
2131 err = ctx->codec->get_encoder_caps(avctx);
2132 if (err < 0)
2133 goto fail;
2134 } else {
2135 // Assume 16x16 blocks.
2136 base_ctx->surface_width = FFALIGN(avctx->width, 16);
2137 base_ctx->surface_height = FFALIGN(avctx->height, 16);
2138 if (ctx->codec->flags & FF_HW_FLAG_SLICE_CONTROL) {
2139 base_ctx->slice_block_width = 16;
2140 base_ctx->slice_block_height = 16;
2141 }
2142 }
2143
2144 err = vaapi_encode_init_rate_control(avctx);
2145 if (err < 0)
2146 goto fail;
2147
2148 err = vaapi_encode_init_gop_structure(avctx);
2149 if (err < 0)
2150 goto fail;
2151
2152 err = vaapi_encode_init_slice_structure(avctx);
2153 if (err < 0)
2154 goto fail;
2155
2156 err = vaapi_encode_init_packed_headers(avctx);
2157 if (err < 0)
2158 goto fail;
2159
2160 err = vaapi_encode_init_roi(avctx);
2161 if (err < 0)
2162 goto fail;
2163
2164 if (avctx->compression_level >= 0) {
2165 err = vaapi_encode_init_quality(avctx);
2166 if (err < 0)
2167 goto fail;
2168 }
2169
2170 if (ctx->max_frame_size) {
2171 err = vaapi_encode_init_max_frame_size(avctx);
2172 if (err < 0)
2173 goto fail;
2174 }
2175
2176 vas = vaCreateConfig(ctx->hwctx->display,
2177 ctx->va_profile, ctx->va_entrypoint,
2178 ctx->config_attributes, ctx->nb_config_attributes,
2179 &ctx->va_config);
2180 if (vas != VA_STATUS_SUCCESS) {
2181 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2182 "configuration: %d (%s).\n", vas, vaErrorStr(vas));
2183 err = AVERROR(EIO);
2184 goto fail;
2185 }
2186
2187 err = vaapi_encode_create_recon_frames(avctx);
2188 if (err < 0)
2189 goto fail;
2190
2191 recon_hwctx = base_ctx->recon_frames->hwctx;
2192 vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
2193 base_ctx->surface_width, base_ctx->surface_height,
2194 VA_PROGRESSIVE,
2195 recon_hwctx->surface_ids,
2196 recon_hwctx->nb_surfaces,
2197 &ctx->va_context);
2198 if (vas != VA_STATUS_SUCCESS) {
2199 av_log(avctx, AV_LOG_ERROR, "Failed to create encode pipeline "
2200 "context: %d (%s).\n", vas, vaErrorStr(vas));
2201 err = AVERROR(EIO);
2202 goto fail;
2203 }
2204
2205 ctx->output_buffer_pool =
2206 ff_refstruct_pool_alloc_ext(sizeof(VABufferID), 0, avctx,
2207 &vaapi_encode_alloc_output_buffer, NULL,
2208 vaapi_encode_free_output_buffer, NULL);
2209 if (!ctx->output_buffer_pool) {
2210 err = AVERROR(ENOMEM);
2211 goto fail;
2212 }
2213
2214 if (ctx->codec->configure) {
2215 err = ctx->codec->configure(avctx);
2216 if (err < 0)
2217 goto fail;
2218 }
2219
2220 base_ctx->output_delay = base_ctx->b_per_p;
2221 base_ctx->decode_delay = base_ctx->max_b_depth;
2222
2223 if (ctx->codec->sequence_params_size > 0) {
2224 ctx->codec_sequence_params =
2225 av_mallocz(ctx->codec->sequence_params_size);
2226 if (!ctx->codec_sequence_params) {
2227 err = AVERROR(ENOMEM);
2228 goto fail;
2229 }
2230 }
2231 if (ctx->codec->picture_params_size > 0) {
2232 ctx->codec_picture_params =
2233 av_mallocz(ctx->codec->picture_params_size);
2234 if (!ctx->codec_picture_params) {
2235 err = AVERROR(ENOMEM);
2236 goto fail;
2237 }
2238 }
2239
2240 if (ctx->codec->init_sequence_params) {
2241 err = ctx->codec->init_sequence_params(avctx);
2242 if (err < 0) {
2243 av_log(avctx, AV_LOG_ERROR, "Codec sequence initialisation "
2244 "failed: %d.\n", err);
2245 goto fail;
2246 }
2247 }
2248
2249 if (ctx->va_packed_headers & VA_ENC_PACKED_HEADER_SEQUENCE &&
2250 ctx->codec->write_sequence_header &&
2251 avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
2252 char data[MAX_PARAM_BUFFER_SIZE];
2253 size_t bit_len = 8 * sizeof(data);
2254
2255 err = ctx->codec->write_sequence_header(avctx, data, &bit_len);
2256 if (err < 0) {
2257 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
2258 "for extradata: %d.\n", err);
2259 goto fail;
2260 } else {
2261 avctx->extradata_size = (bit_len + 7) / 8;
2262 avctx->extradata = av_mallocz(avctx->extradata_size +
2263 AV_INPUT_BUFFER_PADDING_SIZE);
2264 if (!avctx->extradata) {
2265 err = AVERROR(ENOMEM);
2266 goto fail;
2267 }
2268 memcpy(avctx->extradata, data, avctx->extradata_size);
2269 }
2270 }
2271
2272 #if VA_CHECK_VERSION(1, 9, 0)
2273 // check vaSyncBuffer function
2274 vas = vaSyncBuffer(ctx->hwctx->display, VA_INVALID_ID, 0);
2275 if (vas != VA_STATUS_ERROR_UNIMPLEMENTED) {
2276 base_ctx->async_encode = 1;
2277 base_ctx->encode_fifo = av_fifo_alloc2(base_ctx->async_depth,
2278 sizeof(VAAPIEncodePicture*),
2279 0);
2280 if (!base_ctx->encode_fifo)
2281 return AVERROR(ENOMEM);
2282 }
2283 #endif
2284
2285 return 0;
2286
2287 fail:
2288 return err;
2289 }
2290
2291 av_cold int ff_vaapi_encode_close(AVCodecContext *avctx)
2292 {
2293 FFHWBaseEncodeContext *base_ctx = avctx->priv_data;
2294 VAAPIEncodeContext *ctx = avctx->priv_data;
2295 FFHWBaseEncodePicture *pic, *next;
2296
2297 /* We check ctx->frame to know whether ff_vaapi_encode_init()
2298 * has been called and va_config/va_context initialized. */
2299 if (!base_ctx->frame)
2300 return 0;
2301
2302 for (pic = base_ctx->pic_start; pic; pic = next) {
2303 next = pic->next;
2304 vaapi_encode_free(avctx, pic);
2305 }
2306
2307 ff_refstruct_pool_uninit(&ctx->output_buffer_pool);
2308
2309 if (ctx->va_context != VA_INVALID_ID) {
2310 if (ctx->hwctx)
2311 vaDestroyContext(ctx->hwctx->display, ctx->va_context);
2312 ctx->va_context = VA_INVALID_ID;
2313 }
2314
2315 if (ctx->va_config != VA_INVALID_ID) {
2316 if (ctx->hwctx)
2317 vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
2318 ctx->va_config = VA_INVALID_ID;
2319 }
2320
2321 av_freep(&ctx->codec_sequence_params);
2322 av_freep(&ctx->codec_picture_params);
2323
2324 ff_hw_base_encode_close(base_ctx);
2325
2326 return 0;
2327 }
2328