forked from pschatzmann/arduino-audio-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAudioStreams.h
1906 lines (1617 loc) · 48.4 KB
/
AudioStreams.h
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include "AudioConfig.h"
#include "AudioTimer/AudioTimer.h"
#include "AudioTools/AudioTypes.h"
#include "AudioTools/Buffers.h"
#include "AudioTools/AudioLogger.h"
#include "AudioEffects/SoundGenerator.h"
#ifndef URL_CLIENT_TIMEOUT
# define URL_CLIENT_TIMEOUT 60000
#endif
#ifndef URL_HANDSHAKE_TIMEOUT
# define URL_HANDSHAKE_TIMEOUT 120000
#endif
#ifndef IRAM_ATTR
# define IRAM_ATTR
#endif
#ifdef USE_STREAM_WRITE_OVERRIDE
# define STREAM_WRITE_OVERRIDE override
#else
# define STREAM_WRITE_OVERRIDE
#endif
#ifdef USE_STREAM_READ_OVERRIDE
# define STREAM_READ_OVERRIDE override
#else
# define STREAM_READ_OVERRIDE
#endif
#ifdef USE_STREAM_READCHAR_OVERRIDE
# define STREAM_READCHAR_OVERRIDE override
#else
# define STREAM_READCHAR_OVERRIDE
#endif
namespace audio_tools {
/**
* @brief Base class for all Audio Streams. It support the boolean operator to
* test if the object is ready with data
* @author Phil Schatzmann
* @copyright GPLv3
*/
class AudioStream : public Stream, public AudioInfoSupport, public AudioInfoSource {
public:
AudioStream() = default;
virtual ~AudioStream() = default;
AudioStream(AudioStream const&) = delete;
AudioStream& operator=(AudioStream const&) = delete;
virtual bool begin(){return true;}
virtual void end(){}
// Call from subclass or overwrite to do something useful
virtual void setAudioInfo(AudioInfo info) override {
TRACED();
this->info = info;
info.logInfo();
if (p_notify!=nullptr){
p_notify->setAudioInfo(info);
}
}
virtual void setNotifyAudioChange(AudioInfoSupport &bi) override {
p_notify = &bi;
}
virtual size_t readBytes(uint8_t *buffer, size_t length) STREAM_READ_OVERRIDE { return not_supported(0, "readBytes"); }
virtual size_t write(const uint8_t *buffer, size_t size) override{ return not_supported(0,"write"); }
virtual size_t write(uint8_t ch) override {
tmp_out.resize(MAX_SINGLE_CHARS);
if (tmp_out.isFull()){
flush();
}
return tmp_out.write(ch);
}
virtual int available() override { return DEFAULT_BUFFER_SIZE; };
operator bool() { return available() > 0; }
virtual AudioInfo audioInfo() override {
return info;
}
virtual int availableForWrite() override { return DEFAULT_BUFFER_SIZE; }
virtual void flush() override {
if (tmp_out.available()>0){
write((const uint8_t*)tmp_out.address(), tmp_out.available());
}
}
/// Writes len bytes of silence (=0).
virtual void writeSilence(size_t len){
int16_t zero = 0;
for (int j=0;j<len/2;j++){
write((uint8_t*)&zero,2);
}
}
/// Source to generate silence: just sets the buffer to 0
virtual size_t readSilence(uint8_t *buffer, size_t length) {
memset(buffer, 0, length);
return length;
}
// Methods which should be suppressed in the documentation
#ifndef DOXYGEN
virtual size_t readBytes(char *buffer, size_t length) STREAM_READCHAR_OVERRIDE {
return readBytes((uint8_t *)buffer, length);
}
virtual int read() override {
refillReadBuffer();
return tmp_in.read();
}
virtual int peek() override {
refillReadBuffer();
return tmp_in.peek();
}
#endif
protected:
AudioInfoSupport *p_notify=nullptr;
AudioInfo info;
RingBuffer<uint8_t> tmp_in{0};
RingBuffer<uint8_t> tmp_out{0};
virtual int not_supported(int out, const char* msg="") {
LOGE("AudioStream: %s unsupported operation!", msg);
// trigger stacktrace
//assert(false);
return out;
}
void refillReadBuffer() {
tmp_in.resize(MAX_SINGLE_CHARS);
if (tmp_in.isEmpty()){
TRACED();
const int len = tmp_in.size();
uint8_t bytes[len];
int len_eff = readBytes(bytes, len);
//LOGD("tmp_in available: %d / size: %d / to be written %d", tmp_in.available(), tmp_in.size(), len_eff);
tmp_in.writeArray(bytes,len_eff);
}
}
};
/**
* @brief To be used to support implementations where the readBytes is not
* virtual
*
*/
class AudioStreamWrapper : public AudioStream {
public:
AudioStreamWrapper(Stream& s) {
TRACED();
p_stream = &s;
p_stream->setTimeout(clientTimeout);
}
virtual bool begin(){return true;}
virtual void end(){}
virtual size_t readBytes(uint8_t *buffer, size_t length) {
//Serial.print("Timeout audiostream: ");
//Serial.println(p_stream->getTimeout());
return p_stream->readBytes(buffer, length);
}
int read() { return p_stream->read(); }
int peek() { return p_stream->peek(); }
int available() { return p_stream->available(); }
virtual size_t write(uint8_t c) { return p_stream->write(c); }
virtual size_t write(const uint8_t *buffer, size_t size) {
return p_stream->write(buffer, size);
}
virtual int availableForWrite() { return p_stream->availableForWrite(); }
virtual void flush() { p_stream->flush(); }
protected:
Stream *p_stream;
int32_t clientTimeout = URL_CLIENT_TIMEOUT; // 60000;
};
/**
* @brief A simple Stream implementation which is backed by allocated memory
* @ingroup io
* @author Phil Schatzmann
* @copyright GPLv3
*
*/
class MemoryStream : public AudioStream {
public:
MemoryStream(int buffer_size = 512, MemoryType memoryType = RAM) {
LOGD("MemoryStream: %d", buffer_size);
this->buffer_size = buffer_size;
this->memory_type = memoryType;
resize(buffer_size);
}
MemoryStream(const uint8_t *buffer, int buffer_size, MemoryType memoryType = FLASH_RAM) {
LOGD("MemoryStream: %d", buffer_size);
setValue(buffer, buffer_size, memoryType);
}
~MemoryStream() {
TRACED();
if (memoryCanChange() && buffer!=nullptr) free(buffer);
}
// resets the read pointer
bool begin() override {
TRACED();
write_pos = memoryCanChange() ? 0 : buffer_size;
if (this->buffer==nullptr && memoryCanChange()){
resize(buffer_size);
}
read_pos = 0;
return true;
}
virtual size_t write(uint8_t byte) override {
if (buffer==nullptr) return 0;
int result = 0;
if (write_pos < buffer_size) {
result = 1;
buffer[write_pos] = byte;
write_pos++;
}
return result;
}
virtual size_t write(const uint8_t *buffer, size_t size) override {
size_t result = 0;
for (size_t j = 0; j < size; j++) {
if (!write(buffer[j])) {
break;
}
result = j;
}
return result;
}
virtual int available() override {
if (buffer==nullptr) return 0;
int result = write_pos - read_pos;
if (result<=0 && is_loop){
// rewind to start
read_pos = 0;
result = write_pos - read_pos;
// call callback
if (rewind!=nullptr) rewind();
}
return result;
}
virtual int availableForWrite() override {
return buffer_size - write_pos;
}
virtual int read() override {
int result = peek();
if (result >= 0) {
read_pos++;
}
return result;
}
virtual size_t readBytes(uint8_t *buffer, size_t length) override {
size_t count = 0;
while (count < length) {
int c = read();
if (c < 0) break;
*buffer++ = (char)c;
count++;
}
return count;
}
virtual int peek() override {
int result = -1;
if (available() > 0) {
result = buffer[read_pos];
}
return result;
}
virtual void flush() override {}
virtual void end() override {
read_pos = 0;
}
/// clears the audio data: sets all values to 0
virtual void clear(bool reset = false) {
if (memoryCanChange()){
write_pos = 0;
read_pos = 0;
if (buffer==nullptr){
resize(buffer_size);
}
if (reset) {
// we clear the buffer data
memset(buffer, 0, buffer_size);
}
} else {
read_pos = 0;
LOGW("data is read only");
}
}
/// Automatically rewinds to the beginning when reaching the end
virtual void setLoop(bool loop){
is_loop = loop;
}
virtual void resize(size_t size){
if (memoryCanChange()){
buffer_size = size;
switch(memory_type){
#if defined(ESP32) && defined(ARDUINO)
case PS_RAM:
buffer = (buffer==nullptr) ? (uint8_t*)ps_calloc(size,1) : (uint8_t*)ps_realloc(buffer, size);
assert(buffer!=nullptr);
break;
#endif
default:
buffer = (buffer==nullptr) ? (uint8_t*)calloc(size,1) : (uint8_t*)realloc(buffer, size);
assert(buffer!=nullptr);
break;
}
}
}
virtual uint8_t* data(){
return buffer;
}
/// Callback which is executed when we rewind (in loop mode) to the beginning
void setRewindCallback(void (*cb)()){
this->rewind = cb;
}
/// Update the values (buffer and size)
void setValue(const uint8_t *buffer, int buffer_size, MemoryType memoryType = FLASH_RAM) {
this->buffer_size = buffer_size;
this->read_pos = 0;
this->write_pos = buffer_size;
this->buffer = (uint8_t *)buffer;
this->memory_type = memoryType;
}
protected:
int write_pos = 0;
int read_pos = 0;
int buffer_size = 0;
uint8_t *buffer = nullptr;
MemoryType memory_type = RAM;
bool is_loop = false;
void (*rewind)() = nullptr;
bool memoryCanChange() {
return memory_type!=FLASH_RAM;
}
};
/**
* @brief MemoryStream which is written and read using the internal RAM. For each write the data is allocated
* on the heap.
* @ingroup io
* @author Phil Schatzmann
* @copyright GPLv3
*/
class DynamicMemoryStream : public AudioStream {
public:
struct DataNode {
size_t len=0;
uint8_t* data=nullptr;
DataNode() = default;
/// Constructor
DataNode(void*inData, int len){
this->len = len;
this->data = (uint8_t*) malloc(len);
assert(this->data!=nullptr);
memcpy(this->data, inData, len);
}
~DataNode(){
if (data!=nullptr) {
free(data);
data = nullptr;
}
}
};
DynamicMemoryStream() = default;
DynamicMemoryStream(bool isLoop, int defaultBufferSize=DEFAULT_BUFFER_SIZE ) {
this->default_buffer_size = defaultBufferSize;
is_loop = isLoop;
}
// Assign values from ref, clearing the original ref
void assign(DynamicMemoryStream &ref){
audio_list.swap(ref.audio_list);
it = ref.it;
total_available=ref.total_available;
default_buffer_size = ref.default_buffer_size;
alloc_failed = ref.alloc_failed;;
is_loop = ref.is_loop;
ref.clear();
}
/// Intializes the processing
virtual bool begin() override {
clear();
temp_audio.resize(default_buffer_size);
return true;
}
virtual void end() override {
clear();
}
/// Automatically rewinds to the beginning when reaching the end
virtual void setLoop(bool loop){
is_loop = loop;
}
void clear() {
DataNode *p_node;
bool ok;
do{
ok = audio_list.pop_front(p_node);
if (ok){
delete p_node;
}
} while (ok);
temp_audio.reset();
total_available = 0;
alloc_failed = false;
rewind();
}
size_t size(){
return total_available;
}
/// Sets the read position to the beginning
void rewind() {
it = audio_list.begin();
}
virtual size_t write(const uint8_t *buffer, size_t size) override {
DataNode *p_node = new DataNode((void*)buffer, size);
if (p_node->data!=nullptr){
alloc_failed = false;
total_available += size;
audio_list.push_back(p_node);
// setup interator to point to first record
if (it == audio_list.end()){
it = audio_list.begin();
}
return size;
}
alloc_failed = true;
return 0;
}
virtual int availableForWrite() override {
return alloc_failed ? 0 : default_buffer_size;
}
virtual int available() override {
if (it == audio_list.end()){
if (is_loop) rewind();
if (it == audio_list.end()) {
return 0;
}
}
return (*it)->len;
}
virtual size_t readBytes(uint8_t *buffer, size_t length) override {
// provide unprocessed data
if (temp_audio.available()>0){
return temp_audio.readArray(buffer, length);
}
// We have no more data
if (it==audio_list.end()){
if (is_loop){
rewind();
} else {
// stop the processing
return 0;
}
}
// provide data from next node
DataNode *p_node = *it;
int result_len = min(length, (size_t) p_node->len);
memcpy(buffer, p_node->data, result_len);
// save unprocessed data to temp buffer
if (p_node->len>length){
uint8_t *start = p_node->data+result_len;
int uprocessed_len = p_node->len - length;
temp_audio.writeArray(start, uprocessed_len);
}
//move to next pos
++it;
return result_len;
}
List<DataNode*> &list() {
return audio_list;
}
/// @brief Post processing after the recording. We add a smooth transition at the beginning and at the end
/// @tparam T
/// @param factor
template<typename T>
void postProcessSmoothTransition(int channels, float factor = 0.01, int remove=0){
if (remove>0){
for (int j=0;j<remove;j++){
DataNode* node = nullptr;
audio_list.pop_front(node);
if (node!=nullptr) delete node;
node = nullptr;
audio_list.pop_back(node);
if (node!=nullptr) delete node;
}
}
// Remove popping noise
SmoothTransition<T> clean_start(channels, true, false, factor);
auto first = *list().begin();
if (first!=nullptr){
clean_start.convert(first->data,first->len);
}
SmoothTransition<T> clean_end(channels, false, true, factor);
auto last = * (--(list().end()));
if (last!=nullptr){
clean_end.convert(last->data,last->len);
}
}
protected:
List<DataNode*> audio_list;
List<DataNode*>::Iterator it = audio_list.end();
size_t total_available=0;
int default_buffer_size=DEFAULT_BUFFER_SIZE;
bool alloc_failed = false;
RingBuffer<uint8_t> temp_audio{DEFAULT_BUFFER_SIZE};
bool is_loop = false;
};
/**
* @brief Source for reading generated tones. Please note
* - that the output is for one channel only!
* - we do not support reading of individual characters!
* - we do not support any write operations
* @ingroup io
* @param generator
* @author Phil Schatzmann
* @copyright GPLv3
*/
template <class T>
class GeneratedSoundStream : public AudioStream {
public:
GeneratedSoundStream() = default;
GeneratedSoundStream(SoundGenerator<T> &generator) {
TRACED();
setInput(generator);
}
void setInput(SoundGenerator<T> &generator){
this->generator_ptr = &generator;
}
AudioInfo defaultConfig() { return this->generator_ptr->defaultConfig(); }
/// start the processing
bool begin() override {
TRACED();
if (generator_ptr==nullptr){
LOGE("%s",source_not_defined_error);
return false;
}
generator_ptr->begin();
if (audioBaseInfoDependent != nullptr)
audioBaseInfoDependent->setAudioInfo(generator_ptr->audioInfo());
active = true;
return active;
}
/// start the processing
bool begin(AudioInfo cfg) {
TRACED();
if (generator_ptr==nullptr){
LOGE("%s",source_not_defined_error);
return false;
}
generator_ptr->begin(cfg);
if (audioBaseInfoDependent != nullptr)
audioBaseInfoDependent->setAudioInfo(generator_ptr->audioInfo());
active = true;
return active;
}
/// stop the processing
void end() override {
TRACED();
generator_ptr->end();
active = false;
}
virtual void setNotifyAudioChange(AudioInfoSupport &bi) override {
audioBaseInfoDependent = &bi;
}
AudioInfo audioInfo() override {
return generator_ptr->audioInfo();
}
/// This is unbounded so we just return the buffer size
virtual int available() override { return DEFAULT_BUFFER_SIZE; }
/// privide the data as byte stream
size_t readBytes(uint8_t *buffer, size_t length) override {
LOGD("GeneratedSoundStream::readBytes: %u", (unsigned int)length);
return generator_ptr->readBytes(buffer, length);
}
bool isActive() {return active && generator_ptr->isActive();}
operator bool() { return isActive(); }
void flush() override {}
protected:
bool active = false;
SoundGenerator<T> *generator_ptr;
AudioInfoSupport *audioBaseInfoDependent = nullptr;
const char* source_not_defined_error = "Source not defined";
};
/**
* @brief The Arduino Stream supports operations on single characters. This is
* usually not the best way to push audio information, but we will support it
* anyway - by using a buffer. On reads: if the buffer is empty it gets refilled
* - for writes if it is full it gets flushed.
* @author Phil Schatzmann
* @copyright GPLv3
*/
class BufferedStream : public AudioStream {
public:
BufferedStream(size_t buffer_size) {
TRACED();
buffer = new SingleBuffer<uint8_t>(buffer_size);
}
~BufferedStream() {
TRACED();
if (buffer != nullptr) {
delete buffer;
}
}
/// writes a byte to the buffer
virtual size_t write(uint8_t c) override {
if (buffer->isFull()) {
flush();
}
return buffer->write(c);
}
/// Use this method: write an array
virtual size_t write(const uint8_t *data, size_t len) override {
LOGD("%s: %zu", LOG_METHOD, len);
flush();
return writeExt(data, len);
}
/// empties the buffer
virtual void flush() override {
// just dump the memory of the buffer and clear it
if (buffer->available() > 0) {
writeExt(buffer->address(), buffer->available());
buffer->reset();
}
}
/// reads a byte - to be avoided
virtual int read() override {
if (buffer->isEmpty()) {
refill();
}
return buffer->read();
}
/// peeks a byte - to be avoided
virtual int peek() override{
if (buffer->isEmpty()) {
refill();
}
return buffer->peek();
};
/// Use this method !!
size_t readBytes(uint8_t *data, size_t length) override {
if (buffer->isEmpty()) {
return readExt(data, length);
} else {
return buffer->readArray(data, length);
}
}
/// Returns the available bytes in the buffer: to be avoided
virtual int available() override {
if (buffer->isEmpty()) {
refill();
}
return buffer->available();
}
/// Clears all the data in the buffer
void clear() { buffer->reset(); }
protected:
SingleBuffer<uint8_t> *buffer = nullptr;
// refills the buffer with data from i2s
void refill() {
size_t result = readExt(buffer->address(), buffer->size());
buffer->setAvailable(result);
}
virtual size_t writeExt(const uint8_t *data, size_t len) = 0;
virtual size_t readExt(uint8_t *data, size_t length) = 0;
};
/**
* @brief The Arduino Stream which provides silence and simulates a null device
* when used as audio target or audio source
* @ingroup io
* @author Phil Schatzmann
* @copyright GPLv3
*/
class NullStream : public AudioStream {
public:
bool begin(AudioInfo info) {
this->info = info;
return true;
}
AudioInfo defaultConfig() {
AudioInfo info;
return info;
}
size_t write(const uint8_t *buffer, size_t len) override{
return len;
}
size_t readBytes(uint8_t *buffer, size_t len) override{
memset(buffer,0, len);
return len;
}
/// Define object which need to be notified if the basinfo is changing
void setNotifyAudioChange(AudioInfoSupport &bi) override {}
void setAudioInfo(AudioInfo info) override {
this->info = info;
}
};
/**
* @brief A Stream backed by a Ringbuffer. We can write to the end and read from
* the beginning of the stream
* @ingroup io
* @author Phil Schatzmann
* @copyright GPLv3
*/
class RingBufferStream : public AudioStream {
public:
RingBufferStream(int size = DEFAULT_BUFFER_SIZE) {
resize(size);
}
virtual int available() override {
// LOGD("RingBufferStream::available: %zu",buffer->available());
return buffer.available();
}
virtual int availableForWrite() override {
return buffer.availableForWrite();
}
virtual void flush() override {}
virtual int peek() override { return buffer.peek(); }
virtual int read() override { return buffer.read(); }
virtual size_t readBytes(uint8_t *data, size_t length) override {
return buffer.readArray(data, length);
}
virtual size_t write(const uint8_t *data, size_t len) override {
// LOGD("RingBufferStream::write: %zu",len);
return buffer.writeArray(data, len);
}
virtual size_t write(uint8_t c) override { return buffer.write(c); }
void resize(int size){
buffer.resize(size);
}
size_t size() {
return buffer.size();
}
protected:
RingBuffer<uint8_t> buffer{0};
};
/**
* @brief AudioStream class which stores the data in a temporary queue buffer.
* The queue can be consumed e.g. by a callback function by calling readBytes();
* @ingroup io
* @author Phil Schatzmann
* @copyright GPLv3
*/
template <class T>
class QueueStream : public AudioStream {
public:
/// Default constructor
QueueStream(int bufferSize, int bufferCount, bool autoRemoveOldestDataIfFull=false)
: AudioStream() {
owns_buffer = true;
callback_buffer_ptr = new NBuffer<T>(bufferSize, bufferCount);
remove_oldest_data = autoRemoveOldestDataIfFull;
}
/// Create stream from any BaseBuffer subclass
QueueStream(BaseBuffer<T> &buffer){
owns_buffer = false;
callback_buffer_ptr = &buffer;
}
virtual ~QueueStream() {
if(owns_buffer) {
delete callback_buffer_ptr;
}
}
/// Activates the output
virtual bool begin() override {
TRACEI();
active = true;
return true;
}
/// stops the processing
virtual void end() override {
TRACEI();
active = false;
};
int available() override {
return callback_buffer_ptr->available()*sizeof(T);
}
int availableForWrite() override {
return callback_buffer_ptr->availableForWrite()*sizeof(T);
}
virtual size_t write(const uint8_t *data, size_t len) override {
if (!active) return 0;
// make space by deleting oldest entries
if (remove_oldest_data){
int available_bytes = callback_buffer_ptr->availableForWrite()*sizeof(T);
if ((int)len>available_bytes){
int gap = len-available_bytes;
uint8_t tmp[gap];
readBytes(tmp, gap);
}
}
return callback_buffer_ptr->writeArray(data, len / sizeof(T));
}
virtual size_t readBytes(uint8_t *data, size_t len) override {
if (!active) return 0;
return callback_buffer_ptr->readArray(data, len / sizeof(T));
}
/// Clears the data in the buffer
void clear() {
if (active){
callback_buffer_ptr->reset();
}
}
/// Returns true if active
operator bool(){
return active;
}
protected:
BaseBuffer<T> *callback_buffer_ptr;
bool active;
bool remove_oldest_data;
bool owns_buffer;
};
// support legacy name
template <typename T>
using CallbackBufferedStream = QueueStream<T>;
/**
* @brief Both the data of the read or write
* operations will be converted with the help of the indicated converter.
* @ingroup transform
* @tparam T
* @param out
* @param converter
*/
template<typename T>
class ConverterStream : public AudioStream {
public:
ConverterStream(Stream &stream, BaseConverter &converter) : AudioStream() {
p_converter = &converter;
p_stream = &stream;
}
virtual int availableForWrite() { return p_stream->availableForWrite(); }
virtual size_t write(const uint8_t *buffer, size_t size) {
size_t result = p_converter->convert((uint8_t *)buffer, size);
if (result>0) {
size_t result_written = p_stream->write(buffer, result);
return size * result_written / result;
}
return 0;
}
size_t readBytes(uint8_t *data, size_t length) override {
size_t result; p_stream->readBytes(data, length);
return p_converter->convert(data, result);
}
/// Returns the available bytes in the buffer: to be avoided
virtual int available() override {
return p_stream->available();
}
protected:
Stream *p_stream;
BaseConverter *p_converter;
};