Skip to content

Commit d614c73

Browse files
committed
Fix lost audio buffers
1 parent 145ec0e commit d614c73

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

Core/Src/audio.c

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
#define AUDIO_BUFFER_SIZE_BYTES (PICOVOICE_FRAME_SIZE * sizeof(int16_t))
1616

1717
static int32_t _dma_buffer[PICOVOICE_FRAME_SIZE * 2];
18-
18+
static volatile uint8_t _audio_active = 0;
1919
// ---------------------------- Azure RTOS Config --------------------------- //
2020
#define NUM_AUDIO_BUFFERS (16)
2121

@@ -68,6 +68,8 @@ void AUDIO_Start(void)
6868
{
6969
log_info("AUDIO_Start");
7070

71+
_audio_active = 1;
72+
7173
HAL_SAI_Receive_DMA(&hsai_BlockB1, (uint8_t *)_dma_buffer, PICOVOICE_FRAME_SIZE * 2);
7274
}
7375

@@ -76,13 +78,24 @@ void AUDIO_Stop(void)
7678
log_info("Stopping audio capture");
7779

7880
// Stop DMA
81+
_audio_active = 0;
7982
HAL_SAI_DMAStop(&hsai_BlockB1);
8083

81-
// Flush queue
82-
UINT status = tx_queue_flush(&_audio_data_queue);
83-
if (status != TX_SUCCESS)
84+
// Wait 1ms for remaining audio
85+
tx_thread_sleep((1 * TX_TIMER_TICKS_PER_SECOND) / 1000);
86+
87+
// Drain queue, release all pending buffers
88+
int16_t *buffer;
89+
UINT status;
90+
91+
while (tx_queue_receive(&_audio_data_queue, &buffer, TX_NO_WAIT) == TX_SUCCESS)
8492
{
85-
log_fatal("Failed to flush audio data queue: %d", status);
93+
// Release the buffer back to the byte pool
94+
status = tx_block_release(buffer);
95+
if (status != TX_SUCCESS)
96+
{
97+
log_error("Failed to release audio buffer back to byte pool: %d", status);
98+
}
8699
}
87100
}
88101

@@ -111,6 +124,12 @@ static void processData(const int32_t *dma_src, int16_t *dest)
111124

112125
void dmaCallbackHandler(int32_t *dma_buffer)
113126
{
127+
if (!_audio_active)
128+
{
129+
log_debug("Audio inactive, dropping frame");
130+
return;
131+
}
132+
114133
// Allocate buff from byte pool
115134
int16_t *buffer = NULL;
116135
UINT status = tx_block_allocate(&_audio_block_pool, (VOID **)&buffer, TX_NO_WAIT);

0 commit comments

Comments
 (0)