-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsimpleaudio.pas
2480 lines (1942 loc) · 77.8 KB
/
simpleaudio.pas
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
unit simpleaudio;
//------------------------------------------------------------------------------
// A simple audio unit for Ultibo modelled after SDL audio API
// v.0.92 beta - 20170621
// gpl 2.0 or higher
//------------------------------------------------------------------------------
//
// beta changelog
//
// 0.92 - balance control added
// - DMA buffers are now cleaned before use
// - 9-bit noiseshaper function started, not used yet
// - bugfix: close audio now check if it is opened.
//
// 0.91 - fixed the bug which caused 1-channel sound play badly distorted
//
//------------------------------------------------------------------------------
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, Platform, HeapManager, Threads, GlobalConst, math;
type
// ---- I decided to use SDL-like API so this fragment is copied from SDL unit
// ----- and modified somewhat
TAudioSpecCallback = procedure(userdata: Pointer; stream: PUInt8; len:Integer );
PAudioSpec = ^TAudioSpec;
TAudioSpec = record
freq: Integer; // DSP frequency -- samples per second
format: UInt16; // Audio data format
channels: UInt8; // Number of channels: 1 mono, 2 stereo
silence: UInt8; // Audio buffer silence value (calculated)
samples: UInt16; // Audio buffer size in samples
padding: UInt16; // Necessary for some compile environments
size: UInt32; // Audio buffer size in bytes (calculated)
// This function is called when the audio device needs more data.
// 'stream' is a pointer to the audio data buffer
// 'len' is the length of that buffer in bytes.
// Once the callback returns, the buffer will no longer be valid.
// Stereo samples are stored in a LRLRLR ordering.
callback: TAudioSpecCallback;
userdata: Pointer;
// 3 fields added, not in SDL
oversample: UInt8; // oversampling value
range: UInt16; // PWM range
oversampled_size: integer; // oversampled buffer size
end;
const
// ---------- Error codes
freq_too_low= -$11;
freq_too_high= -$12;
format_not_supported= -$21;
invalid_channel_number= -$41;
size_too_low = -$81;
size_too_high= -$81;
callback_not_specified= -$101;
audio_already_opened= -1;
// ---------- Audio formats. Subset of SDL formats
// ---------- These are 99.99% of wave file formats:
AUDIO_U8 = $0008; // Unsigned 8-bit samples
AUDIO_S16 = $8010; // Signed 16-bit samples
AUDIO_F32 = $8120; // Float 32 bit
// SDL based functions
function OpenAudio(desired, obtained: PAudioSpec): Integer;
procedure CloseAudio;
procedure PauseAudio(p:integer);
// Functions not in SDL API
function ChangeAudioParams(desired, obtained: PAudioSpec): Integer;
procedure SetVolume(vol:single);
procedure SetVolume(vol:integer);
procedure setDBVolume(vol:single);
procedure SetBalance(amount:integer);
function getDBVolume:single;
// Simplified functions
function SA_OpenAudio(freq,bits,channels,samples:integer; callback: TAudioSpecCallback):integer;
function SA_ChangeParams(freq,bits,channels,samples:integer): Integer;
function SA_GetCurrentFreq:integer;
function SA_GetCurrentRange:integer;
procedure SA_SetEQ(band,db:integer);
procedure SA_SetEQpreamp(db:integer);
// PWM functions
procedure initpwm(freq,range:integer);
procedure setpwm(channel,value:integer);
// I2S Communication
procedure initI2SMaster;
//procedure initI2SSlavetransmitter;
//procedure initI2SReceiver;
//procedure initI2SMasterreceiver;
var
dmanextcb,
ctrl1adr,
ctrl2adr:cardinal;
et:int64;
eq_preamp:integer=0;
eq:array[0..9] of integer=(0,0,0,0,0,0,0,0,0,0);
eqdbtable:array[-12..12] of integer=(256,288,323,363,408,458,513,579,646,725,814,914,1024,1150,1292,1450,1628,1828,2051,2302,2583,2900,3253,3651,4096);
equalizer_active:boolean=false;
outbuf:array[0..127] of cardinal;
i2stransmitted:boolean=false;
//------------------ End of Interface ------------------------------------------
implementation
uses retromalina, mwindows; //for debug
type
PLongBuffer=^TLongBuffer;
TLongBuffer=array[0..65535] of integer; // 64K DMA buffer
TCtrlBlock=array[0..7] of cardinal;
PCtrlBlock=^TCtrlBlock;
TAudioThread= class(TThread)
private
protected
procedure Execute; override;
public
Constructor Create(CreateSuspended : boolean);
end;
TI2SReceiveThread= class(TThread)
private
protected
procedure Execute; override;
public
Constructor Create(CreateSuspended : boolean);
end;
TI2STransmitThread= class(TThread)
private
protected
procedure Execute; override;
public
Constructor Create(CreateSuspended : boolean);
end;
const nocache=$C0000000; // constant to disable GPU L2 Cache
pll_freq=500000000; // base PLL freq=500 MHz
pwm_base_freq=1923077;
divider=2;
base_freq=pll_freq div divider;
max_pwm_freq=pwm_base_freq div divider;
dma_buffer_size=65536; // max size for simplified channel
// TODO: make the sample buffer size dynamic (?)
sample_buffer_size=32768; // max size for sample buffer.
// -- TODO: generate error if nax size exceeded
// The max allowed by dma_buffer_size is 1536 for 44100/16/2 wave
sample_buffer_32_size=65536;
// ------- Hardware registers addresses --------------------------------------
_pwm_fif1_ph= $7E20C018; // PWM FIFO input reg physical address
_pcm_fif1_ph= $7E203004; // PCM FIFO input reg physical address
_pwm_ctl= $3F20C000; // PWM Control Register MMU address
_pwm_dmac= $3F20C008; // PWM DMA Configuration MMU address
_pwm_rng1= $3F20C010; // PWM Range channel #1 MMU address
_pwm_rng2= $3F20C020; // PWM Range channel #2 MMU address
_pwm_dat1= $3F20C014; // PWM Data channel #1 MMU address
_pwm_dat2= $3F20C024; // PWM Data channel #2 MMU address
_i2s_cs= $3F203000; // I2S Control Register MMU address
_i2s_mode= $3F203008; // I2S Mode MMU address
_i2s_rxc= $3F20300C; // I2S Receiver Configuration MMU address
_i2s_txc= $3f203010; // I2S Transmitter Configuration MMU address
_i2s_dreq= $3f203014; // I2S DMA Configuration MMU address
_gpfsel4= $3F200010; // GPIO Function Select 4 MMU address
_gpfsel1= $3F200004; // GPIO Function Select 1 MMU address
_gpfsel2= $3F200008; // GPIO Function Select 2 MMU address
_pwmclk= $3F1010a0; // PWM clock ctrl reg MMU address
_pwmclk_div= $3F1010a4; // PWM clock divisor MMU address
_pcmclk= $3F101098; // I2S clock ctrl reg MMU address
_pcmclk_div= $3F10109C; // I2S clock ctrl reg MMU address
_dma_enable= $3F007ff0; // DMA enable register
_dma_cs= $3F007000; // DMA control and status
_dma_conblk= $3F007004; // DMA ctrl block address
_dma_nextcb= $3F00701C; // DMA next control block
// ------- Hardware initialization constants
transfer_info=$00050140; // DMA transfer information
// 5 - DMA peripheral code (5 -> PWM)
// 1 - src address increment after read
// 4 - DREQ controls write
pcm_rx_transfer_info=$00030410; // DMA transfer information
// 3 - DMA peripheral code (3 -> PCM_RX)
// 4 - DREQ controls read
// 1 - dst address increment after write
pcm_tx_transfer_info=$00020140; // DMA transfer information
// 2 - DMA peripheral code (2 -> PCM_TX)
// 1 - src address increment after read
// 4 - DREQ controls write
// ----- PWM @ GPIO 18,19 (GPIO) or 40,45 (jack)
and_mask_40_45= %11111111111111000111111111111000; // AND mask for gpio 40 and 45
or_mask_40_45_4= %00000000000000100000000000000100; // OR mask for set Alt Function #0 @ GPIO 40 and 45
and_mask_18_19= %11000000111111111111111111111111; // AND mask for gpio 18 and 19
or_mask_18_19_4= %00010010000000000000000000000000; // OR mask for set Alt Function #5 @ GPIO 18 and 19 as PWM
or_mask_18_19_0= %00100100000000000000000000000000; // OR mask for set Alt Function #0 @ GPIO 18 and 19 as PCM_CLK and PCM_FS
and_mask_20_21= %11111111111111111111111111000000; // AND mask for gpio 18 and 19
or_mask_20_21_0= %00000000000000000000000000100100; // OR mask for set Alt Function #0 @ GPIO 20 and 21 as PCM_DIN and PCM_DOUT
and_mask_12_13= %11111111111111111111000000111111; // AND mask for gpio 12 and 13
or_mask_12_13_0= %00000000000000000000100100000000; // OR mask for set Alt Function #0 @ GPIO 12 and 13 as PWM
// ----- I2S @ GPIO 18,19,20,21 as ALT0 at gpfsel1 and gpfsel2
clk_plld= $5a000016; // set clock to PLL D
clk_osc= $5a000011; // set clock to 19.2 MHz oscillator
clk_stop= $5a000001; // set clock to 19.2 MHz oscillator
clk_stop2= $5a000006; // set clock to 19.2 MHz oscillator
clk_div= $5a000000 + divider shl 12; //002000; // set clock divisor to 2.0
pwm_ctl_val= $0000a1e1; // value for PWM init:
// bit 15: chn#2 set M/S mode=1. Use PWM mode for non-noiseshaped audio and M/S mode for oversampled noiseshaped audio
// bit 13: enable fifo for chn #2
// bit 10 repeat last data
// bit 8: enable chn #2
// bit 7: chn #1 M/S mode on
// bit 6: clear FIFO
// bit 5: enable fifo for chn #1
// bit 2 repeat last data
// bit 0: enable chn #1
pwm_dmac_val= $80000707; // PWM DMA ctrl value:
// bit 31: enable DMA
// bits 15..8: PANIC value
// bits 7..0: DREQ value
dma_chn= 14; // use DMA channel 14 (the last)
pcm_dma_chn= 13; // use DMA channel 13 for PCM tx
pcm_dma_rx_chn= 12; // use DMA channel 12 for PCM RX
var gpfsel4:cardinal absolute _gpfsel4; // GPIO Function Select 4
gpfsel1:cardinal absolute _gpfsel1; // GPIO Function Select 1
gpfsel2:cardinal absolute _gpfsel2; // GPIO Function Select 2
pwmclk:cardinal absolute _pwmclk; // PWM Clock ctrl
pwmclk_div: cardinal absolute _pwmclk_div; // PWM Clock divisor
pwm_ctl:cardinal absolute _pwm_ctl; // PWM Control Register
pwm_dmac:cardinal absolute _pwm_dmac; // PWM DMA Configuration MMU address
pwm_rng1:cardinal absolute _pwm_rng1; // PWM Range channel #1 MMU address
pwm_rng2:cardinal absolute _pwm_rng2; // PWM Range channel #2 MMU address
pwm_dat1:cardinal absolute _pwm_dat1; // PWM Data channel #1 MMU address
pwm_dat2:cardinal absolute _pwm_dat2; // PWM Data channel #2 MMU address
dma_enable:cardinal absolute _dma_enable; // DMA Enable register
dma_cs:cardinal absolute _dma_cs+($100*dma_chn); // DMA ctrl/status
pcm_dma_cs:cardinal absolute _dma_cs+($100*pcm_dma_chn); // DMA ctrl/status
pcm_dma_rx_cs:cardinal absolute _dma_cs+($100*pcm_dma_rx_chn); // DMA ctrl/status
dma_conblk:cardinal absolute _dma_conblk+($100*dma_chn); // DMA ctrl block addr
pcm_dma_conblk:cardinal absolute _dma_conblk+($100*pcm_dma_chn); // DMA ctrl block addr
pcm_dma_rx_conblk:cardinal absolute _dma_conblk+($100*pcm_dma_rx_chn); // DMA ctrl block addr
dma_nextcb:cardinal absolute _dma_nextcb+($100*dma_chn); // DMA next ctrl block addr
pcm_dma_nextcb:cardinal absolute _dma_nextcb+($100*pcm_dma_chn); // DMA next ctrl block addr
pcm_dma_rx_nextcb:cardinal absolute _dma_nextcb+($100*pcm_dma_rx_chn); // DMA next ctrl block addr
dmactrl_ptr:PCardinal=nil; // DMA ctrl block pointer
dmactrl_adr:cardinal absolute dmactrl_ptr; // DMA ctrl block address
dmabuf1_ptr:PCardinal=nil; // DMA data buffer #1 pointer
dmabuf1_adr:cardinal absolute dmabuf1_ptr; // DMA data buffer #1 address
dmabuf2_ptr:PCardinal=nil; // DMA data buffer #2 pointer
dmabuf2_adr:cardinal absolute dmabuf2_ptr; // DMA data buffer #2 address
dma2ctrl_ptr:PCardinal=nil; // DMA ctrl block pointer -- PCM
dma2ctrl_adr:cardinal absolute dma2ctrl_ptr; // DMA ctrl block address
dmabuf3_ptr:PCardinal=nil; // DMA data buffer #3 pointer
dmabuf3_adr:cardinal absolute dmabuf3_ptr; // DMA data buffer #3 address
dmabuf4_ptr:PCardinal=nil; // DMA data buffer #4 pointer
dmabuf4_adr:cardinal absolute dmabuf4_ptr; // DMA data buffer #4 address
dma3ctrl_ptr:PCardinal=nil; // DMA ctrl block pointer -- PCM
dma3ctrl_adr:cardinal absolute dma3ctrl_ptr; // DMA ctrl block address
dmabuf5_ptr:PCardinal=nil; // DMA data buffer #3 pointer
dmabuf5_adr:cardinal absolute dmabuf5_ptr; // DMA data buffer #3 address
dmabuf6_ptr:PCardinal=nil; // DMA data buffer #4 pointer
dmabuf6_adr:cardinal absolute dmabuf6_ptr; // DMA data buffer #4 address
ctrl1_ptr,ctrl2_ptr:PCtrlBlock; // DMA ctrl block array pointers
ctrl1_adr:cardinal absolute ctrl1_ptr; // DMA ctrl block #1 array address
ctrl2_adr:cardinal absolute ctrl2_ptr; // DMA ctrl block #2 array address
ctrl3_ptr,ctrl4_ptr:PCtrlBlock; // DMA ctrl block array pointers for PCM
ctrl3_adr:cardinal absolute ctrl3_ptr; // DMA ctrl block #3 array address
ctrl4_adr:cardinal absolute ctrl4_ptr; // DMA ctrl block #4 array address
ctrl5_ptr,ctrl6_ptr:PCtrlBlock; // DMA ctrl block array pointers for PCM
ctrl5_adr:cardinal absolute ctrl5_ptr; // DMA ctrl block #5 array address
ctrl6_adr:cardinal absolute ctrl6_ptr; // DMA ctrl block #6 array address
i2s_cs:cardinal absolute _i2s_cs; // I2S Control Register MMU address
i2s_mode:cardinal absolute _i2s_mode; // I2S Mode MMU address
i2s_rxc:cardinal absolute _i2s_rxc; // I2S Receiver Configuration MMU address
i2s_txc:cardinal absolute _i2s_txc; // I2S Transmitter Configuration MMU address
i2s_dreq:cardinal absolute _i2s_dreq; // I2S DMA Configuration MMU address
pcmclk:cardinal absolute _pcmclk; // I2S clock control
pcmclk_div:cardinal absolute _pcmclk_div; // I2S clock divider
// CurrentAudioSpec:TAudioSpec;
SampleBuffer_ptr:pointer;
SampleBuffer_ptr_b:PByte absolute SampleBuffer_ptr;
SampleBuffer_ptr_si:PSmallint absolute SampleBuffer_ptr;
SampleBuffer_ptr_f:PSingle absolute SampleBuffer_ptr;
SampleBuffer_adr:cardinal absolute SampleBuffer_ptr;
SampleBuffer_32_ptr:PCardinal;
SampleBuffer_32_adr:cardinal absolute SampleBuffer_32_ptr;
AudioThread:TAudioThread;
I2SReceiveThread:TI2SReceiveThread;
I2STransmitThread:TI2STransmitThread;
AudioOn:integer=0; // 1 - audio worker thread is running
volume:integer=4096; // audio volume; 4096 -> 0 dB
pauseA:integer=1; // 1 - audio is paused
nc:cardinal;
working:integer;
CurrentAudioSpec:TAudioSpec;
s_desired, s_obtained: TAudioSpec;
audio_opened:boolean=false;
balance:integer=128;
dbvolume:single=0;
pwmrange:integer=1024;
t_length_pcm:integer=512;
procedure InitAudioEx(range,t_length:integer); forward;
function noiseshaper8(bufaddr,outbuf,oversample,len:integer):integer; forward;
function noiseshaper9(bufaddr,outbuf,oversample,len:integer):integer; forward;
procedure equalizer(bufaddr,len:integer); forward;
procedure equalizer2(bufaddr,len:integer); forward;
// ------------------------------------------------
// A helper procedure which removes RAM RO limit
// used here to speed up the noise shaper
//-------------------------------------------------
procedure removeramlimits(addr:integer);
var Entry:TPageTableEntry;
begin
Entry:=PageTableGetEntry(addr);
Entry.Flags:=$3b2; //executable, shareable, rw, cacheable, writeback
PageTableSetEntry(Entry);
Entry:=PageTableGetEntry(addr+4096);
Entry.Flags:=$3b2; //executable, shareable, rw, cacheable, writeback
PageTableSetEntry(Entry);
end;
//------------------------------------------------------------------------------
// I2S related procedures for communication
//------------------------------------------------------------------------------
procedure initI2SMaster;
var i:integer;
begin
// init transmitter DMA
dma2ctrl_ptr:=GetAlignedMem(64,32); // get 64 bytes for 2 DMA ctrl blocks
ctrl3_ptr:=PCtrlBlock(dma2ctrl_ptr); // set pointers so the ctrl blocks can be accessed as array
ctrl4_ptr:=PCtrlBlock(dma2ctrl_ptr+8); // second ctrl block is 8 longs further
dmabuf3_ptr:=getmem(t_length_pcm); // allocate 64k for DMA buffer
dmabuf4_ptr:=getmem(t_length_pcm); // .. and the second one
for i:=0 to (t_length_pcm div 4)-1 do
begin
dmabuf3_ptr[i]:=0;
dmabuf4_ptr[i]:=0;
end;
ctrl3_ptr^[0]:=pcm_tx_transfer_info; // transfer info
ctrl3_ptr^[2]:=_pcm_fif1_ph; // destination address
ctrl3_ptr^[1]:=nocache+dmabuf3_adr; // source address -> buffer #1
ctrl3_ptr^[3]:=t_length_pcm; // transfer length
ctrl3_ptr^[4]:=$0; // 2D length, unused
ctrl3_ptr^[5]:=nocache+ctrl4_adr; // next ctrl block -> ctrl block #2
ctrl3_ptr^[6]:=$0; // unused
ctrl3_ptr^[7]:=$0; // unused
ctrl4_ptr^:=ctrl3_ptr^; // copy first block to second
ctrl4_ptr^[5]:=nocache+ctrl3_adr; // next ctrl block -> ctrl block #1
ctrl4_ptr^[1]:=nocache+dmabuf4_adr; // source address -> buffer #2
CleanDataCacheRange(dma2ctrl_adr,64); // now push this into RAM
threadsleep(1);
// init receiver DMA
dma3ctrl_ptr:=GetAlignedMem(64,32); // get 64 bytes for 2 DMA ctrl blocks
ctrl5_ptr:=PCtrlBlock(dma3ctrl_ptr); // set pointers so the ctrl blocks can be accessed as array
ctrl6_ptr:=PCtrlBlock(dma3ctrl_ptr+8); // second ctrl block is 8 longs further
dmabuf5_ptr:=getmem(t_length_pcm); // allocate 64k for DMA buffer
dmabuf6_ptr:=getmem(t_length_pcm); // .. and the second one
background.println('dmabuf5_ptr is '+inttohex(cardinal(dmabuf5_ptr),8));
background.println('dmabuf6_ptr is '+inttohex(cardinal(dmabuf6_ptr),8));
for i:=0 to (t_length_pcm div 4)-1 do
begin
dmabuf5_ptr[i]:=0;
dmabuf6_ptr[i]:=i+1000000;
end;
ctrl5_ptr^[0]:=pcm_rx_transfer_info; // transfer info
ctrl5_ptr^[1]:=_pcm_fif1_ph; // source address
ctrl5_ptr^[2]:=nocache+dmabuf5_adr; // destination address -> buffer #1
ctrl5_ptr^[3]:=t_length_pcm; // transfer length
ctrl5_ptr^[4]:=$0; // 2D length, unused
ctrl5_ptr^[5]:=nocache+ctrl6_adr; // next ctrl block -> ctrl block #2
ctrl5_ptr^[6]:=$0; // unused
ctrl5_ptr^[7]:=$0; // unused
ctrl6_ptr^:=ctrl5_ptr^; // copy first block to second
ctrl6_ptr^[5]:=nocache+ctrl5_adr; // next ctrl block -> ctrl block #1
ctrl6_ptr^[2]:=nocache+dmabuf6_adr; // source address -> buffer #2
CleanDataCacheRange(dma3ctrl_adr,64); // now push this into RAM
threadsleep(1);
background.println('dma control initialized');
// init GPIO: 18 clk, 19 fs, 20 data in, 21 data out
gpfsel1:=(gpfsel1 and and_mask_18_19) or or_mask_18_19_0; // gpio 18/19 as alt#0 -> PCM clk/fs
gpfsel2:=(gpfsel2 and and_mask_20_21) or or_mask_20_21_0; // gpio 20/21 as alt#0 -> PCM in/Out
background.println('gpfsel done');
// set clock to 1 MHz
pcmclk:=clk_stop2; // set PWM clock src=PLLD (500 MHz)
sleep(100);
//pcmclk_div:=$5a07D000; // 2 MHz clock
pcmclk_div:=$5a002000;
//pcmclk:=clk_plld;
pcmclk:=clk_osc;
threadsleep(1);
background.println('pcmclk done');
// init I2S hardware
i2s_cs:=0;
sleep(1);
i2s_cs:= $00018218; // 16:rx err reset, 15: tx err reset, 9: dma enable,4: clear rx fifo, 3: clear tx fif0, 0: enable if
i2s_mode:=$00010002; // master
i2s_txc:= $C008C208; // 2 channels, 32 bit
i2s_rxc:= $C008C208; // 2 channels, 32 bit
//i2s_dreq:=$08382020; // panic tx=8, panic rx=56, lvl tx=rx=32
i2s_dreq:=$10303020; // panic tx=8, panic rx=56, lvl tx=rx=32
i2s_cs :=$0201821F; // start transmitting
background.println('i2s initialized');
dma_enable:=dma_enable or (1 shl pcm_dma_chn); // enable dma channel # dma_chn
pcm_dma_conblk:=nocache+ctrl3_adr; // init DMA ctr block to ctrl block # 1
pcm_dma_cs:=$00FF0003; // start DMA
dma_enable:=dma_enable or (1 shl pcm_dma_rx_chn); // enable dma channel # dma_chn
pcm_dma_rx_conblk:=nocache+ctrl5_adr; // init DMA ctr block to ctrl block # 1
pcm_dma_rx_cs:=$00FF0003; // start DMA
background.println('dma started');
background.println('transmitting started');
i2sreceivethread:=Ti2sreceivethread.Create(true);
i2sreceivethread.start;
I2STransmitThread:=TI2STransmitThread.Create(true);
I2STransmitThread.start;
background.println('transmitting thread running');
end;
//------------------------------------------------------------------------------
// PWM procedures for control purpose
//------------------------------------------------------------------------------
procedure InitPWM(freq,range:integer);
// This inits PWM for the control purpose
var i,pwmdiv,ctlval,pwmdmacval:integer;
begin
pwmdiv:=19200000 div (freq*range);
if pwmdiv>4095 then pwmdiv:=4095;
pwmdiv:=$5a000000 + pwmdiv shl 12;
ctlval:=$00008181; // value for PWM init:
// bit 15: chn#2 set M/S mode=1. Use PWM mode for non-noiseshaped audio and M/S mode for oversampled noiseshaped audio
// bit 13: enable fifo for chn #2
// bit 8: enable chn #2
// bit 7: chn #1 M/S mode on
// bit 6: clear FIFO
// bit 5: enable fifo for chn #1
// bit 0: enable chn #1
pwmdmacval:=$00000000; // PWM DMA disable
closeaudio; // PWM control cannot work with audio on as it uses the same hardware !!!
//pwm_ctl:=ctlval; // stop PWM
gpfsel4:=(gpfsel4 and and_mask_40_45) or or_mask_40_45_4; // gpio 40/45 as alt#0 -> PWM Out
gpfsel1:=(gpfsel1 and and_mask_12_13) or or_mask_12_13_0; // gpio 12/13 as alt#0 -> PWM Out
pwmclk_div:=pwmdiv; // set PWM clock divisor=2 (250 MHz)
pwmclk:=clk_stop; // set PWM clock src=PLLD (500 MHz)
sleep(10); // set PWM clock src=PLLD (500 MHz)
pwmclk:=clk_osc; // set PWM clock src=PLLD (500 MHz)
pwm_rng1:=range; // minimum range for 8-bit noise shaper to avoid overflows
pwm_rng2:=range; //
pwm_dat1:=0;
pwm_dat2:=0;
pwm_dmac:=pwmdmacval; // pwm dma disable
pwm_ctl:=ctlval; // pwm contr0l -
pwmrange:=range;
//pwm_opened:=true;
end;
procedure setpwm(channel,value:integer);
begin
if value<0 then value:=0;
if value>pwmrange then value:=pwmrange;
if channel=0 then pwm_dat1:=value;
if channel=1 then pwm_dat2:=value;
end;
//------------------------------------------------------------------------------
// InitAudioEx - init the GPIO, PWM and DMA for audio subsystem.
//------------------------------------------------------------------------------
procedure InitAudioEx(range,t_length:integer); //TODO don't init second time!!!
var i:integer;
begin
dmactrl_ptr:=GetAlignedMem(64,32); // get 64 bytes for 2 DMA ctrl blocks
ctrl1_ptr:=PCtrlBlock(dmactrl_ptr); // set pointers so the ctrl blocks can be accessed as array
ctrl2_ptr:=PCtrlBlock(dmactrl_ptr+8); // second ctrl block is 8 longs further
dmabuf1_ptr:=getmem(65536); // allocate 64k for DMA buffer
dmabuf2_ptr:=getmem(65536); // .. and the second one
for i:=0 to 16383 do
begin
dmabuf1_ptr[i]:=127;
dmabuf2_ptr[i]:=127;
end;
ctrl1_ptr^[0]:=transfer_info; // transfer info
ctrl1_ptr^[1]:=nocache+dmabuf1_adr; // source address -> buffer #1
ctrl1_ptr^[2]:=_pwm_fif1_ph; // destination address
ctrl1_ptr^[3]:=t_length; // transfer length
ctrl1_ptr^[4]:=$0; // 2D length, unused
ctrl1_ptr^[5]:=nocache+ctrl2_adr; // next ctrl block -> ctrl block #2
ctrl1_ptr^[6]:=$0; // unused
ctrl1_ptr^[7]:=$0; // unused
ctrl2_ptr^:=ctrl1_ptr^; // copy first block to second
ctrl2_ptr^[5]:=nocache+ctrl1_adr; // next ctrl block -> ctrl block #1
ctrl2_ptr^[1]:=nocache+dmabuf2_adr; // source address -> buffer #2
CleanDataCacheRange(dmactrl_adr,64); // now push this into RAM
threadsleep(1);
// Init the hardware
gpfsel4:=(gpfsel4 and and_mask_40_45) or or_mask_40_45_4; // gpio 40/45 as alt#0 -> PWM Out
//gpfsel1:=(gpfsel1 and and_mask_18_19) or or_mask_18_19_4; // gpio 18/19 as alt#0 -> PWM Out
pwmclk:=clk_stop2; // set PWM clock src=PLLD (500 MHz)
sleep(100);
// set PWM clock src=PLLD (500 MHz)
pwmclk_div:=clk_div;
pwmclk:=clk_plld; // set PWM clock src=PLLD (500 MHz)
// set PWM clock src=PLLD (500 MHz)
// set PWM clock divisor=2 (250 MHz)
pwm_rng1:=range; // minimum range for 8-bit noise shaper to avoid overflows
pwm_rng2:=range; //
pwm_ctl:=pwm_ctl_val; // pwm contr0l - enable pwm, clear fifo, use fifo
pwm_dmac:=pwm_dmac_val; // pwm dma enable
dma_enable:=dma_enable or (1 shl dma_chn); // enable dma channel # dma_chn
dma_conblk:=nocache+ctrl1_adr; // init DMA ctr block to ctrl block # 1
dma_cs:=$00FF0003; // start DMA
audio_opened:=true;
//dmanextcb:=dma_nextcb;
//ctrl1adr:=ctrl1_adr;
//ctrl2adr:=ctrl2_adr;
end;
function SA_OpenAudio(freq,bits,channels,samples:integer; callback: TAudioSpecCallback):integer;
label p999;
begin
if audio_opened then
begin
result:=audio_already_opened;
goto p999;
end;
s_desired.freq:=freq;
s_desired.samples:=samples;
s_desired.channels:=channels;
s_desired.samples:=samples;
s_desired.callback:=callback;
case bits of
8:s_desired.format:= AUDIO_U8;
16:s_desired.format:=AUDIO_S16;
32:s_desired.format:=AUDIO_F32;
else
begin
result:=format_not_supported;
exit;
end;
end;
result:=OpenAudio(@s_desired,@s_obtained);
p999:
end;
function SA_ChangeParams(freq,bits,channels,samples:integer): Integer;
begin
s_desired.freq:=freq;
s_desired.samples:=samples;
s_desired.channels:=channels;
s_desired.samples:=samples;
s_desired.callback:=nil;
case bits of
0:s_desired.format:=0;
8:s_desired.format:= AUDIO_U8;
16:s_desired.format:=AUDIO_S16;
32:s_desired.format:=AUDIO_F32;
else
begin
result:=format_not_supported;
exit;
end;
end;
result:=ChangeAudioParams(@s_desired,@s_obtained);
end;
// ----------------------------------------------------------------------
// OpenAudio
// Inits the audio according to specifications in 'desired' record
// The values which in reality had been set are in 'obtained' record
// Returns 0 or the error code, in this case 'obtained' is invalid
//
// You have to set the fields:
//
// freq: samples per second, 8..960 kHz
// format: audio data format
// channels: number of channels: 1 mono, 2 stereo
// samples: audio buffer size in samples. >32, not too long (<384 for stereo 44100 Hz)
// callback: a callback function you have to write in your program
//
// The rest of fields in 'desire' will be ignored. They will be filled in 'obtained'
// ------------------------------------------------------------------------
function OpenAudio(desired, obtained: PAudioSpec): Integer;
label p999;
var maxsize:double;
over_freq:integer;
begin
result:=0;
if audio_opened then
begin
result:=audio_already_opened;
goto p999;
end;
// ----------- check if params can be used
// ----------- the frequency should be between 8 and 960 kHz
if desired^.freq<8000 then
begin
result:=freq_too_low;
exit;
end;
if desired^.freq>max_pwm_freq then
begin
result:=freq_too_high;
exit;
end;
//----------- check if the format is supported
if (desired^.format <> AUDIO_U8) and (desired^.format <> AUDIO_S16) and (desired^.format <> AUDIO_F32) then
begin
result:=format_not_supported;
exit;
end;
//----------- check the channel number
if (desired^.channels < 1) or (desired^.channels>2) then
begin
result:=invalid_channel_number;
exit;
end;
//----------- check the buffer size in samples
//----------- combined with the noise shaper should not exceed 64k
// It is ~384 for 44 kHz S16 samples
if (desired^.samples<32) then
begin
result:=size_too_low;
exit;
end;
maxsize:=65528/max_pwm_freq*desired^.freq/desired^.channels;
if (desired^.samples>maxsize) then
begin
result:=size_too_high;
exit;
end;
if (desired^.callback=nil) then
begin
result:=callback_not_specified;
exit;
end;
// now compute the obtained parameters
obtained^:=desired^;
obtained^.oversample:=max_pwm_freq div desired^.freq;
// the workaround for simply making 432 Hz tuned sound
// the problem is: when going 44100->43298
// the computed oversample changes from 21 to 22
// and this causes the resulting DMA buffer exceed 64K
// Also if I init the 43298 Hz soud, I will want to change it to 44100
// without changing anything else
if obtained^.oversample=22 then obtained^.oversample:=21;
over_freq:=desired^.freq*obtained^.oversample;
obtained^.range:=round(base_freq/over_freq);
obtained^.freq:=round(base_freq/(obtained^.range*obtained^.oversample));
if (desired^.format = AUDIO_U8) then obtained^.silence:=128 else obtained^.silence:=0;
obtained^.padding:=0;
obtained^.size:=obtained^.samples*obtained^.channels;
if obtained^.size>sample_buffer_size then
begin
result:=size_too_high;
exit;
end;
if obtained^.channels=2 then obtained^.oversampled_size:=obtained^.size*4*obtained^.oversample
else obtained^.oversampled_size:=obtained^.size*8*obtained^.oversample; //output is always 2 channels
if obtained^.format=AUDIO_U8 then obtained^.size:=obtained^.size;
if obtained^.format=AUDIO_S16 then obtained^.size:=obtained^.size*2;
if obtained^.format=AUDIO_F32 then obtained^.size:=obtained^.size*4;
InitAudioEx(obtained^.range,obtained^.oversampled_size);
CurrentAudioSpec:=obtained^;
samplebuffer_ptr:=getmem(sample_buffer_size);
samplebuffer_32_ptr:=getmem(sample_buffer_32_size);
removeramlimits(integer(@noiseshaper8)); // noise shaper uses local vars or it will be slower
removeramlimits(integer(@equalizer)); // noise shaper uses local vars or it will be slower
removeramlimits(integer(@equalizer2)); // noise shaper uses local vars or it will be slower
removeramlimits(integer(@noiseshaper9)); // noise shaper uses local vars or it will be slower
// now create and start the audio thread
pauseA:=1;
AudioThread:=TAudioThread.Create(true);
AudioThread.start;
p999:
end;
// ---------- ChangeAudioParams -----------------------------------------
//
// This function will try to change audio parameters
// without closing and reopening the audio system (=loud click)
// The usage is the same as OpenAudio
//
// -----------------------------------------------------------------------
function ChangeAudioParams(desired, obtained: PAudioSpec): Integer;
var maxsize:double;
over_freq:integer;
begin
// -------------- Do all things as in OpenAudio
// -------------- TODO: what is common, should go to one place
result:=0;
if desired^.freq=0 then desired^.freq:=CurrentAudioSpec.freq;
if desired^.freq<8000 then
begin
result:=freq_too_low;
exit;
end;
if desired^.freq>max_pwm_freq then
begin
result:=freq_too_high;
exit;
end;
if desired^.format=0 then desired^.format:=CurrentAudioSpec.format;
if (desired^.format <> AUDIO_U8) and (desired^.format <> AUDIO_S16) and (desired^.format <> AUDIO_F32) then
begin
result:=format_not_supported;
exit;
end;
if desired^.channels=0 then desired^.channels:=CurrentAudioSpec.channels;
if (desired^.channels < 1) or (desired^.channels>2) then
begin
result:=invalid_channel_number;
exit;
end;
if desired^.samples=0 then desired^.samples:=CurrentAudioSpec.samples ;
if (desired^.samples<32) then
begin
result:=size_too_low;
exit;
end;
maxsize:=65528/max_pwm_freq*desired^.freq/desired^.channels;
if (desired^.samples>maxsize) then
begin
result:=size_too_high;
exit;
end;
if (desired^.callback=nil) then desired^.callback:=CurrentAudioSpec.callback;
obtained^:=desired^;
obtained^.oversample:=max_pwm_freq div desired^.freq;
// the workaround for simply making 432 Hz tuned sound
// the problem is: when going 44100->43298
// the computed oversample changes from 21 to 22
// and this causes the resulting DMA buffer exceed 64K
if obtained^.oversample=22 then obtained^.oversample:=21;
over_freq:=desired^.freq*obtained^.oversample;
obtained^.range:=round(base_freq/over_freq);
obtained^.freq:=round(base_freq/(obtained^.range*obtained^.oversample));
if (desired^.format = AUDIO_U8) then obtained^.silence:=128 else obtained^.silence:=0;
obtained^.padding:=0;
obtained^.size:=obtained^.samples*obtained^.channels;
if obtained^.size>sample_buffer_size then
begin
result:=size_too_high;
exit;
end;
if obtained^.channels=2 then obtained^.oversampled_size:=obtained^.size*4*obtained^.oversample
else obtained^.oversampled_size:=obtained^.size*8*obtained^.oversample; //output is always 2 channels
if obtained^.format=AUDIO_S16 then obtained^.size:=obtained^.size * 2;
if obtained^.format=AUDIO_F32 then obtained^.size:=obtained^.size * 4;
// Here the common part ends.
//
// Now we cannot "InitAudio" as it is already init and running
// Instead we will change - only when needed:
//
// - PWM range
// - DMA transfer length
if obtained^.range<>CurrentAudioSpec.range then
begin
pwm_ctl:=0; // stop PWM
pwm_rng1:=obtained^.range; // set a new range
pwm_rng2:=obtained^.range;
pwm_ctl:=pwm_ctl_val; // start PWM
end;
if obtained^.oversampled_size<>CurrentAudioSpec.oversampled_size then
begin
repeat threadsleep(0) until dma_nextcb=nocache+ctrl2_adr;
ctrl1_ptr^[3]:=obtained^.oversampled_size;
repeat threadsleep(0) until dma_nextcb=nocache+ctrl1_adr;
ctrl2_ptr^[3]:=obtained^.oversampled_size;
end;
repeat until working=1;
repeat until working=0;
CurrentAudioSpec:=obtained^;
end;
procedure CloseAudio;
begin
// Stop audio worker thread
//PauseAudio(1);
if audio_opened then
begin
AudioThread.terminate;
repeat threadsleep(1) until AudioOn=0;
// ...then switch off DMA...
ctrl1_ptr^[5]:=0;
ctrl2_ptr^[5]:=0;
// up to 8 ms of audio can still reside in the buffer
threadsleep(20);
// Now disable DMA and PWM...
dma_cs:=$80000000;
pwm_ctl:=0;
sleep(10);
pwmclk:=clk_stop2; // stop the clock
sleep(10);
//... and return the memory to the system
dispose(dmabuf1_ptr);
dispose(dmabuf2_ptr);
freemem(dmactrl_ptr);
freemem(samplebuffer_ptr);
freemem(samplebuffer_32_ptr);
audio_opened:=false;
end;
end;
procedure pauseaudio(p:integer);
begin
if p=1 then pauseA:=1;
if p=0 then pausea:=0;
end;
procedure SetVolume(vol:single);
// Setting the volume as float in range 0..1