libsood

Zig library for Roon Core discovery message, with C-compatible API and WebAssembly.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
  84. 84
  85. 85
  86. 86
  87. 87
  88. 88
  89. 89
  90. 90
  91. 91
  92. 92
  93. 93
  94. 94
  95. 95
  96. 96
  97. 97
  98. 98
  99. 99
  100. 100
  101. 101
  102. 102
  103. 103
  104. 104
  105. 105
  106. 106
  107. 107
  108. 108
  109. 109
  110. 110
  111. 111
  112. 112
  113. 113
  114. 114
  115. 115
  116. 116
  117. 117
  118. 118
  119. 119
  120. 120
  121. 121
  122. 122
  123. 123
  124. 124
  125. 125
  126. 126
  127. 127
  128. 128
  129. 129
  130. 130
  131. 131
  132. 132
  133. 133
  134. 134
  135. 135
  136. 136
  137. 137
  138. 138
  139. 139
  140. 140
  141. 141
  142. 142
  143. 143
  144. 144
  145. 145
  146. 146
  147. 147
  148. 148
  149. 149
  150. 150
  151. 151
  152. 152
  153. 153
  154. 154
  155. 155
  156. 156
  157. 157
  158. 158
  159. 159
  160. 160
  161. 161
  162. 162
  163. 163
  164. 164
  165. 165
  166. 166
  167. 167
  168. 168
  169. 169
  170. 170
  171. 171
  172. 172
  173. 173
  174. 174
  175. 175
  176. 176
  177. 177
  178. 178
  179. 179
  180. 180
  181. 181
  182. 182
  183. 183
  184. 184
  185. 185
  186. 186
  187. 187
  188. 188
  189. 189
  190. 190
  191. 191
  192. 192
  193. 193
  194. 194
  195. 195
  196. 196
  197. 197
  198. 198
// Copyright 2025 Shota FUJI
//
// Licensed under the Zero-Clause BSD License or the Apache License, Version 2.0, at your option.
// You may not use, copy, modify, or distribute this file except according to those terms. You can
// find a copy of the Zero-Clause BSD License at LICENSES/0BSD.txt, and a copy of the Apache License,
// Version 2.0 at LICENSES/Apache-2.0.txt. You may also obtain a copy of the Zero-Clause BSD License
// at <https://opensource.org/license/0bsd> and a copy of the Apache License, Version 2.0 at
// <https://www.apache.org/licenses/LICENSE-2.0>
//
// SPDX-License-Identifier: 0BSD OR Apache-2.0
//
// ===
//
// This example searches Roon Core on computer's subnet then print found one's information on
// stdout. (Bun does not have simply write to stderr. console.error forces text color to be red)
//
// You can run this example by running "bun ./examples/basic.js" from repository root.
// You need Bun (JavaScript runtime) and built ".wasm" file generated by "zig build wasm".
//
// While this works, you should use the official roon-node-api. This is only for demonstration
// purpose.
//
// Unlike basic.zig and basic.c, this example does not retry.

import dgram from "node:dgram";

const wasm = Bun.file(new URL("../zig-out/bin/sood.wasm", import.meta.url));

const { instance } = await WebAssembly.instantiate(await wasm.arrayBuffer());

// Using short alias for brevity.
const x = instance.exports;

const sock = dgram.createSocket({ type: "udp4" });

sock.on("error", err => {
	console.error(err);
});

// As there is no standard for "string" type, every WASM module have to come up with
// their own definition. This module represents strings in "address to UTF8 string
// and its byte size." Every string getters consists of two functions suffixed with
// "_ptr" and "_len". For example, getters for getting "bar" field from "foo" struct
// will be "get_foo_bar_ptr(foo_ptr)" and "get_foo_bar_len(foo_ptr)".
//
//  MEMORY: |   |'b'|'a'|'z'|   |   |
//              ^           ^
//      get_foo_bar_ptr   (end)
//  get_foo_bar_len = (end) - get_foo_bar_ptr
//
// After you know the address and length on the WASM linear memory, converts the byte
// array to UTF-8 string with your platform API/programming language. In this JavaScript
// example, we're using the standard "TextDecoder" web API for parsing the byte array
// (Uint8Array) to JavaScript string (UTF-16).
const utf8Decoder = new TextDecoder();

