Arduino LibHelix
Loading...
Searching...
No Matches
CommonHelix.h
1#pragma once
2#if defined(ARDUINO) && __has_include("Arduino.h")
3#include "Arduino.h"
4#else
5// remove delay statment if used outside of arduino
6#include <stdint.h>
7#define delay(ms)
8#endif
9
10// Not all processors support assert
11#ifndef assert
12#ifdef NDEBUG
13#define assert(condition) ((void)0)
14#else
15#define assert(condition) /*implementation defined*/
16#endif
17#endif
18
19#include "ConfigHelix.h"
20#include "utils/Allocator.h"
21#include "utils/Buffers.h"
22#include "utils/Vector.h"
23#include "utils/helix_log.h"
24
25namespace libhelix {
26
34 public:
35#if defined(ARDUINO) || defined(HELIX_PRINT)
36 void setOutput(Print &output) { this->out = &output; }
37#endif
38
43 virtual bool begin() {
44 frame_buffer.reset();
45 frame_counter = 0;
46
47 if (active) {
48 end();
49 }
50
51 if (!allocateDecoder()) {
52 return false;
53 }
54 frame_buffer.resize(maxFrameSize());
55 pcm_buffer.resize(maxPCMSize());
56 memset(pcm_buffer.data(), 0, maxPCMSize());
57 memset(frame_buffer.data(), 0, maxFrameSize());
58 active = true;
59 return true;
60 }
61
63 virtual void end() {
64 frame_buffer.resize(0);
65 pcm_buffer.resize(0);
66
67 active = false;
68 }
69
76 virtual size_t write(const void *in_ptr, size_t in_size) {
77 LOGI_HELIX("write %zu", in_size);
78 int open = in_size;
79 size_t processed = 0;
80 uint8_t *data = (uint8_t *)in_ptr;
81 while (open > 0) {
82 int bytes = writeChunk(data, MIN(open, HELIX_CHUNK_SIZE));
83 // if we did not advance we leave the loop
84 if (bytes == 0) break;
85 open -= bytes;
86 data += bytes;
87 processed += bytes;
88 }
89 return processed;
90 }
91
93 operator bool() { return active; }
94
95#ifdef ARDUINO
97 uint64_t timeOfLastWrite() { return time_last_write; }
98
100 uint64_t timeOfLastResult() { return time_last_result; }
101#endif
102
109 void flush() {
110 // make room for the marker by decoding the complete frames first
111 if (frame_buffer.availableForWrite() < END_MARKER_LEN) decodeAvailable();
112 if (frame_buffer.availableForWrite() < END_MARKER_LEN) return;
113
114 frame_buffer.writeArray(endSyncWord(), END_MARKER_LEN);
115 // the marker is visible for the sync search, but it is not frame data
116 reserved_tail = END_MARKER_LEN;
117 int rc = 1;
118 while (rc >= 0) {
119 // we must start with sych word
120 if (!presync()) break;
121 // we must end with synch world
122 if (findSynchWord(3) < 0) break;
123 rc = decode();
124 // resynch() removes the processed data
125 if (!resynch(rc)) break;
126 }
127 // the marker was not consumed by any frame: remove it again
128 reserved_tail = 0;
129 frame_buffer.removeEnd(END_MARKER_LEN);
130 }
131
134 virtual size_t maxFrameSize() = 0;
135
137 void setMaxFrameSize(size_t len) { max_frame_size = len; }
138
141 virtual size_t maxPCMSize() = 0;
142
144 void setMaxPCMSize(size_t len) { max_pcm_size = len; }
145
148 void setReference(void *ref) { p_caller_ref = ref; }
149
150#if defined(ARDUINO) || defined(HELIX_PRINT)
152 void setMaxPCMWriteSize(int size) { max_write_size = size; }
153#endif
154
155 protected:
156 static const int END_MARKER_LEN = 4;
157 int reserved_tail = 0; // bytes at the end of frame_buffer that are not frame data
158
160 int decodableBytes() { return MAX(frame_buffer.available() - reserved_tail, 0); }
161
163 virtual const uint8_t *endSyncWord() {
164 static const uint8_t marker[END_MARKER_LEN] = {0xFF, 0xF1, 0x50, 0x80};
165 return marker;
166 }
167
168 bool active = false;
169 bool is_raw = false;
170 Vector<uint8_t> pcm_buffer{0};
171 SingleBuffer<uint8_t> frame_buffer{0};
172 size_t max_frame_size = 0;
173 size_t max_pcm_size = 0;
174 size_t frame_counter = 0;
175 size_t max_write_size = 1024;
176 int delay_ms = -1;
177 int parse_0_count = 0; // keep track of parser returning 0
178 int min_frame_buffer_size = 0;
179 uint64_t time_last_write = 0;
180 uint64_t time_last_result = 0;
181 void *p_caller_ref = nullptr;
182
183#if defined(ARDUINO) || defined(HELIX_PRINT)
184 Print *out = nullptr;
185#endif
186
188 bool presync() {
189 LOGD_HELIX("presynch");
190 bool rc = true;
191 int pos = findSynchWord();
192 if (pos > 3) rc = removeInvalidData(pos);
193
194 return rc;
195 }
196
199 bool resynch(int rc) {
200 LOGD_HELIX("resynch: %d", rc);
201 if (rc > 0) {
202 // remove processed data
203 LOGD_HELIX("removing %d bytes", rc);
204 frame_buffer.clearArray(rc);
205 // reset 0 result counter on success
206 parse_0_count = 0;
207 return true;
208 } else if (rc == 0) {
209 // if we are stuck, request more data and if this does not help we
210 // remove the invalid data
211 parse_0_count++;
212 int pos = findSynchWord(SYNCH_WORD_LEN);
213 LOGD_HELIX("rc: %d - available %d - pos %d", rc,
214 frame_buffer.available(), pos);
215 if (parse_0_count > 2) {
216 return removeInvalidData(pos);
217 }
218 return false;
219 } else if (rc == -1) {
220 // underflow
221 LOGD_HELIX("rc: %d - available %d", rc, frame_buffer.available());
222 return false;
223 } else if (rc < -1) {
224 // generic error handling: remove the data until the next synch word
225 int pos = findSynchWord(SYNCH_WORD_LEN + 1);
227 return true;
228 }
229
230 return true;
231 }
232
235 bool removeInvalidData(int pos) {
236 LOGD_HELIX("removeInvalidData: %d", pos);
237 if (pos > 0) {
238 LOGI_HELIX("removing: %d bytes", pos);
239 frame_buffer.clearArray(pos);
240 return true;
241 } else if (pos <= 0) {
242 frame_buffer.reset();
243 return false;
244 }
245 return true;
246 }
247
249 virtual size_t writeChunk(const void *in_ptr, size_t in_size) {
250 LOGI_HELIX("writeChunk %zu", in_size);
251 // not started (or already ended): there is no frame buffer, so nothing can
252 // be accepted. Returning 0 lets the caller stop instead of looping forever.
253 if (!active) return 0;
254#ifdef ARDUINO
255 time_last_write = millis();
256#endif
257 const uint8_t *data = (const uint8_t *)in_ptr;
258 size_t result = 0;
259 // Accept all input. If the frame buffer is full and the decoder cannot
260 // consume anything, we discard the unusable data so that input progresses.
261 while (result < in_size) {
262 result += frame_buffer.writeArray(data + result, in_size - result);
264 if (result < in_size && frame_buffer.isFull()) {
266 }
267 }
268
269 return result;
270 }
271
274 while (frame_buffer.available() >= minFrameBufferSize()) {
275 if (!presync()) break;
276 int rc = decode();
277 if (!resynch(rc)) break;
278
279 LOGI_HELIX("rc: %d - available %d", rc, frame_buffer.available());
280 }
281 }
282
286 int pos = findSynchWord(1);
287 LOGW_HELIX("discarding unusable data: next sync %d", pos);
288 if (pos > 0) {
289 frame_buffer.clearArray(pos);
290 } else {
291 frame_buffer.reset();
292 }
293 }
294
295#if defined(ARDUINO) || defined(HELIX_PRINT)
296 size_t writeToOut(uint8_t *data, size_t len) {
297 size_t to_write = len;
298 size_t written = 0;
299 while (to_write > 0) {
300 size_t result = out->write(data + written, MIN(to_write, 1024));
301 to_write -= result;
302 written += result;
303 if (result == 0) {
304 break;
305 }
306 }
307 if (len != written)
308 LOGE_HELIX("Could not write result to out: %d of %d written", (int)written,
309 (int)len);
310 return written;
311 }
312#endif
313
315 virtual int decode() = 0;
316
318 virtual bool allocateDecoder() = 0;
319
322 virtual int findSynchWord(int offset = 0) = 0;
323
325 virtual int minFrameBufferSize() { return min_frame_buffer_size; }
328 virtual void setMinFrameBufferSize(int size) { min_frame_buffer_size = size; }
329};
330
331} // namespace libhelix
Common Simple Arduino API.
Definition CommonHelix.h:33
bool removeInvalidData(int pos)
Definition CommonHelix.h:235
virtual size_t maxPCMSize()=0
virtual size_t writeChunk(const void *in_ptr, size_t in_size)
Decoding Loop: We decode the procided data until we run out of data.
Definition CommonHelix.h:249
void setMaxFrameSize(size_t len)
Define your optimized maximum frame size in bytes.
Definition CommonHelix.h:137
void discardUnusableData()
Definition CommonHelix.h:285
void flush()
Decodes all open packets, including the last frame. Call it at the end of the stream....
Definition CommonHelix.h:109
virtual int findSynchWord(int offset=0)=0
void setReference(void *ref)
Definition CommonHelix.h:148
virtual size_t maxFrameSize()=0
virtual void end()
Releases the reserved memory.
Definition CommonHelix.h:63
void decodeAvailable()
Decodes all frames that are complete enough to be decoded.
Definition CommonHelix.h:273
virtual size_t write(const void *in_ptr, size_t in_size)
decodes the next segments from the input. The data can be provided in one big or in small incremental...
Definition CommonHelix.h:76
virtual void setMinFrameBufferSize(int size)
Definition CommonHelix.h:328
uint64_t timeOfLastWrite()
Provides the timestamp in ms of last write.
Definition CommonHelix.h:97
uint64_t timeOfLastResult()
Provides the timestamp in ms of last decoded result.
Definition CommonHelix.h:100
virtual bool begin()
Starts the processing.
Definition CommonHelix.h:43
virtual bool allocateDecoder()=0
Allocate the decoder.
void setMaxPCMSize(size_t len)
Define your optimized maximum pcm buffer size in bytes.
Definition CommonHelix.h:144
int decodableBytes()
the bytes that the decoders may use for a frame
Definition CommonHelix.h:160
virtual int minFrameBufferSize()
Provides the actual minimum frame buffer size.
Definition CommonHelix.h:325
void setMaxPCMWriteSize(int size)
Defines the max chunk size that is wrtten to out (Arduino only)
Definition CommonHelix.h:152
virtual const uint8_t * endSyncWord()
the end marker appended by flush(): a valid ADTS header (AAC)
Definition CommonHelix.h:163
bool resynch(int rc)
Definition CommonHelix.h:199
virtual int decode()=0
Decode w/o parsing.
bool presync()
make sure that we start with a valid sync: remove ID3 data
Definition CommonHelix.h:188