├── .gitignore └── src ├── I2S.h ├── I2S.cpp └── machine_i2s.c /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .DS_Store? 3 | .Trashes 4 | -------------------------------------------------------------------------------- /src/I2S.h: -------------------------------------------------------------------------------- 1 | /* 2 | I2S.h - 3 | I2S digital audio input Arduino library for the Raspberry Pi Pico RP2040 4 | 5 | Copyright (C) 2022 Sfera Labs S.r.l. - All rights reserved. 6 | 7 | For information, see: 8 | http://www.sferalabs.cc/ 9 | 10 | This code is free software; you can redistribute it and/or 11 | modify it under the terms of the GNU Lesser General Public 12 | License as published by the Free Software Foundation; either 13 | version 2.1 of the License, or (at your option) any later version. 14 | See file LICENSE.txt for further informations on licensing terms. 15 | */ 16 | 17 | #ifndef I2S_h 18 | #define I2S_h 19 | 20 | #include 21 | 22 | #define I2S_MODE_MONO 0 23 | #define I2S_MODE_STEREO 1 24 | 25 | class I2SClass { 26 | public: 27 | I2SClass(); 28 | 29 | bool setSCK(pin_size_t pin); 30 | bool setWS(pin_size_t pin); 31 | bool setSD(pin_size_t pin); 32 | bool setBufferSize(int bufferSize); 33 | bool begin(int mode, long sampleRate, int bitsPerSample); 34 | void end(); 35 | int read(void* buffer, size_t size); 36 | 37 | private: 38 | pin_size_t _pin_sck; 39 | pin_size_t _pin_ws; 40 | pin_size_t _pin_sd; 41 | int32_t _bufferSize; 42 | 43 | }; 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /src/I2S.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | I2S.cpp - 3 | I2S digital audio input Arduino library for the Raspberry Pi Pico RP2040 4 | 5 | Copyright (C) 2022 Sfera Labs S.r.l. - All rights reserved. 6 | 7 | For information, see: 8 | http://www.sferalabs.cc/ 9 | 10 | This code is free software; you can redistribute it and/or 11 | modify it under the terms of the GNU Lesser General Public 12 | License as published by the Free Software Foundation; either 13 | version 2.1 of the License, or (at your option) any later version. 14 | See file LICENSE.txt for further informations on licensing terms. 15 | */ 16 | 17 | #include "I2S.h" 18 | #include "machine_i2s.c" 19 | 20 | I2SClass::I2SClass() { 21 | } 22 | 23 | bool I2SClass::setSCK(pin_size_t pin) { 24 | _pin_sck = pin; 25 | return true; 26 | } 27 | 28 | bool I2SClass::setWS(pin_size_t pin) { 29 | _pin_ws = pin; 30 | return true; 31 | } 32 | 33 | bool I2SClass::setSD(pin_size_t pin) { 34 | _pin_sd = pin; 35 | return true; 36 | } 37 | 38 | bool I2SClass::setBufferSize(int bufferSize) { 39 | _bufferSize = bufferSize; 40 | return true; 41 | } 42 | 43 | bool I2SClass::begin(int mode, long sampleRate, int bitsPerSample) { 44 | format_t i2s_format = (mode == I2S_MODE_STEREO) ? STEREO : MONO; 45 | machine_i2s_obj_t* i2s0 = machine_i2s_make_new(0, _pin_sck, _pin_ws, _pin_sd, 46 | RX, bitsPerSample, i2s_format, _bufferSize, sampleRate); 47 | if (i2s0 == NULL) { 48 | return false; 49 | } 50 | return true; 51 | } 52 | 53 | void I2SClass::end() { 54 | machine_i2s_deinit(machine_i2s_obj[0]); 55 | } 56 | 57 | int I2SClass::read(void* buffer, size_t size) { 58 | return machine_i2s_stream_read(machine_i2s_obj[0], buffer, size); 59 | } 60 | -------------------------------------------------------------------------------- /src/machine_i2s.c: -------------------------------------------------------------------------------- 1 | /* 2 | machine_i2s.c - 3 | I2S digital audio input C library for the Raspberry Pi Pico RP2040 4 | 5 | Copyright (C) 2022 Sfera Labs S.r.l. - All rights reserved. 6 | 7 | For information, see: 8 | http://www.sferalabs.cc/ 9 | 10 | This code is adapted from the I2S implementation of the RP2 MicroPython port 11 | by Mike Teachman, available at: 12 | https://github.com/micropython/micropython/blob/master/ports/rp2/machine_i2s.c 13 | Retrieved on January 25 2022. 14 | */ 15 | 16 | /* Original header */ 17 | 18 | /* 19 | * This file is part of the MicroPython project, http://micropython.org/ 20 | * 21 | * The MIT License (MIT) 22 | * 23 | * Copyright (c) 2021 Mike Teachman 24 | * 25 | * Permission is hereby granted, free of charge, to any person obtaining a copy 26 | * of this software and associated documentation files (the "Software"), to deal 27 | * in the Software without restriction, including without limitation the rights 28 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 29 | * copies of the Software, and to permit persons to whom the Software is 30 | * furnished to do so, subject to the following conditions: 31 | * 32 | * The above copyright notice and this permission notice shall be included in 33 | * all copies or substantial portions of the Software. 34 | * 35 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 38 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 39 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 40 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 41 | * THE SOFTWARE. 42 | */ 43 | 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | 50 | #include "hardware/pio.h" 51 | #include "hardware/clocks.h" 52 | #include "hardware/gpio.h" 53 | #include "hardware/dma.h" 54 | #include "hardware/irq.h" 55 | 56 | #define MAX_I2S_RP2 (2) 57 | 58 | // The DMA buffer size was empirically determined. It is a tradeoff between: 59 | // 1. memory use (smaller buffer size desirable to reduce memory footprint) 60 | // 2. interrupt frequency (larger buffer size desirable to reduce interrupt frequency) 61 | #define SIZEOF_DMA_BUFFER_IN_BYTES (256) 62 | #define SIZEOF_HALF_DMA_BUFFER_IN_BYTES (SIZEOF_DMA_BUFFER_IN_BYTES / 2) 63 | #define I2S_NUM_DMA_CHANNELS (2) 64 | 65 | #define NUM_I2S_USER_FORMATS (4) 66 | #define I2S_RX_FRAME_SIZE_IN_BYTES (8) 67 | 68 | #define SAMPLES_PER_FRAME (2) 69 | #define PIO_INSTRUCTIONS_PER_BIT (2) 70 | 71 | #define STATIC static 72 | #define mp_hal_pin_obj_t uint 73 | #define m_new(type, num) ((type *)(malloc(sizeof(type) * (num)))) 74 | #define m_new_obj(type) (m_new(type, 1)) 75 | 76 | typedef enum { 77 | RX, 78 | TX 79 | } i2s_mode_t; 80 | 81 | typedef enum { 82 | MONO, 83 | STEREO 84 | } format_t; 85 | 86 | typedef enum { 87 | BLOCKING, 88 | NON_BLOCKING, 89 | UASYNCIO 90 | } io_mode_t; 91 | 92 | typedef enum { 93 | GP_INPUT = 0, 94 | GP_OUTPUT = 1 95 | } gpio_dir_t; 96 | 97 | typedef struct _ring_buf_t { 98 | uint8_t *buffer; 99 | size_t head; 100 | size_t tail; 101 | size_t size; 102 | } ring_buf_t; 103 | 104 | typedef struct _machine_i2s_obj_t { 105 | uint8_t i2s_id; 106 | mp_hal_pin_obj_t sck; 107 | mp_hal_pin_obj_t ws; 108 | mp_hal_pin_obj_t sd; 109 | i2s_mode_t mode; 110 | int8_t bits; 111 | format_t format; 112 | int32_t rate; 113 | int32_t ibuf; 114 | io_mode_t io_mode; 115 | PIO pio; 116 | uint8_t sm; 117 | const pio_program_t *pio_program; 118 | uint prog_offset; 119 | int dma_channel[I2S_NUM_DMA_CHANNELS]; 120 | uint8_t dma_buffer[SIZEOF_DMA_BUFFER_IN_BYTES]; 121 | ring_buf_t ring_buffer; 122 | uint8_t *ring_buffer_storage; 123 | } machine_i2s_obj_t; 124 | 125 | // Buffer protocol 126 | typedef struct _mp_buffer_info_t { 127 | void *buf; // can be NULL if len == 0 128 | size_t len; // in bytes 129 | int typecode; // as per binary.h 130 | } mp_buffer_info_t; 131 | 132 | STATIC machine_i2s_obj_t* machine_i2s_obj[MAX_I2S_RP2] = {NULL, NULL}; 133 | 134 | // The frame map is used with the readinto() method to transform the audio sample data coming 135 | // from DMA memory (32-bit stereo) to the format specified 136 | // in the I2S constructor. e.g. 16-bit mono 137 | STATIC const int8_t i2s_frame_map[NUM_I2S_USER_FORMATS][I2S_RX_FRAME_SIZE_IN_BYTES] = { 138 | {-1, -1, 0, 1, -1, -1, -1, -1 }, // Mono, 16-bits 139 | { 0, 1, 2, 3, -1, -1, -1, -1 }, // Mono, 32-bits 140 | {-1, -1, 0, 1, -1, -1, 2, 3 }, // Stereo, 16-bits 141 | { 0, 1, 2, 3, 4, 5, 6, 7 }, // Stereo, 32-bits 142 | }; 143 | 144 | STATIC const PIO pio_instances[NUM_PIOS] = {pio0, pio1}; 145 | 146 | // PIO program for 16-bit write 147 | // set(x, 14) .side(0b01) 148 | // label('left_channel') 149 | // out(pins, 1) .side(0b00) 150 | // jmp(x_dec, "left_channel") .side(0b01) 151 | // out(pins, 1) .side(0b10) 152 | // set(x, 14) .side(0b11) 153 | // label('right_channel') 154 | // out(pins, 1) .side(0b10) 155 | // jmp(x_dec, "right_channel") .side(0b11) 156 | // out(pins, 1) .side(0b00) 157 | STATIC const uint16_t pio_instructions_write_16[] = {59438, 24577, 2113, 28673, 63534, 28673, 6213, 24577}; 158 | STATIC const pio_program_t pio_write_16 = { 159 | pio_instructions_write_16, 160 | sizeof(pio_instructions_write_16) / sizeof(uint16_t), 161 | -1 162 | }; 163 | 164 | // PIO program for 32-bit write 165 | // set(x, 30) .side(0b01) 166 | // label('left_channel') 167 | // out(pins, 1) .side(0b00) 168 | // jmp(x_dec, "left_channel") .side(0b01) 169 | // out(pins, 1) .side(0b10) 170 | // set(x, 30) .side(0b11) 171 | // label('right_channel') 172 | // out(pins, 1) .side(0b10) 173 | // jmp(x_dec, "right_channel") .side(0b11) 174 | // out(pins, 1) .side(0b00) 175 | STATIC const uint16_t pio_instructions_write_32[] = {59454, 24577, 2113, 28673, 63550, 28673, 6213, 24577}; 176 | STATIC const pio_program_t pio_write_32 = { 177 | pio_instructions_write_32, 178 | sizeof(pio_instructions_write_32) / sizeof(uint16_t), 179 | -1 180 | }; 181 | 182 | // PIO program for 32-bit read 183 | // set(x, 30) .side(0b00) 184 | // label('left_channel') 185 | // in_(pins, 1) .side(0b01) 186 | // jmp(x_dec, "left_channel") .side(0b00) 187 | // in_(pins, 1) .side(0b11) 188 | // set(x, 30) .side(0b10) 189 | // label('right_channel') 190 | // in_(pins, 1) .side(0b11) 191 | // jmp(x_dec, "right_channel") .side(0b10) 192 | // in_(pins, 1) .side(0b01) 193 | STATIC const uint16_t pio_instructions_read_32[] = {57406, 18433, 65, 22529, 61502, 22529, 4165, 18433}; 194 | STATIC const pio_program_t pio_read_32 = { 195 | pio_instructions_read_32, 196 | sizeof(pio_instructions_read_32) / sizeof(uint16_t), 197 | -1 198 | }; 199 | 200 | STATIC uint8_t dma_get_bits(i2s_mode_t mode, int8_t bits); 201 | STATIC void dma_irq0_handler(void); 202 | STATIC void dma_irq1_handler(void); 203 | STATIC void machine_i2s_deinit(machine_i2s_obj_t *self); 204 | 205 | // Ring Buffer 206 | // Thread safe when used with these constraints: 207 | // - Single Producer, Single Consumer 208 | // - Sequential atomic operations 209 | // One byte of capacity is used to detect buffer empty/full 210 | 211 | STATIC void ringbuf_init(ring_buf_t *rbuf, uint8_t *buffer, size_t size) { 212 | rbuf->buffer = buffer; 213 | rbuf->size = size; 214 | rbuf->head = 0; 215 | rbuf->tail = 0; 216 | } 217 | 218 | STATIC bool ringbuf_push(ring_buf_t *rbuf, uint8_t data) { 219 | size_t next_tail = (rbuf->tail + 1) % rbuf->size; 220 | 221 | if (next_tail != rbuf->head) { 222 | rbuf->buffer[rbuf->tail] = data; 223 | rbuf->tail = next_tail; 224 | return true; 225 | } 226 | 227 | // full 228 | return false; 229 | } 230 | 231 | STATIC bool ringbuf_pop(ring_buf_t *rbuf, uint8_t *data) { 232 | if (rbuf->head == rbuf->tail) { 233 | // empty 234 | return false; 235 | } 236 | 237 | *data = rbuf->buffer[rbuf->head]; 238 | rbuf->head = (rbuf->head + 1) % rbuf->size; 239 | return true; 240 | } 241 | 242 | STATIC bool ringbuf_is_empty(ring_buf_t *rbuf) { 243 | return rbuf->head == rbuf->tail; 244 | } 245 | 246 | STATIC bool ringbuf_is_full(ring_buf_t *rbuf) { 247 | return ((rbuf->tail + 1) % rbuf->size) == rbuf->head; 248 | } 249 | 250 | STATIC size_t ringbuf_available_data(ring_buf_t *rbuf) { 251 | return (rbuf->tail - rbuf->head + rbuf->size) % rbuf->size; 252 | } 253 | 254 | STATIC size_t ringbuf_available_space(ring_buf_t *rbuf) { 255 | return rbuf->size - ringbuf_available_data(rbuf) - 1; 256 | } 257 | 258 | STATIC int8_t get_frame_mapping_index(int8_t bits, format_t format) { 259 | if (format == MONO) { 260 | if (bits == 16) { 261 | return 0; 262 | } else { // 32 bits 263 | return 1; 264 | } 265 | } else { // STEREO 266 | if (bits == 16) { 267 | return 2; 268 | } else { // 32 bits 269 | return 3; 270 | } 271 | } 272 | } 273 | 274 | STATIC uint32_t fill_appbuf_from_ringbuf(machine_i2s_obj_t *self, mp_buffer_info_t *appbuf) { 275 | 276 | // copy audio samples from the ring buffer to the app buffer 277 | // loop, copying samples until the app buffer is filled 278 | // For uasyncio mode, the loop will make an early exit if the ring buffer becomes empty 279 | // Example: 280 | // a MicroPython I2S object is configured for 16-bit mono (2 bytes per audio sample). 281 | // For every frame coming from the ring buffer (8 bytes), 2 bytes are "cherry picked" and 282 | // copied to the supplied app buffer. 283 | // Thus, for every 1 byte copied to the app buffer, 4 bytes are read from the ring buffer. 284 | // If a 8kB app buffer is supplied, 32kB of audio samples is read from the ring buffer. 285 | 286 | uint32_t num_bytes_copied_to_appbuf = 0; 287 | uint8_t *app_p = (uint8_t *)appbuf->buf; 288 | uint8_t appbuf_sample_size_in_bytes = (self->bits == 16? 2 : 4) * (self->format == STEREO ? 2: 1); 289 | uint32_t num_bytes_needed_from_ringbuf = appbuf->len * (I2S_RX_FRAME_SIZE_IN_BYTES / appbuf_sample_size_in_bytes); 290 | uint8_t discard_byte; 291 | while (num_bytes_needed_from_ringbuf) { 292 | 293 | uint8_t f_index = get_frame_mapping_index(self->bits, self->format); 294 | 295 | for (uint8_t i = 0; i < I2S_RX_FRAME_SIZE_IN_BYTES; i++) { 296 | int8_t r_to_a_mapping = i2s_frame_map[f_index][i]; 297 | if (r_to_a_mapping != -1) { 298 | if (self->io_mode == BLOCKING) { 299 | // poll the ringbuf until a sample becomes available, copy into appbuf using the mapping transform 300 | while (ringbuf_pop(&self->ring_buffer, app_p + r_to_a_mapping) == false) { 301 | ; 302 | } 303 | num_bytes_copied_to_appbuf++; 304 | } else if (self->io_mode == UASYNCIO) { 305 | if (ringbuf_pop(&self->ring_buffer, app_p + r_to_a_mapping) == false) { 306 | // ring buffer is empty, exit 307 | goto exit; 308 | } else { 309 | num_bytes_copied_to_appbuf++; 310 | } 311 | } else { 312 | return 0; // should never get here (non-blocking mode does not use this function) 313 | } 314 | } else { // r_a_mapping == -1 315 | // discard unused byte from ring buffer 316 | if (self->io_mode == BLOCKING) { 317 | // poll the ringbuf until a sample becomes available 318 | while (ringbuf_pop(&self->ring_buffer, &discard_byte) == false) { 319 | ; 320 | } 321 | } else if (self->io_mode == UASYNCIO) { 322 | if (ringbuf_pop(&self->ring_buffer, &discard_byte) == false) { 323 | // ring buffer is empty, exit 324 | goto exit; 325 | } 326 | } else { 327 | return 0; // should never get here (non-blocking mode does not use this function) 328 | } 329 | } 330 | num_bytes_needed_from_ringbuf--; 331 | } 332 | app_p += appbuf_sample_size_in_bytes; 333 | } 334 | exit: 335 | return num_bytes_copied_to_appbuf; 336 | } 337 | 338 | STATIC uint32_t copy_appbuf_to_ringbuf(machine_i2s_obj_t *self, mp_buffer_info_t *appbuf) { 339 | 340 | // copy audio samples from the app buffer to the ring buffer 341 | // loop, reading samples until the app buffer is emptied 342 | // for uasyncio mode, the loop will make an early exit if the ring buffer becomes full 343 | 344 | uint32_t a_index = 0; 345 | 346 | while (a_index < appbuf->len) { 347 | if (self->io_mode == BLOCKING) { 348 | // copy a byte to the ringbuf when space becomes available 349 | while (ringbuf_push(&self->ring_buffer, ((uint8_t *)appbuf->buf)[a_index]) == false) { 350 | ; 351 | } 352 | a_index++; 353 | } else if (self->io_mode == UASYNCIO) { 354 | if (ringbuf_push(&self->ring_buffer, ((uint8_t *)appbuf->buf)[a_index]) == false) { 355 | // ring buffer is full, exit 356 | break; 357 | } else { 358 | a_index++; 359 | } 360 | } else { 361 | return 0; // should never get here (non-blocking mode does not use this function) 362 | } 363 | } 364 | 365 | return a_index; 366 | } 367 | 368 | // function is used in IRQ context 369 | STATIC void empty_dma(machine_i2s_obj_t *self, uint8_t *dma_buffer_p) { 370 | // when space exists, copy samples into ring buffer 371 | if (ringbuf_available_space(&self->ring_buffer) >= SIZEOF_HALF_DMA_BUFFER_IN_BYTES) { 372 | for (uint32_t i = 0; i < SIZEOF_HALF_DMA_BUFFER_IN_BYTES; i++) { 373 | ringbuf_push(&self->ring_buffer, dma_buffer_p[i]); 374 | } 375 | } 376 | } 377 | 378 | // function is used in IRQ context 379 | STATIC void feed_dma(machine_i2s_obj_t *self, uint8_t *dma_buffer_p) { 380 | // when data exists, copy samples from ring buffer 381 | if (ringbuf_available_data(&self->ring_buffer) >= SIZEOF_HALF_DMA_BUFFER_IN_BYTES) { 382 | 383 | // copy a block of samples from the ring buffer to the dma buffer. 384 | // STM32 HAL API has a stereo I2S implementation, but not mono 385 | // mono format is implemented by duplicating each sample into both L and R channels. 386 | if ((self->format == MONO) && (self->bits == 16)) { 387 | for (uint32_t i = 0; i < SIZEOF_HALF_DMA_BUFFER_IN_BYTES / 4; i++) { 388 | for (uint8_t b = 0; b < sizeof(uint16_t); b++) { 389 | ringbuf_pop(&self->ring_buffer, &dma_buffer_p[i * 4 + b]); 390 | dma_buffer_p[i * 4 + b + 2] = dma_buffer_p[i * 4 + b]; // duplicated mono sample 391 | } 392 | } 393 | } else if ((self->format == MONO) && (self->bits == 32)) { 394 | for (uint32_t i = 0; i < SIZEOF_HALF_DMA_BUFFER_IN_BYTES / 8; i++) { 395 | for (uint8_t b = 0; b < sizeof(uint32_t); b++) { 396 | ringbuf_pop(&self->ring_buffer, &dma_buffer_p[i * 8 + b]); 397 | dma_buffer_p[i * 8 + b + 4] = dma_buffer_p[i * 8 + b]; // duplicated mono sample 398 | } 399 | } 400 | } else { // STEREO, both 16-bit and 32-bit 401 | for (uint32_t i = 0; i < SIZEOF_HALF_DMA_BUFFER_IN_BYTES; i++) { 402 | ringbuf_pop(&self->ring_buffer, &dma_buffer_p[i]); 403 | } 404 | } 405 | } else { 406 | // underflow. clear buffer to transmit "silence" on the I2S bus 407 | memset(dma_buffer_p, 0, SIZEOF_HALF_DMA_BUFFER_IN_BYTES); 408 | } 409 | } 410 | 411 | STATIC void irq_configure(machine_i2s_obj_t *self) { 412 | if (self->i2s_id == 0) { 413 | irq_set_exclusive_handler(DMA_IRQ_0, dma_irq0_handler); 414 | irq_set_enabled(DMA_IRQ_0, true); 415 | } else { 416 | irq_set_exclusive_handler(DMA_IRQ_1, dma_irq1_handler); 417 | irq_set_enabled(DMA_IRQ_1, true); 418 | } 419 | } 420 | 421 | STATIC void irq_deinit(machine_i2s_obj_t *self) { 422 | if (self->i2s_id == 0) { 423 | irq_set_enabled(DMA_IRQ_0, false); 424 | irq_remove_handler(DMA_IRQ_0, dma_irq0_handler); 425 | } else { 426 | irq_set_enabled(DMA_IRQ_1, false); 427 | irq_remove_handler(DMA_IRQ_1, dma_irq1_handler); 428 | } 429 | } 430 | 431 | STATIC int pio_configure(machine_i2s_obj_t *self) { 432 | if (self->mode == TX) { 433 | if (self->bits == 16) { 434 | self->pio_program = &pio_write_16; 435 | } else { 436 | self->pio_program = &pio_write_32; 437 | } 438 | } else { // RX 439 | self->pio_program = &pio_read_32; 440 | } 441 | 442 | // find a PIO with a free state machine and adequate program space 443 | PIO candidate_pio; 444 | bool is_free_sm; 445 | bool can_add_program; 446 | for (uint8_t p = 0; p < NUM_PIOS; p++) { 447 | candidate_pio = pio_instances[p]; 448 | is_free_sm = false; 449 | can_add_program = false; 450 | 451 | for (uint8_t sm = 0; sm < NUM_PIO_STATE_MACHINES; sm++) { 452 | if (!pio_sm_is_claimed(candidate_pio, sm)) { 453 | is_free_sm = true; 454 | break; 455 | } 456 | } 457 | 458 | if (pio_can_add_program(candidate_pio, self->pio_program)) { 459 | can_add_program = true; 460 | } 461 | 462 | if (is_free_sm && can_add_program) { 463 | break; 464 | } 465 | } 466 | 467 | if (!is_free_sm) { 468 | return -1; 469 | } 470 | 471 | if (!can_add_program) { 472 | return -2; 473 | } 474 | 475 | self->pio = candidate_pio; 476 | self->sm = pio_claim_unused_sm(self->pio, false); 477 | self->prog_offset = pio_add_program(self->pio, self->pio_program); 478 | pio_sm_init(self->pio, self->sm, self->prog_offset, NULL); 479 | 480 | pio_sm_config config = pio_get_default_sm_config(); 481 | 482 | float pio_freq = self->rate * 483 | SAMPLES_PER_FRAME * 484 | dma_get_bits(self->mode, self->bits) * 485 | PIO_INSTRUCTIONS_PER_BIT; 486 | float clkdiv = clock_get_hz(clk_sys) / pio_freq; 487 | sm_config_set_clkdiv(&config, clkdiv); 488 | 489 | if (self->mode == TX) { 490 | sm_config_set_out_pins(&config, self->sd, 1); 491 | sm_config_set_out_shift(&config, false, true, dma_get_bits(self->mode, self->bits)); 492 | sm_config_set_fifo_join(&config, PIO_FIFO_JOIN_TX); // double TX FIFO size 493 | } else { // RX 494 | sm_config_set_in_pins(&config, self->sd); 495 | sm_config_set_in_shift(&config, false, true, dma_get_bits(self->mode, self->bits)); 496 | sm_config_set_fifo_join(&config, PIO_FIFO_JOIN_RX); // double RX FIFO size 497 | } 498 | 499 | sm_config_set_sideset(&config, 2, false, false); 500 | sm_config_set_sideset_pins(&config, self->sck); 501 | sm_config_set_wrap(&config, self->prog_offset, self->prog_offset + self->pio_program->length - 1); 502 | pio_sm_set_config(self->pio, self->sm, &config); 503 | 504 | return 0; 505 | } 506 | 507 | STATIC void pio_deinit(machine_i2s_obj_t *self) { 508 | if (self->pio) { 509 | pio_sm_set_enabled(self->pio, self->sm, false); 510 | pio_sm_unclaim(self->pio, self->sm); 511 | pio_remove_program(self->pio, self->pio_program, self->prog_offset); 512 | } 513 | } 514 | 515 | STATIC void gpio_init_i2s(PIO pio, uint8_t sm, mp_hal_pin_obj_t pin_num, uint8_t pin_val, gpio_dir_t pin_dir) { 516 | uint32_t pinmask = 1 << pin_num; 517 | pio_sm_set_pins_with_mask(pio, sm, pin_val << pin_num, pinmask); 518 | pio_sm_set_pindirs_with_mask(pio, sm, pin_dir << pin_num, pinmask); 519 | pio_gpio_init(pio, pin_num); 520 | } 521 | 522 | STATIC void gpio_configure(machine_i2s_obj_t *self) { 523 | gpio_init_i2s(self->pio, self->sm, self->sck, 0, GP_OUTPUT); 524 | gpio_init_i2s(self->pio, self->sm, self->ws, 0, GP_OUTPUT); 525 | if (self->mode == TX) { 526 | gpio_init_i2s(self->pio, self->sm, self->sd, 0, GP_OUTPUT); 527 | } else { // RX 528 | gpio_init_i2s(self->pio, self->sm, self->sd, 0, GP_INPUT); 529 | } 530 | } 531 | 532 | STATIC uint8_t dma_get_bits(i2s_mode_t mode, int8_t bits) { 533 | if (mode == TX) { 534 | return bits; 535 | } else { // RX 536 | // always read 32 bit words for I2S e.g. I2S MEMS microphones 537 | return 32; 538 | } 539 | } 540 | 541 | // determine which DMA channel is associated to this IRQ 542 | STATIC uint dma_map_irq_to_channel(uint irq_index) { 543 | for (uint ch = 0; ch < NUM_DMA_CHANNELS; ch++) { 544 | if ((dma_irqn_get_channel_status(irq_index, ch))) { 545 | return ch; 546 | } 547 | } 548 | // This should never happen 549 | return -1; 550 | } 551 | 552 | // note: first DMA channel is mapped to the top half of buffer, second is mapped to the bottom half 553 | STATIC uint8_t *dma_get_buffer(machine_i2s_obj_t *i2s_obj, uint channel) { 554 | for (uint8_t ch = 0; ch < I2S_NUM_DMA_CHANNELS; ch++) { 555 | if (i2s_obj->dma_channel[ch] == channel) { 556 | return i2s_obj->dma_buffer + (SIZEOF_HALF_DMA_BUFFER_IN_BYTES * ch); 557 | } 558 | } 559 | // This should never happen 560 | return NULL; 561 | } 562 | 563 | STATIC int dma_configure(machine_i2s_obj_t *self) { 564 | uint8_t num_free_dma_channels = 0; 565 | for (uint8_t ch = 0; ch < NUM_DMA_CHANNELS; ch++) { 566 | if (!dma_channel_is_claimed(ch)) { 567 | num_free_dma_channels++; 568 | } 569 | } 570 | if (num_free_dma_channels < I2S_NUM_DMA_CHANNELS) { 571 | return -1; 572 | } 573 | 574 | for (uint8_t ch = 0; ch < I2S_NUM_DMA_CHANNELS; ch++) { 575 | self->dma_channel[ch] = dma_claim_unused_channel(false); 576 | } 577 | 578 | // The DMA channels are chained together. The first DMA channel is used to access 579 | // the top half of the DMA buffer. The second DMA channel accesses the bottom half of the DMA buffer. 580 | // With chaining, when one DMA channel has completed a data transfer, the other 581 | // DMA channel automatically starts a new data transfer. 582 | enum dma_channel_transfer_size dma_size = (dma_get_bits(self->mode, self->bits) == 16) ? DMA_SIZE_16 : DMA_SIZE_32; 583 | for (uint8_t ch = 0; ch < I2S_NUM_DMA_CHANNELS; ch++) { 584 | dma_channel_config dma_config = dma_channel_get_default_config(self->dma_channel[ch]); 585 | channel_config_set_transfer_data_size(&dma_config, dma_size); 586 | channel_config_set_chain_to(&dma_config, self->dma_channel[(ch + 1) % I2S_NUM_DMA_CHANNELS]); 587 | 588 | uint8_t *dma_buffer = self->dma_buffer + (SIZEOF_HALF_DMA_BUFFER_IN_BYTES * ch); 589 | if (self->mode == TX) { 590 | channel_config_set_dreq(&dma_config, pio_get_dreq(self->pio, self->sm, true)); 591 | channel_config_set_read_increment(&dma_config, true); 592 | channel_config_set_write_increment(&dma_config, false); 593 | dma_channel_configure(self->dma_channel[ch], 594 | &dma_config, 595 | (void *)&self->pio->txf[self->sm], // dest = PIO TX FIFO 596 | dma_buffer, // src = DMA buffer 597 | SIZEOF_HALF_DMA_BUFFER_IN_BYTES / (dma_get_bits(self->mode, self->bits) / 8), 598 | false); 599 | } else { // RX 600 | channel_config_set_dreq(&dma_config, pio_get_dreq(self->pio, self->sm, false)); 601 | channel_config_set_read_increment(&dma_config, false); 602 | channel_config_set_write_increment(&dma_config, true); 603 | dma_channel_configure(self->dma_channel[ch], 604 | &dma_config, 605 | dma_buffer, // dest = DMA buffer 606 | (void *)&self->pio->rxf[self->sm], // src = PIO RX FIFO 607 | SIZEOF_HALF_DMA_BUFFER_IN_BYTES / (dma_get_bits(self->mode, self->bits) / 8), 608 | false); 609 | } 610 | } 611 | 612 | for (uint8_t ch = 0; ch < I2S_NUM_DMA_CHANNELS; ch++) { 613 | dma_irqn_acknowledge_channel(self->i2s_id, self->dma_channel[ch]); // clear pending. e.g. from SPI 614 | dma_irqn_set_channel_enabled(self->i2s_id, self->dma_channel[ch], true); 615 | } 616 | 617 | return 0; 618 | } 619 | 620 | STATIC void dma_deinit(machine_i2s_obj_t *self) { 621 | for (uint8_t ch = 0; ch < I2S_NUM_DMA_CHANNELS; ch++) { 622 | int channel = self->dma_channel[ch]; 623 | 624 | // unchain the channel to prevent triggering a transfer in the chained-to channel 625 | dma_channel_config dma_config = dma_get_channel_config(channel); 626 | channel_config_set_chain_to(&dma_config, channel); 627 | dma_channel_set_config(channel, &dma_config, false); 628 | 629 | dma_irqn_set_channel_enabled(self->i2s_id, channel, false); 630 | dma_channel_abort(channel); // in case a transfer is in flight 631 | dma_channel_unclaim(channel); 632 | } 633 | } 634 | 635 | STATIC void dma_irq_handler(uint8_t irq_index) { 636 | int dma_channel = dma_map_irq_to_channel(irq_index); 637 | if (dma_channel == -1) { 638 | // This should never happen 639 | return; 640 | } 641 | 642 | machine_i2s_obj_t *self = machine_i2s_obj[irq_index]; 643 | if (self == NULL) { 644 | // This should never happen 645 | return; 646 | } 647 | 648 | uint8_t *dma_buffer = dma_get_buffer(self, dma_channel); 649 | if (dma_buffer == NULL) { 650 | // This should never happen 651 | return; 652 | } 653 | 654 | if (self->mode == RX) { 655 | empty_dma(self, dma_buffer); 656 | dma_irqn_acknowledge_channel(irq_index, dma_channel); 657 | dma_channel_set_write_addr(dma_channel, dma_buffer, false); 658 | } 659 | } 660 | 661 | STATIC void dma_irq0_handler(void) { 662 | dma_irq_handler(0); 663 | } 664 | 665 | STATIC void dma_irq1_handler(void) { 666 | dma_irq_handler(1); 667 | } 668 | 669 | 670 | STATIC int machine_i2s_init_helper(machine_i2s_obj_t *self, 671 | mp_hal_pin_obj_t sck, mp_hal_pin_obj_t ws, mp_hal_pin_obj_t sd, 672 | i2s_mode_t i2s_mode, int8_t i2s_bits, format_t i2s_format, 673 | int32_t ring_buffer_len, int32_t i2s_rate) { 674 | // 675 | // ---- Check validity of arguments ---- 676 | // 677 | 678 | // does WS pin follow SCK pin? 679 | // note: SCK and WS are implemented as PIO sideset pins. Sideset pins must be sequential. 680 | if (ws != (sck + 1)) { 681 | return -1; 682 | } 683 | 684 | // is Mode valid? 685 | if ((i2s_mode != RX) && 686 | (i2s_mode != TX)) { 687 | return -2; 688 | } 689 | 690 | // is Bits valid? 691 | if ((i2s_bits != 16) && 692 | (i2s_bits != 32)) { 693 | return -3; 694 | } 695 | 696 | // is Format valid? 697 | if ((i2s_format != MONO) && 698 | (i2s_format != STEREO)) { 699 | return -4; 700 | } 701 | 702 | // is Rate valid? 703 | // Not checked 704 | 705 | // is Ibuf valid? 706 | if (ring_buffer_len > 0) { 707 | self->ring_buffer_storage = m_new(uint8_t, ring_buffer_len); 708 | ; 709 | ringbuf_init(&self->ring_buffer, self->ring_buffer_storage, ring_buffer_len); 710 | } else { 711 | return -5; 712 | } 713 | 714 | self->sck = sck; 715 | self->ws = ws; 716 | self->sd = sd; 717 | self->mode = i2s_mode; 718 | self->bits = i2s_bits; 719 | self->format = i2s_format; 720 | self->rate = i2s_rate; 721 | self->ibuf = ring_buffer_len; 722 | self->io_mode = BLOCKING; 723 | 724 | irq_configure(self); 725 | int err = pio_configure(self); 726 | if (err != 0) { 727 | return err; 728 | } 729 | gpio_configure(self); 730 | err = dma_configure(self); 731 | if (err != 0) { 732 | return err; 733 | } 734 | 735 | pio_sm_set_enabled(self->pio, self->sm, true); 736 | dma_channel_start(self->dma_channel[0]); 737 | 738 | return 0; 739 | } 740 | 741 | STATIC machine_i2s_obj_t* machine_i2s_make_new(uint8_t i2s_id, 742 | mp_hal_pin_obj_t sck, mp_hal_pin_obj_t ws, mp_hal_pin_obj_t sd, 743 | i2s_mode_t i2s_mode, int8_t i2s_bits, format_t i2s_format, 744 | int32_t ring_buffer_len, int32_t i2s_rate) { 745 | if (i2s_id >= MAX_I2S_RP2) { 746 | return NULL; 747 | } 748 | 749 | machine_i2s_obj_t *self; 750 | if (machine_i2s_obj[i2s_id] == NULL) { 751 | self = m_new_obj(machine_i2s_obj_t); 752 | machine_i2s_obj[i2s_id] = self; 753 | self->i2s_id = i2s_id; 754 | } else { 755 | self = machine_i2s_obj[i2s_id]; 756 | machine_i2s_deinit(self); 757 | } 758 | 759 | if (machine_i2s_init_helper(self, sck, ws, sd, i2s_mode, i2s_bits, 760 | i2s_format, ring_buffer_len, i2s_rate) != 0) { 761 | return NULL; 762 | } 763 | return self; 764 | } 765 | 766 | STATIC void machine_i2s_deinit(machine_i2s_obj_t *self) { 767 | // use self->pio as in indication that I2S object has already been de-initialized 768 | if (self->pio != NULL) { 769 | pio_deinit(self); 770 | dma_deinit(self); 771 | irq_deinit(self); 772 | free(self->ring_buffer_storage); 773 | self->pio = NULL; // flag object as de-initialized 774 | } 775 | } 776 | 777 | STATIC int machine_i2s_stream_read(machine_i2s_obj_t *self, void *buf_in, size_t size) { 778 | if (self->mode != RX) { 779 | return -1; 780 | } 781 | 782 | uint8_t appbuf_sample_size_in_bytes = (self->bits / 8) * (self->format == STEREO ? 2: 1); 783 | if (size % appbuf_sample_size_in_bytes != 0) { 784 | return -2; 785 | } 786 | 787 | if (size == 0) { 788 | return 0; 789 | } 790 | 791 | mp_buffer_info_t appbuf; 792 | appbuf.buf = (void *)buf_in; 793 | appbuf.len = size; 794 | uint32_t num_bytes_read = fill_appbuf_from_ringbuf(self, &appbuf); 795 | return num_bytes_read; 796 | } 797 | --------------------------------------------------------------------------------