@@ -117,11 +117,11 @@ class DriverPWMBase {
117117 // restart with prior definitions
118118 bool begin (PWMConfig cfg) {
119119 TRACED ();
120+ decimation_factor = 0 ;
120121 audio_config = cfg;
121122 decimate.setChannels (cfg.channels );
122123 decimate.setBits (cfg.bits_per_sample );
123124 decimate.setFactor (decimation ());
124- LOGI (" decimation: %d" , decimation ());
125125 frame_size = audio_config.channels * (audio_config.bits_per_sample / 8 );
126126 if (audio_config.channels > maxChannels ()) {
127127 LOGE (" Only max %d channels are supported!" , maxChannels ());
@@ -158,9 +158,11 @@ class DriverPWMBase {
158158 }
159159
160160 virtual int availableForWrite () {
161- return is_blocking_write
162- ? audio_config.buffer_size
163- : buffer->availableForWrite () / frame_size * frame_size;
161+ // return is_blocking_write
162+ // ? audio_config.buffer_size
163+ // : buffer->availableForWrite() / frame_size * frame_size;
164+ // we must not write anything bigger then the buffer size
165+ return buffer->size () / frame_size * frame_size;
164166 }
165167
166168 // blocking write for an array: we expect a singed value and convert it into a
@@ -186,11 +188,17 @@ class DriverPWMBase {
186188
187189 size_t result = buffer->writeArray (data, size);
188190 if (result != size) {
189- LOGW (" Could not write all data: %u -> %d" , (unsigned int )size, result);
191+ LOGW (" Could not write all data: %u -> %d" , (unsigned )size, result);
190192 }
191193 // activate the timer now - if not already done
192194 if (!is_timer_started) startTimer ();
193- return result * decimation ();
195+
196+ // adjust the result by the descimation
197+ if (isDecimateActive ()) {
198+ result = result * decimation ();
199+ }
200+ // LOGD("write %u -> %u", len, result);
201+ return result;
194202 }
195203
196204 // When the timer does not have enough data we increase the underflow_count;
@@ -237,6 +245,7 @@ class DriverPWMBase {
237245 bool is_timer_started = false ;
238246 bool is_blocking_write = true ;
239247 Decimate decimate;
248+ int decimation_factor = 0 ;
240249
241250 void deleteBuffer () {
242251 // delete buffer if necessary
@@ -323,9 +332,23 @@ class DriverPWMBase {
323332 }
324333
325334 // / Decimation factor to reduce the sample rate
326- virtual int decimation () { return 1 ; }
335+ virtual int decimation () {
336+ if (decimation_factor == 0 ){
337+ for (int j = 1 ; j < 20 ; j++){
338+ if (audio_config.sample_rate / j <= ANALOG_MAX_SAMPLE_RATE){
339+ decimation_factor = j;
340+ LOGI (" Decimation factor: %d" ,j);
341+ return j;
342+ }
343+ }
344+ decimation_factor = 1 ;
345+ LOGI (" Decimation factor: %d" , (int )decimation_factor);
346+ }
347+
348+ return decimation_factor;
349+ }
327350};
328351
329- } // namespace audio_tools
352+ } // namespace audio_tool
330353
331354#endif
0 commit comments