summaryrefslogtreecommitdiff
path: root/SMMain.c
blob: dc8a0cfd2563385648355960b584b0786730ed73 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
/*
Copyright (C) 2019-2020 Andrei Kopanchuk UZ7HO

This file is part of QtSoundModem

QtSoundModem is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

QtSoundModem is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with QtSoundModem.  If not, see http://www.gnu.org/licenses

*/

// UZ7HO Soundmodem Port by John Wiseman G8BPQ

#include "UZ7HOStuff.h"
#include "fftw3.h"
#include <time.h>
#include "ecc.h"				// RS Constants
#include "hidapi.h"
#include <fcntl.h>
#include <errno.h>
#include <stdint.h>   


void platformInit();
void RsCreate();
void detector_init();
void KISS_init();
void ax25_init();
void init_raduga();
void il2p_init(int il2p_debug);
void SoundFlush();
void BufferFull(short * Samples, int nSamples);
void PollReceivedSamples();
void chk_dcd1(int snd_ch, int buf_size);
void make_core_BPF(UCHAR snd_ch, short freq, short width);
void modulator(UCHAR snd_ch, int buf_size);
void sendAckModeAcks(int snd_ch);
void PktARDOPEncode(UCHAR * Data, int Len, int Chan);
void RUHEncode(unsigned char * Data, int Len, int chan);
void sendRSID(int Chan, int dropTX);
void SetupGPIOPTT();
int stricmp(const unsigned char * pStr1, const unsigned char *pStr2);
int gpioInitialise(void);
int OpenCOMPort(char * pPort, int speed, BOOL SetDTR, BOOL SetRTS, BOOL Quiet, int Stopbits);
void HAMLIBSetPTT(int PTTState);
void FLRigSetPTT(int PTTState);
void StartWatchdog();
void StopWatchdog();
void gpioWrite(unsigned gpio, unsigned level);
BOOL WriteCOMBlock(int fd, char * Block, int BytesToWrite);
void COMSetDTR(int fd);
void COMSetRTS(int fd);
void analiz_frame(int snd_ch, string * frame, char * code, boolean fecflag);
size_t write(int fd, void * buf, size_t count);
int close(int fd);
void SendMgmtPTT(int snd_ch, int PTTState);


BOOL KISSServ;
int KISSPort;

int NeedWaterfallHeaders = 0;

BOOL AGWServ;
int AGWPort;

int Number = 0;				// Number waiting to be sent

int SoundIsPlaying = 0;
int UDPSoundIsPlaying = 0;
int Capturing = 0;

int txmin = 0;
int txmax = 0;

extern unsigned short buffer[2][1200];
extern int SoundMode;
extern int needRSID[4];

extern short * DMABuffer;

unsigned short * SendtoCard(unsigned short * buf, int n);
short * SoundInit();
void DoTX(int Chan);
void UDPPollReceivedSamples();
extern void checkforCWID();


extern int SampleNo;

extern int pnt_change[5];				// Freq Changed Flag

// fftw library interface


fftwf_complex *in, *out;
fftwf_plan p;

int FFTSize = 4096;

char * Wisdom;

void initfft()
{
	fftwf_import_wisdom_from_string(Wisdom); 
	fftwf_set_timelimit(30);

#ifndef WIN32
	printf("It may take up to 30 seconds for the program to start for the first time\n");
#endif

	in = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * 10000);
	out = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * 10000);
	p = fftwf_plan_dft_1d(FFTSize, in, out, FFTW_FORWARD, FFTW_PATIENT);

	Wisdom = fftwf_export_wisdom_to_string();
}

void dofft(short * inp, float * outr, float * outi)
{
	int i;
	
	fftwf_complex * fft = in;

	for (i = 0; i < FFTSize; i++)
	{
		fft[0][0] = inp[0] * 1.0f;
		fft[0][1] = 0;
		fft++;
		inp++;
	}

	fftwf_execute(p); 

	fft = out;

	for (i = 0; i < FFTSize; i++)
	{
		outr[0] = fft[0][0];
		outi[0] = fft[0][1];
		fft++;
		outi++;
		outr++;
	}
}

void freefft()
{
	fftwf_destroy_plan(p);
	fftwf_free(in);
	fftwf_free(out);
}

int nonGUIMode = 0;

void soundMain()
{
	// non platform specific initialisation

	platformInit();

	// initialise fft library

	RsCreate();				// RS code for MPSK

	detector_init();
	KISS_init();
	ax25_init();
	init_raduga();			// Set up waterfall colour table

	initfft();
	il2p_init(1);


	if (nonGUIMode)
	{
		Firstwaterfall = 0;
		Secondwaterfall = 0;
	}

	OpenPTTPort();
}


