Library .java

com.mojang.blaze3d.audio.Library (class): members: isCurrentDeviceDisconnected, supportsDisconnections, DEFAULT_CHANNEL_COUNT, CountingChannelPool, Pool.

com.mojang.blaze3d.audioclass318 linesclient9.0 KB

API Surface (15)

boolean release(final Channel channel)
void cleanup()
int getMaxCount()
int getUsedCount()
void init(final @Nullable String preferredDevice, final DeviceList currentDevices, final boolean useHrtf)
void cleanup()
Listener getListener()
void releaseChannel(final Channel channel)
String getChannelDebugString()
boolean isCurrentDeviceDisconnected()
DeviceTracker createDeviceTracker()
boolean release(final Channel channel)
void cleanup()
int getMaxCount()
int getUsedCount()

Fields & Constants (12)

LOGGER
NO_DEVICE
NO_DEVICE_NAME
DEFAULT_CHANNEL_COUNT
EMPTY
currentDevice
currentDeviceName
context
supportsDisconnections
staticChannels
streamingChannels
listener

String literals (19)

"(None)"
"Get capabilities"
"Failed to get OpenAL capabilities"
"OpenAL 1.1 not supported"
"Create context"
"Unable to create OpenAL context"
"Initialization"
"AL_EXT_source_distance_model is not supported"
"AL_EXT_LINEAR_DISTANCE is not supported"
"Enable per-source distance models"
"ALC_EXT_disconnect"
"Get attributes size"
"Failed to get OpenAL attributes"
"Get attributes"
"Unknown (0x"
"Failed to open OpenAL device"
"Open device"
"Tried to release unknown channel"
"Using polling for tracking audio device changes"

Code Graph: Dependencies (8)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

