-
Notifications
You must be signed in to change notification settings - Fork 1
/
melody-storage.hpp
84 lines (71 loc) · 1.97 KB
/
melody-storage.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#pragma once
#include "logger.hpp"
struct Sound {
unsigned int Frequency{};
unsigned long DurationMs{};
bool IsSeparator{ true };
void StartCountDuration() {
DurationMs = millis();
}
void StopCountDuration() {
DurationMs = millis() - DurationMs;
}
};
class MelodyStorage {
public:
// Return false if buffer is full
[[nodiscard]] bool StartRecording() {
if (IsBufferFull()) {
return false;
}
log("MelodyStorage: start recording melody, used %hu storage length", m_UsedLength);
return true;
}
// Must be called after StartRecording.
// Continue to write melody into buffer.
// Return false if buffer is full.
[[nodiscard]] bool UpdateMelody(unsigned int frequency) {
if (frequency == m_Buffer[m_UsedLength].Frequency) {
return true;
}
if (m_Buffer[m_UsedLength].IsSeparator) {
StartSound(frequency);
} else {
StopSound();
++m_UsedLength;
if (IsBufferFull()) {
return false;
}
StartSound(frequency);
}
return true;
}
void StopRecording() {
m_Buffer[m_UsedLength].IsSeparator = true;
++m_UsedLength;
log("MelodyStorage: stop recording melody, used %hu storage length", m_UsedLength);
}
[[nodiscard]] size_t GetUsedLength() const {
return m_UsedLength;
}
[[nodiscard]] bool IsBufferFull() const {
return m_UsedLength == CAPACITY;
}
[[nodiscard]] const Sound& Read(size_t index) const {
return m_Buffer[index];
}
private:
void StartSound(unsigned int frequency) {
m_Buffer[m_UsedLength].Frequency = frequency;
m_Buffer[m_UsedLength].StartCountDuration();
m_Buffer[m_UsedLength].IsSeparator = false;
}
void StopSound() {
m_Buffer[m_UsedLength].StopCountDuration();
log("MelodyStorage: new sound{ frequency=%u, duration=%lums }",
m_Buffer[m_UsedLength].Frequency, m_Buffer[m_UsedLength].DurationMs);
}
static constexpr auto CAPACITY = 64;
Sound m_Buffer[CAPACITY]{};
size_t m_UsedLength{};
};