void SampleSink(int LR, short Sample)
{
	// This version is passed samples one at a time, as we don't have
	//	enough RAM in embedded systems to hold a full audio frame

	// LR - 1 == Right Chan

#ifdef TEENSY	
		int work = Sample;
		DMABuffer[Number++] = (work + 32768) >> 4; // 12 bit left justify
#else
	if (SCO)			// Single Channel Output - same to both L and R
	{
		DMABuffer[2 * Number] = Sample;
		DMABuffer[1 + 2 * Number] = Sample;
	}
	else
	{
		if (LR)				// Right
		{
			DMABuffer[1 + 2 * Number] = Sample;
			DMABuffer[2 * Number] = 0;
		}
		else
		{
			DMABuffer[2 * Number] = Sample;
			DMABuffer[1 + 2 * Number] = 0;
		}
	}
	if (using48000)
	{
		// Need to upsample to 48K. Try just duplicating sample

		uint32_t * ptr = &DMABuffer[2 * Number];

		*(&ptr[1]) = *(ptr);
		*(&ptr[2]) = *(ptr);
		*(&ptr[3]) = *(ptr);

		Number += 3;
	}
	Number++;
#endif
		if (Number >= SendSize)
		{
			// send this buffer to sound interface

			DMABuffer = SendtoCard(DMABuffer, SendSize);
			Number = 0;
		}
	

//	Last120[Last120Put++] = Sample;

//	if (Last120Put == (intN + 1))
//		Last120Put = 0;

	SampleNo++;
}


void Flush()
{
	SoundFlush(Number);
}

int ipow(int base, int exp)
{
	int result = 1;
	while (exp)
	{
		if (exp & 1)
			result *= base;
		exp >>= 1;
		base *= base;
	}

	return result;
}

int NumberOfBitsNeeded(int PowerOfTwo)
{
	int i;

	for (i = 0; i <= 16; i++)
	{
		if ((PowerOfTwo & ipow(2, i)) != 0)
			return i;

	}
	return 0;
}


int ReverseBits(int Index, int NumBits)
{
	int i, Rev = 0;

	for (i = 0; i < NumBits; i++)
	{
		Rev = (Rev * 2) | (Index & 1);
		Index = Index / 2;
	}

	return Rev;
}


void FourierTransform(int NumSamples, short * RealIn, float * RealOut, float * ImagOut, int InverseTransform)
{
	float AngleNumerator;
	unsigned char NumBits;

	int i, j, K, n, BlockSize, BlockEnd;
	float DeltaAngle, DeltaAr;
	float Alpha, Beta;
	float TR, TI, AR, AI;

	if (InverseTransform)
		AngleNumerator = -2.0f * M_PI;
	else
		AngleNumerator = 2.0f * M_PI;

	NumBits = NumberOfBitsNeeded(NumSamples);

	for (i = 0; i < NumSamples; i++)
	{
		j = ReverseBits(i, NumBits);
		RealOut[j] = RealIn[i];
		ImagOut[j] = 0.0f; // Not using i in ImageIn[i];
	}

	BlockEnd = 1;
	BlockSize = 2;

	while (BlockSize <= NumSamples)
	{
		DeltaAngle = AngleNumerator / BlockSize;
		Alpha = sinf(0.5f * DeltaAngle);
		Alpha = 2.0f * Alpha * Alpha;
		Beta = sinf(DeltaAngle);

		i = 0;

		while (i < NumSamples)
		{
			AR = 1.0f;
			AI = 0.0f;

			j = i;

			for (n = 0; n < BlockEnd; n++)
			{
				K = j + BlockEnd;
				TR = AR * RealOut[K] - AI * ImagOut[K];
				TI = AI * RealOut[K] + AR * ImagOut[K];
				RealOut[K] = RealOut[j] - TR;
				ImagOut[K] = ImagOut[j] - TI;
				RealOut[j] = RealOut[j] + TR;
				ImagOut[j] = ImagOut[j] + TI;
				DeltaAr = Alpha * AR + Beta * AI;
				AI = AI - (Alpha * AI - Beta * AR);
				AR = AR - DeltaAr;
				j = j + 1;
			}
			i = i + BlockSize;
		}
		BlockEnd = BlockSize;
		BlockSize = BlockSize * 2;
	}

	if (InverseTransform)
	{
		//	Normalize the resulting time samples...

		for (i = 0; i < NumSamples; i++)
		{
			RealOut[i] = RealOut[i] / NumSamples;
			ImagOut[i] = ImagOut[i] / NumSamples;
		}
	}
}



int LastBusyCheck = 0;

extern UCHAR CurrentLevel;

#ifdef PLOTSPECTRUM		
float dblMagSpectrum[206];
float dblMaxScale = 0.0f;
extern UCHAR Pixels[4096];
extern UCHAR * pixelPointer;
#endif

extern int blnBusyStatus;
BusyDet = 5;

#define PLOTWATERFALL

int WaterfallActive = 1;
int SpectrumActive;

float BinSize;

extern int intLastStart;
extern int intLastStop;

void SMSortSignals2(float * dblMag, int intStartBin, int intStopBin, int intNumBins, float *  dblAVGSignalPerBin, float *  dblAVGBaselinePerBin);


