File size: 11,028 Bytes
d46f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package com.mojang.blaze3d.audio;

import com.google.common.collect.Sets;
import com.mojang.logging.LogUtils;
import java.nio.IntBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.OptionalLong;
import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.SharedConstants;
import net.minecraft.util.Mth;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10;
import org.lwjgl.openal.ALC;
import org.lwjgl.openal.ALC10;
import org.lwjgl.openal.ALC11;
import org.lwjgl.openal.ALCCapabilities;
import org.lwjgl.openal.ALCapabilities;
import org.lwjgl.openal.ALUtil;
import org.lwjgl.openal.SOFTHRTF;
import org.lwjgl.system.MemoryStack;
import org.slf4j.Logger;

@OnlyIn(Dist.CLIENT)
public class Library {
    static final Logger LOGGER = LogUtils.getLogger();
    private static final int NO_DEVICE = 0;
    private static final int DEFAULT_CHANNEL_COUNT = 30;
    private long currentDevice;
    private long context;
    private boolean supportsDisconnections;
    @Nullable
    private String defaultDeviceName;
    private static final Library.ChannelPool EMPTY = new Library.ChannelPool() {
        @Nullable
        @Override
        public Channel acquire() {
            return null;
        }

        @Override
        public boolean release(Channel p_83708_) {
            return false;
        }

        @Override
        public void cleanup() {
        }

        @Override
        public int getMaxCount() {
            return 0;
        }

        @Override
        public int getUsedCount() {
            return 0;
        }
    };
    private Library.ChannelPool staticChannels = EMPTY;
    private Library.ChannelPool streamingChannels = EMPTY;
    private final Listener listener = new Listener();

    public Library() {
        this.defaultDeviceName = getDefaultDeviceName();
    }

    public void init(@Nullable String p_231085_, boolean p_231086_) {
        this.currentDevice = openDeviceOrFallback(p_231085_);
        this.supportsDisconnections = false;
        ALCCapabilities alccapabilities = ALC.createCapabilities(this.currentDevice);
        if (OpenAlUtil.checkALCError(this.currentDevice, "Get capabilities")) {
            throw new IllegalStateException("Failed to get OpenAL capabilities");
        } else if (!alccapabilities.OpenALC11) {
            throw new IllegalStateException("OpenAL 1.1 not supported");
        } else {
            this.setHrtf(alccapabilities.ALC_SOFT_HRTF && p_231086_);

            try (MemoryStack memorystack = MemoryStack.stackPush()) {
                IntBuffer intbuffer = memorystack.callocInt(3).put(6554).put(1).put(0).flip();
                this.context = ALC10.alcCreateContext(this.currentDevice, intbuffer);
            }

            if (OpenAlUtil.checkALCError(this.currentDevice, "Create context")) {
                throw new IllegalStateException("Unable to create OpenAL context");
            } else {
                ALC10.alcMakeContextCurrent(this.context);
                int j = this.getChannelCount();
                int k = Mth.clamp((int)Mth.sqrt((float)j), 2, 8);
                int i = Mth.clamp(j - k, 8, 255);
                this.staticChannels = new Library.CountingChannelPool(i);
                this.streamingChannels = new Library.CountingChannelPool(k);
                ALCapabilities alcapabilities = AL.createCapabilities(alccapabilities);
                OpenAlUtil.checkALError("Initialization");
                if (!alcapabilities.AL_EXT_source_distance_model) {
                    throw new IllegalStateException("AL_EXT_source_distance_model is not supported");
                } else {
                    AL10.alEnable(512);
                    if (!alcapabilities.AL_EXT_LINEAR_DISTANCE) {
                        throw new IllegalStateException("AL_EXT_LINEAR_DISTANCE is not supported");
                    } else {
                        OpenAlUtil.checkALError("Enable per-source distance models");
                        LOGGER.info("OpenAL initialized on device {}", this.getCurrentDeviceName());
                        this.supportsDisconnections = ALC10.alcIsExtensionPresent(this.currentDevice, "ALC_EXT_disconnect");
                    }
                }
            }
        }
    }

    private void setHrtf(boolean p_242278_) {
        int i = ALC10.alcGetInteger(this.currentDevice, 6548);
        if (i > 0) {
            try (MemoryStack memorystack = MemoryStack.stackPush()) {
                IntBuffer intbuffer = memorystack.callocInt(10).put(6546).put(p_242278_ ? 1 : 0).put(6550).put(0).put(0).flip();
                if (!SOFTHRTF.alcResetDeviceSOFT(this.currentDevice, intbuffer)) {
                    LOGGER.warn("Failed to reset device: {}", ALC10.alcGetString(this.currentDevice, ALC10.alcGetError(this.currentDevice)));
                }
            }
        }
    }

    private int getChannelCount() {
        try (MemoryStack memorystack = MemoryStack.stackPush()) {
            int i = ALC10.alcGetInteger(this.currentDevice, 4098);
            if (OpenAlUtil.checkALCError(this.currentDevice, "Get attributes size")) {
                throw new IllegalStateException("Failed to get OpenAL attributes");
            }

            IntBuffer intbuffer = memorystack.mallocInt(i);
            ALC10.alcGetIntegerv(this.currentDevice, 4099, intbuffer);
            if (OpenAlUtil.checkALCError(this.currentDevice, "Get attributes")) {
                throw new IllegalStateException("Failed to get OpenAL attributes");
            }

            int j = 0;

            while (j < i) {
                int k = intbuffer.get(j++);
                if (k == 0) {
                    break;
                }

                int l = intbuffer.get(j++);
                if (k == 4112) {
                    return l;
                }
            }
        }

        return 30;
    }

