1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package main

import (
	"encoding/binary"
	"fmt"
	"math"
	"strings"
)

// POD Type constants from pipewire-pod.txt
const (
	TypeNone      uint32 = 1
	TypeBool      uint32 = 2
	TypeId        uint32 = 3
	TypeInt       uint32 = 4
	TypeLong      uint32 = 5
	TypeFloat     uint32 = 6
	TypeDouble    uint32 = 7
	TypeString    uint32 = 8
	TypeBytes     uint32 = 9
	TypeRectangle uint32 = 10
	TypeFraction  uint32 = 11
	TypeBitmap    uint32 = 12
	TypeArray     uint32 = 13
	TypeStruct    uint32 = 14
	TypeObject    uint32 = 15
	TypeSequence  uint32 = 16
	TypePointer   uint32 = 17
	TypeFd        uint32 = 18
	TypeChoice    uint32 = 19
	TypePod       uint32 = 20
)

// POD represents a PipeWire POD (Plain Old Data)
// Layout: [size:uint32][type:uint32][payload...][padding to 8 bytes]
type POD struct {
	Size uint32 // Size of payload (not including size/type header)
	Type uint32 // POD type
	Data []byte // Raw payload data (already padded to 8 bytes)
}

// roundUp8 rounds up to nearest multiple of 8
func roundUp8(n int) int {
	return (n + 7) &^ 7
}

// EncodePOD encodes a POD to bytes
func (p *POD) Encode() []byte {
	totalSize := 8 + len(p.Data) // header (8 bytes) + data
	buf := make([]byte, totalSize)
	binary.LittleEndian.PutUint32(buf[0:4], p.Size)
	binary.LittleEndian.PutUint32(buf[4:8], p.Type)
	copy(buf[8:], p.Data)
	return buf
}

// DecodePOD decodes a POD from bytes, returns the POD and number of bytes consumed
func DecodePOD(data []byte) (*POD, int, error) {
	if len(data) < 8 {
		return nil, 0, fmt.Errorf("insufficient data for POD header: need 8, got %d", len(data))
	}

	size := binary.LittleEndian.Uint32(data[0:4])
	podType := binary.LittleEndian.Uint32(data[4:8])

	// Total size is 8 (header) + rounded up payload
	paddedSize := roundUp8(int(size))
	totalSize := 8 + paddedSize

	if len(data) < totalSize {
		return nil, 0, fmt.Errorf("insufficient data for POD payload: need %d, got %d", totalSize, len(data))
	}

	pod := &POD{
		Size: size,
		Type: podType,
		Data: make([]byte, paddedSize),
	}
	copy(pod.Data, data[8:totalSize])

	return pod, totalSize, nil
}

// Helper constructors for basic POD types

// NewNone creates a None POD
func NewNone() *POD {
	return &POD{Size: 0, Type: TypeNone, Data: nil}
}

// NewBool creates a Bool POD
func NewBool(value bool) *POD {
	data := make([]byte, 8)
	if value {
		binary.LittleEndian.PutUint32(data[0:4], 1)
	}
	return &POD{Size: 4, Type: TypeBool, Data: data}
}

// NewInt creates an Int POD
func NewInt(value int32) *POD {
	data := make([]byte, 8)
	binary.LittleEndian.PutUint32(data[0:4], uint32(value))
	return &POD{Size: 4, Type: TypeInt, Data: data}
}

// NewId creates an Id POD
func NewId(value uint32) *POD {
	data := make([]byte, 8)
	binary.LittleEndian.PutUint32(data[0:4], value)
	return &POD{Size: 4, Type: TypeId, Data: data}
}

// NewLong creates a Long POD
func NewLong(value int64) *POD {
	data := make([]byte, 8)
	binary.LittleEndian.PutUint64(data[0:8], uint64(value))
	return &POD{Size: 8, Type: TypeLong, Data: data}
}

// NewFloat creates a Float POD
func NewFloat(value float32) *POD {
	data := make([]byte, 8)
	binary.LittleEndian.PutUint32(data[0:4], math.Float32bits(value))
	return &POD{Size: 4, Type: TypeFloat, Data: data}
}