BOOL SMBusyDetect3(int Chan, float * dblMag, int intStart, int intStop)        // this only called while searching for leader ...once leader detected, no longer called.
{
	// First sort signals and look at highes signals:baseline ratio..

	float dblAVGSignalPerBinNarrow, dblAVGSignalPerBinWide, dblAVGBaselineNarrow, dblAVGBaselineWide;
	float dblSlowAlpha = 0.2f;
	static float dblAvgStoNNarrow[4] = { 0 }, dblAvgStoNWide[4] = {0};
	int intNarrow = 8;  // 8 x 11.72 Hz about 94 z
	int intWide = ((intStop - intStart) * 2) / 3; //* 0.66);
	int blnBusy = FALSE;
	int  BusyDet4th = BusyDet * BusyDet * BusyDet * BusyDet;

	// First sort signals and look at highest signals:baseline ratio..
	// First narrow band (~94Hz)

	SMSortSignals2(dblMag, intStart, intStop, intNarrow, &dblAVGSignalPerBinNarrow, &dblAVGBaselineNarrow);

	// Shouldn't dblAvgStoNNarrow, dblAvgStoNWide be static ??????


	if (intLastStart == intStart && intLastStop == intStop)
		dblAvgStoNNarrow[Chan] = (1 - dblSlowAlpha) * dblAvgStoNNarrow[Chan] + dblSlowAlpha * dblAVGSignalPerBinNarrow / dblAVGBaselineNarrow;
	else
	{
		// This initializes the Narrow average after a bandwidth change

		dblAvgStoNNarrow[Chan] = dblAVGSignalPerBinNarrow / dblAVGBaselineNarrow;
	}

	// Wide band (66% of current bandwidth)

	SMSortSignals2(dblMag, intStart, intStop, intWide, &dblAVGSignalPerBinWide, &dblAVGBaselineWide);

	if (intLastStart == intStart && intLastStop == intStop)
		dblAvgStoNWide[Chan] = (1 - dblSlowAlpha) * dblAvgStoNWide[Chan] + dblSlowAlpha * dblAVGSignalPerBinWide / dblAVGBaselineWide;
	else
	{
		// This initializes the Wide average after a bandwidth change

		dblAvgStoNWide[Chan] = dblAVGSignalPerBinWide / dblAVGBaselineWide;
		intLastStart = intStart;
		intLastStop = intStop;
	}

	// Preliminary calibration...future a function of bandwidth and BusyDet.


	blnBusy = (dblAvgStoNNarrow[Chan] > (3 + 0.008 * BusyDet4th)) || (dblAvgStoNWide[Chan] > (5 + 0.02 * BusyDet4th));

//	if (BusyDet == 0)
//		blnBusy = FALSE;		// 0 Disables check ?? Is this the best place to do this?

//	WriteDebugLog(LOGDEBUG, "Busy %d Wide %f Narrow %f", blnBusy, dblAvgStoNWide, dblAvgStoNNarrow); 

	return blnBusy;
}

extern int compare(const void *p1, const void *p2);

void SMSortSignals2(float * dblMag, int intStartBin, int intStopBin, int intNumBins, float *  dblAVGSignalPerBin, float *  dblAVGBaselinePerBin)
{
	// puts the top intNumber of bins between intStartBin and intStopBin into dblAVGSignalPerBin, the rest into dblAvgBaselinePerBin
	// for decent accuracy intNumBins should be < 75% of intStopBin-intStartBin)

	// This version uses a native sort function which is much faster and reduces CPU loading significantly on wide bandwidths. 

	float dblSort[8192];
	float dblSum1 = 0, dblSum2 = 0;
	int numtoSort = (intStopBin - intStartBin) + 1, i;

	memcpy(dblSort, &dblMag[intStartBin], numtoSort * sizeof(float));

	qsort((void *)dblSort, numtoSort, sizeof(float), compare);

	for (i = numtoSort - 1; i >= 0; i--)
	{
		if (i >= (numtoSort - intNumBins))
			dblSum1 += dblSort[i];
		else
			dblSum2 += dblSort[i];
	}

	*dblAVGSignalPerBin = dblSum1 / intNumBins;
	*dblAVGBaselinePerBin = dblSum2 / (intStopBin - intStartBin - intNumBins - 1);
}

extern void updateDCD(int Chan, BOOL State);

void SMUpdateBusyDetector(int LR, float * Real, float *Imag)
{
	// Energy based detector for each channel.
	// Fed from FFT generated for waterfall display
	// FFT size is 4096

	float dblMag[4096];

	static BOOL blnLastBusyStatus[4];

	float dblMagAvg = 0;
	int i, chan;


	if (Now - LastBusyCheck < 100)	// ??
		return;

	LastBusyCheck = Now;

	// We need to run busy test on the frequncies used by each modem.

	for (chan = 0; chan < 4; chan++)
	{
		int Low, High, Start, End;

		if (soundChannel[chan] != (LR + 1))	// on this side of soundcard 
			continue;

		Low = tx_freq[chan] - txbpf[chan] / 2;
		High = tx_freq[chan] + txbpf[chan] / 2;

//		Low = tx_freq[chan] - 0.5*rx_shift[chan];
//		High = tx_freq[chan] + 0.5*rx_shift[chan];

		// BinSize is width of each fft bin in Hz

		Start = (Low / BinSize);		// First and last bins to process
		End = (High / BinSize);


		for (i = Start; i < End; i++)
		{
			dblMag[i] = powf(Real[i], 2) + powf(Imag[i], 2);	 // first pass
			dblMagAvg += dblMag[i];
		}

		blnBusyStatus = SMBusyDetect3(chan, dblMag, Start, End);

		if (blnBusyStatus && !blnLastBusyStatus[chan])
		{
//			Debugprintf("Ch %d Busy True", chan);
			updateDCD(chan, TRUE);
		}
		else if (blnLastBusyStatus[chan] && !blnBusyStatus)
		{
//			Debugprintf("Ch %d Busy False", chan);
			updateDCD(chan, FALSE);
		}
		blnLastBusyStatus[chan] = blnBusyStatus;
	}
}


