@@ -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