app_buffer.c 2.3 KB

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