extern short rawSamples[2400];	// Get Frame Type need 2400 and we may add 1200
int rawSamplesLength = 0;
extern int maxrawSamplesLength;

void ProcessNewSamples(short * Samples, int nSamples)
{
	if (SoundIsPlaying == FALSE && UDPSoundIsPlaying == FALSE)
		BufferFull(Samples, nSamples);
};

void doCalib(int Chan, int Act)
{
	if (Chan == 0 && calib_mode[1])
		return;						
	
	if (Chan == 1 && calib_mode[0])
		return;

	if (Act == 0)
	{
		calib_mode[Chan] = 0;
		tx_status[Chan] = TX_SILENCE;		// Stop TX
		Flush();
		RadioPTT(Chan, 0);
		Debugprintf("Stop Calib");
	}
	else
	{
		if (calib_mode[Chan] == 0)
			SampleNo = 0;

		calib_mode[Chan] = Act;
	}
}

int Freq_Change(int Chan, int Freq)
{
	int low, high;

	low = round(rx_shift[Chan] / 2 + (RCVR[Chan] * rcvr_offset[Chan]));
	high = round(RX_Samplerate / 2 - (rx_shift[Chan] / 2 + RCVR[Chan] * rcvr_offset[Chan]));

	if (Freq < 300)
		return rx_freq[Chan];				// Dont allow change

	if (Freq < low)
		return rx_freq[Chan];				// Dont allow change

	if (Freq > high)
		return rx_freq[Chan];				// Dont allow change

	rx_freq[Chan] = Freq;
	tx_freq[Chan] = Freq;

	pnt_change[Chan] = TRUE;
	NeedWaterfallHeaders = TRUE;

	return Freq;
}

void MainLoop()
{
	// Called by background thread every 10 ms (maybe)

	// Actually we may have two cards
	
	// Original only allowed one channel per card.
	// I think we should be able to run more, ie two or more
	// modems on same soundcard channel
	
	// So All the soundcard stuff will need to be generalised

	if (UDPServ)
		UDPPollReceivedSamples();

	if (SoundMode == 3)
		UDPPollReceivedSamples();
	else
		PollReceivedSamples();


	for (int i = 0; i < 4; i++)
	{
		if (modem_mode[i] == MODE_ARDOP)
		{
			chk_dcd1(i, 512);
		}
	}
	DoTX(0);
	DoTX(1);
	DoTX(2);
	DoTX(3);

}

