shm.go RawHistoryFolder
1package wlturbo
2
3import (
4 "fmt"
5 "golang.org/x/sys/unix"
6)
7
8// ShmPool represents a shared memory pool
9type ShmPool struct {
10 id uint32
11 fd int
12 size int
13 data []byte
14 offset int
15}
16
17// CreateShmPool creates a new shared memory pool
18func CreateShmPool(size int) (*ShmPool, error) {
19 // Create anonymous file
20 fd, err := CreateAnonymousFile(int64(size))
21 if err != nil {
22 return nil, fmt.Errorf("failed to create anonymous file: %w", err)
23 }
24
25 // Map the file into memory
26 data, err := MapMemory(fd, size)
27 if err != nil {
28 unix.Close(fd)
29 return nil, fmt.Errorf("failed to map memory: %w", err)
30 }
31
32 return &ShmPool{
33 fd: fd,
34 size: size,
35 data: data,
36 }, nil
37}
38
39// Close closes the shared memory pool
40func (p *ShmPool) Close() error {
41 if p.data != nil {
42 if err := UnmapMemory(p.data); err != nil {
43 return err
44 }
45 p.data = nil
46 }
47
48 if p.fd >= 0 {
49 if err := unix.Close(p.fd); err != nil {
50 return err
51 }
52 p.fd = -1
53 }
54
55 return nil
56}
57
58// Data returns the memory-mapped data
59func (p *ShmPool) Data() []byte {
60 return p.data
61}
62
63// FD returns the file descriptor
64func (p *ShmPool) FD() int {
65 return p.fd
66}
67
68// Size returns the pool size
69func (p *ShmPool) Size() int {
70 return p.size
71}
72
73// ShmBuffer represents a buffer allocated from a pool
74type ShmBuffer struct {
75 pool *ShmPool
76 offset int
77 width int
78 height int
79 stride int
80 format uint32
81}
82
83// AllocateBuffer allocates a buffer from the pool
84func (p *ShmPool) AllocateBuffer(width, height, stride int, format uint32) (*ShmBuffer, error) {
85 size := height * stride
86
87 if p.offset+size > p.size {
88 return nil, fmt.Errorf("insufficient space in pool: need %d, have %d", size, p.size-p.offset)
89 }
90
91 buffer := &ShmBuffer{
92 pool: p,
93 offset: p.offset,
94 width: width,
95 height: height,
96 stride: stride,
97 format: format,
98 }
99
100 p.offset += size
101
102 // Align to 64-byte boundary for cache efficiency
103 padding := (64 - (p.offset % 64)) % 64
104 p.offset += padding
105
106 return buffer, nil
107}
108
109// Data returns the buffer's data slice
110func (b *ShmBuffer) Data() []byte {
111 size := b.height * b.stride
112 return b.pool.data[b.offset : b.offset+size]
113}
114
115// Offset returns the buffer's offset in the pool
116func (b *ShmBuffer) Offset() int {
117 return b.offset
118}
119
120// Wayland pixel formats
121const (
122 // 32-bit formats
123 FormatARGB8888 = 0
124 FormatXRGB8888 = 1
125
126 // 24-bit formats
127 FormatRGB888 = 0x34324752 // 'RG24'
128 FormatBGR888 = 0x34324742 // 'BG24'
129
130 // 16-bit formats
131 FormatRGB565 = 0x36314752 // 'RG16'
132 FormatXRGB1555 = 0x35315258 // 'XR15'
133
134 // 8-bit formats
135 FormatY8 = 0x20203859 // 'Y8 '
136)