forked from schreibfaul1/ESP32-audioI2S
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Audio.cpp
2441 lines (2304 loc) · 111 KB
/
Audio.cpp
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
/*
* Audio.cpp
*
* Created on: Oct 26,2018
* Updated on: Jan 04,2021
*
* Author: Wolle
*
* This library plays mp3 files from SD card or icy-webstream via I2S,
* play Google TTS and plays also aac-streams
* no internal DAC, no DeltSigma
*
* etrernal HW on I2S nessesary, e.g.MAX98357A
*
* Updated on: Jan 06,2021 by dkm1978
* added support for ESP32 internal DAC
* In audio.h uncomment #define INTDAC to use internal ESP32 DAC or comment to use External DAC
*
*
*/
#include "Audio.h"
#include "mp3_decoder/mp3_decoder.h"
#include "aac_decoder/aac_decoder.h"
//---------------------------------------------------------------------------------------------------------------------
AudioBuffer::AudioBuffer() {
;
}
AudioBuffer::~AudioBuffer() {
if(m_buffer)
free(m_buffer);
m_buffer = NULL;
}
size_t AudioBuffer::init() {
if(psramInit()) {
// PSRAM found, AudioBuffer will be allocated in PSRAM
m_buffSize = m_buffSizePSRAM;
if(m_buffer == NULL) {
m_buffer = (uint8_t*) ps_calloc(m_buffSize, sizeof(uint8_t));
m_buffSize = m_buffSizePSRAM - m_resBuffSize;
if(m_buffer == NULL) {
// not enough space in PSRAM, use ESP32 Flash Memory instead
m_buffer = (uint8_t*) calloc(m_buffSize, sizeof(uint8_t));
m_buffSize = m_buffSizeRAM - m_resBuffSize;
}
}
} else { // no PSRAM available, use ESP32 Flash Memory"
m_buffSize = m_buffSizeRAM;
m_buffer = (uint8_t*) calloc(m_buffSize, sizeof(uint8_t));
m_buffSize = m_buffSizeRAM - m_resBuffSize;
}
if(!m_buffer)
return 0;
resetBuffer();
return m_buffSize;
}
size_t AudioBuffer::freeSpace() {
if(m_readPtr >= m_writePtr) {
m_freeSpace = (m_readPtr - m_writePtr);
} else {
m_freeSpace = (m_endPtr - m_writePtr) + (m_readPtr - m_buffer);
}
if(m_f_start)
m_freeSpace = m_buffSize;
return m_freeSpace - 1;
}
size_t AudioBuffer::writeSpace() {
if(m_readPtr >= m_writePtr) {
m_writeSpace = (m_readPtr - m_writePtr - 1); // readPtr must not be overtaken
} else {
if(getReadPos() == 0)
m_writeSpace = (m_endPtr - m_writePtr - 1);
else
m_writeSpace = (m_endPtr - m_writePtr);
}
if(m_f_start)
m_writeSpace = m_buffSize - 1;
return m_writeSpace;
}
size_t AudioBuffer::bufferFilled() {
if(m_writePtr >= m_readPtr) {
m_dataLength = (m_writePtr - m_readPtr);
} else {
m_dataLength = (m_endPtr - m_readPtr) + (m_writePtr - m_buffer);
}
return m_dataLength;
}
void AudioBuffer::bytesWritten(size_t bw) {
m_writePtr += bw;
if(m_writePtr == m_endPtr) {
m_writePtr = m_buffer;
}
if(bw && m_f_start)
m_f_start = false;
}
void AudioBuffer::bytesWasRead(size_t br) {
m_readPtr += br;
if(m_readPtr >= m_endPtr) {
size_t tmp = m_readPtr - m_endPtr;
m_readPtr = m_buffer + tmp;
}
}
uint8_t* AudioBuffer::writePtr() {
return m_writePtr;
}
uint8_t* AudioBuffer::readPtr() {
size_t len = m_endPtr - m_readPtr;
if(len < 1600) { // be sure the last frame is completed
memcpy(m_endPtr, m_buffer, 1600);
}
return m_readPtr;
}
void AudioBuffer::resetBuffer() {
m_writePtr = m_buffer;
m_readPtr = m_buffer;
m_endPtr = m_buffer + m_buffSize;
m_f_start = true;
}
uint32_t AudioBuffer::getWritePos() {
return m_writePtr - m_buffer;
}
uint32_t AudioBuffer::getReadPos() {
return m_readPtr - m_buffer;
}
//---------------------------------------------------------------------------------------------------------------------
Audio::Audio(const uint8_t BCLK, const uint8_t LRC, const uint8_t DOUT) {
//i2s configuration
m_i2s_num = I2S_NUM_0; // i2s port number
#ifdef INTDAC
m_i2s_config.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_DAC_BUILT_IN );
m_i2s_config.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S_MSB);
#else
m_i2s_config.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX);
m_i2s_config.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB);
#endif
m_i2s_config.sample_rate = 16000;
m_i2s_config.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT;
m_i2s_config.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT;
m_i2s_config.communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S_MSB);
m_i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; // high interrupt priority
m_i2s_config.dma_buf_count = 8; // max buffers
m_i2s_config.dma_buf_len = 1024; // max value
m_i2s_config.use_apll = APLL_ENABLE;
m_i2s_config.tx_desc_auto_clear = true; // new in V1.0.1
m_i2s_config.fixed_mclk = I2S_PIN_NO_CHANGE;
i2s_driver_install((i2s_port_t)m_i2s_num, &m_i2s_config, 0, NULL);
m_BCLK=BCLK; // Bit Clock
m_LRC=LRC; // Left/Right Clock
m_DOUT=DOUT; // Data Out
setPinout(m_BCLK, m_LRC, m_DOUT, m_DIN);
m_metaline.reserve(100); // preallocate some space #77
m_filter[LEFTCHANNEL].a0 = 1;
m_filter[LEFTCHANNEL].a1 = 2;
m_filter[LEFTCHANNEL].a2 = 1;
m_filter[LEFTCHANNEL].b1 = 2;
m_filter[LEFTCHANNEL].b2 = 1;
m_filter[RIGHTCHANNEL].a0 = 1;
m_filter[RIGHTCHANNEL].a1 = -2;
m_filter[RIGHTCHANNEL].a2 = 1;
m_filter[RIGHTCHANNEL].b1 = -2;
m_filter[RIGHTCHANNEL].b2 = 1;
}
//---------------------------------------------------------------------------------------------------------------------
void Audio::initInBuff() {
static bool f_already_done = false;
if(!f_already_done) {
size_t size = InBuff.init();
if(size == m_buffSizeRAM - m_resBuffSize) {
sprintf(chbuf, "PSRAM not found, inputBufferSize = %u bytes", size - 1);
if(audio_info)
audio_info(chbuf);
m_f_psram = false;
f_already_done = true;
}
if(size == m_buffSizePSRAM - m_resBuffSize) {
sprintf(chbuf, "PSRAM found, inputBufferSize = %u bytes", size - 1);
if(audio_info)
audio_info(chbuf);
m_f_psram = true;
f_already_done = true;
}
}
}
//---------------------------------------------------------------------------------------------------------------------
esp_err_t Audio::I2Sstart(uint8_t i2s_num) {
return i2s_start((i2s_port_t) i2s_num);
}
esp_err_t Audio::I2Sstop(uint8_t i2s_num) {
return i2s_stop((i2s_port_t) i2s_num);
}
//---------------------------------------------------------------------------------------------------------------------
esp_err_t Audio::i2s_mclk_pin_select(const uint8_t pin) {
if(pin != 0 && pin != 1 && pin != 3) {
ESP_LOGE(TAG, "Only support GPIO0/GPIO1/GPIO3, gpio_num:%d", pin);
return ESP_ERR_INVALID_ARG;
}
switch(pin){
case 0:
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0_CLK_OUT1);
WRITE_PERI_REG(PIN_CTRL, 0xFFF0);
break;
case 1:
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD_CLK_OUT3);
WRITE_PERI_REG(PIN_CTRL, 0xF0F0);
break;
case 3:
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0RXD_U, FUNC_U0RXD_CLK_OUT2);
WRITE_PERI_REG(PIN_CTRL, 0xFF00);
break;
default:
break;
}
return ESP_OK;
}
//---------------------------------------------------------------------------------------------------------------------
Audio::~Audio() {
I2Sstop(m_i2s_num);
InBuff.~AudioBuffer();
}
//---------------------------------------------------------------------------------------------------------------------
void Audio::reset() {
stopSong();
I2Sstop(0);
I2Sstart(0);
initInBuff(); // initialize InputBuffer if not already done
InBuff.resetBuffer();
MP3Decoder_FreeBuffers();
AACDecoder_FreeBuffers();
client.stop();
client.flush(); // release memory
clientsecure.stop();
clientsecure.flush();
sprintf(chbuf, "buffers freed, free Heap: %u bytes", ESP.getFreeHeap());
if(audio_info) audio_info(chbuf);
m_f_chunked = false; // Assume not chunked
m_f_ctseen = false; // Contents type not seen yet
m_f_firstmetabyte = false;
m_f_firststream_ready = false;
m_f_localfile = false; // SPIFFS or SD? (onnecttoFS)
m_f_playing = false;
m_f_ssl = false;
m_f_stream = false;
m_f_swm = true; // Assume no metaint (stream without metadata)
m_f_webfile = false; // Assume radiostream (connecttohost)
m_f_webstream = false;
m_audioCurrentTime = 0; // Reset playtimer
m_audioFileDuration = 0;
m_avr_bitrate = 0; // the same as m_bitrate if CBR, median if VBR
m_bitRate = 0; // Bitrate still unknown
m_bytesNotDecoded = 0; // counts all not decodable bytes
m_chunkcount = 0; // for chunked streams
m_codec = CODEC_NONE;
m_contentlength = 0; // If Content-Length is known, count it
m_curSample = 0;
m_icyname = ""; // No StationName yet
m_metaCount = 0; // count bytes between metadata
m_metaint = 0; // No metaint yet
m_metaline = ""; // No metadata yet
m_LFcount = 0; // For end of header detection
m_st_remember = ""; // Delete the last streamtitle
m_totalcount = 0; // Reset totalcount
//TEST loop
m_loop_point = 0;
m_file_size = 0;
//TEST loop
memset(m_filterBuff, 0, sizeof(m_filterBuff)); // zero IIR filterbuffer
}
//---------------------------------------------------------------------------------------------------------------------
bool Audio::connecttohost(String host, const char *user, const char *pwd) {
// user and pwd for authentication only, can be empty
if(host.length() == 0) {
if(audio_info) audio_info("Hostaddress is empty");
return false;
}
reset();
if(m_lastHost != host) { // New host or reconnection?
m_lastHost = host; // Remember the current host
}
sprintf(chbuf, "Connect to new host: \"%s\"", host.c_str());
if(audio_info) audio_info(chbuf);
// authentication
String toEncode = String(user) + ":" + String(pwd);
String authorization = base64::encode(toEncode);
// initializationsequence
int16_t inx; // Position of ":" in hostname
int16_t ampersand; // Position of "&" in hostname
uint16_t port = 80; // Port number for host
String extension = "/"; // May be like "/mp3" in "skonto.ls.lv:8002/mp3"
String hostwoext = ""; // Host without extension and portnumber
String headerdata = "";
m_f_webstream = true;
setDatamode(AUDIO_HEADER); // Handle header
if(host.startsWith("http://")) {
host = host.substring(7);
m_f_ssl = false;
;
}
if(host.startsWith("https://")) {
host = host.substring(8);
m_f_ssl = true;
port = 443;
}
// Is it a playlist?
if(host.endsWith(".m3u") || host.endsWith(".pls") || host.endsWith("asx")) {
m_playlist = host; // Save copy of playlist URL
m_datamode = AUDIO_PLAYLISTINIT; // Yes, start in PLAYLIST mode
if(m_playlist_num == 0) { // First entry to play?
m_playlist_num = 1; // Yes, set index
}
sprintf(chbuf, "Playlist request, entry %d", m_playlist_num);
if(audio_info) audio_info(chbuf); // Most of the time there are zero bytes of metadata
}
// In the URL there may be an extension, like noisefm.ru:8000/play.m3u&t=.m3u
inx = host.indexOf("/"); // Search for begin of extension
if(inx > 0) { // Is there an extension?
extension = host.substring(inx); // Yes, change the default
hostwoext = host.substring(0, inx); // Host without extension
}
// In the URL there may be a portnumber
inx = host.indexOf(":"); // Search for separator
ampersand = host.indexOf("&"); // Search for additional extensions
if(inx >= 0) { // Portnumber available?
if((ampersand == -1) or (ampersand > inx)) { // Portnumber is valid if ':' comes before '&' #82
port = host.substring(inx + 1).toInt(); // Get portnumber as integer
hostwoext = host.substring(0, inx); // Host without portnumber
}
}
sprintf(chbuf, "Connect to \"%s\" on port %d, extension \"%s\"", hostwoext.c_str(), port, extension.c_str());
if(audio_info) audio_info(chbuf);
String resp = String("GET ") + extension + String(" HTTP/1.1\r\n")
+ String("Host: ") + hostwoext + String("\r\n")
+ String("Icy-MetaData:1\r\n")
+ String("Authorization: Basic " + authorization + "\r\n")
+ String("Connection: close\r\n\r\n");
if(m_f_ssl == false) {
if(client.connect(hostwoext.c_str(), port)) {
if(audio_info) audio_info("Connected to server");
client.print(resp);
m_f_running = true;
return true;
}
}
if(m_f_ssl == true) {
if(clientsecure.connect(hostwoext.c_str(), port)) {
if(audio_info) audio_info("SSL/TLS Connected to server");
clientsecure.print(resp);
sprintf(chbuf, "SSL has been established, free Heap: %u bytes", ESP.getFreeHeap());
if(audio_info) audio_info(chbuf);
m_f_running = true;
return true;
}
}
sprintf(chbuf, "Request %s failed!", host.c_str());
if(audio_info) audio_info(chbuf);
if(audio_showstation) audio_showstation("");
if(audio_showstreamtitle) audio_showstreamtitle("");
return false;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//TEST loop
bool Audio::setFileLoop(bool input){
m_f_loop = input;
return input;
}
//-----------------------------------------------------------------------------------------------------------------------------------
bool Audio::connecttoSD(String sdfile) {
return connecttoFS(SD, sdfile);
}
//-----------------------------------------------------------------------------------------------------------------------------------
bool Audio::connecttoFS(fs::FS &fs, String file) {
const uint8_t ascii[60] = {
//129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148 // UTF8(C3)
// Ä Å Æ Ç É Ñ // CHAR
000, 000, 000, 142, 143, 146, 128, 000, 144, 000, 000, 000, 000, 000, 000, 000, 165, 000, 000, 000, // ASCII
//149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168
// Ö Ü ß à ä å æ è
000, 153, 000, 000, 000, 000, 000, 154, 000, 000, 225, 133, 000, 000, 000, 132, 134, 145, 000, 138,
//169, 170, 171, 172. 173. 174. 175, 176, 177, 179, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188
// ê ë ì î ï ñ ò ô ö ù û ü
000, 136, 137, 141, 000, 140, 139, 000, 164, 149, 000, 147, 000, 148, 000, 000, 151, 000, 150, 129};
reset(); // free buffers an set defaults
uint16_t i = 0, j=0, s = 0;
bool f_C3_seen = false;
m_f_localfile = true;
if(!file.startsWith("/")) file = "/" + file;
while(file[i] != 0) { // convert UTF8 to ASCII
if(file[i] == 195){ // C3
i++;
f_C3_seen = true;
continue;
}
path[j] = file[i];
if(path[j] > 128 && path[j] < 189 && f_C3_seen == true) {
s = ascii[path[j] - 129];
if(s != 0) path[j] = s; // found a related ASCII sign
f_C3_seen = false;
}
i++; j++;
}
path[j] = 0;
m_audioName = file.substring(file.lastIndexOf('/') + 1, file.length());
sprintf(chbuf, "Reading file: \"%s\"", m_audioName.c_str());
if(audio_info) audio_info(chbuf);
audiofile = fs.open(path);
m_file_size = audiofile.size();//TEST loop
if(!audiofile) {
if(audio_info) audio_info("Failed to open file for reading");
return false;
}
String afn = (String) audiofile.name(); // audioFileName
if(afn.endsWith(".mp3") || afn.endsWith(".MP3")) { // MP3 section
m_codec = CODEC_MP3;
MP3Decoder_AllocateBuffers();
sprintf(chbuf, "MP3Decoder has been initialized, free Heap: %u bytes", ESP.getFreeHeap());
if(audio_info) audio_info(chbuf);
audiofile.readBytes(chbuf, 10);
if((chbuf[0] != 'I') || (chbuf[1] != 'D') || (chbuf[2] != '3')) {
if(audio_info) audio_info("file has no mp3 tag, skip metadata");
setFilePos(0);
m_loop_point = 0;//TEST loop
m_f_running = true;
return false;
}
m_rev = chbuf[3];
switch(m_rev){
case 2:
m_f_unsync = (chbuf[5] & 0x80);
m_f_exthdr = false;
break;
case 3:
case 4:
m_f_unsync = (chbuf[5] & 0x80); // bit7
m_f_exthdr = (chbuf[5] & 0x40); // bit6 extended header
break;
};
m_id3Size = chbuf[6];
m_id3Size = m_id3Size << 7;
m_id3Size |= chbuf[7];
m_id3Size = m_id3Size << 7;
m_id3Size |= chbuf[8];
m_id3Size = m_id3Size << 7;
m_id3Size |= chbuf[9];
// Every read from now may be unsync'd
sprintf(chbuf, "ID3 version=%i", m_rev);
if(audio_info) audio_info(chbuf);
sprintf(chbuf, "ID3 framesSize=%i", m_id3Size);
if(audio_info) audio_info(chbuf);
readID3Metadata();
m_f_running = true;
//TEST loop
m_loop_point = getFilePos();
sprintf(chbuf, "fp=%u", m_loop_point);
if(audio_info) audio_info(chbuf);
//TEST loop
return true;
} // end MP3 section
if(afn.endsWith(".wav")) { // WAVE section
m_codec = CODEC_WAV;
audiofile.readBytes(chbuf, 4); // read RIFF tag
if((chbuf[0] != 'R') || (chbuf[1] != 'I') || (chbuf[2] != 'F') || (chbuf[3] != 'F')) {
if(audio_info) audio_info("file has no RIFF tag");
setFilePos(0);
return false;
}
audiofile.readBytes(chbuf, 4); // read chunkSize (datalen)
uint32_t cs = (uint32_t) (chbuf[0] + (chbuf[1] << 8) + (chbuf[2] << 16) + (chbuf[3] << 24) - 8);
audiofile.readBytes(chbuf, 4); /* read wav-format */
chbuf[5] = 0;
if((chbuf[0] != 'W') || (chbuf[1] != 'A') || (chbuf[2] != 'V') || (chbuf[3] != 'E')) {
if(audio_info) audio_info("format tag is not WAVE");
setFilePos(0);
return false;
}
while(true) { // skip wave chunks, seek for fmt element
audiofile.readBytes(chbuf, 4); // read wav-format
if((chbuf[0] == 'f') && (chbuf[1] == 'm') && (chbuf[2] == 't')) {
//if(audio_info) audio_info("format tag found");
break;
}
}
audiofile.readBytes(chbuf, 4); // fmt chunksize
cs = (uint32_t) (chbuf[0] + (chbuf[1] << 8));
if(cs > 40) return false; //something is wrong
uint8_t bts = cs - 16; // bytes to skip if fmt chunk is >16
audiofile.readBytes(chbuf, 16);
uint16_t fc = (uint16_t) (chbuf[0] + (chbuf[1] << 8)); // Format code
uint16_t nic = (uint16_t) (chbuf[2] + (chbuf[3] << 8)); // Number of interleaved channels
uint32_t sr = (uint32_t) (chbuf[4] + (chbuf[5] << 8) + (chbuf[6] << 16) + (chbuf[7] << 24)); // Samplerate
uint32_t dr = (uint32_t) (chbuf[8] + (chbuf[9] << 8) + (chbuf[10] << 16) + (chbuf[11] << 24)); // Datarate
uint16_t dbs = (uint16_t) (chbuf[12] + (chbuf[13] << 8)); // Data block size
uint16_t bps = (uint16_t) (chbuf[14] + (chbuf[15] << 8)); // Bits per sample
if(audio_info) {
sprintf(chbuf, "FormatCode=%u", fc);
audio_info(chbuf);
sprintf(chbuf, "Channel=%u", nic);
audio_info(chbuf);
sprintf(chbuf, "SampleRate=%u", sr);
audio_info(chbuf);
sprintf(chbuf, "DataRate=%u", dr);
audio_info(chbuf);
sprintf(chbuf, "DataBlockSize=%u", dbs);
audio_info(chbuf);
sprintf(chbuf, "BitsPerSample=%u", bps);
audio_info(chbuf);
}
if(fc != 1) {
if(audio_info) audio_info("format code is not 1 (PCM)");
return false;
}
if(nic != 1 && nic != 2) {
if(audio_info) audio_info("number of channels must be 1 or 2");
return false;
}
if(bps != 8 && bps != 16) {
if(audio_info) audio_info("bits per sample must be 8 or 16");
return false;
}
setBitsPerSample(bps);
setChannels(nic);
setSampleRate(sr);
m_bitRate = nic * sr * bps;
if(audio_info) sprintf(chbuf, "BitRate=%u", m_bitRate);
audio_info(chbuf);
audiofile.readBytes(chbuf, bts); // skip to data
uint32_t s = getFilePos();
// here can be extra info, seek for data;
while(true) {
setFilePos(s);
audiofile.readBytes(chbuf, 4); /* read header signature */
if((chbuf[0] == 'd') && (chbuf[1] == 'a') && (chbuf[2] == 't') && (chbuf[3] == 'a')) break;
s++;
}
audiofile.readBytes(chbuf, 4); // read chunkSize (datalen)
cs = chbuf[0] + (chbuf[1] << 8) + (chbuf[2] << 16) + (chbuf[3] << 24) - 44;
sprintf(chbuf, "DataLength=%u", cs);
if(audio_info) audio_info(chbuf);
m_f_running = true;
//TEST loop
m_loop_point = getFilePos();
// sprintf(chbuf, "fp=%u", m_loop_point);
// if(audio_info) audio_info(chbuf);
//TEST loop
return true;
} // end WAVE section
if(audio_info) audio_info("Neither wave nor mp3 format found");
return false;
}
//---------------------------------------------------------------------------------------------------------------------
bool Audio::connecttospeech(String speech, String lang){
reset();
String host = "translate.google.com.vn";
String path = "/translate_tts";
uint32_t bytesCanBeWritten = 0;
uint32_t bytesCanBeRead = 0;
int32_t bytesAddedToBuffer = 0;
int16_t bytesDecoded = 0;
String tts= path + "?ie=UTF-8&q=" + urlencode(speech) +
"&tl=" + lang + "&client=tw-ob";
String resp = String("GET ") + tts + String(" HTTP/1.1\r\n")
+ String("Host: ") + host + String("\r\n")
+ String("User-Agent: GoogleTTS for ESP32/1.0.0\r\n")
+ String("Accept-Encoding: identity\r\n")
+ String("Accept: text/html\r\n")
+ String("Connection: close\r\n\r\n");
if(!clientsecure.connect(host.c_str(), 443)) {
Serial.println("Connection failed");
return false;
}
clientsecure.print(resp);
sprintf(chbuf, "SSL has been established, free Heap: %u bytes", ESP.getFreeHeap());
if(audio_info) audio_info(chbuf);
while(clientsecure.connected()) { // read the header
String line = clientsecure.readStringUntil('\n');
line += "\n";
// if(audio_info) audio_info(line.c_str());
if(line == "\r\n") break;
}
m_codec = CODEC_MP3;
AACDecoder_FreeBuffers();
MP3Decoder_AllocateBuffers();
sprintf(chbuf, "MP3Decoder has been initialized, free Heap: %u bytes", ESP.getFreeHeap());
if(audio_info) audio_info(chbuf);
while(!playI2Sremains()) {
;
}
while(clientsecure.available() == 0) {
;
}
while(clientsecure.available() > 0) {
bytesCanBeWritten = InBuff.writeSpace();
bytesAddedToBuffer = clientsecure.read(InBuff.writePtr(), bytesCanBeWritten);
if(bytesAddedToBuffer > 0) InBuff.bytesWritten(bytesAddedToBuffer);
bytesCanBeRead = InBuff.bufferFilled();
if(bytesCanBeRead > 1600) bytesCanBeRead = 1600;
if(bytesCanBeRead == 1600) { // mp3 or aac frame complete?
while(InBuff.bufferFilled() >= 1600) {
bytesDecoded = sendBytes(InBuff.readPtr(), InBuff.bufferFilled());
InBuff.bytesWasRead(bytesDecoded);
}
}
}
do {
bytesDecoded = sendBytes(InBuff.readPtr(), InBuff.bufferFilled());
} while(bytesDecoded > 100);
memset(m_outBuff, 0, sizeof(m_outBuff));
for(int i = 0; i < 4; i++) {
m_validSamples = 2048;
while(m_validSamples) {
playChunk();
}
}
while(!playI2Sremains()) {
;
}
MP3Decoder_FreeBuffers();
stopSong();
clientsecure.stop();
clientsecure.flush();
m_codec = CODEC_NONE;
if(audio_eof_speech) audio_eof_speech(speech.c_str());
return true;
}
//---------------------------------------------------------------------------------------------------------------------
String Audio::urlencode(String str) {
String encodedString = "";
char c;
char code0;
char code1;
for(int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if(c == ' ')
encodedString += '+';
else if(isalnum(c))
encodedString += c;
else {
code1 = (c & 0xf) + '0';
if((c & 0xf) > 9) code1 = (c & 0xf) - 10 + 'A';
c = (c >> 4) & 0xf;
code0 = c + '0';
if(c > 9) code0 = c - 10 + 'A';
encodedString += '%';
encodedString += code0;
encodedString += code1;
}
}
return encodedString;
}
//---------------------------------------------------------------------------------------------------------------------
void Audio::readID3Metadata() {
char frameid[5];
int framesize = 0;
bool compressed;
char value[256];
bool bitorder = false;
uint8_t uni_h = 0;
uint8_t uni_l = 0;
int id3Size = m_id3Size;
String tag = "";
if(m_f_exthdr) {
if(audio_info) audio_info("ID3 extended header");
int ehsz = (audiofile.read() << 24) | (audiofile.read() << 16) | (audiofile.read() << 8) | (audiofile.read());
id3Size -= 4;
for(int j = 0; j < ehsz - 4; j++) {
audiofile.read();
id3Size--;
} // Throw it away
}
else if(audio_info) audio_info("ID3 normal frames");
do {
frameid[0] = audiofile.read();
frameid[1] = audiofile.read();
frameid[2] = audiofile.read();
id3Size -= 3;
if(m_rev == 2)
frameid[3] = 0;
else {
frameid[3] = audiofile.read();
id3Size--;
}
frameid[4] = 0; // terminate the string
tag = frameid;
if(frameid[0] == 0 && frameid[1] == 0 && frameid[2] == 0 && frameid[3] == 0) {
// We're in padding
while(id3Size != 0) {
audiofile.read();
id3Size--;
}
}
else {
if(m_rev == 2) {
framesize = (audiofile.read() << 16) | (audiofile.read() << 8) | (audiofile.read());
id3Size -= 3;
compressed = false;
}
else {
framesize = (audiofile.read() << 24) | (audiofile.read() << 16) | (audiofile.read() << 8)
| (audiofile.read());
id3Size -= 4;
audiofile.read(); // skip 1st flag
id3Size--;
compressed = audiofile.read() & 0x80;
id3Size--;
}
if(compressed) {
log_i("iscompressed");
int decompsize = (audiofile.read() << 24) | (audiofile.read() << 16) | (audiofile.read() << 8)
| (audiofile.read());
id3Size -= 4;
(void) decompsize;
for(int j = 0; j < framesize; j++) {
audiofile.read();
id3Size--;
}
}
// Read the value
uint32_t i = 0;
uint16_t j = 0, k = 0, m = 0;
bool isUnicode;
if(framesize > 0) {
isUnicode = (audiofile.read() == 1) ? true : false;
id3Size--;
if(framesize < 256) {
audiofile.readBytes(value, framesize - 1);
id3Size -= framesize - 1;
i = framesize - 1;
value[framesize - 1] = 0;
}
else {
if(tag == "APIC") { // a image embedded in file, passing it to external function
//log_i("it's a image");
isUnicode = false;
const uint32_t preReadFilePos = getFilePos();
if(audio_id3image) audio_id3image(audiofile, framesize);
setFilePos(preReadFilePos + framesize - 1);
id3Size -= framesize - 1;
}
else {
// store the first 255 bytes in buffer and cut the remains
audiofile.readBytes(value, 255);
id3Size -= 255;
value[255] = 0;
i = 255;
// big block, skip it
setFilePos(getFilePos() + framesize - 1 - 255);
id3Size -= framesize - 1;
}
}
if(isUnicode && framesize > 1) { // convert unicode to utf-8 U+0020...U+07FF
j = 0;
m = 0;
while(m < i - 1) {
if((value[m] == 0xFE) && (value[m + 1] == 0xFF)) {
bitorder = true;
j = m + 2;
} // MSB/LSB
if((value[m] == 0xFF) && (value[m + 1] == 0xFE)) {
bitorder = false;
j = m + 2;
} //LSB/MSB
m++;
} // seek for last bitorder
m = 0;
if(j > 0) {
for(k = j; k < i - 1; k += 2) {
if(bitorder == true) {
uni_h = value[k];
uni_l = value[k + 1];
}
else {
uni_l = value[k];
uni_h = value[k + 1];
}
uint16_t uni_hl = (uni_h << 8) + uni_l;
uint8_t utf8_h = (uni_hl >> 6); // div64
uint8_t utf8_l = uni_l;
if(utf8_h > 3) {
utf8_h += 0xC0;
if(uni_l < 0x40)
utf8_l = uni_l + 0x80;
else if(uni_l < 0x80)
utf8_l = uni_l += 0x40;
else if(uni_l < 0xC0)
utf8_l = uni_l;
else
utf8_l = uni_l - 0x40;
}
if(utf8_h > 3) {
value[m] = utf8_h;
m++;
}
value[m] = utf8_l;
m++;
}
}
value[m] = 0;
i = m;
}
}
chbuf[0] = 0;
j = 0;
k = 0;
while(j < i) {
if(value[j] > 0x19) {
value[k] = value[j];
k++;
}
else {
i--;
}
j++;
} //remove non printables
value[i] = 0; // new termination
// Revision 2
if(tag == "CNT") sprintf(chbuf, "Play counter: %s", value);
if(tag == "COM") sprintf(chbuf, "Comments: %s", value);
if(tag == "CRA") sprintf(chbuf, "Audio encryption: %s", value);
if(tag == "CRM") sprintf(chbuf, "Encrypted meta frame: %s", value);
if(tag == "ETC") sprintf(chbuf, "Event timing codes: %s", value);
if(tag == "EQU") sprintf(chbuf, "Equalization: %s", value);
if(tag == "IPL") sprintf(chbuf, "Involved people list: %s", value);
if(tag == "PIC") sprintf(chbuf, "Attached picture: %s", value);
if(tag == "SLT") sprintf(chbuf, "Synchronized lyric/text: %s", value);
if(tag == "TAL") sprintf(chbuf, "Album/Movie/Show title: %s", value);
if(tag == "TBP") sprintf(chbuf, "BPM (Beats Per Minute): %s", value);
if(tag == "TCM") sprintf(chbuf, "Composer: %s", value);
if(tag == "TCO") sprintf(chbuf, "Content type: %s", value);
if(tag == "TCR") sprintf(chbuf, "Copyright message: %s", value);
if(tag == "TDA") sprintf(chbuf, "Date: %s", value);
if(tag == "TDY") sprintf(chbuf, "Playlist delay: %s", value);
if(tag == "TEN") sprintf(chbuf, "Encoded by: %s", value);
if(tag == "TFT") sprintf(chbuf, "File type: %s", value);
if(tag == "TIM") sprintf(chbuf, "Time: %s", value);
if(tag == "TKE") sprintf(chbuf, "Initial key: %s", value);
if(tag == "TLA") sprintf(chbuf, "Language(s): %s", value);
if(tag == "TLE") sprintf(chbuf, "Length: %s", value);
if(tag == "TMT") sprintf(chbuf, "Media type: %s", value);
if(tag == "TOA") sprintf(chbuf, "Original artist(s)/performer(s): %s", value);
if(tag == "TOF") sprintf(chbuf, "Original filename: %s", value);
if(tag == "TOL") sprintf(chbuf, "Original Lyricist(s)/text writer(s): %s", value);
if(tag == "TOR") sprintf(chbuf, "Original release year: %s", value);
if(tag == "TOT") sprintf(chbuf, "Original album/Movie/Show title: %s", value);
if(tag == "TP1") sprintf(chbuf, "Lead artist(s)/Lead performer(s)/Soloist(s)/Performing group: %s", value);
if(tag == "TP2") sprintf(chbuf, "Band/Orchestra/Accompaniment: %s", value);
if(tag == "TP3") sprintf(chbuf, "Conductor/Performer refinement: %s", value);
if(tag == "TP4") sprintf(chbuf, "Interpreted, remixed, or otherwise modified by: %s", value);
if(tag == "TPA") sprintf(chbuf, "Part of a set: %s", value);
if(tag == "TPB") sprintf(chbuf, "Publisher: %s", value);
if(tag == "TRC") sprintf(chbuf, "ISRC (International Standard Recording Code): %s", value);
if(tag == "TRD") sprintf(chbuf, "Recording dates: %s", value);
if(tag == "TRK") sprintf(chbuf, "Track number/Position in set: %s", value);
if(tag == "TSI") sprintf(chbuf, "Size: %s", value);
if(tag == "TSS") sprintf(chbuf, "Software/hardware and settings used for encoding: %s", value);
if(tag == "TT1") sprintf(chbuf, "Content group description: %s", value);
if(tag == "TT2") sprintf(chbuf, "Title/Songname/Content description: %s", value);
if(tag == "TT3") sprintf(chbuf, "Subtitle/Description refinement: %s", value);
if(tag == "TXT") sprintf(chbuf, "Lyricist/text writer: %s", value);
if(tag == "TXX") sprintf(chbuf, "User defined text information frame: %s", value);
if(tag == "TYE") sprintf(chbuf, "Year: %s", value);
if(tag == "UFI") sprintf(chbuf, "Unique file identifier: %s", value);
if(tag == "ULT") sprintf(chbuf, "Unsychronized lyric/text transcription: %s", value);
if(tag == "WAF") sprintf(chbuf, "Official audio file webpage: %s", value);
if(tag == "WAR") sprintf(chbuf, "Official artist/performer webpage: %s", value);
if(tag == "WAS") sprintf(chbuf, "Official audio source webpage: %s", value);
if(tag == "WCM") sprintf(chbuf, "Commercial information: %s", value);
if(tag == "WCP") sprintf(chbuf, "Copyright/Legal information: %s", value);
if(tag == "WPB") sprintf(chbuf, "Publishers official webpage: %s", value);
if(tag == "WXX") sprintf(chbuf, "User defined URL link frame: %s", value);
// Revision 3
if(tag == "COMM") sprintf(chbuf, "Comment: %s", value);
if(tag == "OWNE") sprintf(chbuf, "Ownership: %s", value);
if(tag == "PRIV") sprintf(chbuf, "Private: %s", value);
if(tag == "SYLT") sprintf(chbuf, "SynLyrics: %s", value);
if(tag == "TALB") sprintf(chbuf, "Album: %s", value);
if(tag == "TBPM") sprintf(chbuf, "BeatsPerMinute: %s", value);
if(tag == "TCMP") sprintf(chbuf, "Compilation: %s", value);
if(tag == "TCOM") sprintf(chbuf, "Composer: %s", value);
if(tag == "TCOP") sprintf(chbuf, "Copyright: %s", value);
if(tag == "TDAT") sprintf(chbuf, "Date: %s", value);
if(tag == "TEXT") sprintf(chbuf, "Lyricist: %s", value);
if(tag == "TIME") sprintf(chbuf, "Time: %s", value);
if(tag == "TIT1") sprintf(chbuf, "Grouping: %s", value);
if(tag == "TIT2") sprintf(chbuf, "Title: %s", value);
if(tag == "TIT3") sprintf(chbuf, "Subtitle: %s", value);
if(tag == "TLAN") sprintf(chbuf, "Language: %s", value);
if(tag == "TLEN") sprintf(chbuf, "Length: %s", value);
if(tag == "TMED") sprintf(chbuf, "Media: %s", value);
if(tag == "TOAL") sprintf(chbuf, "OriginalAlbum: %s", value);
if(tag == "TOPE") sprintf(chbuf, "OriginalArtist: %s", value);
if(tag == "TORY") sprintf(chbuf, "OriginalReleaseYear: %s", value);
if(tag == "TPE1") sprintf(chbuf, "Artist: %s", value);
if(tag == "TPE2") sprintf(chbuf, "Band: %s", value);
if(tag == "TPE3") sprintf(chbuf, "Conductor: %s", value);
if(tag == "TPE4") sprintf(chbuf, "InterpretedBy: %s", value);
if(tag == "TPOS") sprintf(chbuf, "PartOfSet: %s", value);
if(tag == "TPUB") sprintf(chbuf, "Publisher: %s", value);
if(tag == "TRCK") sprintf(chbuf, "Track: %s", value);
if(tag == "TRDA") sprintf(chbuf, "RecordingDates: %s", value);
if(tag == "TXXX") sprintf(chbuf, "UserDefinedText: %s", value);
if(tag == "TYER") sprintf(chbuf, "Year: %s", value);
if(tag == "USER") sprintf(chbuf, "TermsOfUse: %s", value);
if(tag == "USLT") sprintf(chbuf, "Lyrics: %s", value);
if(tag == "XDOR") sprintf(chbuf, "OriginalReleaseTime: %s", value);
if(chbuf[0] != 0) if(audio_id3data) audio_id3data(chbuf);
}
} while(id3Size > 0);
}
//---------------------------------------------------------------------------------------------------------------------
void Audio::stopSong() {
if(m_f_running) {
m_f_running = false;
audiofile.close();
}
memset(m_outBuff, 0, sizeof(m_outBuff)); //Clear OutputBuffer
i2s_zero_dma_buffer((i2s_port_t) m_i2s_num);
}
//---------------------------------------------------------------------------------------------------------------------
bool Audio::playI2Sremains() { // returns true if all dma_buffs flushed
static uint8_t dma_buf_count = 0;
// there is no function to see if dma_buff is empty. So fill the dma completely.
// As soon as all remains played this function returned. Or you can take this to create a short silence.
if(m_sampleRate == 0) setSampleRate(96000);
if(m_channels == 0) setChannels(2);
if(getBitsPerSample() > 8) memset(m_outBuff, 0, sizeof(m_outBuff)); //Clear OutputBuffer (signed)
else memset(m_outBuff, 128, sizeof(m_outBuff)); //Clear OutputBuffer (unsigned, PCM 8u)
//play remains and then flush dmaBuff
m_validSamples = m_i2s_config.dma_buf_len;
while(m_validSamples) {
playChunk();