sock.on("message", (msg, { address }) => {
	// This "dgram" module is of Node.js, hence type of "msg" is non-standard Buffer type.
	// For compability, we're converting it to the standard Uint8Array.
	const messageBuffer = new Uint8Array(msg);

	let responsePtr = null;
	let bytesPtr = null;

	try {
		// In order to pass non-primitive data between WASM host and guest, we need to allocate
		// space at WASM linear memory then fill-in the data to the allocated space.
		// Our "sood.wasm" exports[0] internal memory via "exports.memory".
		// This line calls our allocator and returns the address of the space.
		// [0] ... Actually LLVM automatically exports the memory object.
		bytesPtr = x.allocate_bytes(messageBuffer.length);

		// Once allocated, copy the data byte-to-byte to the WASM linear memory.
		// This procedure differs by your platform/programming language.
		const bytesBuffer = new Uint8Array(x.memory.buffer, bytesPtr, messageBuffer.length);
		bytesBuffer.set(messageBuffer);

		// Allocate a struct to hold parsed result. Since "sood.wasm" knows how many bytes required
		// for the struct, we don't have to specify a size.
		responsePtr = x.allocate_discovery_response();

		// Parse "bytesBuffer", which is copy of "messageBuffer" ("msg"), then fill-in data
		// onto the previously allocated discovery response struct ("allocate_discovery_response").
		// If "result" is non-zero (= error), the discovery response struct remains empty.
		const result = x.parse_discovery_response_into(
			responsePtr,
			bytesPtr,
			messageBuffer.length,
		);

		// "sood.wasm" is not designed to use for reusing allocated space:
		// don't use pointer returned by allocator functions more than once.
		//
		// [DON'T]
		//   const ptr = allocate_discovery_response();
		//   x.parse_discovery_response_into(ptr, bytes1Ptr, bytes1Len);
		//   x.parse_discovery_response_into(ptr, bytes2Ptr, bytes2Len);
		//
		// [DO]
		//   const ptr1 = allocate_discovery_response();
		//   x.parse_discovery_response_into(ptr1, bytes1Ptr, bytes1Len);
		//   const ptr2 = allocate_discovery_response();
		//   x.parse_discovery_response_into(ptr2, bytes2Ptr, bytes2Len);

		// See definition for "WasmResultCode" in "wasm.zig" for each result codes.
		// Like most of the program, 0 means success.
		if (result !== 0) {
			console.log("Non 0 result received:");

			// If you don't have dedicated handlings for individual errors, use
			// "result_code_string_ptr/len" function to get the human readable name for
			// the error code.
			console.log(utf8Decoder.decode(
				new Uint8Array(
					x.memory.buffer,
					x.result_code_string_ptr(result),
					x.result_code_string_len(result),
				),
			));
			return;
		}

		// "get_discovery_response_*" functions retrieve corresponding fields.
		const name = utf8Decoder.decode(
			new Uint8Array(
				x.memory.buffer,
				x.get_discovery_response_name_ptr(responsePtr),
				x.get_discovery_response_name_len(responsePtr),
			),
		);

		const displayVersion = utf8Decoder.decode(
			new Uint8Array(
				x.memory.buffer,
				x.get_discovery_response_display_version_ptr(responsePtr),
				x.get_discovery_response_display_version_len(responsePtr),
			),
		);

		const uniqueId = utf8Decoder.decode(
			new Uint8Array(
				x.memory.buffer,
				x.get_discovery_response_unique_id_ptr(responsePtr),
				x.get_discovery_response_unique_id_len(responsePtr),
			),
		);

		console.log(`Name: \t\t${name}`);
		console.log(`Version: \t${displayVersion}`);
		console.log(`Unique ID: \t${uniqueId}`);

		// SOOD message does not include IP address of the Roon Server. You have to use
		// UDP message's sender IP address.
		console.log(`Address: \t${address}`);

		// HTTP port is unsigned 16-bit integer, therefore simply use the returned value.
		console.log(`HTTP Port: \t${x.get_discovery_response_http_port(responsePtr)}`);

		sock.close();
	} catch (err) {
		console.error(err);
	} finally {
		// Each strings in a parsed data refers to the source bytes, in this example, "bytesBuffer".
		// Because of this, use should free parsed data (discovery response, message, iterator) first
		// then the source bytes.
		if (typeof responsePtr === "number") {
			x.free_discovery_response(responsePtr);
		}

		// Size of bytes are not known in compile time. You have to pass the size.
		if (typeof bytesPtr === "number") {
			x.free_bytes(bytesPtr, messageBuffer.length);
		}
	}
});

const prebuilt = new Uint8Array(
	x.memory.buffer,
	x.prebuilt_discovery_query_ptr(),
	x.prebuilt_discovery_query_len(),
);

// Node.js dgram module takes IP address in string form.
// If you're using API that takes network byte order 32-bit IP address, just reads
// from the address as Uint32 Big Endian.
//
//   const view = new DataView(x.memory.buffer);
//   const multicastAddr = view.getUint32(x.get_discovery_multicast_ipv4_address(), false);
const multicastIpAddr = Array.from(
	new Uint8Array(x.memory.buffer, x.get_discovery_multicast_ipv4_address(), 4),
).map(n => n.toString(10)).join(".");

sock.bind({ port: 0 }, () => {
	// This is what the official roon-node-api. I don't know how important this is.
	sock.setMulticastTTL(1);

	sock.send(prebuilt, 0, prebuilt.length, x.get_discovery_server_udp_port(), multicastIpAddr);
});