Skip to content

Commit b1c3023

Browse files
isHarryhK0lb3
authored andcommitted
feat: optimize reuse strategy of pyfmodex system
1 parent 87a6e5a commit b1c3023

1 file changed

Lines changed: 17 additions & 22 deletions

File tree

UnityPy/export/AudioClipConverter.py

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -112,23 +112,21 @@ def extract_audioclip_samples(
112112
return dump_samples(audio, audio_data, convert_pcm_float)
113113

114114

115-
system_lock = Lock()
116-
system_param = ()
117-
system_instance = None
118-
119-
def get_pyfmodex_system_instance(maxchannels: int, flags: int):
120-
global pyfmodex, system_param, system_instance
121-
# cache strategy check
122-
new_system_param = (maxchannels, flags, None)
123-
if system_param != new_system_param or system_instance is None:
124-
system_param = new_system_param
125-
if system_instance is not None:
126-
system_instance.release()
127-
# create a new instance
128-
system_instance = pyfmodex.System()
129-
system_instance.init(*system_param)
130-
return system_instance
131-
115+
SYSTEM_INSTANCES = {} # (channels, flags) -> (pyfmodex_system_instance, lock)
116+
SYSTEM_GLOBAL_LOCK = Lock()
117+
118+
def get_pyfmodex_system_instance(channels: int, flags: int):
119+
global pyfmodex, SYSTEM_INSTANCES, SYSTEM_GLOBAL_LOCK
120+
with SYSTEM_GLOBAL_LOCK:
121+
instance_key = (channels, flags)
122+
if instance_key in SYSTEM_INSTANCES:
123+
return SYSTEM_INSTANCES[instance_key]
124+
125+
system = pyfmodex.System()
126+
system.init(channels, flags, None)
127+
lock = Lock()
128+
SYSTEM_INSTANCES[instance_key] = (system, lock)
129+
return system, lock
132130

133131
def dump_samples(
134132
clip: AudioClip, audio_data: bytes, convert_pcm_float: bool = True
@@ -139,11 +137,8 @@ def dump_samples(
139137
if not pyfmodex:
140138
return {}
141139

142-
# avoid asynchronous access to pyfmodex
143-
with system_lock:
144-
# init system
145-
system = get_pyfmodex_system_instance(clip.m_Channels, pyfmodex.flags.INIT_FLAGS.NORMAL)
146-
140+
system, lock = get_pyfmodex_system_instance(clip.m_Channels, pyfmodex.flags.INIT_FLAGS.NORMAL)
141+
with lock:
147142
sound = system.create_sound(
148143
bytes(audio_data),
149144
pyfmodex.flags.MODE.OPENMEMORY,

0 commit comments

Comments
 (0)