Загрузка данных


#ifdef MY_CODE
/**
 * Ultra-fast in-place audio rate conversion for 16-bit stereo (packed as 32-bit words).
 * Optimized specifically for Cortex-M7: zero division or modulo operations inside loops.
 */
void audio_convert_rate(int cur_rate, int out_rate, uint8_t *buf, size_t buf_sz) 
{
    /* buf_sz must express the total number of valid uint32_t elements inside the buffer */
    uint32_t *buf32 = (uint32_t *) buf;
    int div;

    if (cur_rate == out_rate) {
        return;
    }

    div = MAX(cur_rate, out_rate) / MIN(cur_rate, out_rate);
    if (div <= 0) {
        return;
    }

    if (cur_rate > out_rate) {
        /* 
         * Downsampling (e.g., 16kHz -> 8kHz). 
         * Compress elements into the front part of the buffer.
         * Safe from boundary overflows. Out_sz is exactly buf_sz / div.
         */
        size_t out_sz = buf_sz / div;
        size_t src_idx = 0;
        
        for (size_t i = 0; i < out_sz; i++) {
            buf32[i] = buf32[src_idx];
            src_idx += div;
        }
        
        /* Optional: Clear the remaining half of the buffer to prevent static noise */
        // memset(&buf32[out_sz], 0, (buf_sz - out_sz) * sizeof(uint32_t));

    } else {
        /* 
         * Upsampling (e.g., 8kHz -> 16kHz). 
         * Stretch elements from the middle towards the end of the buffer.
         * Loop runs backwards to prevent overriding source samples prematurely.
         */
        int src_idx = (buf_sz / div) - 1;
        int target_countdown = div;

        for (int i = (int)buf_sz - 1; i >= 0; i--) {
            buf32[i] = buf32[src_idx];
            
            /* Fast counter instead of using a slow modulo (%) operator */
            if (--target_countdown == 0) {
                src_idx--;
                target_countdown = div;
            }
        }
    }
}
#endif