    @Nullable
    public static String getDefaultDeviceName() {
        if (!ALC10.alcIsExtensionPresent(0L, "ALC_ENUMERATE_ALL_EXT")) {
            return null;
        } else {
            ALUtil.getStringList(0L, 4115);
            return ALC10.alcGetString(0L, 4114);
        }
    }

    public String getCurrentDeviceName() {
        String s = ALC10.alcGetString(this.currentDevice, 4115);
        if (s == null) {
            s = ALC10.alcGetString(this.currentDevice, 4101);
        }

        if (s == null) {
            s = "Unknown";
        }

        return s;
    }

    public synchronized boolean hasDefaultDeviceChanged() {
        String s = getDefaultDeviceName();
        if (Objects.equals(this.defaultDeviceName, s)) {
            return false;
        } else {
            this.defaultDeviceName = s;
            return true;
        }
    }

    private static long openDeviceOrFallback(@Nullable String p_193473_) {
        OptionalLong optionallong = OptionalLong.empty();
        if (p_193473_ != null) {
            optionallong = tryOpenDevice(p_193473_);
        }

        if (optionallong.isEmpty()) {
            optionallong = tryOpenDevice(getDefaultDeviceName());
        }

        if (optionallong.isEmpty()) {
            optionallong = tryOpenDevice(null);
        }

        if (optionallong.isEmpty()) {
            throw new IllegalStateException("Failed to open OpenAL device");
        } else {
            return optionallong.getAsLong();
        }
    }

    private static OptionalLong tryOpenDevice(@Nullable String p_193476_) {
        long i = ALC10.alcOpenDevice(p_193476_);
        return i != 0L && !OpenAlUtil.checkALCError(i, "Open device") ? OptionalLong.of(i) : OptionalLong.empty();
    }

    public void cleanup() {
        this.staticChannels.cleanup();
        this.streamingChannels.cleanup();
        ALC10.alcDestroyContext(this.context);
        if (this.currentDevice != 0L) {
            ALC10.alcCloseDevice(this.currentDevice);
        }
    }

    public Listener getListener() {
        return this.listener;
    }

    @Nullable
    public Channel acquireChannel(Library.Pool p_83698_) {
        return (p_83698_ == Library.Pool.STREAMING ? this.streamingChannels : this.staticChannels).acquire();
    }

    public void releaseChannel(Channel p_83696_) {
        if (!this.staticChannels.release(p_83696_) && !this.streamingChannels.release(p_83696_)) {
            throw new IllegalStateException("Tried to release unknown channel");
        }
    }

    public String getDebugString() {
        return String.format(
            Locale.ROOT, "Sounds: %d/%d + %d/%d", this.staticChannels.getUsedCount(), this.staticChannels.getMaxCount(), this.streamingChannels.getUsedCount(), this.streamingChannels.getMaxCount()
        );
    }

    public List<String> getAvailableSoundDevices() {
        List<String> list = ALUtil.getStringList(0L, 4115);
        return list == null ? Collections.emptyList() : list;
    }

    public boolean isCurrentDeviceDisconnected() {
        return this.supportsDisconnections && ALC11.alcGetInteger(this.currentDevice, 787) == 0;
    }

    @OnlyIn(Dist.CLIENT)
    interface ChannelPool {
        @Nullable
        Channel acquire();

        boolean release(Channel p_83712_);

        void cleanup();

        int getMaxCount();

        int getUsedCount();
    }

    @OnlyIn(Dist.CLIENT)
    static class CountingChannelPool implements Library.ChannelPool {
        private final int limit;
        private final Set<Channel> activeChannels = Sets.newIdentityHashSet();

        public CountingChannelPool(int p_83716_) {
            this.limit = p_83716_;
        }

        @Nullable
        @Override
        public Channel acquire() {
            if (this.activeChannels.size() >= this.limit) {
                if (SharedConstants.IS_RUNNING_IN_IDE) {
                    Library.LOGGER.warn("Maximum sound pool size {} reached", this.limit);
                }

                return null;
            } else {
                Channel channel = Channel.create();
                if (channel != null) {
                    this.activeChannels.add(channel);
                }

                return channel;
            }
        }

        @Override
        public boolean release(Channel p_83719_) {
            if (!this.activeChannels.remove(p_83719_)) {
                return false;
            } else {
                p_83719_.destroy();
                return true;
            }
        }

        @Override
        public void cleanup() {
            this.activeChannels.forEach(Channel::destroy);
            this.activeChannels.clear();
        }

        @Override
        public int getMaxCount() {
            return this.limit;
        }

        @Override
        public int getUsedCount() {
            return this.activeChannels.size();
        }
    }

    @OnlyIn(Dist.CLIENT)
    public static enum Pool {
        STATIC,
        STREAMING;
    }
}