@@ -70,14 +70,69 @@ public Int16[] GetWaveData(byte[] Data, int Offset, int Length)
70
70
return DataOut . ToArray ( ) ;
71
71
}
72
72
73
- /* public static byte[] Encode(Int16[] WaveData)
73
+ public static byte [ ] Encode ( Int16 [ ] WaveData )
74
74
{
75
- Int16[] Diff = new short[WaveData.Length];
75
+ int Last = WaveData [ 0 ] ;
76
+ int Index = GetBestTableIndex ( ( WaveData [ 1 ] - WaveData [ 0 ] ) * 8 ) ;
77
+ int HeaderIndex = Index ;
78
+ byte [ ] Nibbles = new byte [ WaveData . Length - 1 ] ; //nibbles, lets merge it afterwards
76
79
for ( int i = 1 ; i < WaveData . Length ; i ++ )
77
80
{
78
- Diff[i] = (short)(WaveData[i] - WaveData[i - 1]);
81
+ int val = GetBestConfig ( Index , WaveData [ i ] - Last ) ;
82
+ Nibbles [ i - 1 ] = ( byte ) val ;
83
+
84
+ int diff =
85
+ StepTable [ Index ] / 8 +
86
+ StepTable [ Index ] / 4 * ( ( val >> 0 ) & 1 ) +
87
+ StepTable [ Index ] / 2 * ( ( val >> 1 ) & 1 ) +
88
+ StepTable [ Index ] * ( ( val >> 2 ) & 1 ) ;
89
+
90
+ int samp = Last + diff * ( ( ( ( val >> 3 ) & 1 ) == 1 ) ? - 1 : 1 ) ;
91
+ Last = ( short ) MathUtil . Clamp ( samp , short . MinValue , short . MaxValue ) ;
92
+ Index = ( short ) MathUtil . Clamp ( Index + IndexTable [ val & 7 ] , 0 , 88 ) ;
93
+ }
94
+ byte [ ] Result = new byte [ WaveData . Length / 2 + 4 ] ;
95
+ IOUtil . WriteS16LE ( Result , 0 , WaveData [ 0 ] ) ;
96
+ IOUtil . WriteS16LE ( Result , 2 , ( short ) HeaderIndex ) ;
97
+ for ( int i = 0 ; i < Nibbles . Length ; i += 2 )
98
+ {
99
+ Result [ i / 2 + 4 ] = ( byte ) ( Nibbles [ i ] | ( Nibbles [ i + 1 ] << 4 ) ) ;
79
100
}
80
- return null;
81
- }*/
101
+ return Result ;
102
+ }
103
+
104
+ private static int GetBestTableIndex ( int Diff )
105
+ {
106
+ int LowestDiff = int . MaxValue ;
107
+ int LowestIdx = - 1 ;
108
+ for ( int i = 0 ; i < StepTable . Length ; i ++ )
109
+ {
110
+ int diff2 = Math . Abs ( Math . Abs ( Diff ) - StepTable [ i ] ) ;
111
+ if ( diff2 < LowestDiff )
112
+ {
113
+ LowestDiff = diff2 ;
114
+ LowestIdx = i ;
115
+ }
116
+ }
117
+ return LowestIdx ;
118
+ }
119
+
120
+ private static int GetBestConfig ( int Index , int Diff )
121
+ {
122
+ int Result = 0 ;
123
+ if ( Diff < 0 ) Result |= 1 << 3 ;
124
+ Diff = Math . Abs ( Diff ) ;
125
+ int DiffNew = StepTable [ Index ] / 8 ;
126
+ if ( Math . Abs ( DiffNew - Diff ) < StepTable [ Index ] / 4 ) return Result ;
127
+ Result |= 1 ;
128
+ DiffNew += StepTable [ Index ] / 4 ;
129
+ if ( Math . Abs ( DiffNew - Diff ) < StepTable [ Index ] / 2 ) return Result ;
130
+ Result |= 1 << 1 ;
131
+ DiffNew += StepTable [ Index ] / 2 ;
132
+ if ( Math . Abs ( DiffNew - Diff ) < StepTable [ Index ] ) return Result ;
133
+ Result |= 1 << 2 ;
134
+ DiffNew += StepTable [ Index ] ;
135
+ return Result ;
136
+ }
82
137
}
83
138
}
0 commit comments