FFmpeg
Loading...
Searching...
No Matches
vulkan_encode.c
Go to the documentation of this file.
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 "libavutil/mem.h"
20#include "libavutil/avassert.h"
21#include "vulkan_encode.h"
22#include "config.h"
23
25
30
33{
34 FFVulkanFunctions *vk = &ctx->s.vkfn;
35
36 FFVulkanEncodePicture *vp = pic->priv;
37
38 if (vp->in.view)
39 vk->DestroyImageView(ctx->s.hwctx->act_dev, vp->in.view,
40 ctx->s.hwctx->alloc);
41
42 vp->in.view = VK_NULL_HANDLE;
43
44 ctx->slots[vp->dpb_slot.slotIndex] = NULL;
45}
46
48{
49 FFVulkanContext *s = &ctx->s;
50 FFVulkanFunctions *vk = &s->vkfn;
51
52 /* Wait on and free execution pool */
53 ff_vk_exec_pool_free(s, &ctx->enc_pool);
54
55 /* Destroy the session params */
56 if (ctx->session_params)
57 vk->DestroyVideoSessionParametersKHR(s->hwctx->act_dev,
58 ctx->session_params,
59 s->hwctx->alloc);
60
61 /* Destroy the image views of any pictures still in the queue,
62 * as ff_hw_base_encode_close() only frees the picture structs */
63 for (FFHWBaseEncodePicture *pic = ctx->base.pic_start; pic; pic = pic->next)
65
66 av_refstruct_pool_uninit(&ctx->buf_pool);
67
69
71
73}
74
76{
77 int err;
79 FFVulkanEncodePicture *vp = pic->priv;
80
81 AVFrame *f = pic->input_image;
82 AVHWFramesContext *hwfc = (AVHWFramesContext *)f->hw_frames_ctx->data;
83 AVVulkanFramesContext *vkfc = hwfc->hwctx;
84 AVVkFrame *vkf = (AVVkFrame *)f->data[0];
85
86 if (ctx->codec->picture_priv_data_size > 0) {
87 pic->codec_priv = av_mallocz(ctx->codec->picture_priv_data_size);
88 if (!pic->codec_priv)
89 return AVERROR(ENOMEM);
90 }
91
92 /* Input image view */
93 err = ff_vk_create_view(&ctx->s,
94 &vp->in.view, &vp->in.aspect,
95 vkf->img[0], vkfc->format[0],
96 VK_IMAGE_USAGE_VIDEO_ENCODE_SRC_BIT_KHR, 0);
97 if (err < 0)
98 return err;
99
100 /* Reference view: owned by the DPB pool entry */
101 if (!ctx->common.layered_dpb) {
103 vp->dpb.view = di->view;
104 vp->dpb.aspect = di->aspect;
105 } else {
106 vp->dpb.view = ctx->common.layered_view;
107 vp->dpb.aspect = ctx->common.layered_aspect;
108 }
109
110 return 0;
111}
112
114{
116
118
119 return 0;
120}
121
123 VkVideoEncodeRateControlInfoKHR *rc_info,
124 VkVideoEncodeRateControlLayerInfoKHR *rc_layer /* Goes in ^ */)
125{
127
128 *rc_info = (VkVideoEncodeRateControlInfoKHR) {
129 .sType = VK_STRUCTURE_TYPE_VIDEO_ENCODE_RATE_CONTROL_INFO_KHR,
130 .rateControlMode = ctx->opts.rc_mode,
131 };
132
133 if (ctx->opts.rc_mode > VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DISABLED_BIT_KHR) {
134 *rc_layer = (VkVideoEncodeRateControlLayerInfoKHR) {
135 .sType = VK_STRUCTURE_TYPE_VIDEO_ENCODE_RATE_CONTROL_LAYER_INFO_KHR,
136 .averageBitrate = avctx->bit_rate,
137 .maxBitrate = avctx->rc_max_rate ? avctx->rc_max_rate : avctx->bit_rate,
138 .frameRateNumerator = avctx->framerate.num,
139 .frameRateDenominator = avctx->framerate.den,
140 };
141 rc_info->layerCount++;
142 rc_info->pLayers = rc_layer;
143 }
144
145 return ctx->codec->init_pic_rc(avctx, pic, rc_info, rc_layer);
146}
147
149 FFHWBaseEncodePicture *base_pic)
150{
152 FFVulkanFunctions *vk = &ctx->s.vkfn;
153
154 const size_t size_align = ctx->caps.minBitstreamBufferSizeAlignment;
155
156 FFVulkanEncodePicture *vp = base_pic->priv;
157 AVFrame *src = (AVFrame *)base_pic->input_image;
158 AVVkFrame *vkf = (AVVkFrame *)src->data[0];
159
160 int err, max_pkt_size;
161
162 FFVkBuffer *sd_buf;
163
164 int slot_index = -1;
165 FFVkExecContext *exec;
166 VkCommandBuffer cmd_buf;
167 VkImageMemoryBarrier2 img_bar[37];
168 int nb_img_bar = 0;
169
170 /* Coding start/end */
171 VkVideoBeginCodingInfoKHR encode_start;
172 VkVideoEndCodingInfoKHR encode_end = {
173 .sType = VK_STRUCTURE_TYPE_VIDEO_END_CODING_INFO_KHR,
174 };
175
176 VkVideoEncodeRateControlLayerInfoKHR rc_layer;
177 VkVideoEncodeRateControlInfoKHR rc_info;
178 VkVideoEncodeQualityLevelInfoKHR q_info;
179 VkVideoCodingControlInfoKHR encode_ctrl;
180
181 VkVideoReferenceSlotInfoKHR ref_slot[37];
182 VkVideoEncodeInfoKHR encode_info;
183
184 /* Create packet data buffer */
185 max_pkt_size = FFALIGN(3 * ctx->base.surface_width * ctx->base.surface_height + (1 << 16),
186 ctx->caps.minBitstreamBufferSizeAlignment);
187
188 err = ff_vk_get_pooled_buffer(&ctx->s, &ctx->buf_pool, &vp->pkt_buf,
189 VK_BUFFER_USAGE_VIDEO_ENCODE_DST_BIT_KHR,
190 &ctx->profile_list, max_pkt_size,
191 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
192 ctx->s.host_cached_flag);
193 if (err < 0)
194 return err;
195
196 sd_buf = vp->pkt_buf;
197
198 /* Setup rate control */
199 err = init_pic_rc(avctx, base_pic, &rc_info, &rc_layer);
200 if (err < 0)
201 return err;
202
203 q_info = (VkVideoEncodeQualityLevelInfoKHR) {
204 .sType = VK_STRUCTURE_TYPE_VIDEO_ENCODE_QUALITY_LEVEL_INFO_KHR,
205 .pNext = &rc_info,
206 .qualityLevel = ctx->opts.quality,
207 };
208 encode_ctrl = (VkVideoCodingControlInfoKHR) {
209 .sType = VK_STRUCTURE_TYPE_VIDEO_CODING_CONTROL_INFO_KHR,
210 .pNext = &q_info,
211 .flags = VK_VIDEO_CODING_CONTROL_ENCODE_QUALITY_LEVEL_BIT_KHR |
212 VK_VIDEO_CODING_CONTROL_ENCODE_RATE_CONTROL_BIT_KHR |
213 VK_VIDEO_CODING_CONTROL_RESET_BIT_KHR,
214 };
215
216 for (int i = 0; i < ctx->caps.maxDpbSlots; i++) {
217 if (ctx->slots[i] == NULL) {
218 slot_index = i;
219 ctx->slots[i] = base_pic;
220 break;
221 }
222 }
223 av_assert0(slot_index >= 0);
224
225 /* Current picture's ref slot */
226 vp->dpb_res = (VkVideoPictureResourceInfoKHR) {
227 .sType = VK_STRUCTURE_TYPE_VIDEO_PICTURE_RESOURCE_INFO_KHR,
228 .pNext = NULL,
229 .codedOffset = { 0 },
230 .codedExtent = (VkExtent2D){ avctx->width, avctx->height },
231 .baseArrayLayer = ctx->common.layered_dpb ? slot_index : 0,
232 .imageViewBinding = vp->dpb.view,
233 };
234
235 vp->dpb_slot = (VkVideoReferenceSlotInfoKHR) {
236 .sType = VK_STRUCTURE_TYPE_VIDEO_REFERENCE_SLOT_INFO_KHR,
237 .pNext = NULL, // Set later
238 .slotIndex = slot_index,
239 .pPictureResource = &vp->dpb_res,
240 };
241
242 encode_info = (VkVideoEncodeInfoKHR) {
243 .sType = VK_STRUCTURE_TYPE_VIDEO_ENCODE_INFO_KHR,
244 .pNext = NULL, // Set later
245 .flags = 0x0,
246 .srcPictureResource = (VkVideoPictureResourceInfoKHR) {
247 .sType = VK_STRUCTURE_TYPE_VIDEO_PICTURE_RESOURCE_INFO_KHR,
248 .pNext = NULL,
249 .codedOffset = { 0, 0 },
250 .codedExtent = (VkExtent2D){ base_pic->input_image->width,
251 base_pic->input_image->height },
252 .baseArrayLayer = 0,
253 .imageViewBinding = vp->in.view,
254 },
255 .pSetupReferenceSlot = &vp->dpb_slot,
256 .referenceSlotCount = 0,
257 .pReferenceSlots = ref_slot,
258 .dstBuffer = sd_buf->buf,
259 .dstBufferOffset = 0,
260 .dstBufferRange = sd_buf->size,
261 .precedingExternallyEncodedBytes = 0,
262 };
263
264 for (int i = 0; i < MAX_REFERENCE_LIST_NUM; i++) {
265 for (int j = 0; j < base_pic->nb_refs[i]; j++) {
266 FFHWBaseEncodePicture *ref = base_pic->refs[i][j];
267 FFVulkanEncodePicture *rvp = ref->priv;
268 ref_slot[encode_info.referenceSlotCount++] = rvp->dpb_slot;
269 }
270 }
271
272 /* Calling vkCmdBeginVideoCodingKHR requires to declare all references
273 * being enabled upfront, including the current frame's output ref. */
274 ref_slot[encode_info.referenceSlotCount] = vp->dpb_slot;
275 ref_slot[encode_info.referenceSlotCount].slotIndex = -1;
276
277 /* Setup picture parameters */
278 err = ctx->codec->init_pic_params(avctx, base_pic,
279 &encode_info);
280 if (err < 0)
281 return err;
282
283 encode_start = (VkVideoBeginCodingInfoKHR) {
284 .sType = VK_STRUCTURE_TYPE_VIDEO_BEGIN_CODING_INFO_KHR,
285 .pNext = !base_pic->force_idr ? &rc_info : NULL,
286 .videoSession = ctx->common.session,
287 .videoSessionParameters = ctx->session_params,
288 .referenceSlotCount = encode_info.referenceSlotCount + 1,
289 .pReferenceSlots = ref_slot,
290 };
291
292 /* Write header */
293 if (base_pic->type == FF_HW_PICTURE_TYPE_IDR) {
294 uint8_t *hdr_dst = sd_buf->mapped_mem + encode_info.dstBufferOffset;
295 size_t data_size = encode_info.dstBufferRange;
296 err = ctx->codec->write_sequence_headers(avctx, base_pic, hdr_dst, &data_size);
297 if (err < 0)
298 goto fail;
299 encode_info.dstBufferOffset += data_size;
300 encode_info.dstBufferRange -= data_size;
301 }
302
303 /* Write extra units */
304 if (ctx->codec->write_extra_headers) {
305 uint8_t *hdr_dst = sd_buf->mapped_mem + encode_info.dstBufferOffset;
306 size_t data_size = encode_info.dstBufferRange;
307 err = ctx->codec->write_extra_headers(avctx, base_pic, hdr_dst, &data_size);
308 if (err < 0)
309 goto fail;
310 encode_info.dstBufferOffset += data_size;
311 encode_info.dstBufferRange -= data_size;
312 }
313
314 /* Align buffer offset to the required value with filler units */
315 if (ctx->codec->write_filler) {
316 uint8_t *hdr_dst = sd_buf->mapped_mem + encode_info.dstBufferOffset;
317 size_t data_size = encode_info.dstBufferRange;
318
319 uint32_t offset = encode_info.dstBufferOffset;
320 size_t offset_align = ctx->caps.minBitstreamBufferOffsetAlignment;
321
322 uint32_t filler_data = FFALIGN(offset, offset_align) - offset;
323
324 if (filler_data) {
325 while (filler_data < ctx->codec->filler_header_size)
326 filler_data += offset_align;
327
328 filler_data -= ctx->codec->filler_header_size;
329
330 err = ctx->codec->write_filler(avctx, filler_data,
331 hdr_dst, &data_size);
332 if (err < 0)
333 goto fail;
334
335 encode_info.dstBufferOffset += data_size;
336 encode_info.dstBufferRange -= data_size;
337 }
338 }
339
340 /* Flush the headers written above if needed */
341 if (encode_info.dstBufferOffset)
342 RET(ff_vk_flush_buffer(&ctx->s, sd_buf, 0,
343 FFALIGN(encode_info.dstBufferOffset,
344 ctx->s.props.properties.limits.nonCoherentAtomSize),
345 1));
346
347 vp->slices_offset = encode_info.dstBufferOffset;
348
349 /* Align buffer size to the nearest lower alignment requirement. */
350 encode_info.dstBufferRange -= size_align;
351 encode_info.dstBufferRange = FFALIGN(encode_info.dstBufferRange,
352 size_align);
353
354 /* Start command buffer recording */
355 exec = vp->exec = ff_vk_exec_get(&ctx->s, &ctx->enc_pool);
356 err = ff_vk_exec_start(&ctx->s, exec);
357 if (err < 0)
358 goto fail;
359 cmd_buf = exec->buf;
360
361 /* Output packet buffer */
363
364 /* Source image */
365 err = ff_vk_exec_add_dep_frame(&ctx->s, exec, src,
366 VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
367 VK_PIPELINE_STAGE_2_VIDEO_ENCODE_BIT_KHR);
368 if (err < 0) {
369 ff_vk_exec_discard(&ctx->s, exec);
370 goto fail;
371 }
372
373 /* Source image layout conversion. Writes to it happened on other
374 * queues, and were made available by the semaphore wait: their access
375 * flags are not to be carried over, and may not even be valid on this
376 * queue. */
377 img_bar[nb_img_bar] = (VkImageMemoryBarrier2) {
378 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
379 .pNext = NULL,
380 .srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
381 .srcAccessMask = VK_ACCESS_2_NONE,
382 .dstStageMask = VK_PIPELINE_STAGE_2_VIDEO_ENCODE_BIT_KHR,
383 .dstAccessMask = VK_ACCESS_2_VIDEO_ENCODE_READ_BIT_KHR,
384 .oldLayout = vkf->layout[0],
385 .newLayout = VK_IMAGE_LAYOUT_VIDEO_ENCODE_SRC_KHR,
386 .srcQueueFamilyIndex = vkf->queue_family[0],
387 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
388 .image = vkf->img[0],
389 .subresourceRange = (VkImageSubresourceRange) {
390 .aspectMask = vp->in.aspect,
391 .layerCount = 1,
392 .levelCount = 1,
393 },
394 };
396 &img_bar[nb_img_bar], &nb_img_bar);
397
398 /* DPB image barriers are only needed for initial transitions: the
399 * layered image at creation, per-picture recon images here */
400 if (!ctx->common.layered_dpb) {
402
403 if (di->layout != VK_IMAGE_LAYOUT_VIDEO_ENCODE_DPB_KHR) {
404 img_bar[nb_img_bar] = (VkImageMemoryBarrier2) {
405 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
406 .srcStageMask = VK_PIPELINE_STAGE_2_NONE,
407 .srcAccessMask = VK_ACCESS_2_NONE,
408 .dstStageMask = VK_PIPELINE_STAGE_2_VIDEO_ENCODE_BIT_KHR,
409 .dstAccessMask = VK_ACCESS_2_VIDEO_ENCODE_READ_BIT_KHR |
410 VK_ACCESS_2_VIDEO_ENCODE_WRITE_BIT_KHR,
411 .oldLayout = di->layout,
412 .newLayout = VK_IMAGE_LAYOUT_VIDEO_ENCODE_DPB_KHR,
413 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
414 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
415 .image = di->img,
416 .subresourceRange = (VkImageSubresourceRange) {
417 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
418 .layerCount = 1,
419 .levelCount = 1,
420 },
421 };
422 nb_img_bar++;
423 di->layout = VK_IMAGE_LAYOUT_VIDEO_ENCODE_DPB_KHR;
424 }
425 }
426
427 /* One encode-stage memory barrier per submission orders all prior
428 * encode work, references included */
429 VkMemoryBarrier2 mem_bar = {
430 .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
431 .srcStageMask = VK_PIPELINE_STAGE_2_VIDEO_ENCODE_BIT_KHR,
432 .srcAccessMask = VK_ACCESS_2_VIDEO_ENCODE_WRITE_BIT_KHR,
433 .dstStageMask = VK_PIPELINE_STAGE_2_VIDEO_ENCODE_BIT_KHR,
434 .dstAccessMask = VK_ACCESS_2_VIDEO_ENCODE_READ_BIT_KHR |
435 VK_ACCESS_2_VIDEO_ENCODE_WRITE_BIT_KHR,
436 };
437
438 /* Change image layouts, and synchronize the DPB */
439 vk->CmdPipelineBarrier2(cmd_buf, &(VkDependencyInfo) {
440 .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
441 .pMemoryBarriers = &mem_bar,
442 .memoryBarrierCount = 1,
443 .pImageMemoryBarriers = img_bar,
444 .imageMemoryBarrierCount = nb_img_bar,
445 });
446
447 /* Start, use parameters */
448 vk->CmdBeginVideoCodingKHR(cmd_buf, &encode_start);
449
450 /* Send control data */
451 if (!ctx->session_reset) {
452 vk->CmdControlVideoCodingKHR(cmd_buf, &encode_ctrl);
453 ctx->session_reset++;
454 }
455
456 /* Encode */
457 vk->CmdBeginQuery(cmd_buf, ctx->enc_pool.query_pool, exec->query_idx + 0, 0);
458 vk->CmdEncodeVideoKHR(cmd_buf, &encode_info);
459 vk->CmdEndQuery(cmd_buf, ctx->enc_pool.query_pool, exec->query_idx + 0);
460
461 /* End encoding */
462 vk->CmdEndVideoCodingKHR(cmd_buf, &encode_end);
463
464 /* For the host to read the output */
465 vk->CmdPipelineBarrier2(cmd_buf, &(VkDependencyInfo) {
466 .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
467 .pMemoryBarriers = &(VkMemoryBarrier2) {
468 .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
469 .srcStageMask = VK_PIPELINE_STAGE_2_VIDEO_ENCODE_BIT_KHR,
470 .srcAccessMask = VK_ACCESS_2_VIDEO_ENCODE_WRITE_BIT_KHR,
471 .dstStageMask = VK_PIPELINE_STAGE_2_HOST_BIT,
472 .dstAccessMask = VK_ACCESS_2_HOST_READ_BIT,
473 },
474 .memoryBarrierCount = 1,
475 });
476
477 /* End recording and submit for execution */
478 err = ff_vk_exec_submit(&ctx->s, vp->exec);
479 if (err < 0)
480 goto fail;
481
482 /* We don't need to keep the input image any longer, its already ref'd */
483 av_frame_free(&base_pic->input_image);
484
485 return 0;
486
487fail:
488 return err;
489}
490
491static void pkt_buf_free(void *opaque, uint8_t *data)
492{
493 av_refstruct_unref(&opaque);
494}
495
497 FFHWBaseEncodePicture *base_pic)
498{
500 FFVulkanEncodePicture *vp = base_pic->priv;
501
502 av_assert0(base_pic->encode_issued);
503
504 if (base_pic->encode_complete)
505 return;
506
507 ff_vk_exec_wait(&ctx->s, vp->exec);
508 base_pic->encode_complete = 1;
509}
510
513{
514 VkResult ret;
515 int err, offs;
516 FFVulkanEncodePicture *vp = base_pic->priv;
518 FFHWBaseEncodeContext *base_ctx = &ctx->base;
519 AVPacket *pkt_ptr = pkt;
520
521 FFVkBuffer *sd_buf = vp->pkt_buf;
522 uint32_t *query_data;
523
524 vulkan_encode_wait(avctx, base_pic);
525
526 ret = ff_vk_exec_get_query(&ctx->s, vp->exec, (void **)&query_data, 0);
527 if (ret == VK_NOT_READY) {
528 av_log(avctx, AV_LOG_ERROR, "Unable to perform query: %s!\n",
530 return AVERROR(EINVAL);
531 }
532
533 if (ret != VK_NOT_READY && ret != VK_SUCCESS) {
534 av_log(avctx, AV_LOG_ERROR, "Unable to perform query: %s!\n",
536 return AVERROR_EXTERNAL;
537 }
538
539 if (query_data[2] != VK_QUERY_RESULT_STATUS_COMPLETE_KHR) {
540 av_log(avctx, AV_LOG_ERROR, "Unable to encode: %u\n", query_data[2]);
541 return AVERROR_EXTERNAL;
542 }
543
544 /* If the non-coherent alignment is greater than the bitstream buffer
545 * offset's alignment, and the offs value is not aligned already,
546 * align it to the previous alignment point. */
547 offs = vp->slices_offset;
548 if (ctx->s.props.properties.limits.nonCoherentAtomSize >
549 ctx->caps.minBitstreamBufferOffsetAlignment && offs &&
550 (FFALIGN(offs, ctx->s.props.properties.limits.nonCoherentAtomSize) != offs)) {
551 offs -= ctx->s.props.properties.limits.nonCoherentAtomSize;
552 offs = FFALIGN(FFMAX(offs, 0), ctx->s.props.properties.limits.nonCoherentAtomSize);
553 }
554
555 /* Invalidate buffer if needed */
556 err = ff_vk_flush_buffer(&ctx->s, sd_buf, offs,
557 FFALIGN(vp->slices_offset + query_data[0] +
558 query_data[1] - offs,
559 ctx->s.props.properties.limits.nonCoherentAtomSize),
560 0);
561 if (err < 0)
562 return err;
563
564 if (vp->non_independent_frame) {
565 av_assert0(!ctx->prev_buf_ref);
566 size_t prev_buf_size = vp->slices_offset + query_data[0] + query_data[1];
567 ctx->prev_buf_ref = vp->pkt_buf;
568 ctx->prev_buf_size = prev_buf_size;
569 vp->pkt_buf = NULL;
570
571 if (vp->tail_size) {
572 if (base_ctx->tail_pkt->size)
573 return AVERROR_BUG;
574
575 ret = ff_get_encode_buffer(avctx, base_ctx->tail_pkt, vp->tail_size, 0);
576 if (ret < 0)
577 return ret;
578
579 memcpy(base_ctx->tail_pkt->data, vp->tail_data, vp->tail_size);
580 pkt_ptr = base_ctx->tail_pkt;
581 }
582 } else {
583 if (ctx->prev_buf_ref) {
584 FFVkBuffer *prev_sd_buf = ctx->prev_buf_ref;
585 size_t prev_size = ctx->prev_buf_size;
586 size_t size = (vp->slices_offset + query_data[0] + query_data[1]);
587
588 ret = ff_get_encode_buffer(avctx, pkt, prev_size + size, 0);
589 if (ret < 0)
590 return ret;
591
592 memcpy(pkt->data, prev_sd_buf->mapped_mem, prev_size);
593 memcpy(pkt->data + prev_size, sd_buf->mapped_mem, size);
594
595 av_refstruct_unref(&ctx->prev_buf_ref);
597 } else {
598 pkt->data = sd_buf->mapped_mem;
599 pkt->size = vp->slices_offset + /* base offset */
600 query_data[0] /* secondary offset */ +
601 query_data[1] /* size */;
602
603 /* Hand the pooled buffer to the packet with no copy */
604 pkt->buf = av_buffer_create(sd_buf->mapped_mem, pkt->size,
605 pkt_buf_free, vp->pkt_buf, 0);
606 if (!pkt->buf)
607 return AVERROR(ENOMEM);
608 vp->pkt_buf = NULL; /* ownership passed to pkt->buf */
609 }
610 }
611
612 av_log(avctx, AV_LOG_DEBUG, "Frame %"PRId64"/%"PRId64 " encoded\n",
613 base_pic->display_order, base_pic->encode_order);
614
615 return ff_hw_base_encode_set_output_property(&ctx->base, avctx,
616 base_pic, pkt_ptr,
617 ctx->codec->flags & VK_ENC_FLAG_NO_DELAY);
618}
619
621 .priv_size = sizeof(FFVulkanEncodePicture),
623 .issue = &vulkan_encode_issue,
624 .output = &vulkan_encode_output,
625 .free = &vulkan_encode_free,
626};
627
633
634static void vulkan_encode_recon_free(void *opaque, uint8_t *data)
635{
637 /* No wait: pool reuse is ordered by the DPB barrier */
639}
640
642{
645
646 di = av_refstruct_pool_get(ctx->common.dpb->img_pool);
647 if (!di)
648 return AVERROR(ENOMEM);
649
650 /* The frame only carries the pool entry through the base layer */
651 frame->buf[0] = av_buffer_create((uint8_t *)di, sizeof(*di),
653 if (!frame->buf[0]) {
655 return AVERROR(ENOMEM);
656 }
657 frame->data[0] = (uint8_t *)di;
658
659 return 0;
660}
661
663{
664 int err;
665 FFHWBaseEncodeContext *base_ctx = &ctx->base;
666
667 /* Reconstruction images are queue-exclusive; allocate them internally */
668 err = ff_vk_video_dpb_init(&ctx->s, &ctx->common, ctx->pic_format,
669 VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR,
670 VK_IMAGE_TILING_OPTIMAL, &ctx->profile_list,
671 avctx->width, avctx->height,
672 ctx->common.layered_dpb ?
673 ctx->caps.maxDpbSlots : 1);
674 if (err < 0) {
675 av_log(avctx, AV_LOG_ERROR, "Failed to initialise DPB image pool: %s\n",
676 av_err2str(err));
677 return err;
678 }
679
680 if (ctx->common.layered_dpb) {
681 FFVulkanFunctions *vk = &ctx->s.vkfn;
682 FFVkExecContext *exec;
683 VkImageMemoryBarrier2 img_bar;
684
685 ctx->common.layered_img = av_refstruct_pool_get(ctx->common.dpb->img_pool);
686 if (!ctx->common.layered_img)
687 return AVERROR(ENOMEM);
688
689 ctx->common.layered_view = ctx->common.layered_img->view;
690 ctx->common.layered_aspect = ctx->common.layered_img->aspect;
691
692 /* Created eagerly, so transitioned eagerly, matching the decoder */
693 exec = ff_vk_exec_get(&ctx->s, &ctx->enc_pool);
694 err = ff_vk_exec_start(&ctx->s, exec);
695 if (err < 0)
696 return err;
697
698 img_bar = (VkImageMemoryBarrier2) {
699 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
700 .srcStageMask = VK_PIPELINE_STAGE_2_NONE,
701 .srcAccessMask = VK_ACCESS_2_NONE,
702 .dstStageMask = VK_PIPELINE_STAGE_2_VIDEO_ENCODE_BIT_KHR,
703 .dstAccessMask = VK_ACCESS_2_VIDEO_ENCODE_READ_BIT_KHR |
704 VK_ACCESS_2_VIDEO_ENCODE_WRITE_BIT_KHR,
705 .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
706 .newLayout = VK_IMAGE_LAYOUT_VIDEO_ENCODE_DPB_KHR,
707 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
708 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
709 .image = ctx->common.layered_img->img,
710 .subresourceRange = (VkImageSubresourceRange) {
711 .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
712 .layerCount = VK_REMAINING_ARRAY_LAYERS,
713 .levelCount = 1,
714 },
715 };
716 vk->CmdPipelineBarrier2(exec->buf, &(VkDependencyInfo) {
717 .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
718 .pImageMemoryBarriers = &img_bar,
719 .imageMemoryBarrierCount = 1,
720 });
721
722 err = ff_vk_exec_submit(&ctx->s, exec);
723 if (err < 0)
724 return err;
725
726 ctx->common.layered_img->layout = VK_IMAGE_LAYOUT_VIDEO_ENCODE_DPB_KHR;
727 } else {
729 }
730
731 return 0;
732}
733
735{
736 if (ctx->opts.qp) {
737 ctx->explicit_qp = ctx->opts.qp;
738 } else if (avctx->global_quality > 0) {
739 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
740 ctx->explicit_qp = avctx->global_quality / FF_QP2LAMBDA;
741 else
742 ctx->explicit_qp = avctx->global_quality;
743 }
744
745 if (ctx->opts.rc_mode == FF_VK_RC_MODE_AUTO) {
746 if (ctx->explicit_qp >= 0) {
747 ctx->opts.rc_mode = VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DISABLED_BIT_KHR;
748 } else if (avctx->global_quality > 0) {
749 if (avctx->flags & AV_CODEC_FLAG_QSCALE)
750 ctx->explicit_qp = avctx->global_quality / FF_QP2LAMBDA;
751 else
752 ctx->explicit_qp = avctx->global_quality;
753 ctx->opts.rc_mode = VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DISABLED_BIT_KHR;
754 } else if (avctx->bit_rate) {
755 if (ctx->enc_caps.rateControlModes & VK_VIDEO_ENCODE_RATE_CONTROL_MODE_VBR_BIT_KHR)
756 ctx->opts.rc_mode = VK_VIDEO_ENCODE_RATE_CONTROL_MODE_VBR_BIT_KHR;
757 else if (ctx->enc_caps.rateControlModes & VK_VIDEO_ENCODE_RATE_CONTROL_MODE_CBR_BIT_KHR)
758 ctx->opts.rc_mode = VK_VIDEO_ENCODE_RATE_CONTROL_MODE_CBR_BIT_KHR;
759 else
760 ctx->opts.rc_mode = VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DEFAULT_KHR;
761 } else {
762 ctx->explicit_qp = 18;
763 ctx->opts.rc_mode = VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DISABLED_BIT_KHR;
764 av_log(avctx, AV_LOG_WARNING, "No rate control settings specified, using fixed QP = %i\n",
765 ctx->explicit_qp);
766 }
767 } else if (ctx->opts.rc_mode != VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DISABLED_BIT_KHR &&
768 !avctx->bit_rate) {
769 av_log(avctx, AV_LOG_WARNING, "No bitrate specified!\n");
770 return AVERROR(EINVAL);
771 }
772
773 if (ctx->opts.rc_mode && !(ctx->enc_caps.rateControlModes & ctx->opts.rc_mode)) {
774 static const char *rc_modes[] = {
775 [VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DEFAULT_KHR] = "default",
776 [VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DISABLED_BIT_KHR] = "cqp",
777 [VK_VIDEO_ENCODE_RATE_CONTROL_MODE_CBR_BIT_KHR] = "cbr",
778 [VK_VIDEO_ENCODE_RATE_CONTROL_MODE_VBR_BIT_KHR] = "vbr",
779 };
780 av_log(avctx, AV_LOG_ERROR, "Unsupported rate control mode %s, supported are:\n",
781 rc_modes[FFMIN(FF_ARRAY_ELEMS(rc_modes), ctx->opts.rc_mode)]);
782 av_log(avctx, AV_LOG_ERROR, " %s\n", rc_modes[0]);
783 for (int i = VK_VIDEO_ENCODE_RATE_CONTROL_MODE_DISABLED_BIT_KHR;
784 i <= VK_VIDEO_ENCODE_RATE_CONTROL_MODE_VBR_BIT_KHR; i <<= 1) {
785 if (!(ctx->enc_caps.rateControlModes & i))
786 continue;
787 av_log(avctx, AV_LOG_ERROR, " %s\n", rc_modes[i]);
788 }
789 return AVERROR(ENOTSUP);
790 }
791
792 return 0;
793}
794
797{
798 int err;
799
800 /* Write extradata if needed */
801 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
802 uint8_t data[4096];
803 size_t data_len = sizeof(data);
804
805 err = ctx->codec->write_sequence_headers(avctx, NULL, data, &data_len);
806 if (err < 0) {
807 av_log(avctx, AV_LOG_ERROR, "Failed to write sequence header "
808 "for extradata: %d.\n", err);
809 return err;
810 } else {
811 avctx->extradata_size = data_len;
812 avctx->extradata = av_mallocz(avctx->extradata_size +
814 if (!avctx->extradata) {
815 err = AVERROR(ENOMEM);
816 return err;
817 }
818 memcpy(avctx->extradata, data, avctx->extradata_size);
819 }
820 }
821
822 return 0;
823}
824
826 const FFVulkanEncodeDescriptor *vk_desc,
827 const FFVulkanCodec *codec,
828 void *codec_caps, void *quality_pnext)
829{
830 int i, err;
831 VkResult ret;
832 FFVulkanFunctions *vk = &ctx->s.vkfn;
833 FFVulkanContext *s = &ctx->s;
834 FFHWBaseEncodeContext *base_ctx = &ctx->base;
835
837
838 VkVideoFormatPropertiesKHR *ret_info;
839 uint32_t nb_out_fmts = 0;
840 const uint32_t feedback_flags = VK_VIDEO_ENCODE_FEEDBACK_BITSTREAM_BUFFER_OFFSET_BIT_KHR |
841 VK_VIDEO_ENCODE_FEEDBACK_BITSTREAM_BYTES_WRITTEN_BIT_KHR;
842
843 VkPhysicalDeviceVideoEncodeQualityLevelInfoKHR quality_info;
844
845 VkQueryPoolVideoEncodeFeedbackCreateInfoKHR query_create;
846
847 VkVideoSessionCreateInfoKHR session_create = {
848 .sType = VK_STRUCTURE_TYPE_VIDEO_SESSION_CREATE_INFO_KHR,
849 };
850 VkPhysicalDeviceVideoFormatInfoKHR fmt_info = {
851 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_FORMAT_INFO_KHR,
852 .pNext = &ctx->profile_list,
853 };
854
855 if (!avctx->hw_frames_ctx) {
856 av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
857 "required to associate the encoding device.\n");
858 return AVERROR(EINVAL);
859 }
860
861 ctx->base.op = &vulkan_base_encode_ops;
862 ctx->codec = codec;
863
864 s->frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
865 s->frames = (AVHWFramesContext *)s->frames_ref->data;
866 s->hwfc = s->frames->hwctx;
867
868 s->device = (AVHWDeviceContext *)s->frames->device_ref->data;
869 s->hwctx = s->device->hwctx;
870
872 if (!desc)
873 return AVERROR(EINVAL);
874
875 s->extensions = ff_vk_extensions_to_mask(s->hwctx->enabled_dev_extensions,
876 s->hwctx->nb_enabled_dev_extensions);
877
878 if (!(s->extensions & FF_VK_EXT_VIDEO_ENCODE_QUEUE)) {
879 av_log(avctx, AV_LOG_ERROR, "Device does not support the %s extension!\n",
880 VK_KHR_VIDEO_ENCODE_QUEUE_EXTENSION_NAME);
881 return AVERROR(ENOSYS);
882 } else if (!(s->extensions & FF_VK_EXT_VIDEO_MAINTENANCE_1)) {
883 av_log(avctx, AV_LOG_ERROR, "Device does not support the %s extension!\n",
884 VK_KHR_VIDEO_MAINTENANCE_1_EXTENSION_NAME);
885 return AVERROR(ENOSYS);
886 } else if (!(s->extensions & vk_desc->encode_extension)) {
887 av_log(avctx, AV_LOG_ERROR, "Device does not support encoding %s!\n",
888 avcodec_get_name(avctx->codec_id));
889 return AVERROR(ENOSYS);
890 }
891
892 /* Load functions */
893 err = ff_vk_load_functions(s->device, vk, s->extensions, 1, 1);
894 if (err < 0)
895 return err;
896
897 /* Create queue context */
898 ctx->qf_enc = ff_vk_qf_find(s, VK_QUEUE_VIDEO_ENCODE_BIT_KHR, vk_desc->encode_op);
899 if (!ctx->qf_enc) {
900 av_log(avctx, AV_LOG_ERROR, "Encoding of %s is not supported by this device\n",
901 avcodec_get_name(avctx->codec_id));
902 return AVERROR(ENOSYS);
903 }
904
905 /* Load all properties */
906 err = ff_vk_load_props(s);
907 if (err < 0)
908 return err;
909
910 /* Set tuning */
911 ctx->usage_info = (VkVideoEncodeUsageInfoKHR) {
912 .sType = VK_STRUCTURE_TYPE_VIDEO_ENCODE_USAGE_INFO_KHR,
913 .videoUsageHints = ctx->opts.usage,
914 .videoContentHints = ctx->opts.content,
915 .tuningMode = ctx->opts.tune,
916 };
917
918 /* Load up the profile now, needed for caps and to create a query pool */
919 ctx->profile.sType = VK_STRUCTURE_TYPE_VIDEO_PROFILE_INFO_KHR;
920 ctx->profile.pNext = &ctx->usage_info;
921 ctx->profile.videoCodecOperation = vk_desc->encode_op;
922 ctx->profile.chromaSubsampling = ff_vk_subsampling_from_av_desc(desc);
923 ctx->profile.lumaBitDepth = ff_vk_depth_from_av_depth(desc->comp[0].depth);
924 ctx->profile.chromaBitDepth = ctx->profile.lumaBitDepth;
925
926 /* Setup a profile */
927 err = codec->init_profile(avctx, &ctx->profile, &ctx->usage_info);
928 if (err < 0)
929 return err;
930
931 ctx->profile_list.sType = VK_STRUCTURE_TYPE_VIDEO_PROFILE_LIST_INFO_KHR;
932 ctx->profile_list.profileCount = 1;
933 ctx->profile_list.pProfiles = &ctx->profile;
934
935 /* Get the capabilities of the encoder for the given profile */
936 ctx->enc_caps.sType = VK_STRUCTURE_TYPE_VIDEO_ENCODE_CAPABILITIES_KHR;
937 ctx->enc_caps.pNext = codec_caps;
938 ctx->caps.sType = VK_STRUCTURE_TYPE_VIDEO_CAPABILITIES_KHR;
939 ctx->caps.pNext = &ctx->enc_caps;
940
941 /* A pixel format without a video profile representation is not a valid
942 * profile to query the capabilities for */
943 if (ctx->profile.chromaSubsampling == VK_VIDEO_CHROMA_SUBSAMPLING_INVALID_KHR ||
944 ctx->profile.lumaBitDepth == VK_VIDEO_COMPONENT_BIT_DEPTH_INVALID_KHR)
945 ret = VK_ERROR_VIDEO_PROFILE_FORMAT_NOT_SUPPORTED_KHR;
946 else
947 ret = vk->GetPhysicalDeviceVideoCapabilitiesKHR(s->hwctx->phys_dev,
948 &ctx->profile,
949 &ctx->caps);
950 if (ret == VK_ERROR_VIDEO_PROFILE_OPERATION_NOT_SUPPORTED_KHR ||
951 ret == VK_ERROR_VIDEO_PROFILE_CODEC_NOT_SUPPORTED_KHR) {
952 av_log(avctx, AV_LOG_ERROR, "Unable to initialize encoding: "
953 "%s profile \"%s\" not supported!\n",
955 avcodec_profile_name(avctx->codec_id, avctx->profile));
956 return AVERROR(EINVAL);
957 } else if (ret == VK_ERROR_VIDEO_PROFILE_FORMAT_NOT_SUPPORTED_KHR) {
958 av_log(avctx, AV_LOG_ERROR, "Unable to initialize encoding: "
959 "format (%s) not supported!\n",
961 return AVERROR(EINVAL);
962 } else if (ret == VK_ERROR_FEATURE_NOT_PRESENT ||
963 ret == VK_ERROR_FORMAT_NOT_SUPPORTED) {
964 return AVERROR(EINVAL);
965 } else if (ret != VK_SUCCESS) {
966 return AVERROR_EXTERNAL;
967 }
968
969 if ((ctx->enc_caps.supportedEncodeFeedbackFlags & feedback_flags) !=
970 feedback_flags) {
971 av_log(avctx, AV_LOG_ERROR,
972 "Driver does not support required encode feedback flags "
973 "(BUFFER_OFFSET and BYTES_WRITTEN).\n");
974 return AVERROR(ENOTSUP);
975 }
976
977 err = init_rc(avctx, ctx);
978 if (err < 0)
979 return err;
980
981 /* Create command and query pool */
982 query_create = (VkQueryPoolVideoEncodeFeedbackCreateInfoKHR) {
983 .sType = VK_STRUCTURE_TYPE_QUERY_POOL_VIDEO_ENCODE_FEEDBACK_CREATE_INFO_KHR,
984 .pNext = &ctx->profile,
985 .encodeFeedbackFlags = feedback_flags,
986 };
987 err = ff_vk_exec_pool_init(s, ctx->qf_enc, &ctx->enc_pool, base_ctx->async_depth,
988 1, VK_QUERY_TYPE_VIDEO_ENCODE_FEEDBACK_KHR, 0,
989 &query_create);
990 if (err < 0)
991 return err;
992
993 if (ctx->opts.quality > ctx->enc_caps.maxQualityLevels) {
994 av_log(avctx, AV_LOG_ERROR, "Invalid quality level %i: allowed range is "
995 "0 to %i\n",
996 ctx->opts.quality, ctx->enc_caps.maxQualityLevels);
997 return AVERROR(EINVAL);
998 }
999
1000 /* Get quality properties for the profile and quality level */
1001 quality_info = (VkPhysicalDeviceVideoEncodeQualityLevelInfoKHR) {
1002 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VIDEO_ENCODE_QUALITY_LEVEL_INFO_KHR,
1003 .pVideoProfile = &ctx->profile,
1004 .qualityLevel = ctx->opts.quality,
1005 };
1006 ctx->quality_props = (VkVideoEncodeQualityLevelPropertiesKHR) {
1007 .sType = VK_STRUCTURE_TYPE_VIDEO_ENCODE_QUALITY_LEVEL_PROPERTIES_KHR,
1008 .pNext = quality_pnext,
1009 };
1010 ret = vk->GetPhysicalDeviceVideoEncodeQualityLevelPropertiesKHR(s->hwctx->phys_dev,
1011 &quality_info,
1012 &ctx->quality_props);
1013 if (ret != VK_SUCCESS)
1014 return AVERROR_EXTERNAL;
1015
1016 /* Printout informative properties */
1017 av_log(avctx, AV_LOG_VERBOSE, "Encoder capabilities for %s profile \"%s\":\n",
1018 avcodec_get_name(avctx->codec_id),
1019 avcodec_profile_name(avctx->codec_id, avctx->profile));
1020 av_log(avctx, AV_LOG_VERBOSE, " Width: from %i to %i\n",
1021 ctx->caps.minCodedExtent.width, ctx->caps.maxCodedExtent.width);
1022 av_log(avctx, AV_LOG_VERBOSE, " Height: from %i to %i\n",
1023 ctx->caps.minCodedExtent.height, ctx->caps.maxCodedExtent.height);
1024 av_log(avctx, AV_LOG_VERBOSE, " Width alignment: %i\n",
1025 ctx->caps.pictureAccessGranularity.width);
1026 av_log(avctx, AV_LOG_VERBOSE, " Height alignment: %i\n",
1027 ctx->caps.pictureAccessGranularity.height);
1028 av_log(avctx, AV_LOG_VERBOSE, " Bitstream offset alignment: %"PRIu64"\n",
1029 ctx->caps.minBitstreamBufferOffsetAlignment);
1030 av_log(avctx, AV_LOG_VERBOSE, " Bitstream size alignment: %"PRIu64"\n",
1031 ctx->caps.minBitstreamBufferSizeAlignment);
1032 av_log(avctx, AV_LOG_VERBOSE, " Maximum references: %u\n",
1033 ctx->caps.maxDpbSlots);
1034 av_log(avctx, AV_LOG_VERBOSE, " Maximum active references: %u\n",
1035 ctx->caps.maxActiveReferencePictures);
1036 av_log(avctx, AV_LOG_VERBOSE, " Codec header version: %i.%i.%i (driver), %i.%i.%i (compiled)\n",
1037 CODEC_VER(ctx->caps.stdHeaderVersion.specVersion),
1038 CODEC_VER(vk_desc->ext_props.specVersion));
1039 av_log(avctx, AV_LOG_VERBOSE, " Encoder max quality: %i\n",
1040 ctx->enc_caps.maxQualityLevels);
1041 av_log(avctx, AV_LOG_VERBOSE, " Encoder image width alignment: %i\n",
1042 ctx->enc_caps.encodeInputPictureGranularity.width);
1043 av_log(avctx, AV_LOG_VERBOSE, " Encoder image height alignment: %i\n",
1044 ctx->enc_caps.encodeInputPictureGranularity.height);
1045 av_log(avctx, AV_LOG_VERBOSE, " Capability flags:%s%s%s\n",
1046 ctx->caps.flags ? "" :
1047 " none",
1048 ctx->caps.flags & VK_VIDEO_CAPABILITY_PROTECTED_CONTENT_BIT_KHR ?
1049 " protected" : "",
1050 ctx->caps.flags & VK_VIDEO_CAPABILITY_SEPARATE_REFERENCE_IMAGES_BIT_KHR ?
1051 " separate_references" : "");
1052
1053 /* Setup width/height alignment */
1054 base_ctx->surface_width = avctx->coded_width =
1055 FFALIGN(avctx->width, ctx->enc_caps.encodeInputPictureGranularity.width);
1056 base_ctx->surface_height = avctx->coded_height =
1057 FFALIGN(avctx->height, ctx->enc_caps.encodeInputPictureGranularity.height);
1058
1059 /* Setup slice width/height */
1060 base_ctx->slice_block_width = ctx->enc_caps.encodeInputPictureGranularity.width;
1061 base_ctx->slice_block_height = ctx->enc_caps.encodeInputPictureGranularity.height;
1062
1063 /* Check if encoding is possible with the given parameters */
1064 if (avctx->coded_width < ctx->caps.minCodedExtent.width ||
1065 avctx->coded_height < ctx->caps.minCodedExtent.height ||
1066 avctx->coded_width > ctx->caps.maxCodedExtent.width ||
1067 avctx->coded_height > ctx->caps.maxCodedExtent.height) {
1068 av_log(avctx, AV_LOG_ERROR, "Input of %ix%i too large for encoder limits: %ix%i max\n",
1069 avctx->coded_width, avctx->coded_height,
1070 ctx->caps.minCodedExtent.width, ctx->caps.minCodedExtent.height);
1071 return AVERROR(EINVAL);
1072 }
1073
1074 fmt_info.imageUsage = VK_IMAGE_USAGE_VIDEO_ENCODE_DPB_BIT_KHR;
1075
1076 ctx->common.layered_dpb = !(ctx->caps.flags & VK_VIDEO_CAPABILITY_SEPARATE_REFERENCE_IMAGES_BIT_KHR);
1077
1078 /* Get the supported image formats */
1079 ret = vk->GetPhysicalDeviceVideoFormatPropertiesKHR(s->hwctx->phys_dev,
1080 &fmt_info,
1081 &nb_out_fmts, NULL);
1082 if (ret == VK_ERROR_FORMAT_NOT_SUPPORTED ||
1083 (!nb_out_fmts && ret == VK_SUCCESS)) {
1084 return AVERROR(EINVAL);
1085 } else if (ret != VK_SUCCESS) {
1086 av_log(avctx, AV_LOG_ERROR, "Unable to get Vulkan format properties: %s!\n",
1088 return AVERROR_EXTERNAL;
1089 }
1090
1091 ret_info = av_mallocz(sizeof(*ret_info)*nb_out_fmts);
1092 if (!ret_info)
1093 return AVERROR(ENOMEM);
1094
1095 for (int i = 0; i < nb_out_fmts; i++)
1096 ret_info[i].sType = VK_STRUCTURE_TYPE_VIDEO_FORMAT_PROPERTIES_KHR;
1097
1098 ret = vk->GetPhysicalDeviceVideoFormatPropertiesKHR(s->hwctx->phys_dev,
1099 &fmt_info,
1100 &nb_out_fmts, ret_info);
1101 if (ret == VK_ERROR_FORMAT_NOT_SUPPORTED ||
1102 (!nb_out_fmts && ret == VK_SUCCESS)) {
1103 av_free(ret_info);
1104 return AVERROR(EINVAL);
1105 } else if (ret != VK_SUCCESS) {
1106 av_log(avctx, AV_LOG_ERROR, "Unable to get Vulkan format properties: %s!\n",
1108 av_free(ret_info);
1109 return AVERROR_EXTERNAL;
1110 }
1111
1112 av_log(avctx, AV_LOG_VERBOSE, "Supported input formats:\n");
1113 for (i = 0; i < nb_out_fmts; i++)
1114 av_log(avctx, AV_LOG_VERBOSE, " %i: %i\n", i, ret_info[i].format);
1115
1116 for (i = 0; i < nb_out_fmts; i++) {
1117 if (ff_vk_pix_fmt_from_vkfmt(ret_info[i].format) == s->frames->sw_format) {
1118 ctx->pic_format = ret_info[i].format;
1119 break;
1120 }
1121 }
1122
1123 av_free(ret_info);
1124
1125 if (i == nb_out_fmts) {
1126 av_log(avctx, AV_LOG_ERROR, "Pixel format %s of input frames not supported!\n",
1127 av_get_pix_fmt_name(s->frames->sw_format));
1128 return AVERROR(EINVAL);
1129 }
1130
1131 /* Create session */
1132 session_create.pVideoProfile = &ctx->profile;
1133 session_create.flags = VK_VIDEO_SESSION_CREATE_ALLOW_ENCODE_PARAMETER_OPTIMIZATIONS_BIT_KHR;
1134 session_create.queueFamilyIndex = ctx->qf_enc->idx;
1135 session_create.maxCodedExtent = ctx->caps.maxCodedExtent;
1136 session_create.maxDpbSlots = ctx->caps.maxDpbSlots;
1137 session_create.maxActiveReferencePictures = ctx->caps.maxActiveReferencePictures;
1138 session_create.pictureFormat = ctx->pic_format;
1139 session_create.referencePictureFormat = session_create.pictureFormat;
1140 session_create.pStdHeaderVersion = &vk_desc->ext_props;
1141
1142 err = ff_vk_video_common_init(avctx, s, &ctx->common, &session_create);
1143 if (err < 0)
1144 return err;
1145
1146 err = ff_hw_base_encode_init(avctx, &ctx->base);
1147 if (err < 0)
1148 return err;
1149
1150 err = vulkan_encode_create_dpb(avctx, ctx);
1151 if (err < 0)
1152 return err;
1153
1154 base_ctx->async_encode = 1;
1155 base_ctx->encode_fifo = av_fifo_alloc2(base_ctx->async_depth,
1156 sizeof(FFVulkanEncodePicture *), 0);
1157 if (!base_ctx->encode_fifo)
1158 return AVERROR(ENOMEM);
1159
1160 return 0;
1161}
1162
1164 void *codec_params_pnext)
1165{
1166 VkResult ret;
1167 FFVulkanFunctions *vk = &ctx->s.vkfn;
1168 FFVulkanContext *s = &ctx->s;
1169
1170 VkVideoEncodeQualityLevelInfoKHR q_info;
1171 VkVideoSessionParametersCreateInfoKHR session_params_create;
1172
1173 q_info = (VkVideoEncodeQualityLevelInfoKHR) {
1174 .sType = VK_STRUCTURE_TYPE_VIDEO_ENCODE_QUALITY_LEVEL_INFO_KHR,
1175 .pNext = codec_params_pnext,
1176 .qualityLevel = ctx->opts.quality,
1177 };
1178 session_params_create = (VkVideoSessionParametersCreateInfoKHR) {
1179 .sType = VK_STRUCTURE_TYPE_VIDEO_SESSION_PARAMETERS_CREATE_INFO_KHR,
1180 .pNext = &q_info,
1181 .videoSession = ctx->common.session,
1182 .videoSessionParametersTemplate = VK_NULL_HANDLE,
1183 };
1184
1185 /* Create session parameters */
1186 ret = vk->CreateVideoSessionParametersKHR(s->hwctx->act_dev, &session_params_create,
1187 s->hwctx->alloc, &ctx->session_params);
1188 if (ret != VK_SUCCESS) {
1189 av_log(avctx, AV_LOG_ERROR, "Unable to create Vulkan video session parameters: %s!\n",
1191 return AVERROR_EXTERNAL;
1192 }
1193
1194 return 0;
1195}
static const char *const format[]
Definition af_aiir.c:445
static AVFormatContext * ctx
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define f(width, name)
Definition cbs_vp8.c:236
#define s(width, name)
Definition cbs_vp9.c:198
#define NULL
Definition coverity.c:32
static AVPacket * pkt
static AVFrame * frame
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:613
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
Get a buffer for a packet.
Definition encode.c:107
int ret
Definition ffplay.c:391
#define fail
Definition test.h:479
const char * avcodec_profile_name(enum AVCodecID codec_id, int profile)
Return a name for the specified profile, if available.
Definition utils.c:446
#define AV_CODEC_FLAG_QSCALE
Use fixed qscale.
Definition avcodec.h:213
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition avcodec.h:318
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition utils.c:421
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition buffer.c:104
AVBufferRef * av_buffer_create(uint8_t *data, size_t size, void(*free)(void *opaque, uint8_t *data), void *opaque, int flags)
Create an AVBuffer from an existing array.
Definition buffer.c:56
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition avutil.h:226
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition error.h:59
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition error.h:52
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#define AVERROR(e)
Definition error.h:45
AVFifo * av_fifo_alloc2(size_t nb_elems, size_t elem_size, unsigned int flags)
Allocate and initialize an AVFifo with a given element size.
Definition fifo.c:47
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition frame.c:65
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
static av_cold int encode_end(AVCodecContext *avctx)
Definition huffyuvenc.c:985
int ff_hw_base_encode_receive_packet(FFHWBaseEncodeContext *ctx, AVCodecContext *avctx, AVPacket *pkt)
int ff_hw_base_encode_set_output_property(FFHWBaseEncodeContext *ctx, AVCodecContext *avctx, FFHWBaseEncodePicture *pic, AVPacket *pkt, int flag_no_delay)
int ff_hw_base_encode_init(AVCodecContext *avctx, FFHWBaseEncodeContext *ctx)
int ff_hw_base_encode_close(FFHWBaseEncodeContext *ctx)
@ FF_HW_PICTURE_TYPE_IDR
#define MAX_REFERENCE_LIST_NUM
#define HW_CONFIG_ENCODER_FRAMES(format, device_type_)
Definition hwconfig.h:100
unsigned offset
Definition libaomenc.c:763
#define av_cold
Definition attributes.h:117
void ff_vk_exec_pool_free(FFVulkanContext *s, FFVkExecPool *pool)
Definition vulkan.c:335
int ff_vk_exec_pool_init(FFVulkanContext *s, AVVulkanDeviceQueueFamily *qf, FFVkExecPool *pool, int nb_contexts, int nb_queries, VkQueryType query_type, int query_64bit, const void *query_create_pnext)
Allocates/frees an execution pool.
Definition vulkan.c:399
void ff_vk_exec_wait(FFVulkanContext *s, FFVkExecContext *e)
Definition vulkan.c:653
void ff_vk_uninit(FFVulkanContext *s)
Frees main context.
Definition vulkan.c:2800
int ff_vk_load_props(FFVulkanContext *s)
Loads props/mprops/driver_props.
Definition vulkan.c:151
const char * ff_vk_ret2str(VkResult res)
Converts Vulkan return values to strings.
Definition vulkan.c:42
int ff_vk_exec_start(FFVulkanContext *s, FFVkExecContext *e)
Start/submit/wait an execution.
Definition vulkan.c:668
VkResult ff_vk_exec_get_query(FFVulkanContext *s, FFVkExecContext *e, void **data, VkQueryResultFlagBits flags)
Performs nb_queries queries and returns their results and statuses.
Definition vulkan.c:602
void ff_vk_exec_update_frame(FFVulkanContext *s, FFVkExecContext *e, AVFrame *f, VkImageMemoryBarrier2 *bar, uint32_t *nb_img_bar)
Definition vulkan.c:947
FFVkExecContext * ff_vk_exec_get(FFVulkanContext *s, FFVkExecPool *pool)
Retrieve an execution pool.
Definition vulkan.c:630
int ff_vk_exec_submit(FFVulkanContext *s, FFVkExecContext *e)
Definition vulkan.c:991
AVVulkanDeviceQueueFamily * ff_vk_qf_find(FFVulkanContext *s, VkQueueFlagBits dev_family, VkVideoCodecOperationFlagBitsKHR vid_ops)
Chooses an appropriate QF.
Definition vulkan.c:320
void ff_vk_exec_add_dep_refstruct(FFVulkanContext *s, FFVkExecContext *e, void *obj)
Execution dependency management.
Definition vulkan.c:787
int ff_vk_get_pooled_buffer(FFVulkanContext *ctx, AVRefStructPool **buf_pool, FFVkBuffer **buf, VkBufferUsageFlags usage, void *create_pNext, size_t size, VkMemoryPropertyFlagBits mem_props)
Initialize a pool and create AVBufferRefs containing FFVkBuffer.
Definition vulkan.c:1448
int ff_vk_flush_buffer(FFVulkanContext *s, FFVkBuffer *buf, VkDeviceSize offset, VkDeviceSize mem_size, int flush)
Flush or invalidate a single buffer, with a given size and offset.
Definition vulkan.c:1349
void ff_vk_exec_discard(FFVulkanContext *s, FFVkExecContext *e)
Definition vulkan.c:771
int ff_vk_exec_add_dep_frame(FFVulkanContext *s, FFVkExecContext *e, AVFrame *f, VkPipelineStageFlagBits2 wait_stage, VkPipelineStageFlagBits2 signal_stage)
Definition vulkan.c:889
const char * desc
Definition libsvtav1.c:83
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
#define FFALIGN(x, a)
Definition macros.h:78
Memory handling functions.
const char data[16]
Definition mxf.c:155
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition pixdesc.c:3404
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition pixdesc.c:3484
void av_refstruct_unref(void *objp)
Decrement the reference count of the underlying object and automatically free the object if there are...
Definition refstruct.c:121
void * av_refstruct_pool_get(AVRefStructPool *pool)
Get an object from the pool, reusing an old one from the pool when available.
Definition refstruct.c:315
static void av_refstruct_pool_uninit(AVRefStructPool **poolp)
Mark the pool as being available for freeing.
Definition refstruct.h:292
#define FF_ARRAY_ELEMS(a)
main external API structure.
Definition avcodec.h:443
int width
picture width / height.
Definition avcodec.h:605
enum AVPixelFormat sw_pix_fmt
Nominal unaccelerated pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:651
int global_quality
Global quality for codecs which cannot change it per frame.
Definition avcodec.h:1240
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames.
Definition avcodec.h:1477
AVRational framerate
Definition avcodec.h:563
int64_t bit_rate
the average bitrate
Definition avcodec.h:493
int profile
profile
Definition avcodec.h:1646
int64_t rc_max_rate
maximum bitrate
Definition avcodec.h:1293
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:500
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
Definition avcodec.h:526
enum AVCodecID codec_id
Definition avcodec.h:453
int extradata_size
Definition avcodec.h:527
int coded_width
Bitstream width / height, may be different from width/height e.g.
Definition avcodec.h:620
void * priv_data
Definition avcodec.h:470
This structure describes decoded (raw) audio or video data.
Definition frame.h:479
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition frame.h:500
int width
Definition frame.h:551
int height
Definition frame.h:551
This struct aggregates all the (hardware/vendor-specific) "high-level" state, i.e.
Definition hwcontext.h:63
This struct describes a set or pool of "hardware" frames (i.e.
Definition hwcontext.h:118
void * hwctx
The format-specific data, allocated and freed automatically along with this context.
Definition hwcontext.h:153
This structure stores compressed data.
Definition packet.h:587
int size
Definition packet.h:611
uint8_t * data
Definition packet.h:610
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition pixdesc.h:69
int num
Numerator.
Definition rational.h:59
int den
Denominator.
Definition rational.h:60
VkImageLayout layout[AV_NUM_DATA_POINTERS]
uint32_t queue_family[AV_NUM_DATA_POINTERS]
Queue family of the images.
VkImage img[AV_NUM_DATA_POINTERS]
Vulkan images to which the memory is bound to.
Allocated as AVHWFramesContext.hwctx, used to set pool-specific options.
VkFormat format[AV_NUM_DATA_POINTERS]
Vulkan format for each image.
int(* get_recon_frame)(AVCodecContext *avctx, AVFrame *frame)
AVPacket * tail_pkt
Tail data of a pic, now only used for av1 repeat frame header.
int nb_refs[MAX_REFERENCE_LIST_NUM]
struct FFHWBaseEncodePicture * refs[MAX_REFERENCE_LIST_NUM][MAX_PICTURE_REFERENCES]
VkBuffer buf
Definition vulkan.h:95
size_t size
Definition vulkan.h:98
uint8_t * mapped_mem
Definition vulkan.h:103
VkCommandBuffer buf
Definition vulkan.h:142
VkImageLayout layout
VkImageAspectFlags aspect
VkImageView view
int(* init_profile)(AVCodecContext *avctx, VkVideoProfileInfoKHR *profile, void *pnext)
Initialize codec-specific structs in a Vulkan profile.
VkVideoCodecOperationFlagBitsKHR encode_op
VkExtensionProperties ext_props
FFVulkanExtensions encode_extension
struct FFVulkanEncodePicture::@241153336102273375156314120123002360217156257341 in
VkVideoPictureResourceInfoKHR dpb_res
FFVkExecContext * exec
VkImageAspectFlags aspect
struct FFVulkanEncodePicture::@211005011031223012316203343327310203116057373135 dpb
VkVideoReferenceSlotInfoKHR dpb_slot
#define av_free(p)
#define av_mallocz(s)
#define av_log(a,...)
#define src
Definition vp8dsp.c:248
static int ref[MAX_W *MAX_W]
int size
#define RET(x)
Definition vulkan.h:37
static int vulkan_encode_init(AVCodecContext *avctx, FFHWBaseEncodePicture *pic)
static int vulkan_encode_free(AVCodecContext *avctx, FFHWBaseEncodePicture *pic)
const AVCodecHWConfigInternal *const ff_vulkan_encode_hw_configs[]
Paperwork.
av_cold int ff_vulkan_encode_init(AVCodecContext *avctx, FFVulkanEncodeContext *ctx, const FFVulkanEncodeDescriptor *vk_desc, const FFVulkanCodec *codec, void *codec_caps, void *quality_pnext)
Initialize encoder.
static void vulkan_encode_free_pic(FFVulkanEncodeContext *ctx, FFHWBaseEncodePicture *pic)
static int vulkan_encode_output(AVCodecContext *avctx, FFHWBaseEncodePicture *base_pic, AVPacket *pkt)
static int vulkan_encode_create_dpb(AVCodecContext *avctx, FFVulkanEncodeContext *ctx)
static int vulkan_encode_get_recon_frame(AVCodecContext *avctx, AVFrame *frame)
static void vulkan_encode_wait(AVCodecContext *avctx, FFHWBaseEncodePicture *base_pic)
static int vulkan_encode_issue(AVCodecContext *avctx, FFHWBaseEncodePicture *base_pic)
static const FFHWEncodePictureOperation vulkan_base_encode_ops
av_cold void ff_vulkan_encode_uninit(FFVulkanEncodeContext *ctx)
Uninitialize encoder.
static void vulkan_encode_recon_free(void *opaque, uint8_t *data)
static int init_pic_rc(AVCodecContext *avctx, FFHWBaseEncodePicture *pic, VkVideoEncodeRateControlInfoKHR *rc_info, VkVideoEncodeRateControlLayerInfoKHR *rc_layer)
int ff_vulkan_encode_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
Encode.
av_cold int ff_vulkan_write_global_header(AVCodecContext *avctx, FFVulkanEncodeContext *ctx)
Write out the extradata in case its needed.
static av_cold int init_rc(AVCodecContext *avctx, FFVulkanEncodeContext *ctx)
static void pkt_buf_free(void *opaque, uint8_t *data)
int ff_vulkan_encode_create_session_params(AVCodecContext *avctx, FFVulkanEncodeContext *ctx, void *codec_params_pnext)
Create session parameters.
#define FF_VK_RC_MODE_AUTO
#define VK_ENC_FLAG_NO_DELAY
#define FF_VK_EXT_VIDEO_MAINTENANCE_1
#define FF_VK_EXT_VIDEO_ENCODE_QUEUE
static uint64_t ff_vk_extensions_to_mask(const char *const *extensions, int nb_extensions)
static int ff_vk_load_functions(AVHWDeviceContext *ctx, FFVulkanFunctions *vk, uint64_t extensions_mask, int has_inst, int has_dev)
Function loader.
VkVideoComponentBitDepthFlagBitsKHR ff_vk_depth_from_av_depth(int depth)
Get Vulkan's bit depth from an [8:12] integer.
VkVideoChromaSubsamplingFlagBitsKHR ff_vk_subsampling_from_av_desc(const AVPixFmtDescriptor *desc)
Get Vulkan's chroma subsampling from a pixfmt descriptor.
int ff_vk_create_view(FFVulkanContext *s, VkImageView *view, VkImageAspectFlags *aspect, VkImage img, VkFormat vkf, VkImageUsageFlags usage, int layered)
Creates image views for video frames.
av_cold void ff_vk_video_common_uninit(FFVulkanContext *s, FFVkVideoCommon *common)
Free video session and required resources.
av_cold int ff_vk_video_dpb_init(FFVulkanContext *s, FFVkVideoCommon *common, VkFormat format, VkImageUsageFlags usage, VkImageTiling tiling, void *create_pnext, int width, int height, int nb_layers)
Initialize the internal DPB image pool.
enum AVPixelFormat ff_vk_pix_fmt_from_vkfmt(VkFormat vkf)
Get pixfmt from a Vulkan format.
av_cold int ff_vk_video_common_init(AVCodecContext *avctx, FFVulkanContext *s, FFVkVideoCommon *common, VkVideoSessionCreateInfoKHR *session_create)
Initialize video session, allocating and binding necessary memory.
#define CODEC_VER(ver)