Files
audiorecorder/main/main.c
T
2026-11-04 21:43:25 +01:00

1430 lines
34 KiB
C

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "esp_log.h"
#include "esp_err.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "driver/i2s_common.h"
#include "driver/i2s_pdm.h"
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"
#include "driver/sdspi_host.h"
/* =======================================================
* Hardware configuration
* ======================================================= */
/* PDM microphones */
#define MIC_I2S I2S_NUM_0
#define MIC_CLK GPIO_NUM_4
#define MIC_DATA GPIO_NUM_5
/* SD card: SPI2 */
#define SD_PIN_CLK GPIO_NUM_17
#define SD_PIN_MISO GPIO_NUM_16
#define SD_PIN_MOSI GPIO_NUM_18
#define SD_PIN_CS GPIO_NUM_47
/* ST7735 display: SPI3 */
#define LCD_SPI_HOST SPI3_HOST
#define LCD_PIN_SCLK GPIO_NUM_10
#define LCD_PIN_MOSI GPIO_NUM_11
#define LCD_PIN_CS GPIO_NUM_12
#define LCD_PIN_DC GPIO_NUM_13
#define LCD_PIN_RST GPIO_NUM_14
#define LCD_WIDTH 160
#define LCD_HEIGHT 80
/*
* Change these if your particular ST7735 module has
* a GRAM offset. Some 160x80 panels use a non-zero
* column or row offset.
*/
#define LCD_X_OFFSET 1
#define LCD_Y_OFFSET 26
/* BOOT button */
#define BOOT_BUTTON GPIO_NUM_0
#define SD_MOUNT_POINT "/sdcard"
/* =======================================================
* Audio configuration
* ======================================================= */
#define SAMPLE_RATE 48000
#define CHANNELS 2
#define BITS_PER_SAMPLE 16
#define AUDIO_BYTES_PER_SEC \
(SAMPLE_RATE * CHANNELS * (BITS_PER_SAMPLE / 8))
/* =======================================================
* Buffer configuration
* ======================================================= */
#define AUDIO_BUFFER_SIZE 8192
#define AUDIO_BUFFER_COUNT 16
#define WAV_MAX_DATA_BYTES (3900ULL * 1024ULL * 1024ULL)
#define WAVE_SECONDS 2
#define WAVE_COLUMNS 150
#define WAVE_BUCKET_FRAMES ((SAMPLE_RATE * WAVE_SECONDS) / WAVE_COLUMNS)
static uint8_t audio_buffers[AUDIO_BUFFER_COUNT][AUDIO_BUFFER_SIZE];
static uint8_t discard_buffer[AUDIO_BUFFER_SIZE];
#define DROP_WINDOW_SECONDS 60
static uint32_t dropped_per_second[DROP_WINDOW_SECONDS];
static uint32_t drop_second_tag[DROP_WINDOW_SECONDS];
typedef struct {
uint8_t *data;
size_t length;
bool end;
} audio_block_t;
typedef struct {
int16_t min[CHANNELS];
int16_t max[CHANNELS];
} wave_column_t;
static QueueHandle_t free_buffers;
static QueueHandle_t ready_buffers;
static SemaphoreHandle_t writer_finished;
static volatile bool writer_failed = false;
static volatile bool recording_active = false;
static volatile uint64_t recorded_bytes = 0;
static volatile uint32_t recording_started = 0;
static volatile uint32_t dropped_buffers = 0;
static volatile uint64_t dropped_bytes = 0;
static char recording_filename[64] = "";
static wave_column_t wave[WAVE_COLUMNS];
static unsigned wave_head = 0;
static unsigned wave_filled = 1;
static unsigned wave_frame_count = 0;
static const char *TAG = "recorder";
/* =======================================================
* LCD colors
* ======================================================= */
#define LCD_BLACK 0x0000
#define LCD_WHITE 0xFFFF
#define LCD_RED 0xF800
#define LCD_GREEN 0x07E0
#define LCD_BLUE 0x001F
#define LCD_CYAN 0x07FF
#define LCD_YELLOW 0xFFE0
#define LCD_DARK_GRAY 0x4208
static spi_device_handle_t lcd_spi;
static uint16_t lcd_buffer[LCD_WIDTH * LCD_HEIGHT];
/* =======================================================
* LCD low-level driver
* ======================================================= */
static void lcd_command(uint8_t cmd)
{
gpio_set_level(LCD_PIN_DC, 0);
spi_transaction_t t = {
.length = 8,
.tx_buffer = &cmd
};
ESP_ERROR_CHECK(spi_device_polling_transmit(lcd_spi, &t));
}
static void lcd_data(const uint8_t *data, size_t len)
{
if (len == 0) {
return;
}
gpio_set_level(LCD_PIN_DC, 1);
spi_transaction_t t = {
.length = len * 8,
.tx_buffer = data
};
ESP_ERROR_CHECK(spi_device_polling_transmit(lcd_spi, &t));
}
static void lcd_data_byte(uint8_t data)
{
lcd_data(&data, 1);
}
static void lcd_init(void)
{
gpio_config_t gpio_cfg = {
.pin_bit_mask =
(1ULL << LCD_PIN_DC) |
(1ULL << LCD_PIN_RST),
.mode = GPIO_MODE_OUTPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE
};
ESP_ERROR_CHECK(gpio_config(&gpio_cfg));
spi_bus_config_t bus_cfg = {
.mosi_io_num = LCD_PIN_MOSI,
.miso_io_num = -1,
.sclk_io_num = LCD_PIN_SCLK,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = sizeof(lcd_buffer)
};
ESP_ERROR_CHECK(
spi_bus_initialize(
LCD_SPI_HOST,
&bus_cfg,
SPI_DMA_CH_AUTO
)
);
spi_device_interface_config_t dev_cfg = {
.clock_speed_hz = 40000000,
.mode = 0,
.spics_io_num = LCD_PIN_CS,
.queue_size = 1
};
ESP_ERROR_CHECK(
spi_bus_add_device(
LCD_SPI_HOST,
&dev_cfg,
&lcd_spi
)
);
gpio_set_level(LCD_PIN_RST, 0);
vTaskDelay(pdMS_TO_TICKS(100));
gpio_set_level(LCD_PIN_RST, 1);
vTaskDelay(pdMS_TO_TICKS(120));
lcd_command(0x01); // Software reset
vTaskDelay(pdMS_TO_TICKS(150));
lcd_command(0x11); // Sleep out
vTaskDelay(pdMS_TO_TICKS(120));
lcd_command(0x3A); // RGB565
lcd_data_byte(0x05);
lcd_command(0x36); // MADCTL
lcd_data_byte(0x68); // Landscape, BGR
lcd_command(0x21); // Display inversion
lcd_command(0x13); // Normal display mode
lcd_command(0x29); // Display ON
vTaskDelay(pdMS_TO_TICKS(100));
}
/* =======================================================
* LCD drawing
* ======================================================= */
/*
* Convert RGB565 to the byte order expected by ST7735.
*/
static uint16_t lcd_color(uint16_t color)
{
return (uint16_t)((color << 8) | (color >> 8));
}
static void lcd_pixel(int x, int y, uint16_t color)
{
if (x < 0 || x >= LCD_WIDTH ||
y < 0 || y >= LCD_HEIGHT) {
return;
}
lcd_buffer[y * LCD_WIDTH + x] = lcd_color(color);
}
static void lcd_clear(uint16_t color)
{
uint16_t c = lcd_color(color);
for (int i = 0; i < LCD_WIDTH * LCD_HEIGHT; i++) {
lcd_buffer[i] = c;
}
}
static void lcd_rect(int x, int y, int w, int h, uint16_t color)
{
for (int i = x; i < x + w; i++) {
lcd_pixel(i, y, color);
lcd_pixel(i, y + h - 1, color);
}
for (int i = y; i < y + h; i++) {
lcd_pixel(x, i, color);
lcd_pixel(x + w - 1, i, color);
}
}
static void lcd_fill_rect(int x, int y, int w, int h,
uint16_t color)
{
for (int j = y; j < y + h; j++) {
for (int i = x; i < x + w; i++) {
lcd_pixel(i, j, color);
}
}
}
static void lcd_set_window(int x0, int y0, int x1, int y1)
{
uint16_t ax0 = x0 + LCD_X_OFFSET;
uint16_t ax1 = x1 + LCD_X_OFFSET;
uint16_t ay0 = y0 + LCD_Y_OFFSET;
uint16_t ay1 = y1 + LCD_Y_OFFSET;
uint8_t data[4];
lcd_command(0x2A); // CASET
data[0] = ax0 >> 8;
data[1] = ax0;
data[2] = ax1 >> 8;
data[3] = ax1;
lcd_data(data, 4);
lcd_command(0x2B); // RASET
data[0] = ay0 >> 8;
data[1] = ay0;
data[2] = ay1 >> 8;
data[3] = ay1;
lcd_data(data, 4);
lcd_command(0x2C); // RAMWR
}
static void lcd_flush(void)
{
lcd_set_window(0, 0, LCD_WIDTH - 1, LCD_HEIGHT - 1);
gpio_set_level(LCD_PIN_DC, 1);
spi_transaction_t t = {
.length = sizeof(lcd_buffer) * 8,
.tx_buffer = lcd_buffer
};
ESP_ERROR_CHECK(spi_device_polling_transmit(lcd_spi, &t));
}
/* =======================================================
* Small 5x7 font
*
* Only the characters used by the status screen are
* included. Each byte represents one vertical column.
* ======================================================= */
static const uint8_t *font_get(char c)
{
static const uint8_t blank[5] = {0, 0, 0, 0, 0};
static const uint8_t digits[10][5] = {
{0x3E,0x51,0x49,0x45,0x3E}, // 0
{0x00,0x42,0x7F,0x40,0x00}, // 1
{0x42,0x61,0x51,0x49,0x46}, // 2
{0x21,0x41,0x45,0x4B,0x31}, // 3
{0x18,0x14,0x12,0x7F,0x10}, // 4
{0x27,0x45,0x45,0x45,0x39}, // 5
{0x3C,0x4A,0x49,0x49,0x30}, // 6
{0x01,0x71,0x09,0x05,0x03}, // 7
{0x36,0x49,0x49,0x49,0x36}, // 8
{0x06,0x49,0x49,0x29,0x1E} // 9
};
static const uint8_t letters[][5] = {
{0x7E,0x11,0x11,0x11,0x7E}, // A
{0x7F,0x49,0x49,0x49,0x36}, // B
{0x3E,0x41,0x41,0x41,0x22}, // C
{0x7F,0x41,0x41,0x22,0x1C}, // D
{0x7F,0x49,0x49,0x49,0x41}, // E
{0x7F,0x09,0x09,0x09,0x01}, // F
{0x3E,0x41,0x49,0x49,0x7A}, // G
{0x7F,0x08,0x08,0x08,0x7F}, // H
{0x00,0x41,0x7F,0x41,0x00}, // I
{0x20,0x40,0x41,0x3F,0x01}, // J
{0x7F,0x08,0x14,0x22,0x41}, // K
{0x7F,0x40,0x40,0x40,0x40}, // L
{0x7F,0x02,0x0C,0x02,0x7F}, // M
{0x7F,0x04,0x08,0x10,0x7F}, // N
{0x3E,0x41,0x41,0x41,0x3E}, // O
{0x7F,0x09,0x09,0x09,0x06}, // P
{0x3E,0x41,0x51,0x21,0x5E}, // Q
{0x7F,0x09,0x19,0x29,0x46}, // R
{0x46,0x49,0x49,0x49,0x31}, // S
{0x01,0x01,0x7F,0x01,0x01}, // T
{0x3F,0x40,0x40,0x40,0x3F}, // U
{0x1F,0x20,0x40,0x20,0x1F}, // V
{0x3F,0x40,0x38,0x40,0x3F}, // W
{0x63,0x14,0x08,0x14,0x63}, // X
{0x07,0x08,0x70,0x08,0x07}, // Y
{0x61,0x51,0x49,0x45,0x43} // Z
};
if (c >= '0' && c <= '9') {
return digits[c - '0'];
}
if (c >= 'A' && c <= 'Z') {
return letters[c - 'A'];
}
if (c == ':') {
static const uint8_t colon[5] = {
0, 0x36, 0x36, 0, 0
};
return colon;
}
if (c == '.') {
static const uint8_t dot[5] = {
0, 0x60, 0x60, 0, 0
};
return dot;
}
if (c == '-') {
static const uint8_t dash[5] = {
0x08, 0x08, 0x08, 0x08, 0x08
};
return dash;
}
return blank;
}
static void lcd_text(int x, int y, const char *str,
uint16_t color, int scale)
{
while (*str) {
const uint8_t *glyph = font_get(*str++);
for (int col = 0; col < 5; col++) {
for (int row = 0; row < 7; row++) {
if (glyph[col] & (1U << row)) {
lcd_fill_rect(
x + col * scale,
y + row * scale,
scale,
scale,
color
);
}
}
}
x += 6 * scale;
}
}
/* =======================================================
* Display test
* ======================================================= */
static void lcd_test_pattern(void)
{
lcd_clear(LCD_BLACK);
/* Outer boundary */
lcd_rect(0, 0, LCD_WIDTH, LCD_HEIGHT, LCD_WHITE);
/* Inner boundary */
lcd_rect(2, 2, LCD_WIDTH - 4, LCD_HEIGHT - 4, LCD_GREEN);
/* Corner markers */
lcd_fill_rect(5, 5, 10, 10, LCD_RED);
lcd_fill_rect(145, 5, 10, 10, LCD_BLUE);
lcd_fill_rect(5, 65, 10, 10, LCD_YELLOW);
lcd_fill_rect(145, 65, 10, 10, LCD_CYAN);
lcd_text(35, 30, "DISPLAY", LCD_WHITE, 1);
lcd_flush();
}
static uint32_t recording_elapsed_seconds(void)
{
return (xTaskGetTickCount() - recording_started) /
configTICK_RATE_HZ;
}
static void record_dropped_audio(size_t bytes)
{
if (bytes == 0) {
return;
}
dropped_buffers++;
dropped_bytes += bytes;
uint32_t sec = recording_elapsed_seconds();
unsigned index = sec % DROP_WINDOW_SECONDS;
if (drop_second_tag[index] != sec) {
drop_second_tag[index] = sec;
dropped_per_second[index] = 0;
}
dropped_per_second[index]++;
}
static uint32_t get_dropped_last_minute(void)
{
uint32_t now = recording_elapsed_seconds();
uint32_t total = 0;
for (unsigned i = 0; i < DROP_WINDOW_SECONDS; i++) {
uint32_t sec = drop_second_tag[i];
if (sec != UINT32_MAX &&
now >= sec &&
now - sec < DROP_WINDOW_SECONDS) {
total += dropped_per_second[i];
}
}
return total;
}
static int waveform_y(int16_t sample, int center,
int height, int32_t scale)
{
int y = center - ((int32_t)sample * height) / (2 * scale);
if (y < center - height / 2) {
y = center - height / 2;
}
if (y > center + height / 2) {
y = center + height / 2;
}
return y;
}
static void waveform_reset_column(unsigned index)
{
for (int ch = 0; ch < CHANNELS; ch++) {
wave[index].min[ch] = INT16_MAX;
wave[index].max[ch] = INT16_MIN;
}
}
static void waveform_init(void)
{
memset(wave, 0, sizeof(wave));
for (unsigned i = 0; i < WAVE_COLUMNS; i++) {
waveform_reset_column(i);
}
wave_head = 0;
wave_filled = 1;
wave_frame_count = 0;
}
/* Called for each captured audio buffer. */
static void waveform_update(const int16_t *samples, size_t bytes)
{
size_t frames = bytes / (CHANNELS * sizeof(int16_t));
for (size_t i = 0; i < frames; i++) {
for (int ch = 0; ch < CHANNELS; ch++) {
int16_t s = samples[i * CHANNELS + ch];
if (s < wave[wave_head].min[ch]) {
wave[wave_head].min[ch] = s;
}
if (s > wave[wave_head].max[ch]) {
wave[wave_head].max[ch] = s;
}
}
if (++wave_frame_count >= WAVE_BUCKET_FRAMES) {
wave_frame_count = 0;
wave_head = (wave_head + 1) % WAVE_COLUMNS;
if (wave_filled < WAVE_COLUMNS) {
wave_filled++;
}
waveform_reset_column(wave_head);
}
}
}
static void lcd_draw_waveform(int channel, int y_top,
uint16_t color,
uint32_t *max_deviation)
{
const int height = 12;
const int center = y_top + height / 2;
uint32_t peak = 0;
/* Find maximum deviation over the visible window. */
for (unsigned i = 0; i < wave_filled; i++) {
unsigned index = wave_filled == WAVE_COLUMNS
? (wave_head + 1 + i) % WAVE_COLUMNS
: i;
int32_t lo = wave[index].min[channel];
int32_t hi = wave[index].max[channel];
uint32_t a = lo < 0 ? -lo : lo;
uint32_t b = hi < 0 ? -hi : hi;
if (a > peak) peak = a;
if (b > peak) peak = b;
}
*max_deviation = peak;
/* Minimum scale keeps quiet waveforms visible. */
int32_t scale = peak < 512 ? 512 : peak;
lcd_fill_rect(5, y_top, WAVE_COLUMNS, height, LCD_BLACK);
/* Zero reference line. */
for (int x = 0; x < WAVE_COLUMNS; x++) {
lcd_pixel(5 + x, center, LCD_DARK_GRAY);
}
/* Draw oldest column on the left, newest on the right. */
for (unsigned i = 0; i < wave_filled; i++) {
unsigned index = wave_filled == WAVE_COLUMNS
? (wave_head + 1 + i) % WAVE_COLUMNS
: i;
int y_min = waveform_y(
wave[index].min[channel], center, height, scale);
int y_max = waveform_y(
wave[index].max[channel], center, height, scale);
for (int y = y_max; y <= y_min; y++) {
lcd_pixel(5 + i, y, color);
}
}
}
/* =======================================================
* Status display
* ======================================================= */
static void lcd_update_status(void)
{
lcd_clear(LCD_BLACK);
if (recording_active) {
lcd_fill_rect(5, 5, 7, 7, LCD_RED);
lcd_text(16, 5, "REC", LCD_RED, 1);
} else {
lcd_fill_rect(5, 5, 7, 7, LCD_GREEN);
lcd_text(16, 5, "STOP", LCD_GREEN, 1);
}
/* Recorded megabytes */
char size_text[30];
snprintf(size_text, sizeof(size_text),
"%06.1fMB",
(double)recorded_bytes / (1024.0 * 1024.0));
lcd_text(48, 5, size_text, LCD_CYAN, 1);
uint32_t elapsed = 0;
if (recording_active) {
elapsed = (xTaskGetTickCount() - recording_started) /
configTICK_RATE_HZ;
}
char time_text[20];
snprintf(time_text, sizeof(time_text),
"%02" PRIu32 ":%02" PRIu32 ":%02" PRIu32,
elapsed / 3600,
(elapsed / 60) % 60,
elapsed % 60);
lcd_text(105, 5, time_text, LCD_WHITE, 1);
uint32_t peak_l = 0;
uint32_t peak_r = 0;
/* Left microphone waveform. */
lcd_draw_waveform(0, 17, LCD_CYAN, &peak_l);
/* Right microphone waveform. */
lcd_draw_waveform(1, 37, LCD_YELLOW, &peak_r);
char level_text[24];
snprintf(level_text, sizeof(level_text),
"L MAX %05" PRIu32, peak_l);
lcd_text(5, 52, level_text, LCD_CYAN, 1);
snprintf(level_text, sizeof(level_text),
"R MAX %05" PRIu32, peak_r);
lcd_text(5, 62, level_text, LCD_YELLOW, 1);
char dropped_text[24];
snprintf(dropped_text, sizeof(dropped_text),
"D %05" PRIu32, dropped_buffers);
lcd_text(5, 72, dropped_text,
dropped_buffers ? LCD_RED : LCD_GREEN, 1);
snprintf(dropped_text, sizeof(dropped_text),
"1M %05" PRIu32, get_dropped_last_minute());
lcd_text(90, 72, dropped_text,
get_dropped_last_minute() ? LCD_RED : LCD_GREEN, 1);
lcd_flush();
}
/* =======================================================
* WAV file handling
* ======================================================= */
typedef struct __attribute__((packed)) {
char riff[4];
uint32_t file_size;
char wave[4];
char fmt[4];
uint32_t fmt_size;
uint16_t audio_format;
uint16_t channels;
uint32_t sample_rate;
uint32_t byte_rate;
uint16_t block_align;
uint16_t bits_per_sample;
char data[4];
uint32_t data_size;
} wav_header_t;
_Static_assert(sizeof(wav_header_t) == 44,
"WAV header must be 44 bytes");
static bool write_wav_header(FILE *fp, uint32_t data_size)
{
wav_header_t h = {
.riff = {'R', 'I', 'F', 'F'},
.file_size = 36 + data_size,
.wave = {'W', 'A', 'V', 'E'},
.fmt = {'f', 'm', 't', ' '},
.fmt_size = 16,
.audio_format = 1,
.channels = CHANNELS,
.sample_rate = SAMPLE_RATE,
.byte_rate = AUDIO_BYTES_PER_SEC,
.block_align = CHANNELS * (BITS_PER_SAMPLE / 8),
.bits_per_sample = BITS_PER_SAMPLE,
.data = {'d', 'a', 't', 'a'},
.data_size = data_size
};
if (fseek(fp, 0, SEEK_SET) != 0) {
return false;
}
if (fwrite(&h, sizeof(h), 1, fp) != 1) {
return false;
}
return true;
}
/* =======================================================
* Recording file management
* ======================================================= */
static FILE *open_next_recording(char *filename,
size_t filename_size)
{
for (unsigned int i = 0; i < 1000; i++) {
char short_name[20];
snprintf(short_name, sizeof(short_name),
"REC%03u.WAV", i);
snprintf(filename, filename_size,
SD_MOUNT_POINT "/%s", short_name);
FILE *test = fopen(filename, "rb");
if (test) {
fclose(test);
continue;
}
FILE *fp = fopen(filename, "wb");
if (!fp) {
ESP_LOGE(TAG, "Cannot create %s", filename);
return NULL;
}
static uint8_t stdio_buffer[32768];
if (setvbuf(fp, (char *)stdio_buffer, _IOFBF,
sizeof(stdio_buffer)) != 0) {
ESP_LOGW(TAG, "Could not configure stdio buffer");
}
if (!write_wav_header(fp, 0)) {
fclose(fp);
return NULL;
}
fflush(fp);
strlcpy(recording_filename, short_name,
sizeof(recording_filename));
recorded_bytes = 0;
ESP_LOGI(TAG, "Recording file: %s", filename);
return fp;
}
ESP_LOGE(TAG, "No available RECxxx.WAV filename");
return NULL;
}
static bool finalize_recording(FILE **fp, uint32_t audio_bytes)
{
if (!*fp) {
return true;
}
bool ok = write_wav_header(*fp, audio_bytes);
if (fflush(*fp) != 0) {
ok = false;
}
if (fsync(fileno(*fp)) != 0) {
ok = false;
}
if (fclose(*fp) != 0) {
ok = false;
}
*fp = NULL;
return ok;
}
/* =======================================================
* SD card initialization
* ======================================================= */
static sdmmc_card_t *sd_card;
static esp_err_t init_sd_card(void)
{
spi_bus_config_t bus_cfg = {
.mosi_io_num = SD_PIN_MOSI,
.miso_io_num = SD_PIN_MISO,
.sclk_io_num = SD_PIN_CLK,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
.max_transfer_sz = 32768
};
esp_err_t ret = spi_bus_initialize(
SPI2_HOST,
&bus_cfg,
SDSPI_DEFAULT_DMA
);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "SD SPI init failed: %s",
esp_err_to_name(ret));
return ret;
}
sdmmc_host_t host = SDSPI_HOST_DEFAULT();
host.slot = SPI2_HOST;
host.max_freq_khz = 20000;
sdspi_device_config_t slot_config =
SDSPI_DEVICE_CONFIG_DEFAULT();
slot_config.gpio_cs = SD_PIN_CS;
slot_config.host_id = SPI2_HOST;
esp_vfs_fat_sdmmc_mount_config_t mount_config = {
.format_if_mount_failed = false,
.max_files = 4,
.allocation_unit_size = 16 * 1024
};
ret = esp_vfs_fat_sdspi_mount(
SD_MOUNT_POINT,
&host,
&slot_config,
&mount_config,
&sd_card
);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "SD mount failed: %s",
esp_err_to_name(ret));
return ret;
}
sdmmc_card_print_info(stdout, sd_card);
return ESP_OK;
}
/* =======================================================
* Microphone initialization
* ======================================================= */
static i2s_chan_handle_t mic_rx;
static esp_err_t init_microphones(void)
{
i2s_chan_config_t chan_cfg =
I2S_CHANNEL_DEFAULT_CONFIG(MIC_I2S, I2S_ROLE_MASTER);
chan_cfg.dma_desc_num = 8;
chan_cfg.dma_frame_num = 1023;
esp_err_t ret = i2s_new_channel(
&chan_cfg,
NULL,
&mic_rx
);
if (ret != ESP_OK) {
return ret;
}
i2s_pdm_rx_config_t pdm_cfg = {
.clk_cfg =
I2S_PDM_RX_CLK_DEFAULT_CONFIG(SAMPLE_RATE),
.slot_cfg =
I2S_PDM_RX_SLOT_PCM_FMT_DEFAULT_CONFIG(
I2S_DATA_BIT_WIDTH_16BIT,
I2S_SLOT_MODE_STEREO
),
.gpio_cfg = {
.clk = MIC_CLK,
.din = MIC_DATA,
.invert_flags = {
.clk_inv = false
}
}
};
ret = i2s_channel_init_pdm_rx_mode(mic_rx, &pdm_cfg);
if (ret != ESP_OK) {
return ret;
}
return i2s_channel_enable(mic_rx);
}
/* =======================================================
* SD writer task
* ======================================================= */
static void sd_writer_task(void *arg)
{
FILE *fp = NULL;
char filename[64];
uint32_t audio_bytes = 0;
uint64_t total_bytes = 0;
fp = open_next_recording(filename, sizeof(filename));
if (!fp) {
writer_failed = true;
}
while (true) {
audio_block_t block = {0};
if (xQueueReceive(ready_buffers, &block,
portMAX_DELAY) != pdTRUE) {
continue;
}
if (block.end) {
break;
}
if (fp && !writer_failed) {
/*
* Rotate before exceeding the WAV size limit.
*/
if ((uint64_t)audio_bytes + block.length >
WAV_MAX_DATA_BYTES) {
ESP_LOGI(TAG, "Rotating WAV file");
if (!finalize_recording(&fp, audio_bytes)) {
writer_failed = true;
}
audio_bytes = 0;
if (!writer_failed) {
fp = open_next_recording(
filename,
sizeof(filename)
);
if (!fp) {
writer_failed = true;
}
}
}
if (fp && !writer_failed) {
size_t written = fwrite(
block.data,
1,
block.length,
fp
);
if (written != block.length) {
ESP_LOGE(TAG, "SD write failed");
writer_failed = true;
} else {
audio_bytes += block.length;
total_bytes += block.length;
recorded_bytes = total_bytes;
}
/*
* Update the WAV header approximately
* every 1 MiB.
*/
if ((audio_bytes % (1024 * 1024)) <
AUDIO_BUFFER_SIZE) {
if (!write_wav_header(fp, audio_bytes)) {
writer_failed = true;
}
if (fflush(fp) != 0) {
writer_failed = true;
}
if (fseek(fp, 0, SEEK_END) != 0) {
writer_failed = true;
}
if (fsync(fileno(fp)) != 0) {
writer_failed = true;
}
}
}
}
/* Give the buffer back to the capture task. */
uint8_t *ptr = block.data;
xQueueSend(free_buffers, &ptr, portMAX_DELAY);
}
if (fp) {
if (!finalize_recording(&fp, audio_bytes)) {
writer_failed = true;
}
}
ESP_LOGI(TAG, "Written: %" PRIu64 " bytes", total_bytes);
xSemaphoreGive(writer_finished);
vTaskDelete(NULL);
}
/* =======================================================
* Recording session
* ======================================================= */
static esp_err_t record_audio_buffered(void)
{
writer_failed = false;
recorded_bytes = 0;
dropped_buffers = 0;
dropped_bytes = 0;
memset(dropped_per_second, 0, sizeof(dropped_per_second));
for (unsigned i = 0; i < DROP_WINDOW_SECONDS; i++) {
drop_second_tag[i] = UINT32_MAX;
}
free_buffers = xQueueCreate(
AUDIO_BUFFER_COUNT,
sizeof(uint8_t *)
);
ready_buffers = xQueueCreate(
AUDIO_BUFFER_COUNT,
sizeof(audio_block_t)
);
writer_finished = xSemaphoreCreateBinary();
if (!free_buffers || !ready_buffers || !writer_finished) {
ESP_LOGE(TAG, "Queue allocation failed");
return ESP_ERR_NO_MEM;
}
for (int i = 0; i < AUDIO_BUFFER_COUNT; i++) {
uint8_t *ptr = audio_buffers[i];
xQueueSend(free_buffers, &ptr, 0);
}
if (xTaskCreate(
sd_writer_task,
"sd_writer",
8192,
NULL,
5,
NULL
) != pdPASS) {
ESP_LOGE(TAG, "Could not start writer task");
vQueueDelete(free_buffers);
vQueueDelete(ready_buffers);
vSemaphoreDelete(writer_finished);
return ESP_ERR_NO_MEM;
}
waveform_init();
recording_active = true;
recording_started = xTaskGetTickCount();
lcd_update_status();
ESP_LOGI(TAG, "Recording started");
TickType_t last_display_update = 0;
bool stop = false;
while (!stop && !writer_failed) {
/*
* BOOT button: active low.
*/
if (gpio_get_level(BOOT_BUTTON) == 0) {
vTaskDelay(pdMS_TO_TICKS(40));
if (gpio_get_level(BOOT_BUTTON) == 0) {
ESP_LOGI(TAG, "Stop requested");
stop = true;
continue;
}
}
uint8_t *buffer = NULL;
if (xQueueReceive(free_buffers, &buffer, 0) != pdTRUE) {
/*
* No application buffer available.
* Drain I2S into the discard buffer so DMA keeps running.
*/
size_t discarded = 0;
esp_err_t discard_ret = i2s_channel_read(
mic_rx,
discard_buffer,
sizeof(discard_buffer),
&discarded,
pdMS_TO_TICKS(500)
);
discarded &= ~((size_t)3);
if (discarded > 0) {
record_dropped_audio(discarded);
/* Avoid flooding the serial console. */
if (dropped_buffers == 1 ||
dropped_buffers % 100 == 0) {
ESP_LOGW(TAG,
"Audio dropped: total=%" PRIu32
", last minute=%" PRIu32
", bytes=%" PRIu64,
dropped_buffers,
get_dropped_last_minute(),
dropped_bytes);
}
} else if (discard_ret != ESP_OK &&
discard_ret != ESP_ERR_TIMEOUT) {
ESP_LOGE(TAG, "I2S discard read failed: %s",
esp_err_to_name(discard_ret));
}
continue;
}
size_t bytes_read = 0;
esp_err_t ret = i2s_channel_read(
mic_rx,
buffer,
AUDIO_BUFFER_SIZE,
&bytes_read,
pdMS_TO_TICKS(100)
);
/*
* A timeout can still return partial audio data.
* Only discard the buffer if no data was received.
*/
if (bytes_read == 0) {
if (ret != ESP_OK && ret != ESP_ERR_TIMEOUT) {
ESP_LOGE(TAG, "I2S read failed: %s",
esp_err_to_name(ret));
}
uint8_t *ptr = buffer;
xQueueSend(free_buffers, &ptr, portMAX_DELAY);
continue;
}
if (ret != ESP_OK && ret != ESP_ERR_TIMEOUT) {
ESP_LOGW(TAG, "I2S read warning: %s, bytes=%u",
esp_err_to_name(ret),
(unsigned)bytes_read);
}
bytes_read &= ~((size_t)3);
if (bytes_read == 0) {
uint8_t *ptr = buffer;
xQueueSend(free_buffers, &ptr, portMAX_DELAY);
continue;
}
waveform_update((const int16_t *)buffer, bytes_read);
audio_block_t block = {
.data = buffer,
.length = bytes_read,
.end = false
};
if (xQueueSend(
ready_buffers,
&block,
pdMS_TO_TICKS(100)
) != pdTRUE) {
ESP_LOGE(TAG, "Audio queue full");
uint8_t *ptr = buffer;
xQueueSend(free_buffers, &ptr, portMAX_DELAY);
stop = true;
writer_failed = true;
continue;
}
/*
* Refresh the LCD twice per second.
*/
TickType_t now = xTaskGetTickCount();
if ((now - last_display_update) >=
pdMS_TO_TICKS(100)) {
lcd_update_status();
last_display_update = now;
}
}
recording_active = false;
/*
* Stop I2S before waiting for the writer to finish.
*/
i2s_channel_disable(mic_rx);
/*
* Send end marker after all queued audio blocks.
*/
audio_block_t end_block = {
.data = NULL,
.length = 0,
.end = true
};
xQueueSend(ready_buffers, &end_block, portMAX_DELAY);
xSemaphoreTake(writer_finished, portMAX_DELAY);
lcd_update_status();
vQueueDelete(free_buffers);
vQueueDelete(ready_buffers);
vSemaphoreDelete(writer_finished);
ESP_LOGI(TAG, "Recording stopped");
return writer_failed ? ESP_FAIL : ESP_OK;
}
/* =======================================================
* BOOT button
* ======================================================= */
static void init_button(void)
{
gpio_config_t cfg = {
.pin_bit_mask = 1ULL << BOOT_BUTTON,
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE
};
ESP_ERROR_CHECK(gpio_config(&cfg));
}
static void wait_for_button_press(void)
{
/* Wait for button release. */
while (gpio_get_level(BOOT_BUTTON) == 0) {
vTaskDelay(pdMS_TO_TICKS(20));
}
/* Wait for next press. */
while (gpio_get_level(BOOT_BUTTON) != 0) {
vTaskDelay(pdMS_TO_TICKS(20));
}
vTaskDelay(pdMS_TO_TICKS(50));
}
/* =======================================================
* Application
* ======================================================= */
void app_main(void)
{
ESP_LOGI(TAG, "Pocket Dongle starting");
/* Display first, so startup errors can be visible later. */
lcd_init();
//lcd_test_pattern();
//vTaskDelay(pdMS_TO_TICKS(2000));
lcd_clear(LCD_BLACK);
lcd_text(5, 25, "STARTING", LCD_WHITE, 1);
lcd_flush();
init_button();
ESP_ERROR_CHECK(init_sd_card());
ESP_ERROR_CHECK(init_microphones());
/*
* Start recording automatically.
*
* BOOT:
* - while recording: stop and finalize WAV
* - while stopped: start a new recording
*/
while (true) {
esp_err_t ret = record_audio_buffered();
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Recording error: %s",
esp_err_to_name(ret));
lcd_clear(LCD_BLACK);
lcd_text(5, 25, "ERROR", LCD_RED, 1);
lcd_flush();
}
ESP_LOGI(TAG, "Press BOOT to start recording");
lcd_update_status();
wait_for_button_press();
esp_err_t enable_ret = i2s_channel_enable(mic_rx);
if (enable_ret != ESP_OK) {
ESP_LOGE(TAG, "I2S enable failed: %s",
esp_err_to_name(enable_ret));
break;
}
}
}