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