@@ -101,24 +101,60 @@ static const int16_t adaptationTable[] =
101101 768 , 614 , 512 , 409 , 307 , 230 , 230 , 230
102102};
103103
104+ int firstBitSet (int x)
105+ {
106+ int position=0 ;
107+ while (x!=0 )
108+ {
109+ x>>=1 ;
110+ ++position;
111+ }
112+ return position;
113+ }
114+
115+ #ifndef __has_builtin
116+ #define __has_builtin (x ) 0
117+ #endif
118+
119+ int multiplyCheckOverflow (int a, int b, int *result)
120+ {
121+ #if (defined __GNUC__ && __GNUC__ >= 5) || ( __clang__ && __has_builtin(__builtin_mul_overflow))
122+ return __builtin_mul_overflow (a, b, result);
123+ #else
124+ if (firstBitSet (a)+firstBitSet (b)>31 ) // int is signed, so we can't use 32 bits
125+ return true ;
126+ *result = a * b;
127+ return false ;
128+ #endif
129+ }
130+
131+
104132// Compute a linear PCM value from the given differential coded value.
105133static int16_t decodeSample (ms_adpcm_state &state,
106- uint8_t code, const int16_t *coefficient)
134+ uint8_t code, const int16_t *coefficient, bool *ok= NULL )
107135{
108136 int linearSample = (state.sample1 * coefficient[0 ] +
109137 state.sample2 * coefficient[1 ]) >> 8 ;
138+ int delta;
110139
111140 linearSample += ((code & 0x08 ) ? (code - 0x10 ) : code) * state.delta ;
112141
113142 linearSample = clamp (linearSample, MIN_INT16, MAX_INT16);
114143
115- int delta = (state.delta * adaptationTable[code]) >> 8 ;
144+ if (multiplyCheckOverflow (state.delta , adaptationTable[code], &delta))
145+ {
146+ if (ok) *ok=false ;
147+ _af_error (AF_BAD_COMPRESSION, " Error decoding sample" );
148+ return 0 ;
149+ }
150+ delta >>= 8 ;
116151 if (delta < 16 )
117152 delta = 16 ;
118153
119154 state.delta = delta;
120155 state.sample2 = state.sample1 ;
121156 state.sample1 = linearSample;
157+ if (ok) *ok=true ;
122158
123159 return static_cast <int16_t >(linearSample);
124160}
@@ -212,13 +248,16 @@ int MSADPCM::decodeBlock(const uint8_t *encoded, int16_t *decoded)
212248 {
213249 uint8_t code;
214250 int16_t newSample;
251+ bool ok;
215252
216253 code = *encoded >> 4 ;
217- newSample = decodeSample (*state[0 ], code, coefficient[0 ]);
254+ newSample = decodeSample (*state[0 ], code, coefficient[0 ], &ok);
255+ if (!ok) return 0 ;
218256 *decoded++ = newSample;
219257
220258 code = *encoded & 0x0f ;
221- newSample = decodeSample (*state[1 ], code, coefficient[1 ]);
259+ newSample = decodeSample (*state[1 ], code, coefficient[1 ], &ok);
260+ if (!ok) return 0 ;
222261 *decoded++ = newSample;
223262
224263 encoded++;
0 commit comments