int ARDOPSendToCard(int Chan, int Len)
{
	// Send Next Block of samples to the soundcard


	short * in = &ARDOPTXBuffer[Chan][ARDOPTXPtr[Chan]];		// Enough to hold whole frame of samples
	short * out = DMABuffer;

	int LR = modemtoSoundLR[Chan];

	int i;

	for (i = 0; i < Len; i++)
	{
		if (SCO)			// Single Channel Output - same to both L and R
		{
			*out++ = *in;
			*out++ = *in++;
		}
		else
		{
			if (LR)				// Right
			{
				*out++ = 0;
				*out++ = *in++;
			}
			else
			{
				*out++ = *in++;
				*out++ = 0;
			}
		}
	}

	DMABuffer = SendtoCard(DMABuffer, Len);

	ARDOPTXPtr[Chan] += Len;

	// See if end of buffer

	if (ARDOPTXPtr[Chan] > ARDOPTXLen[Chan])
		return 1;

	return 0;
}
void DoTX(int Chan)
{
	// This kicks off a send sequence or calibrate

//	printtick("dotx");

	if (calib_mode[Chan])
	{
		// Maybe new calib or continuation

		if (pnt_change[Chan])
		{
			make_core_BPF(Chan, rx_freq[Chan], bpf[Chan]);
			make_core_TXBPF(Chan, tx_freq[Chan], txbpf[Chan]);
			pnt_change[Chan] = FALSE;
		}
		
		// Note this may block in SendtoCard

		modulator(Chan, tx_bufsize);
		return;
	}

	// I think we have to detect NO_DATA here and drop PTT and return to SILENCE

	if (tx_status[Chan] == TX_NO_DATA)
	{
		Flush();
		Debugprintf("TX Complete %d", SampleNo);
		RadioPTT(Chan, 0);
		Continuation[Chan] = 0;

		tx_status[Chan] = TX_SILENCE;

		// We should now send any ackmode acks as the channel is now free for dest to reply

		sendAckModeAcks(Chan);
	}

	if (tx_status[Chan] != TX_SILENCE)
	{
		// Continue the send

		if (modem_mode[Chan] == MODE_ARDOP || modem_mode[Chan] == MODE_RUH)
		{
//			if (SeeIfCardBusy())
//				return 0;

			if (ARDOPSendToCard(Chan, SendSize) == 1)
			{
				// End of TX

				Number = 0;
				Flush();

				// See if more to send. If so, don't drop PTT

				if (all_frame_buf[Chan].Count)
				{
					SoundIsPlaying = TRUE;
					Number = 0;

					Continuation[Chan] = 1;

					Debugprintf("TX Continuing");

					string * myTemp = Strings(&all_frame_buf[Chan], 0);			// get message
					string * tx_data;

					if ((myTemp->Data[0] & 0x0f) == 12)			// ACKMODE
					{
						// Save copy then copy data up 3 bytes

						Add(&KISS_acked[Chan], duplicateString(myTemp));

						mydelete(myTemp, 0, 3);
						myTemp->Length -= sizeof(void *);
					}
					else
					{
						// Just remove control 

						mydelete(myTemp, 0, 1);
					}

					tx_data = duplicateString(myTemp);		// so can free original below

					Delete(&all_frame_buf[Chan], 0);			// This will invalidate temp

					AGW_AX25_frame_analiz(Chan, FALSE, tx_data);

					put_frame(Chan, tx_data, "", TRUE, FALSE);

					if (modem_mode[Chan] == MODE_ARDOP)
						PktARDOPEncode(tx_data->Data, tx_data->Length - 2, Chan);
					else
						RUHEncode(tx_data->Data, tx_data->Length - 2, Chan);

					freeString(tx_data);

					// Samples are now in DMABuffer = Send first block

					DMABuffer = SoundInit();

					ARDOPSendToCard(Chan, SendSize);
					tx_status[Chan] = TX_FRAME;
					return;
				}

				Debugprintf("TX Complete %d", SampleNo); 
				RadioPTT(Chan, 0);
				Continuation[Chan] = 0;

				tx_status[Chan] = TX_SILENCE;

				// We should now send any ackmode acks as the channel is now free for dest to reply
			}

			return;
		}

		modulator(Chan, tx_bufsize); 
		return;
	}

	if (SoundIsPlaying || UDPSoundIsPlaying)
		return;

	// Not doing anything so see if we have anything new to send

	// See if frequency has changed

	if (pnt_change[Chan])
	{
		make_core_BPF(Chan, rx_freq[Chan], bpf[Chan]);
		make_core_TXBPF(Chan, tx_freq[Chan], txbpf[Chan]);
		pnt_change[Chan] = FALSE;
	}

	// See if we need an RSID

	if (needRSID[Chan])
	{
		needRSID[Chan] = 0;

		// Note this may block in SampleSink

		Debugprintf("Sending RSID");
		sendRSID(Chan, all_frame_buf[Chan].Count == 0);
		return;
	}

	if (all_frame_buf[Chan].Count == 0)
		return;

	// Start a new send. modulator should handle TXD etc

	checkforCWID();		// See if need to start CWID timer in afteractivity mode

	Debugprintf("TX Start");
	SampleNo = 0;

	SoundIsPlaying = TRUE;
	RadioPTT(Chan, 1);
	Number = 0;

	if (modem_mode[Chan] == MODE_ARDOP)
	{
		// I think ARDOP will have to generate a whole frame of samples
		// then send them out a bit at a time to avoid stopping here for
		// possibly 10's of seconds

		// Can do this here as unlike normal ardop we don't need to run on Teensy
		// to 12000 sample rate we need either 24K or 48K per second, depending on
		// where we do the stereo mux. 

		// Slowest rate is 50 baud, so a 255 byte packet would take about a minute
		// allowing for RS overhead. Not really realistic put perhaps should be possible.
		// RAM isn't an issue so maybe allocate 2 MB. 

		// ?? Should we allow two ARDOP modems - could make sense if we can run sound
		// card channels independently

		string * myTemp = Strings(&all_frame_buf[Chan], 0);			// get message
		string * tx_data;

		if ((myTemp->Data[0] & 0x0f) == 12)			// ACKMODE
		{
			// Save copy then copy data up 3 bytes

			Add(&KISS_acked[Chan], duplicateString(myTemp));

			mydelete(myTemp, 0, 3);
			myTemp->Length -= sizeof(void *);
		}
		else
		{
			// Just remove control 

			mydelete(myTemp, 0, 1);
		}

		tx_data = duplicateString(myTemp);		// so can free original below

		Delete(&all_frame_buf[Chan], 0);			// This will invalidate temp

		AGW_AX25_frame_analiz(Chan, FALSE, tx_data);

		put_frame(Chan, tx_data, "", TRUE, FALSE);

		PktARDOPEncode(tx_data->Data, tx_data->Length - 2, Chan);

		freeString(tx_data);

		// Samples are now in DMABuffer = Send first block

		ARDOPSendToCard(Chan, SendSize);
		tx_status[Chan] = TX_FRAME;

	}
	else if (modem_mode[Chan] == MODE_RUH)
	{
		// Same as for ARDOP. Generate a whole frame of samples 
		// then send them out a bit at a time to avoid stopping here

		// We allow two RUH modems

		string * myTemp = Strings(&all_frame_buf[Chan], 0);			// get message
		string * tx_data;

		if ((myTemp->Data[0] & 0x0f) == 12)			// ACKMODE
		{
			// Save copy then copy data up 3 bytes

			Add(&KISS_acked[Chan], duplicateString(myTemp));

			mydelete(myTemp, 0, 3);
			myTemp->Length -= sizeof(void *);
		}
		else
		{
			// Just remove control 

			mydelete(myTemp, 0, 1);
		}

		tx_data = duplicateString(myTemp);		// so can free original below

		Delete(&all_frame_buf[Chan], 0);			// This will invalidate temp

		AGW_AX25_frame_analiz(Chan, FALSE, tx_data);

		put_frame(Chan, tx_data, "", TRUE, FALSE);

		RUHEncode(tx_data->Data, tx_data->Length - 2, Chan);

		freeString(tx_data);

		// Samples are now in DMABuffer = Send first block

		ARDOPSendToCard(Chan, SendSize);
		tx_status[Chan] = TX_FRAME;

	}
	else
		modulator(Chan, tx_bufsize);

	return;
}

