audio_buffer.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #pragma once
  2. #include <stdbool.h>
  3. #include <stddef.h>
  4. #include <stdint.h>
  5. #include "esp_err.h"
  6. #include "freertos/FreeRTOS.h"
  7. #include "freertos/portmacro.h"
  8. #include "freertos/semphr.h"
  9. #include "audio_receiver.h"
  10. #define AAC_FRAMES_PER_PACKET 352
  11. #define AUDIO_MAX_CHANNELS 2
  12. #define AUDIO_BYTES_PER_SAMPLE 2
  13. #define MAX_SAMPLES_PER_FRAME 4096
  14. typedef struct __attribute__((packed)) {
  15. uint32_t rtp_timestamp;
  16. uint16_t samples_per_channel;
  17. uint8_t channels;
  18. uint8_t reserved;
  19. } audio_frame_header_t;
  20. #define MAX_RING_BUFFER_FRAMES 1000
  21. #define BYTES_PER_FRAME \
  22. ((size_t)sizeof(audio_frame_header_t) + \
  23. ((size_t)AAC_FRAMES_PER_PACKET * (size_t)AUDIO_MAX_CHANNELS * \
  24. (size_t)AUDIO_BYTES_PER_SAMPLE))
  25. #define AUDIO_BUFFER_SIZE (MAX_RING_BUFFER_FRAMES * BYTES_PER_FRAME)
  26. typedef struct {
  27. uint8_t *pool; // Pre-allocated frame data in PSRAM
  28. uint16_t *sorted; // Slot indices sorted by RTP timestamp
  29. uint16_t *free_stack; // Stack of free slot indices
  30. int count; // Frames currently in buffer
  31. int free_top; // Top of free stack (next free slot)
  32. int capacity; // Max frames
  33. size_t slot_size; // BYTES_PER_FRAME
  34. portMUX_TYPE lock; // Spinlock for count/index manipulation
  35. SemaphoreHandle_t data_ready; // Counting semaphore (blocks consumer)
  36. uint8_t *frame_buffer; // Temp assembly buffer
  37. int16_t *decode_buffer; // Decode buffer pointer
  38. size_t decode_capacity_samples;
  39. } audio_buffer_t;
  40. esp_err_t audio_buffer_init(audio_buffer_t *buffer);
  41. void audio_buffer_deinit(audio_buffer_t *buffer);
  42. void audio_buffer_flush(audio_buffer_t *buffer);
  43. int audio_buffer_get_frame_count(audio_buffer_t *buffer);
  44. bool audio_buffer_is_nearly_full(audio_buffer_t *buffer);
  45. bool audio_buffer_take(audio_buffer_t *buffer, void **item, size_t *item_size,
  46. TickType_t ticks);
  47. void audio_buffer_return(audio_buffer_t *buffer, void *item);
  48. int16_t *audio_buffer_get_decode_buffer(audio_buffer_t *buffer,
  49. size_t *capacity_samples);
  50. bool audio_buffer_queue_decoded(audio_buffer_t *buffer, audio_stats_t *stats,
  51. uint32_t timestamp, const int16_t *pcm_data,
  52. size_t samples, int channels);
  53. /**
  54. * Peek at the RTP timestamp of the oldest (lowest-timestamp) frame in the
  55. * buffer without removing it. Returns false if the buffer is empty.
  56. */
  57. bool audio_buffer_oldest_timestamp(audio_buffer_t *buffer, uint32_t *timestamp);