Repository navigation
Expand file tree
/
Copy pathApp.cpp
More file actions
6686 lines (6389 loc) · 245 KB
/
Copy pathApp.cpp
File metadata and controls
6686 lines (6389 loc) · 245 KB
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
#include "App.h"
#include <algorithm>
#include <math.h>
#include <string.h>
#include "A2dpSourceDiagnostics.h"
#include "Config.h"
#include "Log.h"
#include "Platform.h"
#include "driver/gpio.h"
#include "pgmspace.h"
#include "esp_a2dp_legacy_api.h"
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_cpu.h"
#include "esp_coexist.h"
#include "esp_event.h"
#include "esp_heap_caps.h"
#include "mdns.h"
#include "esp_netif.h"
#include "nvs.h"
#include "esp_system.h"
#include "esp_timer.h"
#include "esp_wifi.h"
#include "freertos/idf_additions.h"
#include "nvs_flash.h"
#include "perfmon.h"
// 切り分け用: App.hをSYNTH_RENDER_PROFILING=1で確定させた後、
// App.cppの計測実行コードだけをcompile outする。追加されたclass layoutと
// renderVoiceFramesのABIは維持する。
#if SYNTH_RENDER_PROFILING
#define SYNTH_RENDER_PROFILING_LAYOUT 1
#else
#define SYNTH_RENDER_PROFILING_LAYOUT 0
#endif
#if SYNTH_RENDER_PROFILING && !SYNTH_RENDER_PROFILE_RUNTIME
#undef SYNTH_RENDER_PROFILING
#define SYNTH_RENDER_PROFILING 0
#endif
#if SYNTH_RENDER_PROFILING
#define SYNTH_RENDER_PROFILING_EXECUTION 1
#else
#define SYNTH_RENDER_PROFILING_EXECUTION 0
#endif
#if SYNTH_RENDER_PROFILE_CLOCK_READS
#define RENDER_PROFILE_CCOUNT() esp_cpu_get_cycle_count()
#define RENDER_PROFILE_TIME_US() static_cast<uint32_t>(esp_timer_get_time())
#else
#define RENDER_PROFILE_CCOUNT() 0U
#define RENDER_PROFILE_TIME_US() 0U
#endif
namespace {
using std::max;
using std::min;
App* g_app = nullptr;
#if SYNTH_RENDER_PROFILING && SYNTH_RENDER_PROFILE_VOICE_CODE
// renderVoiceFrames()のABIを変更せずに、呼出し元Coreのprofile対象を選ぶ。
// slot 0はCore0/helper、slot 1はCore1/mainだけが書き込むため、mutexやatomicは不要。
struct RendererProfileCallContext {
uint32_t bank;
bool helperCore;
};
RendererProfileCallContext g_rendererProfileCallContexts[2] = {};
#endif
// dual-core rendererの固定部分和buffer。未初期化領域へ置き、firmware imageを増やさない。
constexpr size_t kParallelRenderFrames = 256;
#if APP_USE_32BIT_IRAM_AUDIO_BUFFERS
constexpr size_t kIramAudioRingFrames = 4096;
struct AudioIramBuffers {
uint32_t audioRing[kIramAudioRingFrames];
int32_t mainMixedLeftQ15[kParallelRenderFrames];
int32_t mainMixedRightQ15[kParallelRenderFrames];
int32_t mainReverbInputQ15[kParallelRenderFrames];
int32_t mainChorusInputQ15[kParallelRenderFrames];
int32_t helperMixedLeftQ15[kParallelRenderFrames];
int32_t helperMixedRightQ15[kParallelRenderFrames];
int32_t helperReverbInputQ15[kParallelRenderFrames];
int32_t helperChorusInputQ15[kParallelRenderFrames];
};
static_assert(sizeof(AudioIramBuffers) == 24 * 1024,
"IRAM audio buffer slab must remain 24 KiB");
AudioIramBuffers* g_audioIramBuffers = nullptr;
int32_t* g_mainMixedLeftQ15 = nullptr;
int32_t* g_mainMixedRightQ15 = nullptr;
int32_t* g_mainReverbInputQ15 = nullptr;
int32_t* g_mainChorusInputQ15 = nullptr;
int32_t* g_helperMixedLeftQ15 = nullptr;
int32_t* g_helperMixedRightQ15 = nullptr;
int32_t* g_helperReverbInputQ15 = nullptr;
int32_t* g_helperChorusInputQ15 = nullptr;
#else
int32_t g_mainMixedLeftQ15[kParallelRenderFrames];
int32_t g_mainMixedRightQ15[kParallelRenderFrames];
int32_t g_mainReverbInputQ15[kParallelRenderFrames];
int32_t g_mainChorusInputQ15[kParallelRenderFrames];
int32_t g_helperMixedLeftQ15[kParallelRenderFrames];
int32_t g_helperMixedRightQ15[kParallelRenderFrames];
int32_t g_helperReverbInputQ15[kParallelRenderFrames];
int32_t g_helperChorusInputQ15[kParallelRenderFrames];
#endif
// Delay sendはIRAM slabとは分離してDRAMに置く。hot dataをIRAMへ置かない。
int32_t g_mainDelayInputQ15[kParallelRenderFrames];
int32_t g_helperDelayInputQ15[kParallelRenderFrames];
#if APP_USE_ADPCM_TONES
uint32_t g_adpcmNibbleDecodeCount = 0;
uint32_t g_adpcmCacheResetCount = 0;
uint32_t g_adpcmPairHitCount = 0;
uint32_t g_adpcmBlockBoundaryCount = 0;
uint32_t g_adpcmMaxDecodePerRead = 0;
#endif
#if APP_USE_MULAW_TONES
int16_t g_mulawDecodeTable[256];
#if APP_ENABLE_MULAW_CACHE_STATS
uint32_t g_mulawSameIndexHitCount = 0;
uint32_t g_mulawOneStepHitCount = 0;
uint32_t g_mulawReloadCount = 0;
#endif
#endif
constexpr uint32_t kFlashEraseBlockSize = 4096;
constexpr EventBits_t kWifiConnectedBit = BIT0;
constexpr EventBits_t kWifiFailedBit = BIT1;
constexpr uint8_t kWifiRetriesBeforeFailure = 10;
constexpr uint32_t kWifiConnectTimeoutMs = 15000;
constexpr uint32_t kWifiSetupButtonPollMs = 20;
constexpr uint32_t kWifiRollbackRetryMs = 250;
constexpr char kWifiNvsNamespace[] = "wifi_cfg";
constexpr char kWifiNvsSsidKey[] = "ssid";
constexpr char kWifiNvsPasswordKey[] = "password";
constexpr char kWifiNvsForceSetupKey[] = "force_setup";
constexpr char kWifiPlaceholderSsid[] = "YOUR_WIFI_SSID";
constexpr char kWifiPlaceholderPassword[] = "YOUR_WIFI_PASSWORD";
constexpr char kProvisioningApSsid[] = "ESP32-Tiny-MIDI-Setup";
constexpr char kProvisioningApPassword[] = "12345678";
constexpr char kProvisioningApIp[] = "192.168.4.1";
constexpr char kMdnsHostname[] = "esp32-tiny-midi";
constexpr char kMdnsInstanceName[] = "ESP32 Tiny MIDI Synthesizer";
bool wifiDeadlineReached(uint32_t nowMs, uint32_t deadlineMs) {
return static_cast<int32_t>(nowMs - deadlineMs) >= 0;
}
bool wifiSetupButtonLongPressed() {
const int pinNumber = Config::WifiSetupButtonGpio;
if (pinNumber < 0 || pinNumber >= static_cast<int>(GPIO_NUM_MAX)) {
Log::infof("Wi-Fi setup button GPIO is invalid: %d", pinNumber);
return false;
}
gpio_config_t buttonConfig = {};
buttonConfig.pin_bit_mask = 1ULL << static_cast<uint32_t>(pinNumber);
buttonConfig.mode = GPIO_MODE_INPUT;
buttonConfig.pull_up_en = Config::WifiSetupButtonActiveLow
? GPIO_PULLUP_ENABLE : GPIO_PULLUP_DISABLE;
buttonConfig.pull_down_en = Config::WifiSetupButtonActiveLow
? GPIO_PULLDOWN_DISABLE : GPIO_PULLDOWN_ENABLE;
buttonConfig.intr_type = GPIO_INTR_DISABLE;
const esp_err_t configResult = gpio_config(&buttonConfig);
if (configResult != ESP_OK) {
Log::infof("Wi-Fi setup button GPIO%d init failed: %s", pinNumber,
esp_err_to_name(configResult));
return false;
}
const int activeLevel = Config::WifiSetupButtonActiveLow ? 0 : 1;
const gpio_num_t pin = static_cast<gpio_num_t>(pinNumber);
if (gpio_get_level(pin) != activeLevel) {
return false;
}
const TickType_t holdTicks = pdMS_TO_TICKS(Config::WifiSetupButtonHoldMs);
const TickType_t pollTicks = max<TickType_t>(
1, pdMS_TO_TICKS(kWifiSetupButtonPollMs));
const TickType_t startedAt = xTaskGetTickCount();
while (gpio_get_level(pin) == activeLevel) {
if (static_cast<TickType_t>(xTaskGetTickCount() - startedAt) >= holdTicks) {
Log::infof(
"Wi-Fi provisioning requested by BOOT button: GPIO%d held for %lu ms",
pinNumber,
static_cast<unsigned long>(Config::WifiSetupButtonHoldMs));
return true;
}
vTaskDelay(pollTicks);
}
return false;
}
void copyWifiConfigField(uint8_t* destination, size_t capacity,
const char* source) {
if (destination == nullptr || capacity == 0 || source == nullptr) return;
const size_t length = min(strlen(source), capacity);
memcpy(destination, source, length);
if (length < capacity) destination[length] = '\0';
}
bool requestProvisioningOnNextBoot() {
nvs_handle_t handle = 0;
if (nvs_open(kWifiNvsNamespace, NVS_READWRITE, &handle) != ESP_OK) return false;
esp_err_t result = nvs_set_u8(handle, kWifiNvsForceSetupKey, 1);
if (result == ESP_OK) result = nvs_commit(handle);
nvs_close(handle);
return result == ESP_OK;
}
bool consumeProvisioningRequest() {
nvs_handle_t handle = 0;
if (nvs_open(kWifiNvsNamespace, NVS_READWRITE, &handle) != ESP_OK) return false;
uint8_t requested = 0;
const bool present =
nvs_get_u8(handle, kWifiNvsForceSetupKey, &requested) == ESP_OK && requested != 0;
if (present) {
nvs_erase_key(handle, kWifiNvsForceSetupKey);
nvs_commit(handle);
}
nvs_close(handle);
return present;
}
constexpr int32_t kQ15One = 32767;
constexpr uint32_t kQ16One = 65536;
// Keep the adaptive helper split conservative for Core 0, which also runs
// Wi-Fi/Bluetooth and MIDI parsing, while allowing up to half the active
// voices on Core 0 when the adaptive measurements show enough headroom.
constexpr uint32_t kHelperVoiceCapMax = 14u;
constexpr uint32_t kHelperVoiceCapNumerator = 7u;
constexpr uint32_t kHelperVoiceCapDenominator = 16u;
constexpr uint32_t kAutoPlaybackStabilizationMs = 3000u;
struct StereoPanQ15 {
int16_t left;
int16_t right;
};
constexpr StereoPanQ15 kChannelPanQ15[16] = {
{32767, 32767}, {32767, 18022}, {18022, 32767}, {32767, 24575},
{24575, 32767}, {32767, 11468}, {11468, 32767}, {32767, 27852},
{27852, 32767}, {32767, 32767}, {32767, 21299}, {21299, 32767},
{32767, 14745}, {14745, 32767}, {32767, 29490}, {32767, 32767}};
inline uint32_t packStereoFrame(int16_t left, int16_t right) {
return static_cast<uint16_t>(left) |
(static_cast<uint32_t>(static_cast<uint16_t>(right)) << 16);
}
inline int16_t stereoLeft(uint32_t frame) {
return static_cast<int16_t>(frame & 0xFFFFu);
}
inline int16_t stereoRight(uint32_t frame) {
return static_cast<int16_t>(frame >> 16);
}
constexpr uint32_t kRenderHistogramUpperUs[16] = {
250, 500, 750, 1000, 1500, 2000, 3000, 4000,
5000, 6000, 7000, 8000, 10000, 12000, 16000, 20000};
constexpr float kMidiPitchClassHz[12] = {
8.1757989156f, 8.6619572180f, 9.1770239974f, 9.7227182413f,
10.3008611535f, 10.9133822323f, 11.5623257097f, 12.2498573744f,
12.9782717994f, 13.7500000000f, 14.5676175474f, 15.4338531643f};
enum class PcmRole : uint8_t {
Bass = 0,
Lead,
Pad,
Organ,
Brass,
Bell,
Pluck,
Kick
};
struct PcmSampleDef {
#if APP_USE_ADPCM_TONES || APP_USE_MULAW_TONES
const uint8_t* data;
#else
const int16_t* data;
#endif
uint32_t length;
uint32_t loopStart;
uint32_t loopEnd;
uint32_t cycleLength;
bool loopEnabled;
bool fixedPitch;
uint32_t sourceRate;
};
struct PcmToneDataDef {
#if APP_USE_ADPCM_TONES || APP_USE_MULAW_TONES
const uint8_t* carrier;
uint32_t carrierLength;
uint32_t cycleLength;
uint32_t loopStart;
uint32_t loopEnd;
#if APP_USE_MULAW_TONES
uint32_t sourceRate;
#endif
#else
const int16_t* carrier[3];
const int16_t* mod[3];
uint32_t carrierLength[3];
uint32_t modLength[3];
uint32_t cycleLength[3];
#endif
};
#if APP_USE_MULAW_TONES
struct GeneratedGsToneDef {
uint8_t bankMsb;
uint8_t program;
const uint8_t* data;
uint32_t length;
uint32_t loopStart;
uint32_t loopEnd;
uint32_t cycleLength;
uint32_t sourceRate;
};
#endif
#if APP_USE_MULAW_TONES
#include "MulawToneSamples.generated.h"
#include "MulawDrumSamples.generated.h"
#include "MulawGsToneSamples.generated.h"
#elif APP_USE_ADPCM_TONES
#include "AdpcmToneSamples.generated.h"
#else
#include "PcmToneSamples.generated.h"
#endif
#if APP_USE_ADPCM_TONES || APP_USE_MULAW_TONES
using ToneSamplePointer = const uint8_t*;
#else
using ToneSamplePointer = const int16_t*;
#endif
constexpr PcmSampleDef makeLoopedSample(
ToneSamplePointer data,
uint32_t length,
uint32_t cycleLength) {
return PcmSampleDef{
data,
length,
0,
static_cast<uint32_t>(length > 0 ? length - 1 : 0),
cycleLength,
true,
false,
44100};
}
constexpr PcmSampleDef makeOneShotSample(
ToneSamplePointer data,
uint32_t length,
uint32_t cycleLength,
bool fixedPitch = false) {
return PcmSampleDef{
data,
length,
0,
static_cast<uint32_t>(length > 0 ? length - 1 : 0),
cycleLength,
false,
fixedPitch,
44100};
}
const char* sbcSampleRateToText(uint8_t sampleRateMask) {
if (sampleRateMask & ESP_A2D_SBC_CIE_SF_48K) {
return "48k";
}
if (sampleRateMask & ESP_A2D_SBC_CIE_SF_44K) {
return "44.1k";
}
if (sampleRateMask & ESP_A2D_SBC_CIE_SF_32K) {
return "32k";
}
if (sampleRateMask & ESP_A2D_SBC_CIE_SF_16K) {
return "16k";
}
return "?";
}
const char* sbcChannelModeToText(uint8_t channelModeMask) {
if (channelModeMask & ESP_A2D_SBC_CIE_CH_MODE_JOINT_STEREO) {
return "joint";
}
if (channelModeMask & ESP_A2D_SBC_CIE_CH_MODE_STEREO) {
return "stereo";
}
if (channelModeMask & ESP_A2D_SBC_CIE_CH_MODE_DUAL_CHANNEL) {
return "dual";
}
if (channelModeMask & ESP_A2D_SBC_CIE_CH_MODE_MONO) {
return "mono";
}
return "?";
}
uint8_t sampleRateToSbcMask(uint32_t sampleRateHz) {
if (sampleRateHz >= 44100) {
return ESP_A2D_SBC_CIE_SF_44K;
}
if (sampleRateHz >= 32000) {
return ESP_A2D_SBC_CIE_SF_32K;
}
return ESP_A2D_SBC_CIE_SF_16K;
}
uint32_t sbcMaskToSampleRateHz(uint8_t sampleRateMask) {
if (sampleRateMask & ESP_A2D_SBC_CIE_SF_48K) {
return 48000;
}
if (sampleRateMask & ESP_A2D_SBC_CIE_SF_44K) {
return 44100;
}
if (sampleRateMask & ESP_A2D_SBC_CIE_SF_32K) {
return 32000;
}
if (sampleRateMask & ESP_A2D_SBC_CIE_SF_16K) {
return 16000;
}
return Config::SampleRateHz;
}
size_t maxOutputFramesForSynthChunk(
size_t chunkFrames,
uint32_t synthSampleRateHz,
uint32_t outputSampleRateHz) {
const uint32_t safeSynthRate = max<uint32_t>(1, synthSampleRateHz);
const uint32_t safeOutputRate = max<uint32_t>(1, outputSampleRateHz);
const uint64_t scaled =
(static_cast<uint64_t>(chunkFrames) * safeOutputRate + safeSynthRate - 1) /
safeSynthRate;
return static_cast<size_t>(scaled + 2);
}
void ensureWaveTablesInitialized() {
// 周波数表はconstexprでFlashに置くため、起動時初期化は不要。
#if APP_USE_MULAW_TONES
for (uint16_t code = 0; code < 256; ++code) {
const uint8_t value = static_cast<uint8_t>(~code);
int32_t magnitude =
(static_cast<int32_t>(value & 0x0f) << 3) + 0x84;
magnitude <<= (value >> 4) & 0x07;
magnitude -= 0x84;
g_mulawDecodeTable[code] = static_cast<int16_t>(
(value & 0x80) ? -magnitude : magnitude);
}
#endif
}
#if APP_USE_MULAW_TONES
inline int16_t IRAM_ATTR readMulawSampleLinearQ15Raw(
const uint8_t* data,
uint16_t length,
uint32_t samplePosQ16,
uint16_t& cachedIndex,
int16_t& cachedSample0,
int16_t& cachedSample1,
bool& cacheValid) {
if (data == nullptr || length == 0) return 0;
uint16_t index = static_cast<uint16_t>(samplePosQ16 >> 16);
if (index >= length - 1) {
index = static_cast<uint16_t>(length - 1);
}
if (!cacheValid || index < cachedIndex || index > cachedIndex + 1) {
#if APP_ENABLE_MULAW_CACHE_STATS
++g_mulawReloadCount;
#endif
cachedSample0 = g_mulawDecodeTable[data[index]];
cachedSample1 = index + 1 < length
? g_mulawDecodeTable[data[index + 1]]
: cachedSample0;
cachedIndex = index;
cacheValid = true;
} else if (index == cachedIndex + 1) {
#if APP_ENABLE_MULAW_CACHE_STATS
++g_mulawOneStepHitCount;
#endif
cachedSample0 = cachedSample1;
cachedSample1 = index + 1 < length
? g_mulawDecodeTable[data[index + 1]]
: cachedSample0;
cachedIndex = index;
#if APP_ENABLE_MULAW_CACHE_STATS
} else {
++g_mulawSameIndexHitCount;
#endif
}
const uint32_t frac = samplePosQ16 & 0xffffu;
return static_cast<int16_t>(
cachedSample0 +
(((static_cast<int32_t>(cachedSample1) - cachedSample0) *
static_cast<int32_t>(frac)) >> 16));
}
#endif
#if APP_USE_ADPCM_TONES
DRAM_ATTR const int8_t kImaIndexDelta[8] = {-1, -1, -1, -1, 2, 4, 6, 8};
DRAM_ATTR const int16_t kImaStepTable[89] = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31,
34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130,
143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449,
494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411,
1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026,
4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442,
11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623,
27086, 29794, 32767};
inline int16_t decodeImaNibble(
uint8_t code, int16_t predictor, uint8_t& stepIndex) {
const int32_t step = kImaStepTable[stepIndex];
const int32_t delta =
(step * static_cast<int32_t>(((code & 7) << 1) + 1)) >> 3;
const int32_t signMask = -static_cast<int32_t>(code >> 3);
int32_t decoded = static_cast<int32_t>(predictor) +
((delta ^ signMask) - signMask);
if (decoded > 32767) decoded = 32767;
else if (decoded < -32768) decoded = -32768;
int32_t nextStepIndex =
static_cast<int32_t>(stepIndex) + kImaIndexDelta[code & 7];
if (nextStepIndex > 88) nextStepIndex = 88;
else if (nextStepIndex < 0) nextStepIndex = 0;
stepIndex = static_cast<uint8_t>(nextStepIndex);
return static_cast<int16_t>(decoded);
}
inline int16_t readAdpcmSampleLinearQ15Raw(
const uint8_t* data,
uint16_t length,
uint32_t samplePosQ16,
uint16_t& cachedIndex,
int16_t& cachedSample0,
int16_t& cachedSample1,
uint8_t& cachedStepIndex,
bool& cacheValid) {
if (data == nullptr || length == 0) return 0;
uint16_t index = static_cast<uint16_t>(samplePosQ16 >> 16);
if (index >= length) index = static_cast<uint16_t>(length - 1);
const uint16_t blockStart = static_cast<uint16_t>(index & ~(kImaAdpcmBlockSamples - 1));
if (cacheValid && cachedIndex == index + 1 &&
(cachedIndex / kImaAdpcmBlockSamples) == (index / kImaAdpcmBlockSamples)) {
++g_adpcmPairHitCount;
const uint32_t frac = samplePosQ16 & 0xffffu;
return static_cast<int16_t>(cachedSample0 +
(((static_cast<int32_t>(cachedSample1) - cachedSample0) *
static_cast<int32_t>(frac)) >> 16));
}
if (!cacheValid || index < cachedIndex ||
(cachedIndex / kImaAdpcmBlockSamples) != (index / kImaAdpcmBlockSamples)) {
++g_adpcmCacheResetCount;
const uint8_t* block = data +
(static_cast<uint32_t>(index) / kImaAdpcmBlockSamples) * kImaAdpcmBlockBytes;
cachedSample0 = static_cast<int16_t>(
static_cast<uint16_t>(block[0]) | (static_cast<uint16_t>(block[1]) << 8));
cachedSample1 = cachedSample0;
cachedStepIndex = min<uint8_t>(88, block[2]);
cachedIndex = blockStart;
cacheValid = true;
}
const uint8_t* block = data +
(static_cast<uint32_t>(index) / kImaAdpcmBlockSamples) * kImaAdpcmBlockBytes;
uint32_t decodeCount = 0;
while (cachedIndex < index) {
const uint16_t nextWithinBlock =
static_cast<uint16_t>((cachedIndex + 1) - blockStart);
const uint16_t nibbleIndex = static_cast<uint16_t>(nextWithinBlock - 1);
const uint8_t packed = block[4 + (nibbleIndex >> 1)];
const uint8_t code =
(nibbleIndex & 1) ? static_cast<uint8_t>(packed >> 4) : (packed & 0x0f);
cachedSample0 = cachedSample1;
cachedSample1 = decodeImaNibble(code, cachedSample1, cachedStepIndex);
++cachedIndex;
++decodeCount;
}
const int16_t a = cachedSample1;
int16_t b = a;
if (index + 1 < length) {
if (((index + 1) % kImaAdpcmBlockSamples) == 0) {
++g_adpcmBlockBoundaryCount;
const uint8_t* nextBlock = block + kImaAdpcmBlockBytes;
b = static_cast<int16_t>(
static_cast<uint16_t>(nextBlock[0]) |
(static_cast<uint16_t>(nextBlock[1]) << 8));
cachedSample0 = b;
cachedSample1 = b;
cachedStepIndex = min<uint8_t>(88, nextBlock[2]);
cachedIndex = static_cast<uint16_t>(index + 1);
} else {
const uint16_t nibbleIndex = static_cast<uint16_t>(index - blockStart);
const uint8_t packed = block[4 + (nibbleIndex >> 1)];
const uint8_t code =
(nibbleIndex & 1) ? static_cast<uint8_t>(packed >> 4) : (packed & 0x0f);
b = decodeImaNibble(code, a, cachedStepIndex);
++decodeCount;
cachedSample0 = a;
cachedSample1 = b;
cachedIndex = static_cast<uint16_t>(index + 1);
}
}
g_adpcmNibbleDecodeCount += decodeCount;
if (decodeCount > g_adpcmMaxDecodePerRead) {
g_adpcmMaxDecodePerRead = decodeCount;
}
const uint32_t frac = samplePosQ16 & 0xffffu;
return static_cast<int16_t>(
a + (((static_cast<int32_t>(b) - a) * static_cast<int32_t>(frac)) >> 16));
}
#else
inline int16_t readPcmSampleLinearQ15Raw(
const int16_t* data,
uint16_t length,
uint32_t samplePosQ16) {
if (data == nullptr || length == 0) {
return 0;
}
const uint32_t index = samplePosQ16 >> 16;
if (index >= length - 1) {
return data[length - 1];
}
const int16_t a = data[index];
const int16_t b = data[index + 1];
const uint32_t frac = samplePosQ16 & 0xffffu;
return static_cast<int16_t>(
a + (((static_cast<int32_t>(b) - a) * static_cast<int32_t>(frac)) >> 16));
}
#endif
inline bool advancePcmPositionQ16Raw(
uint32_t& samplePosQ16,
uint32_t sampleStepQ16,
uint16_t length,
uint16_t loopStart,
uint16_t loopEnd,
bool loopEnabled) {
samplePosQ16 += sampleStepQ16;
if (!loopEnabled) {
return (samplePosQ16 >> 16) < length;
}
if (loopEnd <= loopStart || loopEnd >= length) {
return true;
}
const uint32_t loopStartQ16 = static_cast<uint32_t>(loopStart) << 16;
const uint32_t loopEndQ16 = static_cast<uint32_t>(loopEnd) << 16;
const uint32_t loopLenQ16 = loopEndQ16 - loopStartQ16;
if (samplePosQ16 >= loopEndQ16 && loopLenQ16 > 0) {
samplePosQ16 -= loopLenQ16;
if (samplePosQ16 >= loopEndQ16) {
samplePosQ16 = loopStartQ16 + ((samplePosQ16 - loopStartQ16) % loopLenQ16);
}
}
return true;
}
inline __attribute__((always_inline)) void advanceLoopedPositionQ16Raw(
uint32_t& samplePosQ16,
uint32_t sampleStepQ16,
uint32_t loopStartQ16,
uint32_t loopEndQ16,
uint32_t loopLengthQ16) {
samplePosQ16 += sampleStepQ16;
if (samplePosQ16 < loopEndQ16) {
return;
}
samplePosQ16 -= loopLengthQ16;
// 通常pitchは1回の減算で収まる。極端なpitchだけ安全な剰余経路へ入る。
if (samplePosQ16 >= loopEndQ16) {
samplePosQ16 = loopStartQ16 +
((samplePosQ16 - loopStartQ16) % loopLengthQ16);
}
}
inline __attribute__((always_inline)) bool advanceOneShotPositionQ16Raw(
uint32_t& samplePosQ16,
uint32_t sampleStepQ16,
uint32_t sampleLengthQ16) {
// Check before addition. A 65,535-sample one-shot ends near UINT32_MAX in
// Q16 and a high pitch step could otherwise wrap the position to zero.
if (samplePosQ16 >= sampleLengthQ16 ||
sampleStepQ16 >= sampleLengthQ16 - samplePosQ16) {
samplePosQ16 = sampleLengthQ16;
return false;
}
samplePosQ16 += sampleStepQ16;
return true;
}
inline bool advancePcmPositionQ16(
uint32_t& samplePosQ16,
uint32_t sampleStepQ16,
const PcmSampleDef& sample) {
return advancePcmPositionQ16Raw(
samplePosQ16,
sampleStepQ16,
sample.length,
sample.loopStart,
sample.loopEnd,
sample.loopEnabled);
}
PcmSampleDef sampleForToneClass(
MidiEvent::ToneClass toneClass,
App::WaveTableSet waveTableSet,
bool secondaryLayer) {
size_t toneIndex = static_cast<size_t>(toneClass);
#if APP_USE_MULAW_TONES
(void)waveTableSet;
(void)secondaryLayer;
if (toneIndex >= 128) toneIndex = 0;
const PcmToneDataDef& toneData = g_mulawToneData[toneIndex];
const uint8_t* data = toneData.carrier;
const uint32_t length = toneData.carrierLength;
const uint32_t cycleLength = toneData.cycleLength;
const uint32_t loopStart = toneData.loopStart;
const uint32_t loopEnd = toneData.loopEnd;
const uint32_t sourceRate = toneData.sourceRate;
#elif APP_USE_ADPCM_TONES
(void)waveTableSet;
(void)secondaryLayer;
const uint8_t program = static_cast<uint8_t>(toneIndex & 0x7f);
toneIndex =
program <= 3 ? (program == 1 ? 19 : (program == 3 ? 20 : 18)) :
program <= 5 ? 14 : program <= 7 ? 9 : program <= 10 ? 11 :
program <= 15 ? 3 : program <= 20 ? 15 : program <= 23 ? 31 :
program == 24 ? 21 : program <= 26 ? 22 : program <= 31 ? 23 :
program <= 33 ? 24 : program <= 35 ? 12 : program <= 39 ? 7 :
program <= 43 ? 25 : program <= 47 ? 26 : program <= 51 ? 25 :
program <= 55 ? 26 : program == 56 ? 27 : program <= 63 ? 10 :
program <= 68 ? 28 : program <= 70 ? 29 : program == 71 ? 30 :
program <= 75 ? 13 : program <= 79 ? 6 : program <= 83 ? 0 :
program <= 87 ? 8 : program <= 95 ? 16 : program <= 103 ? 4 :
program <= 111 ? 11 : program <= 119 ? 5 : 16;
const PcmToneDataDef& toneData = g_adpcmToneData[toneIndex];
const uint8_t* data = toneData.carrier;
const uint32_t length = toneData.carrierLength;
const uint32_t cycleLength = toneData.cycleLength;
const uint32_t loopStart = toneData.loopStart;
const uint32_t loopEnd = toneData.loopEnd;
#else
const uint8_t program = static_cast<uint8_t>(toneIndex & 0x7f);
toneIndex =
program <= 3 ? (program == 1 ? 19 : (program == 3 ? 20 : 18)) :
program <= 5 ? 14 : program <= 7 ? 9 : program <= 10 ? 11 :
program <= 15 ? 3 : program <= 20 ? 15 : program <= 23 ? 31 :
program == 24 ? 21 : program <= 26 ? 22 : program <= 31 ? 23 :
program <= 33 ? 24 : program <= 35 ? 12 : program <= 39 ? 7 :
program <= 43 ? 25 : program <= 47 ? 26 : program <= 51 ? 25 :
program <= 55 ? 26 : program == 56 ? 27 : program <= 63 ? 10 :
program <= 68 ? 28 : program <= 70 ? 29 : program == 71 ? 30 :
program <= 75 ? 13 : program <= 79 ? 6 : program <= 83 ? 0 :
program <= 87 ? 8 : program <= 95 ? 16 : program <= 103 ? 4 :
program <= 111 ? 11 : program <= 119 ? 5 : 16;
const size_t setIndex = waveTableSet == App::WaveTableSet::Famicom
? 1
: (waveTableSet == App::WaveTableSet::Soft ? 2 : 0);
const PcmToneDataDef& toneData = g_pcmToneData[toneIndex];
const int16_t* data = secondaryLayer ? toneData.mod[setIndex] : toneData.carrier[setIndex];
const uint32_t length =
secondaryLayer ? toneData.modLength[setIndex] : toneData.carrierLength[setIndex];
const uint32_t cycleLength = toneData.cycleLength[setIndex];
#endif
// Some GM percussion/effect programs are short single-cycle waveforms
// (roughly 135-200 samples). Treating the entire 112-127 range as one-shot
// ended those waves after only a few milliseconds and produced a click.
// Generated long samples advertise a distinct pitch cycle and are the
// actual one-shots; short samples whose cycle equals their length must loop.
#if APP_USE_ADPCM_TONES || APP_USE_MULAW_TONES
if (loopEnd > loopStart && loopEnd <= length) {
PcmSampleDef sample = makeLoopedSample(data, length, cycleLength);
sample.sourceRate = sourceRate;
sample.loopStart = loopStart;
sample.loopEnd = loopEnd;
return sample;
}
PcmSampleDef sample = makeOneShotSample(data, length, cycleLength, false);
sample.sourceRate = sourceRate;
return sample;
#else
if (length != cycleLength) {
return makeOneShotSample(data, length, cycleLength, false);
}
return makeLoopedSample(data, length, cycleLength);
#endif
}
#if APP_USE_MULAW_TONES
bool sampleForGsTone(uint8_t bankMsb, uint8_t program, PcmSampleDef& sample) {
if (bankMsb == 0) return false;
for (const GeneratedGsToneDef& tone : g_mulawGsToneData) {
if (tone.bankMsb != bankMsb || tone.program != program) continue;
sample = PcmSampleDef{
tone.data,
tone.length,
tone.loopStart,
tone.loopEnd,
tone.cycleLength,
tone.loopEnd > tone.loopStart,
false,
tone.sourceRate};
return true;
}
return false;
}
#endif
#if APP_USE_MULAW_TONES
struct DrumMapEntry {
uint8_t firstNote;
uint8_t lastNote;
uint8_t sampleIndex;
};
// GM Standard Kit notes 35-81 and GS extension notes 82-87 use dedicated
// samples. Only undefined low notes 27-34 retain the side-stick fallback.
constexpr DrumMapEntry kGmDrumMap[] = {
{27, 34, kMulawDrumSideStick},
{35, 35, kMulawDrumAcousticBassDrum},
{36, 36, kMulawDrumBassDrum1},
{37, 37, kMulawDrumSideStick},
{38, 38, kMulawDrumAcousticSnare},
{39, 39, kMulawDrumHandClap},
{40, 40, kMulawDrumElectricSnare},
{41, 41, kMulawDrumLowFloorTom},
{42, 42, kMulawDrumClosedHiHat},
{43, 43, kMulawDrumHighFloorTom},
{44, 44, kMulawDrumPedalHiHat},
{45, 45, kMulawDrumLowTom},
{46, 46, kMulawDrumOpenHiHat},
{47, 47, kMulawDrumLowMidTom},
{49, 49, kMulawDrumCrashCymbal1},
{48, 48, kMulawDrumHiMidTom},
{50, 50, kMulawDrumHighTom},
{51, 51, kMulawDrumRideCymbal1},
{52, 52, kMulawDrumChineseCymbal},
{53, 53, kMulawDrumRideBell},
{54, 54, kMulawDrumTambourine},
{55, 55, kMulawDrumSplashCymbal},
{56, 56, kMulawDrumCowbell},
{57, 57, kMulawDrumCrashCymbal2},
{58, 58, kMulawDrumVibraslap},
{59, 59, kMulawDrumRideCymbal2},
{60, 60, kMulawDrumHiBongo},
{61, 61, kMulawDrumLowBongo},
{62, 62, kMulawDrumMuteHiConga},
{63, 63, kMulawDrumOpenHiConga},
{64, 64, kMulawDrumLowConga},
{65, 65, kMulawDrumHighTimbale},
{66, 66, kMulawDrumLowTimbale},
{67, 67, kMulawDrumHighAgogo},
{68, 68, kMulawDrumLowAgogo},
{69, 69, kMulawDrumCabasa},
{70, 70, kMulawDrumMaracas},
{71, 71, kMulawDrumShortWhistle},
{72, 72, kMulawDrumLongWhistle},
{73, 73, kMulawDrumShortGuiro},
{74, 74, kMulawDrumLongGuiro},
{75, 75, kMulawDrumClaves},
{76, 76, kMulawDrumHighWoodBlock},
{77, 77, kMulawDrumLowWoodBlock},
{78, 78, kMulawDrumMuteCuica},
{79, 79, kMulawDrumOpenCuica},
{80, 80, kMulawDrumMuteTriangle},
{81, 81, kMulawDrumOpenTriangle},
{82, 82, kMulawDrumShaker},
{83, 83, kMulawDrumJingleBell},
{84, 84, kMulawDrumBellTree},
{85, 85, kMulawDrumCastanets},
{86, 86, kMulawDrumMuteSurdo},
{87, 87, kMulawDrumOpenSurdo},
};
bool sampleForGmDrum(
uint8_t midiNote,
PcmSampleDef& sample,
float& pitchRatio) {
for (const DrumMapEntry& entry : kGmDrumMap) {
if (midiNote < entry.firstNote || midiNote > entry.lastNote) {
continue;
}
const GeneratedMulawDrumDef& drum = g_mulawDrumSamples[entry.sampleIndex];
sample = makeOneShotSample(drum.data, drum.length, 1, true);
pitchRatio = powf(
2.0f,
(static_cast<int>(midiNote) - drum.rootNote) / 12.0f);
return true;
}
return false;
}
#endif
void formatBdAddr(const esp_bd_addr_t address, char* buffer, size_t capacity) {
if (buffer == nullptr || capacity == 0) {
return;
}
snprintf(
buffer,
capacity,
"%02X:%02X:%02X:%02X:%02X:%02X",
address[0],
address[1],
address[2],
address[3],
address[4],
address[5]);
}
bool parseBdAddr(const char* text, esp_bd_addr_t out) {
if (text == nullptr || out == nullptr) {
return false;
}
unsigned int values[6];
if (sscanf(
text,
"%02x:%02x:%02x:%02x:%02x:%02x",
&values[0],
&values[1],
&values[2],
&values[3],
&values[4],
&values[5]) != 6) {
return false;
}
for (int i = 0; i < 6; ++i) {
out[i] = static_cast<uint8_t>(values[i]);
}
return true;
}
bool getNameFromEir(uint8_t* eir, char* bdname, uint8_t* bdnameLen) {
if (eir == nullptr || bdname == nullptr || bdnameLen == nullptr) {
return false;
}
uint8_t* remoteBdname = nullptr;
uint8_t remoteBdnameLen = 0;
remoteBdname = esp_bt_gap_resolve_eir_data(
eir,
ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME,
&remoteBdnameLen);
if (remoteBdname == nullptr) {
remoteBdname = esp_bt_gap_resolve_eir_data(
eir,
ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME,
&remoteBdnameLen);
}
if (remoteBdname == nullptr || remoteBdnameLen == 0) {
return false;
}
const uint8_t length = min<uint8_t>(remoteBdnameLen, ESP_BT_GAP_MAX_BDNAME_LEN);
memcpy(bdname, remoteBdname, length);
bdname[length] = 0;
*bdnameLen = length;
return true;
}
float midiToHz(int midiNote) {
if (midiNote < 0) {
midiNote = 0;
} else if (midiNote > 127) {
midiNote = 127;
}
return ldexpf(kMidiPitchClassHz[midiNote % 12], midiNote / 12);
}
const char* resetReasonToText(esp_reset_reason_t reason) {
switch (reason) {
case ESP_RST_POWERON:
return "poweron";
case ESP_RST_EXT:
return "external";
case ESP_RST_SW:
return "software";
case ESP_RST_PANIC:
return "panic";
case ESP_RST_INT_WDT:
return "int_wdt";
case ESP_RST_TASK_WDT:
return "task_wdt";
case ESP_RST_WDT:
return "other_wdt";
case ESP_RST_DEEPSLEEP:
return "deepsleep";
case ESP_RST_BROWNOUT:
return "brownout";
case ESP_RST_SDIO:
return "sdio";
default:
return "unknown";
}
}
constexpr char kSongMagic[8] = {'F', 'M', 'S', 'O', 'N', 'G', '2', '\0'};
constexpr char kRawMidiMagic[8] = {'R', 'A', 'W', 'M', 'I', 'D', '1', '\0'};