void RX2TX(int snd_ch)
{
	if (snd_status[snd_ch] == SND_IDLE)
	{
		DoTX(snd_ch);
	}
}

// PTT Stuff

int hPTTDevice = 0;
char PTTPort[80] = "";			// Port for Hardware PTT - may be same as control port.
int PTTBAUD = 19200;
int PTTMode = PTTRTS;			// PTT Control Flags.

char PTTOnString[128] = "";
char PTTOffString[128] = "";

UCHAR PTTOnCmd[64];
UCHAR PTTOnCmdLen = 0;

UCHAR PTTOffCmd[64];
UCHAR PTTOffCmdLen = 0;

int pttGPIOPin = 17;			// Default
int pttGPIOPinR = 17;
BOOL pttGPIOInvert = FALSE;
BOOL useGPIO = FALSE;
BOOL gotGPIO = FALSE;

int HamLibPort = 4532;
char HamLibHost[32] = "127.0.0.1";

int FLRigPort = 12345;
char FLRigHost[32] = "127.0.0.1";

char CM108Addr[80] = "";

int VID = 0;
int PID = 0;

// CM108 Code

char * CM108Device = NULL;

void DecodeCM108(char * ptr)
{
	// Called if Device Name or PTT = Param is CM108

#ifdef WIN32

	// Next Param is VID and PID - 0xd8c:0x8 or Full device name
	// On Windows device name is very long and difficult to find, so 
	//	easier to use VID/PID, but allow device in case more than one needed

	char * next;
	long VID = 0, PID = 0;
	char product[256] = "Unknown";

	struct hid_device_info *devs, *cur_dev;
	const char *path_to_open = NULL;
	hid_device *handle = NULL;

	if (strlen(ptr) > 16)
		CM108Device = _strdup(ptr);
	else
	{
		VID = strtol(ptr, &next, 0);
		if (next)
			PID = strtol(++next, &next, 0);

		// Look for Device

		devs = hid_enumerate((unsigned short)VID, (unsigned short)PID);
		cur_dev = devs;

		while (cur_dev)
		{
			if (cur_dev->product_string)
				wcstombs(product, cur_dev->product_string, 255);
			
			Debugprintf("HID Device %s VID %X PID %X", product, cur_dev->vendor_id, cur_dev->product_id);
			if (cur_dev->vendor_id == VID && cur_dev->product_id == PID)
			{
				path_to_open = cur_dev->path;
				break;
			}
			cur_dev = cur_dev->next;
		}

		if (path_to_open)
		{
			handle = hid_open_path(path_to_open);

			if (handle)
			{
				hid_close(handle);
				CM108Device = _strdup(path_to_open);
			}
			else
			{
				Debugprintf("Unable to open CM108 device %x %x", VID, PID);
			}
		}
		else
			Debugprintf("Couldn't find CM108 device %x %x", VID, PID);

		hid_free_enumeration(devs);
	}
#else

	// Linux - Next Param HID Device, eg /dev/hidraw0

	CM108Device = _strdup(ptr);
#endif
}

char * strlop(char * buf, char delim)
{
	// Terminate buf at delim, and return rest of string

	char * ptr = strchr(buf, delim);

	if (ptr == NULL) return NULL;

	*(ptr)++ = 0;
	return ptr;
}

