commit fba6ffacd43c0a528bf2b3eb6d19435e83fe6811 Author: rardog Date: Thu Sep 24 13:00:20 2026 +0300 Initial commit: recovered Forge 1.16.5 project, improved GUI, added WAV/MP3 support diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ba2cf0d --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.gradle/ +build/ +run/ +out/ +.idea/ +*.ipr +*.iws +*.iml +.project +.classpath +.settings/ +*.log +bin/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..f5663e2 --- /dev/null +++ b/build.gradle @@ -0,0 +1,72 @@ +buildscript { + repositories { + maven { url = 'https://maven.minecraftforge.net' } + mavenCentral() + } + dependencies { + classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true + } +} +apply plugin: 'net.minecraftforge.gradle' +apply plugin: 'eclipse' +apply plugin: 'maven-publish' + +version = '1.0.4' +group = 'com.example.soundmod' +archivesBaseName = 'soundmod' + +java.toolchain.languageVersion = JavaLanguageVersion.of(8) + +minecraft { + mappings channel: 'official', version: '1.16.5' + + runs { + client { + workingDirectory project.file('run') + property 'forge.logging.markers', 'REGISTRIES' + property 'forge.logging.console.level', 'debug' + mods { + soundmod { + source sourceSets.main + } + } + } + server { + workingDirectory project.file('run') + property 'forge.logging.markers', 'REGISTRIES' + property 'forge.logging.console.level', 'debug' + mods { + soundmod { + source sourceSets.main + } + } + } + } +} + +configurations { + shade + implementation.extendsFrom shade +} + +dependencies { + minecraft 'net.minecraftforge:forge:1.16.5-36.2.39' + shade 'javazoom:jlayer:1.0.1' +} + +jar { + from { + configurations.shade.collect { it.isDirectory() ? it : zipTree(it) } + } + manifest { + attributes([ + "Specification-Title": "soundmod", + "Specification-Vendor": "Codex", + "Specification-Version": "1", + "Implementation-Title": project.name, + "Implementation-Version": "${version}", + "Implementation-Vendor": "Codex", + "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ") + ]) + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..29b2ac4 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx3G +org.gradle.daemon=false diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..eddabd2 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..22c6b82 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.4-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..379a658 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob//platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..8508ef6 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/soundmod-1.0.4.jar b/soundmod-1.0.4.jar new file mode 100644 index 0000000..d22390f Binary files /dev/null and b/soundmod-1.0.4.jar differ diff --git a/src/main/java/com/example/soundmod/SoundMod.java b/src/main/java/com/example/soundmod/SoundMod.java new file mode 100644 index 0000000..b98ead4 --- /dev/null +++ b/src/main/java/com/example/soundmod/SoundMod.java @@ -0,0 +1,84 @@ +/* + * Decompiled with CFR 0.152. + * + * Could not load the following classes: + * com.mojang.brigadier.CommandDispatcher + * net.minecraft.command.CommandSource + * net.minecraftforge.api.distmarker.Dist + * net.minecraftforge.common.MinecraftForge + * net.minecraftforge.event.RegisterCommandsEvent + * net.minecraftforge.eventbus.api.IEventBus + * net.minecraftforge.fml.DistExecutor + * net.minecraftforge.fml.ModLoadingContext + * net.minecraftforge.fml.common.Mod + * net.minecraftforge.fml.config.ModConfig$Type + * net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent + * net.minecraftforge.fml.event.server.FMLServerStartedEvent + * net.minecraftforge.fml.event.server.FMLServerStoppingEvent + * net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext + * org.apache.logging.log4j.LogManager + * org.apache.logging.log4j.Logger + */ +package com.example.soundmod; + +import com.example.soundmod.client.ClientHooks; +import com.example.soundmod.command.ModCommands; +import com.example.soundmod.core.ModConfig; +import com.example.soundmod.net.NetworkHandler; +import com.example.soundmod.registry.ModBlocks; +import com.example.soundmod.registry.ModContainers; +import com.example.soundmod.registry.ModItems; +import com.example.soundmod.registry.ModTileEntities; +import com.example.soundmod.sounddata.server.ServerSoundRepository; +import com.mojang.brigadier.CommandDispatcher; +import net.minecraft.command.CommandSource; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.common.MinecraftForge; +import net.minecraftforge.event.RegisterCommandsEvent; +import net.minecraftforge.eventbus.api.IEventBus; +import net.minecraftforge.fml.DistExecutor; +import net.minecraftforge.fml.ModLoadingContext; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; +import net.minecraftforge.fml.event.server.FMLServerStartedEvent; +import net.minecraftforge.fml.event.server.FMLServerStoppingEvent; +import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +@Mod(value="soundmod") +public class SoundMod { + public static final String MODID = "soundmod"; + public static final Logger LOGGER = LogManager.getLogger(); + + public SoundMod() { + IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus(); + ModBlocks.BLOCKS.register(modBus); + ModItems.ITEMS.register(modBus); + ModTileEntities.TILES.register(modBus); + ModContainers.CONTAINERS.register(modBus); + modBus.addListener(this::commonSetup); + ModLoadingContext.get().registerConfig(net.minecraftforge.fml.config.ModConfig.Type.COMMON, ModConfig.SPEC); + MinecraftForge.EVENT_BUS.addListener(this::onServerStarted); + MinecraftForge.EVENT_BUS.addListener(this::onServerStopping); + MinecraftForge.EVENT_BUS.addListener(this::onRegisterCommands); + DistExecutor.safeRunWhenOn((Dist)Dist.CLIENT, () -> ClientHooks::register); + } + + private void commonSetup(FMLCommonSetupEvent event) { + event.enqueueWork(NetworkHandler::register); + } + + private void onServerStarted(FMLServerStartedEvent event) { + ServerSoundRepository.get().bindServer(event.getServer()); + } + + private void onServerStopping(FMLServerStoppingEvent event) { + ServerSoundRepository.get().unbindServer(); + } + + private void onRegisterCommands(RegisterCommandsEvent event) { + ModCommands.register((CommandDispatcher)event.getDispatcher()); + } +} + diff --git a/src/main/java/com/example/soundmod/client/ClientHooks.java b/src/main/java/com/example/soundmod/client/ClientHooks.java new file mode 100644 index 0000000..cbbcb3a --- /dev/null +++ b/src/main/java/com/example/soundmod/client/ClientHooks.java @@ -0,0 +1,66 @@ +/* + * Decompiled with CFR 0.152. + * + * Could not load the following classes: + * net.minecraft.client.gui.ScreenManager + * net.minecraft.inventory.container.ContainerType + * net.minecraftforge.api.distmarker.Dist + * net.minecraftforge.client.event.RenderGameOverlayEvent$Text + * net.minecraftforge.client.event.RenderWorldLastEvent + * net.minecraftforge.event.TickEvent$ClientTickEvent + * net.minecraftforge.event.TickEvent$Phase + * net.minecraftforge.eventbus.api.SubscribeEvent + * net.minecraftforge.fml.common.Mod$EventBusSubscriber + * net.minecraftforge.fml.common.Mod$EventBusSubscriber$Bus + * net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent + */ +package com.example.soundmod.client; + +import com.example.soundmod.client.audio.AudioPlaybackService; +import com.example.soundmod.client.debug.DebugOverlayRenderer; +import com.example.soundmod.client.screen.SoundPlayerScreen; +import com.example.soundmod.registry.ModContainers; +import net.minecraft.client.gui.ScreenManager; +import net.minecraft.inventory.container.ContainerType; +import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.event.RenderGameOverlayEvent; +import net.minecraftforge.client.event.RenderWorldLastEvent; +import net.minecraftforge.event.TickEvent; +import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; + +@Mod.EventBusSubscriber(modid="soundmod", value={Dist.CLIENT}, bus=Mod.EventBusSubscriber.Bus.MOD) +public final class ClientHooks { + private ClientHooks() { + } + + public static void register() { + } + + @SubscribeEvent + public static void onClientSetup(FMLClientSetupEvent event) { + ScreenManager.register((ContainerType)((ContainerType)ModContainers.SOUND_PLAYER.get()), SoundPlayerScreen::new); + } + + @Mod.EventBusSubscriber(modid="soundmod", value={Dist.CLIENT}) + public static class ClientForgeEvents { + @SubscribeEvent + public static void onClientTick(TickEvent.ClientTickEvent event) { + if (event.phase == TickEvent.Phase.END) { + AudioPlaybackService.get().tick(); + } + } + + @SubscribeEvent + public static void onRenderWorld(RenderWorldLastEvent event) { + DebugOverlayRenderer.render(event.getMatrixStack(), event.getPartialTicks()); + } + + @SubscribeEvent + public static void onRenderHud(RenderGameOverlayEvent.Text event) { + DebugOverlayRenderer.renderHud(event.getMatrixStack()); + } + } +} + diff --git a/src/main/java/com/example/soundmod/client/audio/AudioPlaybackService.java b/src/main/java/com/example/soundmod/client/audio/AudioPlaybackService.java new file mode 100644 index 0000000..6cb7262 --- /dev/null +++ b/src/main/java/com/example/soundmod/client/audio/AudioPlaybackService.java @@ -0,0 +1,652 @@ +/* + * Decompiled with CFR 0.152. + * + * Could not load the following classes: + * net.minecraft.client.Minecraft + * net.minecraft.client.entity.player.ClientPlayerEntity + * net.minecraft.entity.Entity + * net.minecraft.util.math.BlockPos + * net.minecraft.util.math.BlockRayTraceResult + * net.minecraft.util.math.RayTraceContext + * net.minecraft.util.math.RayTraceContext$BlockMode + * net.minecraft.util.math.RayTraceContext$FluidMode + * net.minecraft.util.math.RayTraceResult$Type + * net.minecraft.util.math.vector.Vector3d + * org.lwjgl.BufferUtils + * org.lwjgl.openal.AL10 + * org.lwjgl.stb.STBVorbis + * org.lwjgl.stb.STBVorbisInfo + * org.lwjgl.system.MemoryStack + * org.lwjgl.system.MemoryUtil + */ +package com.example.soundmod.client.audio; + +import com.example.soundmod.SoundMod; +import com.example.soundmod.common.AttenuationMode; +import com.example.soundmod.common.SoundSettings; +import com.example.soundmod.core.ModConfig; +import com.example.soundmod.core.SoundDebug; +import com.example.soundmod.net.NetworkHandler; +import com.example.soundmod.net.packet.C2SRequestSoundPacket; +import com.example.soundmod.sounddata.client.ClientSoundCache; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.IOException; +import java.nio.Buffer; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.IntBuffer; +import java.nio.ShortBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.UnsupportedAudioFileException; +import javazoom.jl.decoder.Bitstream; +import javazoom.jl.decoder.Decoder; +import javazoom.jl.decoder.Header; +import javazoom.jl.decoder.JavaLayerException; +import javazoom.jl.decoder.SampleBuffer; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.player.ClientPlayerEntity; +import net.minecraft.entity.Entity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.BlockRayTraceResult; +import net.minecraft.util.math.RayTraceContext; +import net.minecraft.util.math.RayTraceResult; +import net.minecraft.util.math.vector.Vector3d; +import org.lwjgl.BufferUtils; +import org.lwjgl.openal.AL10; +import org.lwjgl.stb.STBVorbis; +import org.lwjgl.stb.STBVorbisInfo; +import org.lwjgl.system.MemoryStack; +import org.lwjgl.system.MemoryUtil; + +public final class AudioPlaybackService { + private static final int REPLAY_DEBOUNCE_TICKS = 6; + private static final AudioPlaybackService INSTANCE = new AudioPlaybackService(); + private final Map active = new HashMap(); + + public static AudioPlaybackService get() { + return INSTANCE; + } + + private AudioPlaybackService() { + } + + public synchronized void play(String sourceId, BlockPos pos, SoundSettings settings) { + long gameTime; + SoundSettings safe = SoundSettings.sanitizedCopy(settings); + if (safe.volume != settings.volume || safe.pitch != settings.pitch || safe.radius != settings.radius) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "sanitized params vol={}=>{} pitch={}=>{} radius={}=>{}", Float.valueOf(settings.volume), Float.valueOf(safe.volume), Float.valueOf(settings.pitch), Float.valueOf(safe.pitch), Float.valueOf(settings.radius), Float.valueOf(safe.radius)); + } + SoundDebug.log(SoundDebug.Level.L1, "PLAYBACK", sourceId, "play request soundId={} pos={} {} {} vol={} pitch={} loop={} radius={}", safe.soundId, pos.getX(), pos.getY(), pos.getZ(), Float.valueOf(safe.volume), Float.valueOf(safe.pitch), safe.loop, Float.valueOf(safe.radius)); + Path file = ClientSoundCache.get().resolveBySoundId(safe.soundId); + if (file == null) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "cache miss soundId={} -> request from server", safe.soundId); + NetworkHandler.CHANNEL.sendToServer((Object)new C2SRequestSoundPacket(safe.soundId)); + return; + } + SoundDebug.log(SoundDebug.Level.L2, "PLAYBACK", sourceId, "resolved cache file={}", file); + PlayingSource current = this.active.get(sourceId); + long l = gameTime = Minecraft.getInstance().level != null ? Minecraft.getInstance().level.getGameTime() : Long.MIN_VALUE; + if (!safe.crossfade && current != null && current.settings.soundId.equals(safe.soundId) && gameTime != Long.MIN_VALUE && gameTime - current.startedAtTick <= 6L) { + SoundDebug.log(SoundDebug.Level.L3, "PLAYBACK", sourceId, "replay suppressed soundId={} dt={}", safe.soundId, gameTime - current.startedAtTick); + return; + } + if (safe.crossfade && current != null) { + current.fadeOutTicks = Math.max(1, safe.fadeOutTicks); + SoundDebug.log(SoundDebug.Level.L2, "PLAYBACK", sourceId, "crossfade enabled fadeOutTicks={}", safe.fadeOutTicks); + } else { + this.stop(sourceId); + } + try { + this.enforceActiveLimit(safe.priority); + DecodedPcm pcm = this.decodeAudio(file); + int buffer = AL10.alGenBuffers(); + int alErr1 = AL10.alGetError(); + if (alErr1 != 0) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "alGenBuffers error={}", alErr1); + } + int format = pcm.channels == 1 ? 4353 : 4355; + AL10.alBufferData((int)buffer, (int)format, (ShortBuffer)pcm.samples, (int)pcm.sampleRate); + int alErr2 = AL10.alGetError(); + if (alErr2 != 0) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "alBufferData error={} format={} channels={} sampleRate={} samples={}", alErr2, format, pcm.channels, pcm.sampleRate, pcm.samples.remaining()); + } + int source = AL10.alGenSources(); + int alErr3 = AL10.alGetError(); + if (alErr3 != 0) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "alGenSources error={}", alErr3); + } + AL10.alSourcei((int)source, (int)4105, (int)buffer); + AL10.alSourcef((int)source, (int)4106, (float)safe.volume); + AL10.alSourcef((int)source, (int)4099, (float)safe.pitch); + AL10.alSourcei((int)source, (int)4103, (int)(safe.loop ? 1 : 0)); + this.configureSpatial(source, pos, safe.use3d); + AL10.alSourcePlay((int)source); + int alErr4 = AL10.alGetError(); + if (alErr4 != 0) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "alSourcePlay error={}", alErr4); + } + SoundDebug.log(SoundDebug.Level.L1, "PLAYBACK", sourceId, "play started source={} buffer={} channels={} sampleRate={} frames={}", source, buffer, pcm.channels, pcm.sampleRate, pcm.frames); + PlayingSource src = new PlayingSource(sourceId, source, buffer, pos, safe, gameTime); + src.fadeInTicks = safe.fadeInTicks; + src.targetGain = safe.volume; + if (safe.reverb && safe.reverbStrength > 0.01f) { + src.reverbSource = this.createReverbSource(sourceId, pos, safe, buffer); + } + if (src.fadeInTicks > 0) { + AL10.alSourcef((int)source, (int)4106, (float)0.0f); + } + this.active.put(sourceId, src); + } + catch (Exception e) { + SoundMod.LOGGER.error("Failed to play custom sound {}", (Object)safe.soundId, (Object)e); + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "play failed soundId={} reason={}", safe.soundId, e.getMessage()); + } + } + + public synchronized void updateLive(String sourceId, BlockPos pos, SoundSettings settings) { + SoundSettings safe = SoundSettings.sanitizedCopy(settings); + PlayingSource current = this.active.get(sourceId); + if (current == null) { + SoundDebug.log(SoundDebug.Level.L2, "PLAYBACK", "LIVE", "source missing -> fallback play sourceId={} soundId={}", sourceId, safe.soundId); + this.play(sourceId, pos, safe); + return; + } + if (!current.settings.soundId.equals(safe.soundId)) { + SoundDebug.log(SoundDebug.Level.L1, "PLAYBACK", "LIVE", "restart reason=soundId_change sourceId={} old={} new={} crossfade={}", sourceId, current.settings.soundId, safe.soundId, safe.crossfade); + if (safe.crossfade) { + current.fadeOutTicks = Math.max(1, safe.fadeOutTicks); + } else { + this.stop(sourceId); + } + this.play(sourceId, pos, safe); + return; + } + current.settings = safe; + current.pos = pos; + current.targetGain = safe.volume; + current.fadeInTicks = Math.max(0, current.fadeInTicks); + this.configureSpatial(current.source, pos, safe.use3d); + AL10.alSourcei((int)current.source, (int)4103, (int)(safe.loop ? 1 : 0)); + if (safe.reverb && safe.reverbStrength > 0.01f) { + if (current.reverbSource <= 0) { + current.reverbSource = this.createReverbSource(sourceId, pos, safe, current.buffer); + } else { + this.configureSpatial(current.reverbSource, pos, safe.use3d); + } + } else if (current.reverbSource > 0) { + AL10.alSourceStop((int)current.reverbSource); + AL10.alDeleteSources((int)current.reverbSource); + current.reverbSource = 0; + } + current.lastLiveUpdateTick = this.currentGameTime(); + SoundDebug.log(SoundDebug.Level.L2, "PLAYBACK", "LIVE", "updated sourceId={} soundId={} vol={} pitch={} radius={} attn={} use3d={} doppler={} occlusion={} reverb={}", sourceId, safe.soundId, Float.valueOf(safe.volume), Float.valueOf(safe.pitch), Float.valueOf(safe.radius), safe.attenuationMode.name(), safe.use3d, safe.doppler, safe.occlusion, safe.reverb); + } + + public synchronized void stop(String sourceId) { + PlayingSource src = this.active.remove(sourceId); + if (src == null) { + return; + } + SoundDebug.log(SoundDebug.Level.L2, "PLAYBACK", sourceId, "stop source={} buffer={}", src.source, src.buffer); + AL10.alSourceStop((int)src.source); + AL10.alDeleteSources((int)src.source); + if (src.reverbSource > 0) { + AL10.alSourceStop((int)src.reverbSource); + AL10.alDeleteSources((int)src.reverbSource); + } + AL10.alDeleteBuffers((int)src.buffer); + } + + public synchronized boolean isPlaying(String sourceId) { + return this.active.containsKey(sourceId); + } + + public synchronized void tick() { + if (this.active.isEmpty()) { + return; + } + Minecraft mc = Minecraft.getInstance(); + ClientPlayerEntity player = mc.player; + if (player == null || mc.level == null) { + return; + } + Vector3d playerPos = player.position(); + ArrayList remove = new ArrayList(); + int topPriority = Integer.MIN_VALUE; + String dominantCategory = "ambient"; + for (PlayingSource src : this.active.values()) { + if (src.settings.priority > topPriority) { + topPriority = src.settings.priority; + dominantCategory = src.settings.category; + continue; + } + if (src.settings.priority != topPriority || this.categoryRank(src.settings.category) <= this.categoryRank(dominantCategory)) continue; + dominantCategory = src.settings.category; + } + for (PlayingSource src : this.active.values()) { + int state = AL10.alGetSourcei((int)src.source, (int)4112); + if (SoundDebug.enabled(SoundDebug.Level.L3)) { + SoundDebug.log(SoundDebug.Level.L3, "PLAYBACK", src.sourceId, "tick state={} gainTarget={}", state, Float.valueOf(src.targetGain)); + } + if (state == 4116 && !src.settings.loop) { + remove.add(src.sourceId); + continue; + } + float gain = this.computeAttenuatedGain(src, playerPos); + float occlusionFactor = this.computeOcclusionFactor(src, playerPos); + gain *= occlusionFactor; + gain = this.applyFades(src, gain); + gain = this.applyPriorityDucking(src, gain, topPriority, dominantCategory); + AL10.alSourcef((int)src.source, (int)4106, (float)Math.max(0.0f, gain)); + float pitch = src.settings.pitch; + if (src.settings.occlusion && src.settings.use3d && occlusionFactor < 0.999f && !"voice".equals(src.settings.category)) { + pitch *= Math.max(0.9f, 1.0f - src.settings.occlusionStrength * 0.12f); + } + if (src.settings.doppler && src.settings.use3d) { + Vector3d velocity = player.getDeltaMovement(); + Vector3d sourceDir = new Vector3d((double)src.pos.getX() + 0.5 - playerPos.x, (double)src.pos.getY() + 0.5 - playerPos.y, (double)src.pos.getZ() + 0.5 - playerPos.z); + double len = Math.max(1.0E-4, sourceDir.length()); + double radial = (velocity.x * sourceDir.x + velocity.y * sourceDir.y + velocity.z * sourceDir.z) / len; + float dopplerPitch = (float)Math.max(0.75, Math.min(1.25, 1.0 + radial * 0.04)); + pitch *= dopplerPitch; + } + AL10.alSourcef((int)src.source, (int)4099, (float)pitch); + if (src.reverbSource <= 0) continue; + float wetGain = Math.max(0.0f, gain * src.settings.reverbStrength * 0.45f); + AL10.alSourcef((int)src.reverbSource, (int)4106, (float)wetGain); + } + for (String id : remove) { + this.stop(id); + } + } + + private float applyFades(PlayingSource src, float gain) { + if (src.fadeInTicks > 0) { + int elapsed = src.settings.fadeInTicks - src.fadeInTicks; + float alpha = src.settings.fadeInTicks <= 0 ? 1.0f : (float)elapsed / (float)src.settings.fadeInTicks; + --src.fadeInTicks; + return gain * Math.min(1.0f, alpha); + } + if (src.fadeOutTicks > 0) { + float alpha = (float)src.fadeOutTicks / (float)Math.max(1, src.settings.fadeOutTicks); + --src.fadeOutTicks; + if (src.fadeOutTicks <= 0) { + this.stop(src.sourceId); + return 0.0f; + } + return gain * alpha; + } + return gain; + } + + private float computeOcclusionFactor(PlayingSource src, Vector3d playerPos) { + if (!src.settings.occlusion || !src.settings.use3d) { + return 1.0f; + } + Minecraft mc = Minecraft.getInstance(); + BlockRayTraceResult trace = mc.level.clip(new RayTraceContext(playerPos, new Vector3d((double)src.pos.getX() + 0.5, (double)src.pos.getY() + 0.5, (double)src.pos.getZ() + 0.5), RayTraceContext.BlockMode.COLLIDER, RayTraceContext.FluidMode.NONE, (Entity)mc.player)); + if (trace.getType() != RayTraceResult.Type.MISS) { + float damp = Math.max(0.0f, 1.0f - src.settings.occlusionStrength); + return damp; + } + return 1.0f; + } + + private float computeAttenuatedGain(PlayingSource src, Vector3d playerPos) { + double atten; + if (!src.settings.use3d) { + return src.targetGain; + } + double dx = playerPos.x - ((double)src.pos.getX() + 0.5); + double dy = playerPos.y - ((double)src.pos.getY() + 0.5); + double dz = playerPos.z - ((double)src.pos.getZ() + 0.5); + double distance = Math.sqrt(dx * dx + dy * dy + dz * dz); + if (src.settings.attenuationMode == AttenuationMode.NONE || src.settings.radius <= 0.1f) { + return src.targetGain; + } + double t = Math.min(1.0, distance / (double)src.settings.radius); + switch (src.settings.attenuationMode) { + case EXPONENTIAL: { + atten = Math.pow(1.0 - t, 2.0); + break; + } + case LOGARITHMIC: { + atten = 1.0 - Math.log10(1.0 + 9.0 * t); + break; + } + default: { + atten = 1.0 - t; + } + } + return (float)Math.max(0.0, (double)src.targetGain * atten); + } + + public synchronized Collection snapshot() { + ArrayList out = new ArrayList(); + long nowTick = this.currentGameTime(); + for (PlayingSource src : this.active.values()) { + int alState = AL10.alGetSourcei((int)src.source, (int)4112); + ClientSoundCache.Status status = ClientSoundCache.get().status(src.settings.soundId); + boolean liveUpdated = nowTick != Long.MIN_VALUE && src.lastLiveUpdateTick != Long.MIN_VALUE && nowTick - src.lastLiveUpdateTick <= 40L; + out.add(new PlayingSourceView(src.sourceId, src.settings.soundId, (double)src.pos.getX() + 0.5, (double)src.pos.getY() + 0.5, (double)src.pos.getZ() + 0.5, src.settings.radius, src.settings.priority, status.name(), alState, liveUpdated)); + } + return out; + } + + private float applyPriorityDucking(PlayingSource src, float gain, int topPriority, String dominantCategory) { + if (topPriority == Integer.MIN_VALUE || src.settings.priority >= topPriority) { + return gain; + } + double strength = (Double)ModConfig.DUCKING_STRENGTH.get(); + double base = Math.max(0.05, 1.0 - strength); + double categoryFactor = this.categoryDuckingFactor(src.settings.category, dominantCategory); + return (float)((double)gain * base * categoryFactor); + } + + private double categoryDuckingFactor(String sourceCategory, String dominantCategory) { + boolean sourceForeground = this.isForegroundCategory(sourceCategory); + boolean dominantForeground = this.isForegroundCategory(dominantCategory); + if (dominantForeground && !sourceForeground) { + return 0.55; + } + if (!dominantForeground && sourceForeground) { + return 0.9; + } + return 0.78; + } + + private boolean isForegroundCategory(String category) { + return "voice".equals(category) || "effect".equals(category); + } + + private int categoryRank(String category) { + if ("voice".equals(category)) { + return 4; + } + if ("effect".equals(category)) { + return 3; + } + if ("ambient".equals(category)) { + return 2; + } + if ("music".equals(category)) { + return 1; + } + return 0; + } + + private void enforceActiveLimit(int incomingPriority) { + int maxActive = (Integer)ModConfig.MAX_ACTIVE_SOURCES.get(); + if (this.active.size() < maxActive) { + return; + } + String victimId = null; + PlayingSource victim = null; + for (Map.Entry e : this.active.entrySet()) { + PlayingSource src = e.getValue(); + if (victim != null && src.settings.priority >= victim.settings.priority && (src.settings.priority != victim.settings.priority || src.startedAtTick >= victim.startedAtTick)) continue; + victimId = e.getKey(); + victim = src; + } + if (victim != null && victimId != null && victim.settings.priority <= incomingPriority) { + SoundDebug.log(SoundDebug.Level.L2, "PLAYBACK", victimId, "evict by limiter incomingPriority={} victimPriority={}", incomingPriority, victim.settings.priority); + this.stop(victimId); + } + } + + private void configureSpatial(int source, BlockPos pos, boolean use3d) { + AL10.alSourcef((int)source, (int)4129, (float)0.0f); + if (use3d) { + AL10.alSourcei((int)source, (int)514, (int)0); + AL10.alSource3f((int)source, (int)4100, (float)((float)pos.getX() + 0.5f), (float)((float)pos.getY() + 0.5f), (float)((float)pos.getZ() + 0.5f)); + } else { + AL10.alSourcei((int)source, (int)514, (int)1); + AL10.alSource3f((int)source, (int)4100, (float)0.0f, (float)0.0f, (float)0.0f); + } + } + + private int createReverbSource(String sourceId, BlockPos pos, SoundSettings safe, int buffer) { + int wet = AL10.alGenSources(); + int err = AL10.alGetError(); + if (err != 0) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "reverb source create error={}", err); + return 0; + } + AL10.alSourcei((int)wet, (int)4105, (int)buffer); + AL10.alSourcei((int)wet, (int)4103, (int)(safe.loop ? 1 : 0)); + AL10.alSourcef((int)wet, (int)4106, (float)Math.max(0.0f, safe.volume * safe.reverbStrength * 0.45f)); + AL10.alSourcef((int)wet, (int)4099, (float)Math.max(0.5f, safe.pitch * 0.97f)); + this.configureSpatial(wet, pos, safe.use3d); + if (safe.use3d) { + float ox = (float)((sourceId.hashCode() >> 2 & 7) - 3) * 0.12f; + float oy = (float)((sourceId.hashCode() >> 5 & 7) - 3) * 0.06f; + float oz = (float)((sourceId.hashCode() >> 8 & 7) - 3) * 0.12f; + AL10.alSource3f((int)wet, (int)4100, (float)((float)pos.getX() + 0.5f + ox), (float)((float)pos.getY() + 0.5f + oy), (float)((float)pos.getZ() + 0.5f + oz)); + } + AL10.alSourcePlay((int)wet); + int playErr = AL10.alGetError(); + if (playErr != 0) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", sourceId, "reverb play error={}", playErr); + AL10.alDeleteSources((int)wet); + return 0; + } + return wet; + } + + private long currentGameTime() { + return Minecraft.getInstance().level != null ? Minecraft.getInstance().level.getGameTime() : Long.MIN_VALUE; + } + + /* + * Loose catch block + */ + private DecodedPcm decodeVorbis(Path file) throws IOException { + byte[] data = Files.readAllBytes(file); + SoundDebug.log(SoundDebug.Level.L2, "PLAYBACK", "DECODE", "read file={} bytes={}", file, data.length); + ByteBuffer ogg = MemoryUtil.memAlloc((int)data.length); + ogg.put(data); + ogg.flip(); + try { + try (MemoryStack stack = MemoryStack.stackPush();){ + IntBuffer error = stack.mallocInt(1); + long decoder = STBVorbis.stb_vorbis_open_memory((ByteBuffer)ogg, (IntBuffer)error, null); + if (decoder == 0L) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", "DECODE", "stb_vorbis_open_memory failed file={} code={}", file, error.get(0)); + throw new IOException("stb_vorbis_open_memory failed: " + error.get(0)); + } + STBVorbisInfo info = STBVorbisInfo.mallocStack((MemoryStack)stack); + STBVorbis.stb_vorbis_get_info((long)decoder, (STBVorbisInfo)info); + int channels = info.channels(); + int sampleRate = info.sample_rate(); + int estimatedFrames = STBVorbis.stb_vorbis_stream_length_in_samples((long)decoder); + ShortBuffer pcm = BufferUtils.createShortBuffer((int)Math.max(1, estimatedFrames * channels)); + int decodedFrames = STBVorbis.stb_vorbis_get_samples_short_interleaved((long)decoder, (int)channels, (ShortBuffer)pcm); + STBVorbis.stb_vorbis_close((long)decoder); + if (decodedFrames <= 0) { + SoundDebug.warn(SoundDebug.Level.L1, "PLAYBACK", "DECODE", "decode produced no samples file={} decodedFrames={}", file, decodedFrames); + throw new IOException("stb_vorbis_get_samples_short_interleaved returned " + decodedFrames); + } + int decodedShorts = decodedFrames * channels; + pcm.position(0); + pcm.limit(decodedShorts); + SoundDebug.log(SoundDebug.Level.L1, "PLAYBACK", "DECODE", "decode ok channels={} sampleRate={} frames={} pcmShorts={}", channels, sampleRate, decodedFrames, pcm.remaining()); + DecodedPcm decodedPcm = new DecodedPcm(pcm, channels, sampleRate, decodedFrames); + return decodedPcm; + } + } + finally { + MemoryUtil.memFree((Buffer)ogg); + } + } + + private DecodedPcm decodeAudio(Path file) throws IOException { + String name = file.getFileName().toString().toLowerCase(Locale.ROOT); + if (name.endsWith(".wav")) { + return this.decodeWav(file); + } else if (name.endsWith(".mp3")) { + return this.decodeMp3(file); + } else { + return this.decodeVorbis(file); + } + } + + private DecodedPcm decodeWav(Path file) throws IOException { + try { + AudioInputStream stream = AudioSystem.getAudioInputStream(file.toFile()); + AudioFormat baseFormat = stream.getFormat(); + int channels = baseFormat.getChannels(); + int sampleRate = (int) baseFormat.getSampleRate(); + AudioFormat decodedFormat = new AudioFormat( + AudioFormat.Encoding.PCM_SIGNED, + baseFormat.getSampleRate(), + 16, + baseFormat.getChannels(), + baseFormat.getChannels() * 2, + baseFormat.getSampleRate(), + false + ); + AudioInputStream pcmStream = AudioSystem.getAudioInputStream(decodedFormat, stream); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[4096]; + int n; + while ((n = pcmStream.read(buf)) != -1) { + out.write(buf, 0, n); + } + pcmStream.close(); + stream.close(); + + byte[] pcmBytes = out.toByteArray(); + ShortBuffer shortBuf = BufferUtils.createShortBuffer(pcmBytes.length / 2); + ByteBuffer byteBuffer = ByteBuffer.wrap(pcmBytes).order(ByteOrder.LITTLE_ENDIAN); + while (byteBuffer.remaining() >= 2) { + shortBuf.put(byteBuffer.getShort()); + } + shortBuf.flip(); + int frames = shortBuf.remaining() / channels; + SoundDebug.log(SoundDebug.Level.L1, "PLAYBACK", "DECODE", "wav decode ok channels={} sampleRate={} frames={} pcmShorts={}", channels, sampleRate, frames, shortBuf.remaining()); + return new DecodedPcm(shortBuf, channels, sampleRate, frames); + } catch (UnsupportedAudioFileException e) { + throw new IOException("Unsupported WAV file: " + e.getMessage(), e); + } + } + + private DecodedPcm decodeMp3(Path file) throws IOException { + try (InputStream in = Files.newInputStream(file); + BufferedInputStream bin = new BufferedInputStream(in)) { + Bitstream bitstream = new Bitstream(bin); + Decoder decoder = new Decoder(); + + Header header = bitstream.readFrame(); + if (header == null) { + throw new IOException("Empty or invalid MP3 file: " + file); + } + + int channels = (header.mode() == Header.SINGLE_CHANNEL) ? 1 : 2; + int sampleRate = header.frequency(); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + while (header != null) { + SampleBuffer output = (SampleBuffer) decoder.decodeFrame(header, bitstream); + short[] pcm = output.getBuffer(); + int len = output.getBufferLength(); + for (int i = 0; i < len; i++) { + short s = pcm[i]; + out.write(s & 0xFF); + out.write((s >> 8) & 0xFF); + } + bitstream.closeFrame(); + header = bitstream.readFrame(); + } + + byte[] pcmBytes = out.toByteArray(); + ShortBuffer shortBuf = BufferUtils.createShortBuffer(pcmBytes.length / 2); + ByteBuffer byteBuffer = ByteBuffer.wrap(pcmBytes).order(ByteOrder.LITTLE_ENDIAN); + while (byteBuffer.remaining() >= 2) { + shortBuf.put(byteBuffer.getShort()); + } + shortBuf.flip(); + int frames = shortBuf.remaining() / channels; + SoundDebug.log(SoundDebug.Level.L1, "PLAYBACK", "DECODE", "mp3 decode ok channels={} sampleRate={} frames={} pcmShorts={}", channels, sampleRate, frames, shortBuf.remaining()); + return new DecodedPcm(shortBuf, channels, sampleRate, frames); + } catch (JavaLayerException e) { + throw new IOException("Failed to decode MP3 file: " + e.getMessage(), e); + } + } + + private static class PlayingSource { + final String sourceId; + final int source; + final int buffer; + BlockPos pos; + SoundSettings settings; + final long startedAtTick; + float targetGain; + int fadeInTicks; + int fadeOutTicks; + int reverbSource; + long lastLiveUpdateTick = Long.MIN_VALUE; + + PlayingSource(String sourceId, int source, int buffer, BlockPos pos, SoundSettings settings, long startedAtTick) { + this.sourceId = sourceId; + this.source = source; + this.buffer = buffer; + this.pos = pos; + this.settings = settings; + this.startedAtTick = startedAtTick; + this.targetGain = settings.volume; + } + } + + private static class DecodedPcm { + final ShortBuffer samples; + final int channels; + final int sampleRate; + final int frames; + + DecodedPcm(ShortBuffer samples, int channels, int sampleRate, int frames) { + this.samples = samples; + this.channels = channels; + this.sampleRate = sampleRate; + this.frames = frames; + } + } + + public static final class PlayingSourceView { + public final String sourceId; + public final String soundId; + public final double x; + public final double y; + public final double z; + public final float radius; + public final int priority; + public final String cacheStatus; + public final int alState; + public final boolean liveUpdated; + + private PlayingSourceView(String sourceId, String soundId, double x, double y, double z, float radius, int priority, String cacheStatus, int alState, boolean liveUpdated) { + this.sourceId = sourceId; + this.soundId = soundId; + this.x = x; + this.y = y; + this.z = z; + this.radius = radius; + this.priority = priority; + this.cacheStatus = cacheStatus; + this.alState = alState; + this.liveUpdated = liveUpdated; + } + } +} + diff --git a/src/main/java/com/example/soundmod/client/debug/DebugOverlayRenderer.java b/src/main/java/com/example/soundmod/client/debug/DebugOverlayRenderer.java new file mode 100644 index 0000000..1f405ae --- /dev/null +++ b/src/main/java/com/example/soundmod/client/debug/DebugOverlayRenderer.java @@ -0,0 +1,119 @@ +/* + * Decompiled with CFR 0.152. + * + * Could not load the following classes: + * com.mojang.blaze3d.matrix.MatrixStack + * com.mojang.blaze3d.vertex.IVertexBuilder + * net.minecraft.client.Minecraft + * net.minecraft.client.renderer.IRenderTypeBuffer$Impl + * net.minecraft.client.renderer.RenderType + * net.minecraft.client.renderer.WorldRenderer + * net.minecraft.util.math.AxisAlignedBB + * net.minecraft.util.math.vector.Vector3d + * net.minecraft.util.text.ITextComponent + * net.minecraft.util.text.StringTextComponent + */ +package com.example.soundmod.client.debug; + +import com.example.soundmod.client.audio.AudioPlaybackService; +import com.example.soundmod.client.debug.DebugState; +import com.mojang.blaze3d.matrix.MatrixStack; +import com.mojang.blaze3d.vertex.IVertexBuilder; +import java.util.ArrayList; +import java.util.Collection; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.IRenderTypeBuffer; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.WorldRenderer; +import net.minecraft.util.math.AxisAlignedBB; +import net.minecraft.util.math.vector.Vector3d; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.StringTextComponent; + +public final class DebugOverlayRenderer { + private DebugOverlayRenderer() { + } + + public static void render(MatrixStack stack, float partialTicks) { + if (!DebugState.isEnabled()) { + return; + } + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.level == null) { + return; + } + Vector3d camera = mc.gameRenderer.getMainCamera().getPosition(); + Collection sources = AudioPlaybackService.get().snapshot(); + IRenderTypeBuffer.Impl bufferSource = mc.renderBuffers().bufferSource(); + IVertexBuilder lineBuilder = bufferSource.getBuffer(RenderType.lines()); + for (AudioPlaybackService.PlayingSourceView source : sources) { + float[] color = DebugOverlayRenderer.colorFor(source); + AxisAlignedBB bb = new AxisAlignedBB(source.x - (double)source.radius - camera.x, source.y - (double)source.radius - camera.y, source.z - (double)source.radius - camera.z, source.x + (double)source.radius - camera.x, source.y + (double)source.radius - camera.y, source.z + (double)source.radius - camera.z); + WorldRenderer.renderLineBox((MatrixStack)stack, (IVertexBuilder)lineBuilder, (AxisAlignedBB)bb, (float)color[0], (float)color[1], (float)color[2], (float)0.85f); + } + bufferSource.endBatch(RenderType.lines()); + } + + public static void renderHud(MatrixStack stack) { + if (!DebugState.isEnabled()) { + return; + } + Minecraft mc = Minecraft.getInstance(); + if (mc.player == null || mc.level == null || mc.font == null) { + return; + } + Collection snapshot = AudioPlaybackService.get().snapshot(); + ArrayList sources = new ArrayList(snapshot); + sources.sort((a, b) -> Integer.compare(b.priority, a.priority)); + int x = 8; + int y = 8; + mc.font.drawShadow(stack, (ITextComponent)new StringTextComponent("SOUNDDBG Active Sources: " + sources.size()), (float)x, (float)y, 0xFFFFFF); + y += 10; + int limit = Math.min(8, sources.size()); + for (int i = 0; i < limit; ++i) { + AudioPlaybackService.PlayingSourceView s = (AudioPlaybackService.PlayingSourceView)sources.get(i); + int color = DebugOverlayRenderer.colorIntFor(s); + String line = String.format("#%d p=%d %s sid=%s st=%s cache=%s%s", i + 1, s.priority, s.sourceId, s.soundId, DebugOverlayRenderer.alStateName(s.alState), s.cacheStatus, s.liveUpdated ? " LIVE-UPDATED" : ""); + mc.font.drawShadow(stack, (ITextComponent)new StringTextComponent(line), (float)x, (float)y, color); + y += 10; + } + } + + private static float[] colorFor(AudioPlaybackService.PlayingSourceView source) { + if ("ERROR".equals(source.cacheStatus) || "MISSING".equals(source.cacheStatus)) { + return new float[]{0.95f, 0.15f, 0.15f}; + } + if ("TRANSFERRING".equals(source.cacheStatus)) { + return new float[]{0.95f, 0.85f, 0.2f}; + } + if (source.alState == 4114) { + return new float[]{0.2f, 0.9f, 0.25f}; + } + return new float[]{0.2f, 0.9f, 1.0f}; + } + + private static int colorIntFor(AudioPlaybackService.PlayingSourceView source) { + float[] c = DebugOverlayRenderer.colorFor(source); + int r = (int)(Math.max(0.0f, Math.min(1.0f, c[0])) * 255.0f); + int g = (int)(Math.max(0.0f, Math.min(1.0f, c[1])) * 255.0f); + int b = (int)(Math.max(0.0f, Math.min(1.0f, c[2])) * 255.0f); + return r << 16 | g << 8 | b; + } + + private static String alStateName(int state) { + if (state == 4114) { + return "PLAYING"; + } + if (state == 4115) { + return "PAUSED"; + } + if (state == 4116) { + return "STOPPED"; + } + if (state == 4113) { + return "INITIAL"; + } + return Integer.toString(state); + } +} + diff --git a/src/main/java/com/example/soundmod/client/debug/DebugState.java b/src/main/java/com/example/soundmod/client/debug/DebugState.java new file mode 100644 index 0000000..f58db63 --- /dev/null +++ b/src/main/java/com/example/soundmod/client/debug/DebugState.java @@ -0,0 +1,20 @@ +/* + * Decompiled with CFR 0.152. + */ +package com.example.soundmod.client.debug; + +public final class DebugState { + private static boolean enabled; + + private DebugState() { + } + + public static boolean isEnabled() { + return enabled; + } + + public static void setEnabled(boolean enabled) { + DebugState.enabled = enabled; + } +} + diff --git a/src/main/java/com/example/soundmod/client/screen/SoundPlayerScreen.java b/src/main/java/com/example/soundmod/client/screen/SoundPlayerScreen.java new file mode 100644 index 0000000..492e43b --- /dev/null +++ b/src/main/java/com/example/soundmod/client/screen/SoundPlayerScreen.java @@ -0,0 +1,1377 @@ +package com.example.soundmod.client.screen; + +import com.example.soundmod.client.audio.AudioPlaybackService; +import com.example.soundmod.common.ActivationMode; +import com.example.soundmod.common.AttenuationMode; +import com.example.soundmod.common.RedstoneMode; +import com.example.soundmod.common.ScenarioQueue; +import com.example.soundmod.common.SoundManifestEntry; +import com.example.soundmod.common.SoundSettings; +import com.example.soundmod.common.ZoneIntersectionPolicy; +import com.example.soundmod.common.ZoneShape; +import com.example.soundmod.core.SoundDebug; +import com.example.soundmod.gameplay.container.SoundPlayerContainer; +import com.example.soundmod.gameplay.tile.SoundPlayerTileEntity; +import com.example.soundmod.net.ClientTransferManager; +import com.example.soundmod.net.NetworkHandler; +import com.example.soundmod.net.packet.C2SUpdateConfigPacket; +import com.example.soundmod.sounddata.client.ClientSoundCache; +import com.mojang.blaze3d.matrix.MatrixStack; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import net.minecraft.client.Minecraft; +import net.minecraft.client.entity.player.ClientPlayerEntity; +import net.minecraft.client.gui.screen.inventory.ContainerScreen; +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.client.gui.widget.Widget; +import net.minecraft.client.gui.widget.button.Button; +import net.minecraft.entity.player.PlayerInventory; +import net.minecraft.inventory.container.Container; +import net.minecraft.nbt.CompoundNBT; +import net.minecraft.nbt.INBT; +import net.minecraft.nbt.JsonToNBT; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.text.ITextComponent; +import net.minecraft.util.text.StringTextComponent; + +public class SoundPlayerScreen extends ContainerScreen { + + // Palette + private static final int COLOR_BG_SHADOW = 0x90000000; + private static final int COLOR_BG_MAIN = 0xEE161B22; + private static final int COLOR_BG_INNER = 0xEE1F242C; + private static final int COLOR_BG_BOX = 0xCC11141B; + private static final int COLOR_ACCENT = 0xFF388BFD; + private static final int COLOR_ACCENT_HOVER = 0xFF58A6FF; + private static final int COLOR_TEXT_TITLE = 0xFFFFFF; + private static final int COLOR_TEXT_LABEL = 0xFFA0A6B2; + private static final int COLOR_TEXT_MUTED = 0xFF767F8D; + private static final int COLOR_GREEN = 0xFF3FB950; + private static final int COLOR_YELLOW = 0xFFD29922; + private static final int COLOR_RED = 0xFFF85149; + + private static final String[] CATEGORIES = new String[]{"music", "ambient", "effect", "voice"}; + private static final int SOUND_LIST_ROWS = 5; + private static final int ROW_HEIGHT = 12; + + private Tab activeTab = Tab.BASIC; + private SoundSettings localSettings = new SoundSettings(); + private final List sourceScenarioSteps = new ArrayList<>(); + private final List zoneScenarioSteps = new ArrayList<>(); + private boolean sourceScenarioLoop; + private boolean zoneScenarioLoop; + private boolean editingZoneScenario; + private boolean sourceEnabled = true; + private boolean zoneEnabled = true; + private boolean wizardCompleted = true; + private ZoneShape zoneShape = ZoneShape.SPHERE; + private float zoneRadius = 12.0f; + private float zoneBoxX = 8.0f; + private float zoneBoxY = 4.0f; + private float zoneBoxZ = 8.0f; + private boolean zoneAutoStartOnEnter = true; + private boolean zoneStopOnExit = true; + private ZoneIntersectionPolicy zonePolicy = ZoneIntersectionPolicy.HIGHEST_PRIORITY; + private boolean zoneUseCustomCoords; + private int zoneSourceX; + private int zoneSourceY; + private int zoneSourceZ; + + // Controls - Basic + private TextFieldWidget soundIdField; + private TextFieldWidget searchField; + private TextFieldWidget volumeField; + private TextFieldWidget pitchField; + private TextFieldWidget radiusField; + private TextFieldWidget priorityField; + private Button previewButton; + private Button loopButton; + private Button categoryButton; + private Button clearFilterButton; + private Button volMinusBtn; + private Button volPlusBtn; + private Button pitchMinusBtn; + private Button pitchPlusBtn; + + // Controls - Effects + private Button use3dButton; + private Button attenuationButton; + private Button occlusionButton; + private Button reverbButton; + private Button dopplerButton; + private Button crossfadeButton; + private TextFieldWidget occlusionStrengthField; + private TextFieldWidget reverbStrengthField; + private TextFieldWidget fadeInField; + private TextFieldWidget fadeOutField; + + // Controls - Trigger + private Button activationModeButton; + private Button redstoneModeButton; + private Button sourceEnabledButton; + private Button zoneEnabledButton; + private TextFieldWidget startDelayField; + private TextFieldWidget repeatDelayField; + + // Controls - Zone + private Button zoneShapeButton; + private Button zonePolicyButton; + private Button zoneAutoStartButton; + private Button zoneStopOnExitButton; + private Button zoneUseCustomCoordsButton; + private Button myPosButton; + private TextFieldWidget zoneRadiusField; + private TextFieldWidget zoneBoxXField; + private TextFieldWidget zoneBoxYField; + private TextFieldWidget zoneBoxZField; + private TextFieldWidget zoneSourceXField; + private TextFieldWidget zoneSourceYField; + private TextFieldWidget zoneSourceZField; + + // Controls - Scenario + private Button scenarioTargetButton; + private Button scenarioLoopButton; + private TextFieldWidget scenarioSoundField; + private TextFieldWidget scenarioDelayField; + private Button scenarioUseCurrentBtn; + private Button scenarioAddButton; + private Button scenarioRemoveButton; + private Button scenarioUpButton; + private Button scenarioDownButton; + + // Fixed bottom bar controls + private Button saveButton; + private Button copyConfigButton; + private Button pasteConfigButton; + private Button playNowButton; + private Button stopNowButton; + + // Tab buttons + private final List