// NewDouble creates a Double POD
func NewDouble(value float64) *POD {
	data := make([]byte, 8)
	binary.LittleEndian.PutUint64(data[0:8], math.Float64bits(value))
	return &POD{Size: 8, Type: TypeDouble, Data: data}
}

// NewString creates a String POD (null-terminated, padded to 8 bytes)
func NewString(value string) *POD {
	strBytes := []byte(value)
	size := len(strBytes) + 1 // include null terminator
	paddedSize := roundUp8(size)
	data := make([]byte, paddedSize)
	copy(data, strBytes)
	// data is already zero-initialized, so null terminator is implicit
	return &POD{Size: uint32(size), Type: TypeString, Data: data}
}

// NewStruct creates a Struct POD from a list of child PODs
func NewStruct(children ...*POD) *POD {
	// Calculate total size
	var totalSize int
	for _, child := range children {
		totalSize += 8 + len(child.Data) // each child is header + data
	}

	data := make([]byte, roundUp8(totalSize))
	offset := 0
	for _, child := range children {
		childBytes := child.Encode()
		copy(data[offset:], childBytes)
		offset += len(childBytes)
	}

	return &POD{Size: uint32(totalSize), Type: TypeStruct, Data: data}
}

// GetInt extracts an int32 from an Int POD
func (p *POD) GetInt() (int32, error) {
	if p.Type != TypeInt {
		return 0, fmt.Errorf("POD type is %d, expected Int (%d)", p.Type, TypeInt)
	}
	if len(p.Data) < 4 {
		return 0, fmt.Errorf("insufficient data for Int")
	}
	return int32(binary.LittleEndian.Uint32(p.Data[0:4])), nil
}

// GetLong extracts an int64 from a Long POD
func (p *POD) GetLong() (int64, error) {
	if p.Type != TypeLong {
		return 0, fmt.Errorf("POD type is %d, expected Long (%d)", p.Type, TypeLong)
	}
	if len(p.Data) < 8 {
		return 0, fmt.Errorf("insufficient data for Long")
	}
	return int64(binary.LittleEndian.Uint64(p.Data[0:8])), nil
}

// GetString extracts a string from a String POD
func (p *POD) GetString() (string, error) {
	if p.Type != TypeString {
		return "", fmt.Errorf("POD type is %d, expected String (%d)", p.Type, TypeString)
	}
	// Find null terminator
	for i := 0; i < len(p.Data) && i < int(p.Size); i++ {
		if p.Data[i] == 0 {
			return string(p.Data[0:i]), nil
		}
	}
	// No null terminator found within size
	if int(p.Size) <= len(p.Data) {
		return string(p.Data[0:p.Size]), nil
	}
	return string(p.Data), nil
}

// GetStructChildren extracts child PODs from a Struct
func (p *POD) GetStructChildren() ([]*POD, error) {
	if p.Type != TypeStruct {
		return nil, fmt.Errorf("POD type is %d, expected Struct (%d)", p.Type, TypeStruct)
	}

	var children []*POD
	offset := 0
	dataLen := int(p.Size)

	for offset < dataLen {
		child, consumed, err := DecodePOD(p.Data[offset:dataLen])
		if err != nil {
			return nil, fmt.Errorf("failed to decode child POD at offset %d: %w", offset, err)
		}
		children = append(children, child)
		offset += consumed
	}

	return children, nil
}

// ParseStruct is a helper to parse a struct into expected types
// It decodes children and returns them as a slice
func ParseStruct(p *POD) ([]*POD, error) {
	return p.GetStructChildren()
}

