Skip to content

Commit c7962f4

Browse files
committed
perf: 优化 FLAC 解码器 decodeFrame 方法
用整数位移替换浮点运算,改善内存访问模式, 解决高采样率/高深度 FLAC 播放时游戏卡死的问题
1 parent 2caae7f commit c7962f4

File tree

1 file changed

+33
-11
lines changed

1 file changed

+33
-11
lines changed

zmusic-core/src/main/java/me/zhenxin/zmusic/player/decoder/flac/FlacDecoder.java

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -144,18 +144,40 @@ public int readAudioBlock(int[][] samples, int off) throws IOException {
144144
public BuffPack decodeFrame() throws Exception {
145145
int blockSamples = readAudioBlock(samples, 0);
146146
int sampleBytesLen = 0;
147-
for (int i = 0; i < blockSamples; i++) {
148-
for (int ch = 0; ch < streamInfo.numChannels; ch++) {
149-
int val = samples[ch][i];
150-
if (streamInfo.sampleDepth == 24) {
151-
float temp = val / 16777216f;
152-
val = (int) (temp * 0x7FFF);
153-
} else if (streamInfo.sampleDepth == 32) {
154-
float temp = val / 1099511627776f;
155-
val = (int) (temp * 0x7FFF);
147+
int depth = streamInfo.sampleDepth;
148+
int numCh = streamInfo.numChannels;
149+
150+
// 按声道优先处理,改善 CPU 缓存命中率
151+
for (int ch = 0; ch < numCh; ch++) {
152+
int[] channelSamples = samples[ch];
153+
for (int i = 0; i < blockSamples; i++) {
154+
int val = channelSamples[i];
155+
156+
// 使用整数运算替换浮点运算,提升性能
157+
if (depth == 16) {
158+
// 16 位:直接使用
159+
} else if (depth == 24) {
160+
// 24 位:右移 8 位到 16 位 (除以 2^8)
161+
val = val >> 8;
162+
} else if (depth == 20) {
163+
// 20 位:右移 4 位到 16 位
164+
val = val >> 4;
165+
} else if (depth == 32) {
166+
// 32 位:右移 16 位到 16 位
167+
val = val >> 16;
168+
} else {
169+
// 其他位深度:使用整数运算
170+
int shift = depth - 16;
171+
if (shift > 0) {
172+
val = val >> shift;
173+
} else {
174+
val = val << (-shift);
175+
}
156176
}
157-
for (int j = 0; j < 2; j++, sampleBytesLen++)
158-
sampleBytes[sampleBytesLen] = (byte) (val >>> (j << 3));
177+
178+
// 小端序存储
179+
sampleBytes[sampleBytesLen++] = (byte) val;
180+
sampleBytes[sampleBytesLen++] = (byte) (val >>> 8);
159181
}
160182
}
161183
pack.len = sampleBytesLen;

0 commit comments

Comments
 (0)