void OpenPTTPort()
{
	PTTMode &= ~PTTCM108;
	PTTMode &= ~PTTHAMLIB;

	if (PTTPort[0] && strcmp(PTTPort, "None") != 0)
	{
		if (PTTMode == PTTCAT)
		{
			// convert config strings from Hex

			char * ptr1 = PTTOffString;
			UCHAR * ptr2 = PTTOffCmd;
			char c;
			int val;

			while (c = *(ptr1++))
			{
				val = c - 0x30;
				if (val > 15) val -= 7;
				val <<= 4;
				c = *(ptr1++) - 0x30;
				if (c > 15) c -= 7;
				val |= c;
				*(ptr2++) = val;
			}

			PTTOffCmdLen = ptr2 - PTTOffCmd;

			ptr1 = PTTOnString;
			ptr2 = PTTOnCmd;

			while (c = *(ptr1++))
			{
				val = c - 0x30;
				if (val > 15) val -= 7;
				val <<= 4;
				c = *(ptr1++) - 0x30;
				if (c > 15) c -= 7;
				val |= c;
				*(ptr2++) = val;
			}

			PTTOnCmdLen = ptr2 - PTTOnCmd;
		}

		if (stricmp(PTTPort, "GPIO") == 0)
		{
			// Initialise GPIO for PTT if available

#ifdef __ARM_ARCH

			if (gpioInitialise() == 0)
			{
				printf("GPIO interface for PTT available\n");
				gotGPIO = TRUE;

				SetupGPIOPTT();
			}
			else
				printf("Couldn't initialise GPIO interface for PTT\n");

#else
			printf("GPIO interface for PTT not available on this platform\n");
#endif

		}
		else if (stricmp(PTTPort, "CM108") == 0)
		{
			DecodeCM108(CM108Addr);
			PTTMode |= PTTCM108;
		}

		else if (stricmp(PTTPort, "HAMLIB") == 0)
		{
			PTTMode |= PTTHAMLIB;
			HAMLIBSetPTT(0);			// to open port
			return;
		}
		else if (stricmp(PTTPort, "FLRIG") == 0)
		{
			PTTMode |= PTTFLRIG;
			FLRigSetPTT(0);			// to open port
			return;
		}

		else		//  Not GPIO
		{
			hPTTDevice = OpenCOMPort(PTTPort, PTTBAUD, FALSE, FALSE, FALSE, 0);
		}
	}
}

void ClosePTTPort()
{
	if (hPTTDevice)
		CloseCOMPort(hPTTDevice);
	
	hPTTDevice = 0;
}
void CM108_set_ptt(int PTTState)
{
	char io[5];
	hid_device *handle;
	int n;

	io[0] = 0;
	io[1] = 0;
	io[2] = 1 << (3 - 1);
	io[3] = PTTState << (3 - 1);
	io[4] = 0;

	if (CM108Device == NULL)
		return;

#ifdef WIN32
	handle = hid_open_path(CM108Device);

	if (!handle) {
		printf("unable to open device\n");
		return;
	}

	n = hid_write(handle, io, 5);
	if (n < 0)
	{
		printf("Unable to write()\n");
		printf("Error: %ls\n", hid_error(handle));
	}

	hid_close(handle);

#else

	int fd;

	fd = open(CM108Device, O_WRONLY);

	if (fd == -1)
	{
		printf("Could not open %s for write, errno=%d\n", CM108Device, errno);
		return;
	}

	io[0] = 0;
	io[1] = 0;
	io[2] = 1 << (3 - 1);
	io[3] = PTTState << (3 - 1);
	io[4] = 0;

	n = write(fd, io, 5);
	if (n != 5)
	{
		printf("Write to %s failed, n=%d, errno=%d\n", CM108Device, n, errno);
	}

	close(fd);
#endif
	return;

}

float amplitudes[4] = { 32000, 32000, 32000, 32000 };
extern float amplitude;
void startpttOnTimer();
extern void UpdatePTTStats(int Chan, int State);

void RadioPTT(int snd_ch, BOOL PTTState)
{
	snd_status[snd_ch] = PTTState; // SND_IDLE = 0 SND_TX = 1 

	if (PTTState)
	{
		txmax = txmin = 0;
		amplitude = amplitudes[snd_ch];
		StartWatchdog();
	}
	else
	{
		Debugprintf("Output peaks = %d, %d, amp %f", txmin, txmax, amplitude);
		amplitudes[snd_ch] = amplitude;
		StopWatchdog();
	}

	if ((PTTMode & PTTHOST))
	{
		// Send PTT ON/OFF to any mgmt connections

		SendMgmtPTT(snd_ch, PTTState);
	}

	UpdatePTTStats(snd_ch, PTTState);

#ifdef __ARM_ARCH
	if (useGPIO)
	{
		if (DualPTT && modemtoSoundLR[snd_ch] == 1)
			gpioWrite(pttGPIOPinR, (pttGPIOInvert ? (1 - PTTState) : (PTTState)));
		else
			gpioWrite(pttGPIOPin, (pttGPIOInvert ? (1 - PTTState) : (PTTState)));
		startpttOnTimer();
		return;
	}

#endif

	if ((PTTMode & PTTCM108))
	{
		CM108_set_ptt(PTTState);
		startpttOnTimer();
		return;
	}
	
	if ((PTTMode & PTTHAMLIB))
	{
		HAMLIBSetPTT(PTTState);
		startpttOnTimer();
		return;
	}

	if ((PTTMode & PTTFLRIG))
	{
		FLRigSetPTT(PTTState);
		startpttOnTimer();
		return;
	}

	if (hPTTDevice == 0)
	{
		startpttOnTimer();
		return;
	}
	if ((PTTMode & PTTCAT))
	{
		if (PTTState)
			WriteCOMBlock(hPTTDevice, PTTOnCmd, PTTOnCmdLen);
		else
			WriteCOMBlock(hPTTDevice, PTTOffCmd, PTTOffCmdLen);

		return;
	}

	if (DualPTT && modemtoSoundLR[snd_ch] == 1)		// use DTR
	{
		if (PTTState)
			COMSetDTR(hPTTDevice);
		else
			COMClearDTR(hPTTDevice);
	}
	else
	{
		if ((PTTMode & PTTRTS))
		{
			if (PTTState)
				COMSetRTS(hPTTDevice);
			else
				COMClearRTS(hPTTDevice);
		}
	}

				
	startpttOnTimer();

}

