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