app_buffer.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <inttypes.h>
  2. #include <furi/core/string.h>
  3. #include <furi.h>
  4. #include <furi_hal.h>
  5. #include "app_buffer.h"
  6. /* Allocate and initialize a samples buffer. */
  7. RawSamplesBuffer *raw_samples_alloc(void) {
  8. RawSamplesBuffer *buf = malloc(sizeof(*buf));
  9. buf->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
  10. raw_samples_reset(buf);
  11. return buf;
  12. }
  13. /* Free a sample buffer. Should be called when the mutex is released. */
  14. void raw_samples_free(RawSamplesBuffer *s) {
  15. furi_mutex_free(s->mutex);
  16. free(s);
  17. }
  18. /* This just set all the samples to zero and also resets the internal
  19. * index. There is no need to call it after raw_samples_alloc(), but only
  20. * when one wants to reset the whole buffer of samples. */
  21. void raw_samples_reset(RawSamplesBuffer *s) {
  22. furi_mutex_acquire(s->mutex,FuriWaitForever);
  23. s->total = RAW_SAMPLES_NUM;
  24. s->idx = 0;
  25. s->short_pulse_dur = 0;
  26. memset(s->level,0,sizeof(s->level));
  27. memset(s->dur,0,sizeof(s->dur));
  28. furi_mutex_release(s->mutex);
  29. }
  30. /* Add the specified sample in the circular buffer. */
  31. void raw_samples_add(RawSamplesBuffer *s, bool level, uint32_t dur) {
  32. furi_mutex_acquire(s->mutex,FuriWaitForever);
  33. s->level[s->idx] = level;
  34. s->dur[s->idx] = dur;
  35. s->idx = (s->idx+1) % RAW_SAMPLES_NUM;
  36. furi_mutex_release(s->mutex);
  37. }
  38. /* Get the sample from the buffer. It is possible to use out of range indexes
  39. * as 'idx' because the modulo operation will rewind back from the start. */
  40. void raw_samples_get(RawSamplesBuffer *s, uint32_t idx, bool *level, uint32_t *dur)
  41. {
  42. furi_mutex_acquire(s->mutex,FuriWaitForever);
  43. idx = (s->idx + idx) % RAW_SAMPLES_NUM;
  44. *level = s->level[idx];
  45. *dur = s->dur[idx];
  46. furi_mutex_release(s->mutex);
  47. }
  48. /* Copy one buffer to the other, including current index. */
  49. void raw_samples_copy(RawSamplesBuffer *dst, RawSamplesBuffer *src) {
  50. furi_mutex_acquire(src->mutex,FuriWaitForever);
  51. furi_mutex_acquire(dst->mutex,FuriWaitForever);
  52. dst->idx = src->idx;
  53. dst->short_pulse_dur = src->short_pulse_dur;
  54. memcpy(dst->level,src->level,sizeof(dst->level));
  55. memcpy(dst->dur,src->dur,sizeof(dst->dur));
  56. furi_mutex_release(src->mutex);
  57. furi_mutex_release(dst->mutex);
  58. }