char ShortDT[] = "HH:MM:SS";

char * ShortDateTime()
{
	struct tm * tm;
	time_t NOW = time(NULL);

	tm = gmtime(&NOW);

	sprintf(ShortDT, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
	return ShortDT;
}


// Reed Solomon Stuff


int NPAR = -1;	// Number of Parity Bytes - used in RS Code

int xMaxErrors = 0;

int RSEncode(UCHAR * bytToRS, UCHAR * RSBytes, int DataLen, int RSLen)
{
	// This just returns the Parity Bytes. I don't see the point
	// in copying the message about

	unsigned char Padded[256];		// The padded Data

	int Length = DataLen + RSLen;	// Final Length of packet
	int PadLength = 255 - Length;	// Padding bytes needed for shortened RS codes

	//	subroutine to do the RS encode. For full length and shortend RS codes up to 8 bit symbols (mm = 8)

	if (NPAR != RSLen)		// Changed RS Len, so recalc constants;
	{
		NPAR = RSLen;
		xMaxErrors = NPAR / 2;
		initialize_ecc();
	}

	// Copy the supplied data to end of data array.

	memset(Padded, 0, PadLength);
	memcpy(&Padded[PadLength], bytToRS, DataLen);

	encode_data(Padded, 255 - RSLen, RSBytes);

	return RSLen;
}

//	Main RS decode function

extern int index_of[];
extern int recd[];
extern int Corrected[256];
extern int tt;		//  number of errors that can be corrected 
extern int kk;		// Info Symbols

extern BOOL blnErrorsCorrected;


BOOL RSDecode(UCHAR * bytRcv, int Length, int CheckLen, BOOL * blnRSOK)
{


	// Using a modified version of Henry Minsky's code

	//Copyright Henry Minsky (hqm@alum.mit.edu) 1991-2009

	// Rick's Implementation processes the byte array in reverse. and also 
	//	has the check bytes in the opposite order. I've modified the encoder
	//	to allow for this, but so far haven't found a way to mske the decoder
	//	work, so I have to reverse the data and checksum to decode G8BPQ Nov 2015

	//	returns TRUE if was ok or correction succeeded, FALSE if correction impossible

	UCHAR intTemp[256];				// WOrk Area to pass to Decoder		
	int i;
	UCHAR * ptr2 = intTemp;
	UCHAR * ptr1 = &bytRcv[Length - CheckLen - 1]; // Last Byte of Data

	int DataLen = Length - CheckLen;
	int PadLength = 255 - Length;		// Padding bytes needed for shortened RS codes

	*blnRSOK = FALSE;

	if (Length > 255 || Length < (1 + CheckLen))		//Too long or too short 
		return FALSE;

	if (NPAR != CheckLen)		// Changed RS Len, so recalc constants;
	{
		NPAR = CheckLen;
		xMaxErrors = NPAR / 2;

		initialize_ecc();
	}


	//	We reverse the data while zero padding it to speed things up

	//	We Need (Data Reversed) (Zero Padding) (Checkbytes Reversed)

	// Reverse Data

	for (i = 0; i < DataLen; i++)
	{
		*(ptr2++) = *(ptr1--);
	}

	//	Clear padding

	memset(ptr2, 0, PadLength);

	ptr2 += PadLength;

	// Error Bits

	ptr1 = &bytRcv[Length - 1];			// End of check bytes

	for (i = 0; i < CheckLen; i++)
	{
		*(ptr2++) = *(ptr1--);
	}

	decode_data(intTemp, 255);

	// check if syndrome is all zeros 

	if (check_syndrome() == 0)
	{
		// RS ok, so no need to correct

		*blnRSOK = TRUE;
		return TRUE;		// No Need to Correct
	}

	if (correct_errors_erasures(intTemp, 255, 0, 0) == 0) // Dont support erasures at the momnet

		// Uncorrectable

		return FALSE;

	// Data has been corrected, so need to reverse again

	ptr1 = &intTemp[DataLen - 1];
	ptr2 = bytRcv; // Last Byte of Data

	for (i = 0; i < DataLen; i++)
	{
		*(ptr2++) = *(ptr1--);
	}

	// ?? Do we need to return the check bytes ??

	// Yes, so we can redo RS Check on supposedly connected frame

	ptr1 = &intTemp[254];	// End of Check Bytes

	for (i = 0; i < CheckLen; i++)
	{
		*(ptr2++) = *(ptr1--);
	}

	return TRUE;
}

extern TStringList detect_list[5];
extern TStringList detect_list_c[5];

void ProcessPktFrame(int snd_ch, UCHAR * Data, int frameLen)
{
	string * pkt = newString();

	stringAdd(pkt, Data, frameLen + 2);			// 2 for crc (not actually there)

	analiz_frame(snd_ch, pkt, "ARDOP", 1);

}