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