Skip to content

Fix audio DMA buffer allocation on RP2040 #10278

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions ports/raspberrypi/audio_dma.c
Original file line number Diff line number Diff line change
Expand Up @@ -227,14 +227,31 @@ audio_dma_result audio_dma_setup_playback(
max_buffer_length /= dma->sample_spacing;
}

#ifdef PICO_RP2350
dma->buffer[0] = (uint8_t *)port_realloc(dma->buffer[0], max_buffer_length, true);
#else
dma->buffer[0] = (uint8_t *)m_realloc(dma->buffer[0],
#if MICROPY_MALLOC_USES_ALLOCATED_SIZE
dma->buffer_length[0], // Old size
#endif
max_buffer_length);
#endif
dma->buffer_length[0] = max_buffer_length;

if (dma->buffer[0] == NULL) {
return AUDIO_DMA_MEMORY_ERROR;
}

if (!single_buffer) {
#ifdef PICO_RP2350
dma->buffer[1] = (uint8_t *)port_realloc(dma->buffer[0], max_buffer_length, true);
#else
dma->buffer[1] = (uint8_t *)m_realloc(dma->buffer[0],
#if MICROPY_MALLOC_USES_ALLOCATED_SIZE
dma->buffer_length[1], // Old size
#endif
max_buffer_length);
#endif
dma->buffer[1] = (uint8_t *)port_realloc(dma->buffer[1], max_buffer_length, true);
dma->buffer_length[1] = max_buffer_length;

Expand Down Expand Up @@ -429,11 +446,27 @@ void audio_dma_init(audio_dma_t *dma) {
}

void audio_dma_deinit(audio_dma_t *dma) {
#ifdef PICO_RP2350
port_free(dma->buffer[0]);
#else
#if MICROPY_MALLOC_USES_ALLOCATED_SIZE
m_free(dma->buffer[0], dma->buffer_length[0]);
#else
m_free(dma->buffer[0]);
#endif
#endif
dma->buffer[0] = NULL;
dma->buffer_length[0] = 0;

#ifdef PICO_RP2350
port_free(dma->buffer[1]);
#else
#if MICROPY_MALLOC_USES_ALLOCATED_SIZE
m_free(dma->buffer[1], dma->buffer_length[1]);
#else
m_free(dma->buffer[1]);
#endif
#endif
dma->buffer[1] = NULL;
dma->buffer_length[1] = 0;
}
Expand Down
2 changes: 1 addition & 1 deletion ports/raspberrypi/audio_dma.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ typedef enum {

typedef struct {
mp_obj_t sample;
uint8_t *buffer[2]; // Allocated through port_malloc so they are dma-able
uint8_t *buffer[2]; // Allocated through port_malloc on RP2350 so they are dma-able
size_t buffer_length[2];
uint32_t channels_to_load_mask;
uint32_t output_register_address;
Expand Down
Loading