1package vulkan
2
3import (
4 "fmt"
5 "image"
6 "math"
7 "os"
8 "runtime"
9 "strconv"
10 "unsafe"
11
12 "github.com/bnema/neferwl/internal/ports"
13 "github.com/bnema/zerowrap"
14
15 vk "github.com/bnema/purego-vulkan/vulkan"
16)
17
18// Renderer is owned by one goroutine; its methods must not be called concurrently.
19type Renderer struct {
20 width, height int
21 // queuePriority is the global priority the queue got: realtime, high
22 // or default.
23 queuePriority string
24 instance vk.Instance
25 id *vk.InstanceDispatch
26 device vk.Device
27 dd *vk.DeviceDispatch
28 queue vk.Queue
29 // own is the SDR composition image; HDR uses hdrOwn and PQ targets.
30 own target
31 hdrOwn target // linear BT.709 in units of SDR reference white
32 targets []*target
33 current int
34 renderMods []uint64
35 hdrMods []uint64
36 hdrNits float64
37 hdr hdrPass
38 hdrError error
39 // modPlanes is the memory plane count of each probed target modifier
40 // (SDR and HDR): DCC modifiers have more than one.
41 modPlanes map[uint64]uint32
42 // log reports the chosen target modifier; the zero value discards.
43 log zerowrap.Logger
44 // traceDamage logs every frame's redrawn area (--debug=render-damage).
45 traceDamage bool
46 // hdrReadback makes exported HDR targets transfer sources, for GPU tests
47 // and headless --screenshot-raw (SetHDRReadback); never DRM.
48 hdrReadback bool
49 // virtual: the output has no display (headless), so ExportTargets
50 // accepts an empty modifier list for HDR (SetVirtualOutput).
51 virtual bool
52 physical vk.PhysicalDevice
53 // One converted cursor image is kept; changes replace it in bounded memory.
54 cursorCache cursorConversion
55 // lastHDRTarget is the index in targets of the exported PQ target the
56 // last HDR frame rendered into; -1 when the current targets hold none.
57 lastHDRTarget int
58 // last is the target of the last frame: what captures copy.
59 last *target
60 // captures are the readback slots (capture.go), allocated on the
61 // first capture; capturePass converts HDR frames into captureSDR.
62 captures []*captureSlot
63 capturePass hdrPass
64 captureSDR target
65 sync captureSync
66 pool vk.CommandPool
67 memory vk.PhysicalDeviceMemoryProperties
68 family uint32
69 // Frames in flight (frame.go): frame is the last frame recorded,
70 // submitted the last submitted, completed the last known finished.
71 slots [frameSlots]frameSlot
72 frame, submitted, completed uint64
73 deferred []deferredFree
74 // syncFD: frames export a sync file (else Render waits for them).
75 syncFD bool
76 // dmabuf is what clients may send; imports are their buffers by ID.
77 dmabuf ports.DMABufSupport
78 imports map[uint64]*imported
79 // pools are client wl_shm pools mapped by pool ID.
80 pools map[uint64]*mapping
81 // retired are pool mappings replaced this frame, unmapped once the
82 // frame's copies are done.
83 retired [][]byte
84 // shm are the GPU copies of wl_shm surfaces (shm.go); copied counts
85 // the bytes copied into them, for tests.
86 shm map[shmKey]*shmSurface
87 copied int
88 // shmRects is scratch for shmCopyFor.
89 shmRects []image.Rectangle
90 // marks date the frames for Trim's wall-clock eviction (trim.go).
91 marks []trimMark
92 // redrawn counts the target pixels drawn (TakeRedrawn).
93 redrawn int
94 // fullRedraws counts why whole targets or windows were redrawn; each
95 // TakeRedrawn logs and resets it.
96 fullRedraws fullRedraws
97 // cursors are the exported cursor images (CursorBuffers).
98 cursors [2]*cursorImage
99 // compose draws every frame (compose.go); maxRange bounds one
100 // storage buffer binding.
101 compose composer
102 maxRange int
103 // Scratch belongs to the renderer goroutine; neither slice is published.
104 scratchDraws []draw
105 scratchCovers []image.Rectangle
106 damage damageRegion
107 damageSeen map[ports.WindowID]bool
108 damageDrawn map[ports.WindowID]heldWindow
109 frameDMAs []*imported
110 frameAcquires map[*imported]*os.File
111 frameWaits []vk.Semaphore
112 frameStages []vk.PipelineStageFlags
113 // call holds the structs a per-frame Vulkan call is handed by pointer.
114 call callScratch
115 // capCall holds the structs a capture hands Vulkan by pointer.
116 capCall captureScratch
117}
118
119// priorityAttempts falls back to an ordinary queue when elevated priority is unavailable.
120func priorityAttempts(supported bool) []vk.QueueGlobalPriority {
121 if supported {
122 return []vk.QueueGlobalPriority{vk.QueueGlobalPriorityRealtime, vk.QueueGlobalPriorityHigh, 0}
123 }
124 return []vk.QueueGlobalPriority{0}
125}
126
127func checked(name string, result vk.Result) error {
128 if err := vk.Check(result); err != nil {
129 return fmt.Errorf("%s: %w", name, err)
130 }
131 return nil
132}
133
134func New(width, height int) (r *Renderer, err error) {
135 if width <= 0 || height <= 0 || width > math.MaxUint32 || height > math.MaxUint32 || uint64(width)*uint64(height) > uint64(math.MaxInt/4) {
136 return nil, fmt.Errorf("invalid renderer dimensions %d x %d", width, height)
137 }
138 r = &Renderer{width: width, height: height, lastHDRTarget: -1, imports: map[uint64]*imported{}, pools: map[uint64]*mapping{}, shm: map[shmKey]*shmSurface{}}
139 defer func() {
140 if err != nil {
141 r.Close()
142 r = nil
143 }
144 }()
145 if err = vk.Init(); err != nil {
146 return nil, fmt.Errorf("vk.Init: %w", err)
147 }
148 app := vk.ApplicationInfo{SType: vk.StructureTypeApplicationInfo, ApiVersion: vk.MakeVersion(1, 3, 0)}
149 info := vk.InstanceCreateInfo{SType: vk.StructureTypeInstanceCreateInfo, ApplicationInfo: &app}
150 if err = checked("vkCreateInstance", vk.Global().CreateInstance(&info, nil, &r.instance)); err != nil {
151 return
152 }
153 r.id, err = vk.LoadInstanceDispatch(r.instance)
154 if err != nil {
155 err = fmt.Errorf("LoadInstanceDispatch: %w", err)
156 return
157 }
158 var count uint32
159 if err = checked("vkEnumeratePhysicalDevices(count)", r.id.EnumeratePhysicalDevices(r.instance, &count, nil)); err != nil {
160 return
161 }
162 if count == 0 {
163 err = fmt.Errorf("no Vulkan 1.3 device")
164 return
165 }
166 devices := make([]vk.PhysicalDevice, count)
167 if err = checked("vkEnumeratePhysicalDevices", r.id.EnumeratePhysicalDevices(r.instance, &count, &devices[0])); err != nil {
168 return
169 }
170 index := -1
171 if value, ok := os.LookupEnv("NEFERWL_VK_DEVICE"); ok {
172 index, err = strconv.Atoi(value)
173 if err != nil || index < 0 || index >= int(count) {
174 err = fmt.Errorf("invalid NEFERWL_VK_DEVICE index %q", value)
175 return
176 }
177 }
178 var physical vk.PhysicalDevice
179 var family uint32
180 for i, device := range devices[:count] {
181 if index >= 0 && i != index {
182 continue
183 }
184 var properties vk.PhysicalDeviceProperties
185 r.id.GetPhysicalDeviceProperties(device, &properties)
186 if properties.ApiVersion < vk.MakeVersion(1, 3, 0) {
187 continue
188 }
189 var n uint32
190 r.id.GetPhysicalDeviceQueueFamilyProperties(device, &n, nil)
191 if n == 0 {
192 continue
193 }
194 families := make([]vk.QueueFamilyProperties, n)
195 r.id.GetPhysicalDeviceQueueFamilyProperties(device, &n, &families[0])
196 for j, f := range families[:n] {
197 if f.QueueCount > 0 && f.QueueFlags&vk.QueueGraphicsBit != 0 {
198 physical = device
199 family = uint32(j)
200 break
201 }
202 }
203 if physical != 0 {
204 break
205 }
206 }
207 if physical == 0 {
208 err = fmt.Errorf("no Vulkan 1.3 device with a graphics queue")
209 return
210 }
211 r.id.GetPhysicalDeviceMemoryProperties(physical, &r.memory)
212 var properties vk.PhysicalDeviceProperties
213 r.id.GetPhysicalDeviceProperties(physical, &properties)
214 r.maxRange = int(properties.Limits.MaxStorageBufferRange)
215 r.family = family
216 priority := float32(1)
217 qi := vk.DeviceQueueCreateInfo{SType: vk.StructureTypeDeviceQueueCreateInfo, QueueFamilyIndex: family, QueueCount: 1, QueuePriorities: &priority}
218 dynamicRendering := vk.PhysicalDeviceDynamicRenderingFeatures{SType: vk.StructureTypePhysicalDeviceDynamicRenderingFeatures, DynamicRendering: 1}
219 indexing := descriptorIndexingFeatures{SType: descriptorIndexingFeaturesType}
220 features := vk.PhysicalDeviceFeatures2{SType: vk.StructureTypePhysicalDeviceFeatures2, Next: unsafe.Pointer(&indexing)}
221 r.id.GetPhysicalDeviceFeatures2(physical, &features)
222 r.compose.resources = 1
223 coreFeatures := vk.PhysicalDeviceFeatures{}
224 if features.Features.ShaderSampledImageArrayDynamicIndexing != 0 && features.Features.ShaderStorageBufferArrayDynamicIndexing != 0 && indexing.ShaderSampledImageArrayNonUniformIndexing != 0 && indexing.ShaderStorageBufferArrayNonUniformIndexing != 0 {
225 limit := composeResourceLimit(properties.Limits)
226 if limit > 1 {
227 r.compose.resources, r.compose.indexing = limit, true
228 coreFeatures.ShaderSampledImageArrayDynamicIndexing = 1
229 coreFeatures.ShaderStorageBufferArrayDynamicIndexing = 1
230 // Enable only the array indexing features used by these shaders.
231 indexing = descriptorIndexingFeatures{SType: descriptorIndexingFeaturesType, ShaderSampledImageArrayNonUniformIndexing: 1, ShaderStorageBufferArrayNonUniformIndexing: 1}
232 dynamicRendering.Next = unsafe.Pointer(&indexing)
233 }
234 }
235 di := vk.DeviceCreateInfo{SType: vk.StructureTypeDeviceCreateInfo, Next: unsafe.Pointer(&dynamicRendering), QueueCreateInfoCount: 1, QueueCreateInfos: &qi, EnabledFeatures: &coreFeatures}
236 // dmabuf import needs every extension; without them clients use wl_shm.
237 var extNames [][]byte
238 var extPtrs []*byte
239 have := r.extensions(physical)
240 dmabufSupported := true
241 for _, e := range deviceExtensions {
242 if !have[e] {
243 dmabufSupported = false
244 }
245 }
246 if dmabufSupported {
247 for _, e := range deviceExtensions {
248 extNames = append(extNames, append([]byte(e), 0))
249 extPtrs = append(extPtrs, &extNames[len(extNames)-1][0])
250 }
251 di.EnabledExtensionCount = uint32(len(extPtrs))
252 di.PpEnabledExtensionNames = &extPtrs[0]
253 }
254 globalExt := ""
255 if have[vk.KHRGlobalPriorityExtensionName] {
256 globalExt = vk.KHRGlobalPriorityExtensionName
257 } else if have[vk.EXTGlobalPriorityExtensionName] {
258 globalExt = vk.EXTGlobalPriorityExtensionName
259 }
260 var global vk.DeviceQueueGlobalPriorityCreateInfo
261 chosen := "default"
262 for _, attempt := range priorityAttempts(globalExt != "") {
263 qi.Next = nil
264 count := len(extPtrs)
265 if attempt != 0 {
266 global = vk.DeviceQueueGlobalPriorityCreateInfo{SType: vk.StructureTypeDeviceQueueGlobalPriorityCreateInfo, GlobalPriority: attempt}
267 qi.Next = unsafe.Pointer(&global)
268 extNames = append(extNames, append([]byte(globalExt), 0))
269 extPtrs = append(extPtrs, &extNames[len(extNames)-1][0])
270 chosen = "realtime"
271 if attempt == vk.QueueGlobalPriorityHigh {
272 chosen = "high"
273 }
274 } else {
275 chosen = "default"
276 }
277 di.EnabledExtensionCount = uint32(len(extPtrs))
278 if len(extPtrs) > 0 {
279 di.PpEnabledExtensionNames = &extPtrs[0]
280 } else {
281 di.PpEnabledExtensionNames = nil
282 }
283 result := r.id.CreateDevice(physical, &di, nil, &r.device)
284 runtime.KeepAlive(global)
285 runtime.KeepAlive(coreFeatures)
286 runtime.KeepAlive(indexing)
287 runtime.KeepAlive(dynamicRendering)
288 runtime.KeepAlive(qi)
289 runtime.KeepAlive(extNames)
290 runtime.KeepAlive(extPtrs)
291 extPtrs = extPtrs[:count]
292 extNames = extNames[:count]
293 if result == vk.Success {
294 err = nil
295 break
296 }
297 err = checked("vkCreateDevice", result)
298 if attempt == 0 {
299 return
300 }
301 }
302 r.queuePriority = chosen
303 r.dd, err = vk.LoadDeviceDispatch(r.id, r.device)
304 if err != nil {
305 err = fmt.Errorf("LoadDeviceDispatch: %w", err)
306 return
307 }
308 runtime.KeepAlive(extNames)
309 runtime.KeepAlive(extPtrs)
310 if dmabufSupported {
311 // Clients need the render node to allocate on the right GPU.
312 if sup := r.probeDMABuf(physical); sup.Device != 0 {
313 r.dmabuf = sup
314 r.probeRenderModifiers(physical)
315 r.physical = physical
316 }
317 // VK_KHR_external_semaphore_fd (enabled above): frames export
318 // their fence as a sync file.
319 r.syncFD = r.dd.HasGetSemaphoreFdKHR()
320 }
321 r.dd.GetDeviceQueue(r.device, family, 0, &r.queue)
322 extent := vk.Extent3D{Width: uint32(width), Height: uint32(height), Depth: 1}
323 ii := vk.ImageCreateInfo{SType: vk.StructureTypeImageCreateInfo, ImageType: vk.ImageType2d, Format: vk.FormatB8g8r8a8Unorm, Extent: extent, MipLevels: 1, ArrayLayers: 1, Samples: vk.SampleCount1Bit, Tiling: vk.ImageTilingOptimal, Usage: targetUsage | vk.ImageUsageSampledBit, SharingMode: vk.SharingModeExclusive, InitialLayout: vk.ImageLayoutUndefined}
324 if err = checked("vkCreateImage", r.dd.CreateImage(r.device, &ii, nil, &r.own.image)); err != nil {
325 return
326 }
327 var req vk.MemoryRequirements
328 r.dd.GetImageMemoryRequirements(r.device, r.own.image, &req)
329 var kind uint32
330 kind, err = r.findMemoryType(req.MemoryTypeBits, vk.MemoryPropertyDeviceLocalBit)
331 if err != nil {
332 return
333 }
334 alloc := vk.MemoryAllocateInfo{SType: vk.StructureTypeMemoryAllocateInfo, AllocationSize: req.Size, MemoryTypeIndex: kind}
335 if err = checked("vkAllocateMemory(image)", r.dd.AllocateMemory(r.device, &alloc, nil, &r.own.memory)); err != nil {
336 return
337 }
338 if err = checked("vkBindImageMemory", r.dd.BindImageMemory(r.device, r.own.image, r.own.memory, 0)); err != nil {
339 return
340 }
341 pi := vk.CommandPoolCreateInfo{SType: vk.StructureTypeCommandPoolCreateInfo, Flags: vk.CommandPoolCreateResetCommandBufferBit, QueueFamilyIndex: family}
342 if err = checked("vkCreateCommandPool", r.dd.CreateCommandPool(r.device, &pi, nil, &r.pool)); err != nil {
343 return
344 }
345 if err = r.createSlots(); err != nil {
346 return
347 }
348 if err = r.createView(&r.own); err != nil {
349 return
350 }
351 if err = r.createComposer(); err != nil {
352 return
353 }
354 runtime.KeepAlive(priority)
355 return
356}
357
358func (r *Renderer) findMemoryType(bits uint32, props vk.MemoryPropertyFlags) (uint32, error) {
359 for i := uint32(0); i < r.memory.MemoryTypeCount; i++ {
360 if bits&(uint32(1)<<i) != 0 && r.memory.MemoryTypes[i].PropertyFlags&props == props {
361 return i, nil
362 }
363 }
364 return 0, fmt.Errorf("no Vulkan memory type for bits %#x and properties %#x", bits, props)
365}
366
367// CopiedBytes reports cumulative wl_shm bytes copied into GPU storage.
368// It is diagnostic only and must be read by the renderer's owner goroutine.
369func (r *Renderer) CopiedBytes() int { return r.copied }
370
371// TakeRedrawn returns the target pixels drawn since the last call and
372// resets the count.
373func (r *Renderer) TakeRedrawn() int {
374 n := r.redrawn
375 r.redrawn = 0
376 if f := r.fullRedraws.take(); f != (fullRedraws{}) {
377 r.log.Debug().Int("target", f[fullTarget]).Int("scene", f[fullScene]).Int("new_window", f[fullNewWindow]).
378 Int("empty", f[fullEmpty]).Int("children", f[fullChildren]).Int("history", f[fullHistory]).Msg("full redraws")
379 }
380 return n
381}
382
383// SetLogger sets the logger (with its component field) for render target
384// events. Not on the port; the zero logger discards.
385func (r *Renderer) SetLogger(l zerowrap.Logger) { r.log = l }
386
387// SetTraceDamage logs the redrawn pixels, draw count and partial flag of
388// every frame at debug level (--debug=render-damage). Off by default.
389func (r *Renderer) SetTraceDamage(on bool) { r.traceDamage = on }
390
391// QueuePriority is the global priority the queue got: realtime, high or
392// default.
393func (r *Renderer) QueuePriority() string { return r.queuePriority }
394
395// Pixels reads the last frame back through a capture slot, waiting for
396// the GPU on the calling goroutine (slot fence, no sync file needed):
397// headless screenshots and tests only. Nil when no slot is free (both
398// leased to captures) or the copy failed: never a silent black image.
399func (r *Renderer) Pixels() *image.RGBA {
400 cf, err := r.debugCapture()
401 if err != nil {
402 return nil
403 }
404 defer r.EndCapture(cf)
405 out := image.NewRGBA(image.Rect(0, 0, r.width, r.height))
406 if err := cf.Read(image.Rect(0, 0, r.width, r.height), out.Pix, out.Stride); err != nil {
407 return nil
408 }
409 for i := 0; i < len(out.Pix); i += 4 {
410 out.Pix[i], out.Pix[i+2] = out.Pix[i+2], out.Pix[i]
411 }
412 return out
413}
414
415// SetHDRReadback makes the exported HDR targets transfer sources so that
416// HDRPixels can read them (they are not in production: the DRM path never
417// sets it). Call before ExportTargets. Not on the port.
418func (r *Renderer) SetHDRReadback(on bool) { r.hdrReadback = on }
419
420// HDRPixels reads the last HDR frame's XRGB2101010 target back, each 10-bit
421// code scaled to 16 bits (c<<6 | c>>4), alpha opaque. It waits for the GPU:
422// debug only. Nil when the output is SDR, the target is not readable (no
423// SetHDRReadback), no HDR frame was rendered, every slot is leased or the
424// copy failed.
425func (r *Renderer) HDRPixels() *image.RGBA64 {
426 var out *image.RGBA64
427 err := r.readHDRTarget(func(words []uint32) {
428 out = image.NewRGBA64(image.Rect(0, 0, r.width, r.height))
429 for i, w := range words {
430 p := out.Pix[i*8 : i*8+8]
431 for ch, c := range [3]uint32{w >> 20 & 1023, w >> 10 & 1023, w & 1023} {
432 v := uint16(c<<6 | c>>4)
433 p[ch*2], p[ch*2+1] = byte(v>>8), byte(v)
434 }
435 p[6], p[7] = 0xff, 0xff
436 }
437 })
438 if err != nil {
439 return nil
440 }
441 return out
442}
443
444// Missing from the bindings: VK_QUEUE_FAMILY_IGNORED, VK_WHOLE_SIZE.
445const (
446 queueFamilyIgnored = ^uint32(0)
447 wholeSize = ^vk.DeviceSize(0)
448)
449
450func (r *Renderer) Close() {
451 if r == nil {
452 return
453 }
454 if r.dd != nil {
455 d := r.dd
456 if r.device != 0 {
457 _ = checked("vkDeviceWaitIdle", d.DeviceWaitIdle(r.device))
458 r.idle()
459 }
460 r.dropTargets()
461 r.destroyHDR()
462 r.dropCursors()
463 for id, im := range r.imports {
464 r.release(im)
465 delete(r.imports, id)
466 }
467 r.frame += importTTL + 1
468 r.dropPools()
469 r.dropShm()
470 r.destroySlots()
471 r.destroyCaptures()
472 if r.pool != 0 {
473 d.DestroyCommandPool(r.device, r.pool, nil)
474 r.pool = 0
475 }
476 r.destroyComposer()
477 r.freeTarget(&r.hdrOwn)
478 r.freeTarget(&r.own)
479 d.DestroyDevice(r.device, nil)
480 r.device = 0
481 } else if r.device != 0 && r.id != nil {
482 if vk.VkDestroyDevice != nil {
483 vk.VkDestroyDevice(r.device, nil)
484 }
485 r.device = 0
486 }
487 if r.instance != 0 {
488 if r.id != nil {
489 r.id.DestroyInstance(r.instance, nil)
490 } else if vk.VkDestroyInstance != nil {
491 vk.VkDestroyInstance(r.instance, nil)
492 }
493 r.instance = 0
494 }
495}