Library.java318 lines · Minecraft 26.3 · verbatim
1
package com.mojang.blaze3d.audio;
2
3
import com.google.common.collect.Sets;
4
import com.mojang.logging.LogUtils;
5
import java.nio.IntBuffer;
6
import java.util.HexFormat;
7
import java.util.Locale;
8
import java.util.OptionalLong;
9
import java.util.Set;
10
import net.fabricmc.api.EnvType;
11
import net.fabricmc.api.Environment;
12
import net.minecraft.SharedConstants;
13
import net.minecraft.util.Mth;
14
import org.jspecify.annotations.Nullable;
15
import org.lwjgl.openal.AL;
16
import org.lwjgl.openal.AL10;
17
import org.lwjgl.openal.ALC;
18
import org.lwjgl.openal.ALC10;
19
import org.lwjgl.openal.ALC11;
20
import org.lwjgl.openal.ALCCapabilities;
21
import org.lwjgl.openal.ALCapabilities;
22
import org.lwjgl.system.MemoryStack;
23
import org.slf4j.Logger;
24
25
@Environment(EnvType.CLIENT)
26
public class Library {
27
	private static final Logger LOGGER = LogUtils.getLogger();
28
	public static final int NO_DEVICE = 0;
29
	private static final String NO_DEVICE_NAME = "(None)";
30
	private static final int DEFAULT_CHANNEL_COUNT = 30;
31
	private long currentDevice;
32
	private String currentDeviceName = "(None)";
33
	private long context;
34
	private boolean supportsDisconnections;
35
	private static final Library.ChannelPool EMPTY = new Library.ChannelPool() {
36
		@Override
37
		public @Nullable Channel acquire() {
38
			return null;
39
		}
40
41
		@Override
42
		public boolean release(final Channel channel) {
43
			return false;
44
		}
45
46
		@Override
47
		public void cleanup() {
48
		}
49
50
		@Override
51
		public int getMaxCount() {
52
			return 0;
53
		}
54
55
		@Override
56
		public int getUsedCount() {
57
			return 0;
58
		}
59
	};
60
	private Library.ChannelPool staticChannels = EMPTY;
61
	private Library.ChannelPool streamingChannels = EMPTY;
62
	private final Listener listener = new Listener();
63
64
	public void init(final @Nullable String preferredDevice, final DeviceList currentDevices, final boolean useHrtf) {
65
		this.currentDeviceName = "(None)";
66
		this.currentDevice = openDeviceOrFallback(preferredDevice, currentDevices.defaultDevice());
67
		this.currentDeviceName = queryDeviceName(this.currentDevice);
68
		this.supportsDisconnections = false;
69
		ALCCapabilities alcCapabilities = ALC.createCapabilities(this.currentDevice);
70
		if (OpenAlUtil.checkALCError(this.currentDevice, "Get capabilities")) {
71
			throw new IllegalStateException("Failed to get OpenAL capabilities");
72
		}
73
74
		if (!alcCapabilities.OpenALC11) {
75
			throw new IllegalStateException("OpenAL 1.1 not supported");
76
		}
77
78
		try (MemoryStack stack = MemoryStack.stackPush()) {
79
			IntBuffer attr = this.createAttributes(stack, alcCapabilities.ALC_SOFT_HRTF && useHrtf);
80
			this.context = ALC10.alcCreateContext(this.currentDevice, attr);
81
		}
82
83
		if (OpenAlUtil.checkALCError(this.currentDevice, "Create context")) {
84
			throw new IllegalStateException("Unable to create OpenAL context");
85
		}
86
87
		ALC10.alcMakeContextCurrent(this.context);
88
		int totalChannelCount = this.getChannelCount();
89
		int streamingChannelCount = Mth.clamp((int)Mth.sqrt(totalChannelCount), 2, 8);
90
		int staticChannelCount = Mth.clamp(totalChannelCount - streamingChannelCount, 8, 255);
91
		this.staticChannels = new Library.CountingChannelPool(staticChannelCount);
92
		this.streamingChannels = new Library.CountingChannelPool(streamingChannelCount);
93
		ALCapabilities alCapabilities = AL.createCapabilities(alcCapabilities);
94
		OpenAlUtil.checkALError("Initialization");
95
		if (!alCapabilities.AL_EXT_source_distance_model) {
96
			throw new IllegalStateException("AL_EXT_source_distance_model is not supported");
97
		}
98
99
		AL10.alEnable(512);
100
		if (!alCapabilities.AL_EXT_LINEAR_DISTANCE) {
101
			throw new IllegalStateException("AL_EXT_LINEAR_DISTANCE is not supported");
102
		}
103
104
		OpenAlUtil.checkALError("Enable per-source distance models");
105
		LOGGER.info("OpenAL initialized on device {}", this.currentDeviceName);
106
		this.supportsDisconnections = ALC10.alcIsExtensionPresent(this.currentDevice, "ALC_EXT_disconnect");
107
	}
108
109
	private IntBuffer createAttributes(final MemoryStack stack, final boolean enableHrtf) {
110
		int maxAttributes = 5;
111
		IntBuffer attr = stack.callocInt(11);
112
		int numHrtf = ALC10.alcGetInteger(this.currentDevice, 6548);
113
		if (numHrtf > 0) {
114
			attr.put(6546).put(enableHrtf ? 1 : 0);
115
			attr.put(6550).put(0);
116
		}
117
118
		attr.put(6554).put(1);
119
		return attr.put(0).flip();
120
	}
121
122
	private int getChannelCount() {
123
		try (MemoryStack stack = MemoryStack.stackPush()) {
124
			int size = ALC10.alcGetInteger(this.currentDevice, 4098);
125
			if (OpenAlUtil.checkALCError(this.currentDevice, "Get attributes size")) {
126
				throw new IllegalStateException("Failed to get OpenAL attributes");
127
			}
128
129
			IntBuffer attributes = stack.mallocInt(size);
130
			ALC10.alcGetIntegerv(this.currentDevice, 4099, attributes);
131
			if (OpenAlUtil.checkALCError(this.currentDevice, "Get attributes")) {
132
				throw new IllegalStateException("Failed to get OpenAL attributes");
133
			}
134
135
			int pos = 0;
136
137
			while (pos < size) {
138
				int attribute = attributes.get(pos++);
139
				if (attribute == 0) {
140
					break;
141
				}
142
143
				int attributeValue = attributes.get(pos++);
144
				if (attribute == 4112) {
145
					return attributeValue;
146
				}
147
			}
148
		}
149
150
		return 30;
151
	}
152
153
	public @Nullable String currentDeviceName() {
154
		return this.currentDeviceName;
155
	}
156
157
	private static String queryDeviceName(final long deviceId) {
158
		String name = ALC10.alcGetString(deviceId, 4115);
159
		if (name == null) {
160
			name = ALC10.alcGetString(deviceId, 4101);
161
		}
162
163
		if (name == null) {
164
			name = "Unknown (0x" + HexFormat.of().toHexDigits(deviceId) + ")";
165
		}
166
167
		return name;
168
	}
169
170
	private static long openDeviceOrFallback(final @Nullable String preferredDevice, final @Nullable String systemDefaultDevice) {
171
		OptionalLong device = OptionalLong.empty();
172
		if (preferredDevice != null) {
173
			device = tryOpenDevice(preferredDevice);
174
		}
175
176
		if (device.isEmpty() && systemDefaultDevice != null) {
177
			device = tryOpenDevice(systemDefaultDevice);
178
		}
179
180
		if (device.isEmpty()) {
181
			device = tryOpenDevice(null);
182
		}
183
184
		if (device.isEmpty()) {
185
			throw new IllegalStateException("Failed to open OpenAL device");
186
		} else {
187
			return device.getAsLong();
188
		}
189
	}
190
191
	private static OptionalLong tryOpenDevice(final @Nullable String name) {
192
		long device = ALC10.alcOpenDevice(name);
193
		return device != 0L && !OpenAlUtil.checkALCError(device, "Open device") ? OptionalLong.of(device) : OptionalLong.empty();
194
	}
195
196
	public void cleanup() {
197
		this.staticChannels.cleanup();
198
		this.streamingChannels.cleanup();
199
		ALC10.alcDestroyContext(this.context);
200
		if (this.currentDevice != 0L) {
201
			ALC10.alcCloseDevice(this.currentDevice);
202
		}
203
	}
204
205
	public Listener getListener() {
206
		return this.listener;
207
	}
208
209
	public @Nullable Channel acquireChannel(final Library.Pool pool) {
210
		return (pool == Library.Pool.STREAMING ? this.streamingChannels : this.staticChannels).acquire();
211
	}
212
213
	public void releaseChannel(final Channel channel) {
214
		if (!this.staticChannels.release(channel) && !this.streamingChannels.release(channel)) {
215
			throw new IllegalStateException("Tried to release unknown channel");
216
		}
217
	}
218
219
	public String getChannelDebugString() {
220
		return String.format(
221
			Locale.ROOT,
222
			"Sounds: %d/%d + %d/%d",
223
			this.staticChannels.getUsedCount(),
224
			this.staticChannels.getMaxCount(),
225
			this.streamingChannels.getUsedCount(),
226
			this.streamingChannels.getMaxCount()
227
		);
228
	}
229
230
	public boolean isCurrentDeviceDisconnected() {
231
		return this.supportsDisconnections && ALC11.alcGetInteger(this.currentDevice, 787) == 0;
232
	}
233
234
	public static DeviceTracker createDeviceTracker() {
235
		DeviceList deviceList = DeviceList.query();
236
		if (CallbackDeviceTracker.isSupported()) {
237
			LOGGER.debug("Using SOFT_system_events callback for tracking audio device changes");
238
			return CallbackDeviceTracker.createAndInstall(deviceList);
239
		} else {
240
			LOGGER.debug("Using polling for tracking audio device changes");
241
			return new PollingDeviceTracker(deviceList);
242
		}
243
	}
244
245
	@Environment(EnvType.CLIENT)
246
	private interface ChannelPool {
247
		@Nullable Channel acquire();
248
249
		boolean release(Channel channel);
250
251
		void cleanup();
252
253
		int getMaxCount();
254
255
		int getUsedCount();
256
	}
257
258
	@Environment(EnvType.CLIENT)
259
	private static class CountingChannelPool implements Library.ChannelPool {
260
		private final int limit;
261
		private final Set<Channel> activeChannels = Sets.newIdentityHashSet();
262
263
		public CountingChannelPool(final int limit) {
264
			this.limit = limit;
265
		}
266
267
		@Override
268
		public @Nullable Channel acquire() {
269
			if (this.activeChannels.size() >= this.limit) {
270
				if (SharedConstants.IS_RUNNING_IN_IDE) {
271
					Library.LOGGER.warn("Maximum sound pool size {} reached", this.limit);
272
				}
273
274
				return null;
275
			} else {
276
				Channel channel = Channel.create();
277
				if (channel != null) {
278
					this.activeChannels.add(channel);
279
				}
280
281
				return channel;
282
			}
283
		}
284
285
		@Override
286
		public boolean release(final Channel channel) {
287
			if (!this.activeChannels.remove(channel)) {
288
				return false;
289
			}
290
291
			channel.destroy();
292
			return true;
293
		}
294
295
		@Override
296
		public void cleanup() {
297
			this.activeChannels.forEach(Channel::destroy);
298
			this.activeChannels.clear();
299
		}
300
301
		@Override
302
		public int getMaxCount() {
303
			return this.limit;
304
		}
305
306
		@Override
307
		public int getUsedCount() {
308
			return this.activeChannels.size();
309
		}
310
	}
311
312
	@Environment(EnvType.CLIENT)
313
	public enum Pool {
314
		STATIC,
315
		STREAMING;
316
	}
317
}
318

Decompiled Minecraft 26.3 source of Library (com/mojang/blaze3d/audio/Library.java) with Mojang official mappings, stored verbatim on the site.