// PrettyPrint returns a human-readable string representation of a POD
func (p *POD) PrettyPrint(indent int) string {
	prefix := ""
	for range indent {
		prefix += "  "
	}

	switch p.Type {
	case TypeNone:
		return prefix + "None"
	case TypeBool:
		if len(p.Data) >= 4 {
			val := binary.LittleEndian.Uint32(p.Data[0:4])
			return prefix + fmt.Sprintf("Bool(%v)", val != 0)
		}
		return prefix + "Bool(error: insufficient data)"
	case TypeId:
		if len(p.Data) >= 4 {
			val := binary.LittleEndian.Uint32(p.Data[0:4])
			return prefix + fmt.Sprintf("Id(%d)", val)
		}
		return prefix + "Id(error: insufficient data)"
	case TypeInt:
		val, err := p.GetInt()
		if err != nil {
			return prefix + fmt.Sprintf("Int(error: %v)", err)
		}
		return prefix + fmt.Sprintf("Int(%d)", val)
	case TypeLong:
		val, err := p.GetLong()
		if err != nil {
			return prefix + fmt.Sprintf("Long(error: %v)", err)
		}
		return prefix + fmt.Sprintf("Long(%d)", val)
	case TypeFloat:
		if len(p.Data) >= 4 {
			val := math.Float32frombits(binary.LittleEndian.Uint32(p.Data[0:4]))
			return prefix + fmt.Sprintf("Float(%f)", val)
		}
		return prefix + "Float(error: insufficient data)"
	case TypeDouble:
		if len(p.Data) >= 8 {
			val := math.Float64frombits(binary.LittleEndian.Uint64(p.Data[0:8]))
			return prefix + fmt.Sprintf("Double(%f)", val)
		}
		return prefix + "Double(error: insufficient data)"
	case TypeString:
		val, err := p.GetString()
		if err != nil {
			return prefix + fmt.Sprintf("String(error: %v)", err)
		}
		return prefix + fmt.Sprintf("String(%q)", val)
	case TypeStruct:
		children, err := p.GetStructChildren()
		if err != nil {
			return prefix + fmt.Sprintf("Struct(error: %v)", err)
		}
		var result strings.Builder
		result.WriteString(prefix + fmt.Sprintf("Struct(%d children) [\n", len(children)))
		for i, child := range children {
			result.WriteString(prefix + fmt.Sprintf("  [%d]: %s\n", i, child.PrettyPrint(indent + 2)[len(prefix)+2:]))
		}
		result.WriteString(prefix + "]")
		return result.String()
	case TypeObject:
		// Object format: [object_type:uint32][object_id:uint32][properties...]
		// Each property: [key:uint32][flags:uint32][POD value]
		if len(p.Data) < 8 {
			return prefix + "Object(error: insufficient data)"
		}
		objectType := binary.LittleEndian.Uint32(p.Data[0:4])
		objectID := binary.LittleEndian.Uint32(p.Data[4:8])
		var result strings.Builder
		result.WriteString(prefix + fmt.Sprintf("Object(type=%d, id=%d) [\n", objectType, objectID))

		// Parse properties
		offset := 8 // Skip object_type and object_id (8 bytes total)
		propIndex := 0
		for offset < len(p.Data) {
			// Each property starts with key (4 bytes) and flags (4 bytes)
			if len(p.Data)-offset < 8 {
				break
			}

			key := binary.LittleEndian.Uint32(p.Data[offset : offset+4])
			flags := binary.LittleEndian.Uint32(p.Data[offset+4 : offset+8])
			offset += 8

			// Now parse the POD value
			if offset >= len(p.Data) {
				result.WriteString(prefix + fmt.Sprintf("  [%d]: key=%d, flags=0x%x (no value)\n", propIndex, key, flags))
				break
			}

			propPod, bytesRead, err := DecodePOD(p.Data[offset:])
			if err != nil {
				result.WriteString(prefix + fmt.Sprintf("  [%d]: key=%d, flags=0x%x (error: %v)\n", propIndex, key, flags, err))
				break
			}

			result.WriteString(prefix + fmt.Sprintf("  [%d]: key=%d, flags=0x%x => %s\n",
				propIndex, key, flags, propPod.PrettyPrint(indent + 2)[len(prefix)+2:]))
			offset += bytesRead
			propIndex++
		}

		result.WriteString(prefix + "]")
		return result.String()
	case TypeArray:
		return prefix + fmt.Sprintf("Array(size=%d)", p.Size)
	case TypeBytes:
		return prefix + fmt.Sprintf("Bytes(size=%d)", p.Size)
	case TypeChoice:
		return prefix + fmt.Sprintf("Choice(size=%d)", p.Size)
	default:
		return prefix + fmt.Sprintf("Unknown(type=%d, size=%d)", p.Type, p.Size)
	}
}