File: Concat.cpp

package info (click to toggle)
supercollider-sc3-plugins 3.7.1~repack-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 14,332 kB
  • ctags: 11,704
  • sloc: cpp: 140,180; lisp: 14,746; ansic: 2,133; xml: 86; makefile: 82; haskell: 21; sh: 8
file content (1261 lines) | stat: -rw-r--r-- 28,452 bytes parent folder | download | duplicates (4)
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
/*
	SuperCollider real time audio synthesis system
 Copyright (c) 2002 James McCartney. All rights reserved.
	http://www.audiosynth.com

 This program 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 2 of the License, or
 (at your option) any later version.

 This program 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 this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

//Concat, Concat2: real-time concatenative synthesis UGens by Nick Collins (after Schwarz, Casey, Sturm et al)
//originally for my PhD 2006

//I developed for 44100 sample rate, with 256 FFT (without overlap) for low latency operation. It will probably work at 48000 without major problems
//assumes block size is 64

//features- ZCR over last 1024 samples = 4 frames, RMS energy over frame, then from the FFT- spec centroid, spec variance, spec rolloff

#include "SC_PlugIn.h"
//#include "SCComplex.h"
//#include "FFT_UGens.h"
#include "SC_fftlib.h"
//#include "SC_Constants.h"
//
//#include <vecLib/vecLib.h>
//#include <string.h>
//#include <math.h>
//#include <stdlib.h>
#include <stdio.h>

static InterfaceTable *ft;

struct Concat : Unit {

	//essential constants
	int m_sr;
	int m_blocksize;
	int m_fftsize;
	int m_nover2;
	int m_blocksperframe;
	int m_samplesforzcr;

	//FFT data
	int m_bufWritePos;

	scfft *m_scfftsource, *m_scfftcontrol;
	float * m_FFTBufsource, *m_FFTBufcontrol;

	//To fix a database once captured enough
	int m_freezestore;

	//stored samples

	float * m_controlstore;
	float * m_sourcestore;
	int m_controlcounter;
	int m_sourcecounter;
	int m_sourcesize;
	int m_controlsize;

	//stored features (for source stream only)
	int m_sourceframes;
	int m_featurecounter;

	//time domain
	float * m_rms;
	float * m_zcr;

	//frequency domain
	float * m_speccentroid;
	float * m_spectilt;

	//control playback
	int m_matchlocation;
	int m_matchcounter;
	int m_matchframes;
	int m_fadeoutlocation;

};

struct Concat2 : public Concat {

	int m_nover4;
	float m_matchamp,m_fadeoutamp;	//will also scale based on input amplitude, to avoid noise when no significant input

};


extern "C"
{
	//required interface functions
	void Concat_next(Concat *unit, int numSamples);
	void Concat_Ctor(Concat *unit);
	void Concat_Dtor(Concat *unit);

	int Concat_CtorCommon(Concat *unit);
	void Concat_DtorCommon(Concat *unit);

	void Concat2_next(Concat2 *unit, int numSamples);
	void Concat2_Ctor(Concat2 *unit);
	void Concat2_Dtor(Concat2 *unit);

}

//other functions
void Concat_dofft(Concat *unit, scfft *, float *);	//call FFT and in place data to powers
void sourcefeatures(Concat *unit, float * fftbuf);
void matchfeatures(Concat *unit, float * fftbuf);
float calcst(float * fftbuf);
float calcsc(float * fftbuf, int nover2);
float calcsc2(float * fftbuf, int nover2);
void sourcefeatures2(Concat2 *unit, float * fftbuf);
void matchfeatures2(Concat2 *unit, float * fftbuf);



int Concat_CtorCommon(Concat *unit) {

	//CHECK SAMPLING RATE AND BUFFER SIZE
	unit->m_blocksize = unit->mWorld->mFullRate.mBufLength;

	if(unit->m_blocksize!=64) {
		printf("Concat complains: block size not 64, you have %d\n", unit->m_blocksize);
		return 0;
	}

	unit->m_sr = unit->mWorld->mSampleRate; //(int)(unit->mWorld->mSampleRate+0.1);

	if(unit->m_sr!=44100) {
		printf("Concat complains: sample rate not 44100, you have %d\n", unit->m_sr);
		//return 0; //not necessarily catastrophic
	}

	//printf("sr %d block size %d \n", unit->m_sr, unit->m_blocksize);

	///set up sizes

	unit->m_fftsize=256; //could make conditional on SR, blocksize must divide this!

	unit->m_nover2=unit->m_fftsize/2;

	unit->m_blocksperframe=unit->m_fftsize/unit->m_blocksize; //should be an integer- excat if power of two, else an approximation (good enough for RMS, zerocrossing counts)

	unit->m_samplesforzcr= (unit->m_blocksperframe*unit->m_blocksize)*4; //will also give number of stored samples of the control input, calculated in this way to guarantee an integer

	////////FFT data///////////

	unit->m_FFTBufsource = (float*)RTAlloc(unit->mWorld, unit->m_fftsize * sizeof(float));
	unit->m_FFTBufcontrol = (float*)RTAlloc(unit->mWorld, unit->m_fftsize * sizeof(float));

	//unit->m_FFTBufsourceafter = (float*)RTAlloc(unit->mWorld, unit->m_fftsize * sizeof(float));
	//unit->m_FFTBufcontrolafter = (float*)RTAlloc(unit->mWorld, unit->m_fftsize * sizeof(float));

	unit->m_bufWritePos = 0;


	SCWorld_Allocator alloc(ft, unit->mWorld);
	//no overlap
	unit->m_scfftsource = scfft_create(unit->m_fftsize, unit->m_fftsize, kHannWindow, unit->m_FFTBufsource, unit->m_FFTBufsource, kForward, alloc);
	unit->m_scfftcontrol = scfft_create(unit->m_fftsize, unit->m_fftsize, kHannWindow, unit->m_FFTBufcontrol, unit->m_FFTBufcontrol, kForward, alloc);

	//stores
	unit->m_sourcesize=(((int)(floor(ZIN0(2)*unit->m_sr + .5f)))/(unit->m_fftsize))*(unit->m_fftsize); //integer divide then multiply to make sure its an integer multiple of frames
	unit->m_controlsize= unit->m_samplesforzcr;

	unit->m_controlstore = (float*)RTAlloc(unit->mWorld, unit->m_controlsize * sizeof(float));
	unit->m_sourcestore= (float*)RTAlloc(unit->mWorld, unit->m_sourcesize * sizeof(float));;
	unit->m_controlcounter=0;
	unit->m_sourcecounter=0;

	Clear(unit->m_controlsize, unit->m_controlstore);
	Clear(unit->m_sourcesize, unit->m_sourcestore);

	//features
	unit->m_sourceframes= unit->m_sourcesize/unit->m_fftsize; //should divide perfectly due to earlier correction
	unit->m_featurecounter=0;

	unit->m_rms= (float*)RTAlloc(unit->mWorld, unit->m_sourceframes * sizeof(float));
	unit->m_zcr= (float*)RTAlloc(unit->mWorld, unit->m_sourceframes * sizeof(float));
	unit->m_speccentroid= (float*)RTAlloc(unit->mWorld, unit->m_sourceframes * sizeof(float));
	unit->m_spectilt= (float*)RTAlloc(unit->mWorld, unit->m_sourceframes * sizeof(float));

	Clear(unit->m_sourceframes, unit->m_rms);
	Clear(unit->m_sourceframes, unit->m_zcr);
	Clear(unit->m_sourceframes, unit->m_speccentroid);
	Clear(unit->m_sourceframes, unit->m_spectilt);

	//match setup
	unit->m_matchlocation=0;
	unit->m_matchcounter=1; //immediately seek a match
	unit->m_matchframes=1;
	unit->m_fadeoutlocation= (-1); //negative means do nothing

	return 1;

}

void Concat_DtorCommon(Concat *unit) {

	if(unit->m_scfftsource) {
	SCWorld_Allocator alloc(ft, unit->mWorld);
	scfft_destroy(unit->m_scfftsource, alloc);
	scfft_destroy(unit->m_scfftcontrol, alloc);
	}

	RTFree(unit->mWorld, unit->m_FFTBufsource);
	RTFree(unit->mWorld, unit->m_FFTBufcontrol);
	//RTFree(unit->mWorld, unit->m_hanning);

	RTFree(unit->mWorld, unit->m_controlstore);
	RTFree(unit->mWorld, unit->m_sourcestore);

	RTFree(unit->mWorld, unit->m_rms);
	RTFree(unit->mWorld, unit->m_zcr);
	RTFree(unit->mWorld, unit->m_speccentroid);
	RTFree(unit->mWorld, unit->m_spectilt);


}




void Concat_Ctor(Concat* unit) {

	int check = Concat_CtorCommon(unit);

	if (check==1)
		unit->mCalcFunc = (UnitCalcFunc)&Concat_next;
	else
	{
		SETCALC(*ClearUnitOutputs);
		unit->mDone = true;
	}
}




void Concat2_Ctor(Concat2* unit) {

	int check = Concat_CtorCommon(unit);

	if (check==1) {

		unit->m_nover4=unit->m_fftsize/4;

		unit->m_matchamp=0.0;
		unit->m_fadeoutamp=0.0;

		unit->mCalcFunc = (UnitCalcFunc)&Concat2_next;

	}
	else {
		SETCALC(*ClearUnitOutputs);
		unit->mDone = true;
	}
}





void Concat_Dtor(Concat *unit)
{

	Concat_DtorCommon(unit);

}

void Concat2_Dtor(Concat2 *unit)
{

	Concat_DtorCommon(unit);

}

void Concat_next(Concat *unit, int numSamples) {

	float *controlin = IN(0);
	float *sourcein = IN(1);

	float *output = ZOUT(0);

	float * store=unit->m_sourcestore;

	int sourcecounter= unit->m_sourcecounter;
	int sourcesize=unit->m_sourcesize;

	float * control=unit->m_controlstore;
	int controlcounter= unit->m_controlcounter;
	int controlsize=unit->m_controlsize;

	int bufpos= unit->m_bufWritePos;

	float * fftbuf1=unit->m_FFTBufsource;
	float * fftbuf2=unit->m_FFTBufcontrol;

	float freeze = ZIN0(6);

	for(int j=0; j<numSamples; ++j) {

		float val1=sourcein[j];
		float val2= controlin[j];

		//only write into buffer if allowed
		if(freeze<0.5) {
			store[sourcecounter]= val1;

			sourcecounter= (sourcecounter+1)%sourcesize;
		}

		fftbuf1[bufpos]=val1;

		control[controlcounter]= val2;
		controlcounter= (controlcounter+1)%controlsize;
		fftbuf2[bufpos]=val2;

		++bufpos;
	}

	unit->m_sourcecounter=sourcecounter;
	unit->m_controlcounter=controlcounter;

	if (bufpos==unit->m_fftsize) {

		//only update source features if recording
		if (freeze<0.5) {
			//frame ready- could be within if?
			Concat_dofft(unit,unit->m_scfftsource, fftbuf1);
			//calc source FFT and features to store
			sourcefeatures(unit,fftbuf1);
		}


		//if new match required
		//calc control FFT and features for match
		if(unit->m_matchcounter>= unit->m_matchframes) {

			Concat_dofft(unit,unit->m_scfftcontrol, fftbuf2);
			matchfeatures(unit, fftbuf2);

			} else
			//otherwise increase matchcounter (it was reset in the other branch)
			++unit->m_matchcounter;

		//feature counter ALWAYS updated to keep in step with write position- updated after matchfeatures so matchfeatures references to the nearest last frame
		unit->m_featurecounter=(unit->m_featurecounter+1)%(unit->m_sourceframes);


		//restart FFT data collection
		bufpos=0;
	}

	unit->m_bufWritePos=bufpos;

	int readpos= unit->m_matchlocation;

	int fadepos= unit->m_fadeoutlocation;

	//crossfade on this block
	if(fadepos>=0) {

		for (int i=0; i<numSamples; ++i) {

			float fade= (float)i/((float)numSamples);
			//fade *= fade;

			*++output = ((1.0-fade)*store[fadepos]) + (fade*store[readpos]);
			++readpos;
			++fadepos;
		}

		unit->m_fadeoutlocation = (-1);
	} else { //else just read

		for (int i=0; i<numSamples; ++i) {
			*++output = store[readpos];
			++readpos;
		}

	}

	//only need to modulo here since 64 always divides store size
	unit->m_matchlocation= (readpos)%sourcesize;

}



void Concat2_next(Concat2 *unit, int numSamples)
{
	float *controlin = IN(0);
	float *sourcein = IN(1);

	float *output = ZOUT(0);

	float * store=unit->m_sourcestore;

	int sourcecounter= unit->m_sourcecounter;
	int sourcesize=unit->m_sourcesize;

	float * control=unit->m_controlstore;
	int controlcounter= unit->m_controlcounter;
	int controlsize=unit->m_controlsize;

	int bufpos= unit->m_bufWritePos;

	float * fftbuf1=unit->m_FFTBufsource;
	float * fftbuf2=unit->m_FFTBufcontrol;

	float freeze = ZIN0(6);

	for(int j=0; j<numSamples; ++j) {

		float val1=sourcein[j];
		float val2= controlin[j];

		//only write into buffer if allowed
		if(freeze<0.5) {
			store[sourcecounter]= val1;

			sourcecounter= (sourcecounter+1)%sourcesize;
		}

		fftbuf1[bufpos]=val1;

		control[controlcounter]= val2;
		controlcounter= (controlcounter+1)%controlsize;
		fftbuf2[bufpos]=val2;

		++bufpos;
	}

	unit->m_sourcecounter=sourcecounter;
	unit->m_controlcounter=controlcounter;

	if (bufpos==unit->m_fftsize) {

		//printf("fft block\t");

		//frame ready
		Concat_dofft(unit,unit->m_scfftsource, fftbuf1);

		//only update source features if recording
		if (freeze<0.5)
			//calc source FFT and features to store
			sourcefeatures2(unit,fftbuf1);

		//frame ready, amazingly, this line was missing before! so was calculating based on time domain versus frequency domain!

		if(unit->m_matchcounter>= unit->m_matchframes) {
			//if new match required
			//calc control FFT and features for match
			Concat_dofft(unit,unit->m_scfftcontrol, fftbuf2);
			matchfeatures2(unit, fftbuf2);

		} else
			//otherwise increase matchcounter (it was reset in the other branch)
			++unit->m_matchcounter;

		//feature counter ALWAYS updated to keep in step with write position- updated after matchfeatures so matchfeatures references to the nearest last frame
		unit->m_featurecounter=(unit->m_featurecounter+1)%(unit->m_sourceframes);


		//restart FFT data collection
		bufpos=0;
	}

	unit->m_bufWritePos=bufpos;

	int readpos= unit->m_matchlocation;

	int fadepos= unit->m_fadeoutlocation;

	float readamp= unit->m_matchamp;

	float fadeamp= unit->m_fadeoutamp;

	//crossfade on this block
	if(fadepos>=0) {

		for (int i=0; i<numSamples; ++i) {

			float fade= (float)i/((float)numSamples);
			//fade *= fade;

			*++output = ((1.0-fade)*store[fadepos]*fadeamp) + (fade*store[readpos]*readamp);
			++readpos;
			++fadepos;
		}

		unit->m_fadeoutlocation = (-1);
	} else { //else just read

		for (int i=0; i<numSamples; ++i) {
			*++output = store[readpos]*readamp;
			++readpos;
		}

	}

	//only need to modulo here since 64 always divides store size
	unit->m_matchlocation= (readpos)%sourcesize;

}





//calculated with SC findlogbins program

//find log bins program for 10 bins, for sr=44100, fftsize=256
//
//(
//var sr, binsize, fftsize, nyquist, num, numbins, divisions;
//var logbin;
//var top, bottom;
//var tmp;
//
//sr=44100;
//fftsize=256;
//numbins=fftsize.div(2);
//
//binsize=sr/fftsize;
//
//num=10;
//
//nyquist= sr*0.5;
//
//top= log10(nyquist);
//bottom=log10(binsize);
//
//tmp= (top-bottom)*((num).reciprocal);
//
//divisions=bottom+Array.series(num,tmp,tmp);
//
//Post << divisions << nl;
//
////logbin= Array.fill(numbins, {arg i; log10((i+1)*binsize +0.001)});
//
////invert to find bin positions
//((10**divisions)/binsize).floor.asInteger; //.round(1.0).asInteger
//)

int stbins[11]= {0, 1, 2, 4, 6, 11, 18, 29, 48, 78, 128 };

//avoid bin 0
//int stbins[11]= {1, 2, 3, 5, 9, 14, 21, 34, 52, 82, 128};

float calcst(float * fftbuf) {

	int i;

	float sum;

	//take bins into 10 log spaced bins (averaging power), take log of the power, calculate the slope of the least-squares line ((8) prob and stats, p280 , 2nd ed., Schaum's)
	float average[10];

	int j, firstindex, secondindex;

	float avav=0.0;

	for (i=0; i<10; ++i) {

		sum=0.0;

		firstindex=stbins[i];
		secondindex=stbins[i+1];

		for (j=firstindex; j<secondindex; ++j) {
			sum += fftbuf[j];
		}

		average[i]= log10(sum/(secondindex-firstindex)+0.001);
		avav +=average[i];
	}

	avav /=10;

	float topsum=0.0, bottomsum=0.0;
	float tmp;

	for (i=0; i<10; ++i) {

		tmp=(average[i]-avav);

		topsum += tmp*((i+1)-5.5);
		bottomsum += tmp*tmp;

	}

	float st;

	if (bottomsum>0.001)
		st= topsum/bottomsum;
	else
		st=(-1000.0);

	//
//	if(st<0.0) st= -(log10(1-st));
//	else st= log10(1+st);
//
//	//clamp
//	if(st<-2) st=-2;
//	if (st>2) st=2;
//
//	st= (st+2)*0.25;
//

	st= atan(st); //now between -pi/2 and pi/2

	st= (st+pi2)/pi;

	//printf("c1 %f avav %f topsum %f bottomsum %f st %f test %f test2 %f \n", average[0], avav, topsum, bottomsum, st, topsum/bottomsum, atan(topsum/bottomsum));

	return st;

}


float calcsc(float * fftbuf, int nover2) {

	int i;
	float sum=1.0f, val;
	float centroid=0.0f;

	for (i=1; i<nover2; ++i) {

		val= fftbuf[i];

		centroid+= val*i;
		sum+= val;
	}

	//printf("sum %f\n", sum);
	//centroid=centroid/sum;

	//avoid division by zero threat
	if(sum>0.01f)
		centroid=centroid/sum;
	else
		centroid=centroid;

	centroid=log2((centroid/(nover2))+1.0f);

	return centroid; //normalised bin location
}



float calcsc2(float * fftbuf, int nover2) {

	int i;
	float sum=1.0f, val;
	float centroid=0.0f;

	for (i=1; i<nover2; ++i) {

		val= log(fftbuf[i]+1); //no log before!

		centroid+= val*i;
		sum+= val;
	}

	//causes divide by zero
	//centroid=centroid/sum;

	if(sum>0.01f)
		centroid=centroid/sum;
	else
		centroid=centroid;

	centroid=log2((centroid/(nover2))+1);

	return centroid; //normalised bin location
}



void sourcefeatures(Concat *unit, float * fftbuf) {
	int i, pos;

	float * store=unit->m_sourcestore;

	int sourcecounter= unit->m_sourcecounter;
	int sourcesize=unit->m_sourcesize;

	int featurecounter= unit->m_featurecounter;

	////////ZCR feature (counts - to + only)

	int zcrsize= unit->m_samplesforzcr;

	int zcrstart= (sourcecounter + sourcesize- zcrsize)%sourcesize;

	int zcrcount=0;

	float prevval=0.0, val;

	for (i=0; i<zcrsize; ++i) {

		pos= (zcrstart+i)%sourcesize;

		val= store[pos];

		if ((val>=(-0.00000001)) && (prevval<0.00000001))
			++zcrcount;

		prevval=val;
	}

	float zcrfeature= log10(zcrcount/(0.5*zcrsize*0.2)+1);

	if(zcrfeature>2) zcrfeature=2;

	unit->m_zcr[featurecounter]= zcrfeature*0.5; //normalise how? divide by zcrsize/2 or more and clamp to 1? Could correct with weighting

	////RMS
	int framesize=unit->m_fftsize;
	int framestart= (sourcecounter + sourcesize- framesize)%sourcesize;

	//float sum=0.0;
	float maxrms=0.0;

	for (i=0; i<framesize; ++i) {

		pos= (framestart+i)%sourcesize;

		val= store[pos];

		val=val*val;

		if(val>maxrms) {
		maxrms=val;
		}

		//sum+= val*val;
	}

	//sum=sum/framesize;

	//take into pseudo-decibels to even out volume differences on a more psychoacoustic scale
	unit->m_rms[featurecounter]= log10(1+(maxrms*9)); //sqrt(sum/framesize); //root mean square from 0.0 to 1.0

	//printf("SOURCE rms %f counter %d\n",unit->m_rms[featurecounter], featurecounter);


	unit->m_speccentroid[featurecounter]=calcsc(fftbuf, unit->m_nover2);

	//spectral tilt
	unit->m_spectilt[featurecounter]=calcst(fftbuf);

	//update
	//printf("zcr %f rms %f sc %f st %f counter %d\n",unit->m_zcr[featurecounter],unit->m_rms[featurecounter],unit->m_speccentroid[featurecounter],unit->m_spectilt[featurecounter], featurecounter);

}






//calculate features for current control input then find a match in the source
void matchfeatures(Concat *unit, float * fftbuf) {
	int i, pos;

	float * store=unit->m_controlstore;

	int controlcounter= unit->m_controlcounter;
	int controlsize=unit->m_controlsize;

	////////ZCR feature (counts - to + only)
	int zcrsize= unit->m_samplesforzcr;

	int zcrcount=0;

	float prevval=0.0, val;

	for (i=0; i<zcrsize; ++i) {

		val= store[i];

		if ((val>=(-0.00000001)) && (prevval<0.00000001))
			++zcrcount;

		prevval=val;
	}

	float zcrfeature= log10(zcrcount/(0.5*zcrsize*0.2)+1);

	if(zcrfeature>2) zcrfeature=2;

	zcrfeature= zcrfeature*0.5;

	//float zcrfeature= zcrcount/(0.5*zcrsize); //normalise how? divide by zcrsize/2 or more and clamp to 1? Could correct with weighting

	////RMS
	int framesize=unit->m_fftsize;
	int framestart= (controlcounter + controlsize- framesize)%controlsize;

	//float sum=0.0;
	float maxrms=0.0;

	for (i=0; i<framesize; ++i) {

		pos= (framestart+i)%controlsize;

		val= store[pos];

			val=val*val;

		if(val>maxrms) {
		maxrms=val;
		}

		//sum+= val*val;
	}

	//sum/framesize
	float rmsfeature= log10(1+((maxrms)*9)); //sqrt(sum/framesize); //root mean square from 0.0 to 1.0

	//printf("TARGET rms %f\n",rmsfeature);

	float scfeature=calcsc(fftbuf, unit->m_nover2);

	float stfeature=calcst(fftbuf);

	//find locations to search
	float seekstart= ZIN0(3); //in seconds
	float seekdur= ZIN0(4);	  //in seconds

	int featurecounter= unit->m_featurecounter;


	int sourceframes= unit->m_sourceframes;

	int beginsearch= (featurecounter + sourceframes - ((int)((seekstart*unit->m_sr)/(unit->m_fftsize))))%(sourceframes);
	int searchlength= (int)((seekdur*unit->m_sr)/(unit->m_fftsize));

	searchlength= sc_max(searchlength,1);

	//find best match

	float * zcr= unit->m_zcr;
	float * rms= unit->m_rms;
	float * sc= unit->m_speccentroid;
	float * st= unit->m_spectilt;

	float zcrweight= ZIN0(7);
	float rmsweight= ZIN0(8);
	float scweight=	 ZIN0(9);
	float stweight=	 ZIN0(10);

	int best=0;
	float bestscore= 1000000000.0;

	float zcrdiff, rmsdiff, scdiff, stdiff, score;

	//not sure if I like this or not!
	float randscore= ZIN0(11);

	RGen& rgen = *unit->mParent->mRGen;

	for (i=0; i<searchlength; ++i) {

		pos= (beginsearch+i)%sourceframes;

		zcrdiff= zcrfeature- zcr[pos];
		rmsdiff= rmsfeature- rms[pos];
		scdiff= scfeature- sc[pos];
		stdiff= stfeature- st[pos];

		score= zcrweight*(zcrdiff*zcrdiff) + rmsweight*(rmsdiff*rmsdiff) + scweight*(scdiff*scdiff) + stweight*(stdiff*stdiff)+(rgen.frand()*randscore);

		//could add match randomisation factor here score=score+ZIN0()

		if (score< bestscore) {
			bestscore= score;
			best=i;
		}
	}

	int answer= (beginsearch+best)%sourceframes;

	//printf("zcr %f rms %f sc %f\n",zcrfeature,rmsfeature,scfeature);

	zcrdiff= zcrfeature- zcr[answer];
	rmsdiff= rmsfeature- rms[answer];
	scdiff= scfeature- sc[answer];

	score= zcrweight*(zcrdiff*zcrdiff) + rmsweight*(rmsdiff*rmsdiff) + scweight*(scdiff*scdiff);

	//printf("zcrdiff %f rmsdiff %f scdiff %f score %f answer %d\n",zcrdiff,rmsdiff,scdiff,score, answer);

	//store best match sample and reset read pointer and fft frame counter
	//setting read out on current sample read

	unit->m_fadeoutlocation= unit->m_matchlocation; //next sample to be read now faded
	unit->m_matchlocation=answer*(unit->m_fftsize);
	unit->m_matchcounter=0;

	float matchlength=  ZIN0(5);

	int matchframes= (int)((matchlength*unit->m_sr)/(unit->m_fftsize));

	unit->m_matchframes= sc_max(matchframes,1);

	//printf("begin %d length %d answer %d\n",beginsearch, searchlength, answer);

}






void sourcefeatures2(Concat2 *unit, float * fftbuf) {
	int i, pos;

	float * store=unit->m_sourcestore;

	int sourcecounter= unit->m_sourcecounter;
	int sourcesize=unit->m_sourcesize;

	int featurecounter= unit->m_featurecounter;

	////////ZCR feature (counts - to + only)

	int zcrsize= unit->m_samplesforzcr;

	int zcrstart= (sourcecounter + sourcesize- zcrsize)%sourcesize;

	int zcrcount=0;

	float prevval=0.0, val;

	for (i=0; i<zcrsize; ++i) {

		pos= (zcrstart+i)%sourcesize;

		val= store[pos];

		if ((val>=(-0.00000001)) && (prevval<0.00000001))
			++zcrcount;

		prevval=val;
	}

	float zcrfeature= log10(zcrcount/(0.5*zcrsize*0.2)+1);

	if(zcrfeature>2) zcrfeature=2;

	unit->m_zcr[featurecounter]= zcrfeature*0.5; //normalise how? divide by zcrsize/2 or more and clamp to 1? Could correct with weighting

	////RMS
	int framesize=unit->m_fftsize;
	int framestart= (sourcecounter + sourcesize- framesize)%sourcesize;

	float maxrms=0.0; //sum=0.0,

	for (i=0; i<framesize; ++i) {

		pos= (framestart+i)%sourcesize;

		val= store[pos];

		val=val*val;

		if(val>maxrms) {
			maxrms=val;
		}

		//sum+= val*val;
	}

	//sum=sum/framesize;

	//rmsfeature= sc_min(rmsfeature,1.0); //if want clamped to 1

	//take into pseudo-decibels to even out volume differences on a more psychoacoustic scale
	unit->m_rms[featurecounter]= log10(1+(maxrms*9)); //sqrt(sum/framesize); //root mean square from 0.0 to 1.0

	//printf("SOURCE rms %f counter %d\n",unit->m_rms[featurecounter], featurecounter);


	unit->m_speccentroid[featurecounter]=sc_min(2*calcsc2(fftbuf, unit->m_nover4),1.0); //was unit->m_nover2 and no clamp

	//spectral tilt
	unit->m_spectilt[featurecounter]=calcst(fftbuf);

	//update
	//printf("zcr %f rms %f sc %f st %f counter %d\n",unit->m_zcr[featurecounter],unit->m_rms[featurecounter],unit->m_speccentroid[featurecounter],unit->m_spectilt[featurecounter], featurecounter);

}






//calculate features for current control input then find a match in the source
void matchfeatures2(Concat2 *unit, float * fftbuf) {
	int i, pos;
	float val;
	int matchfailure;

	float threshold= ZIN0(12);

	matchfailure= 0;

	float * store=unit->m_controlstore;

	int controlcounter= unit->m_controlcounter;
	int controlsize=unit->m_controlsize;

	////RMS
	int framesize=unit->m_fftsize;
	int framestart= (controlcounter + controlsize- framesize)%controlsize;

	float maxrms=0.0; //sum=0.0,

	for (i=0; i<framesize; ++i) {

		pos= (framestart+i)%controlsize;

		val= store[pos];

		val=val*val;

		if(val>maxrms) {
			maxrms=val;
		}

		//sum+= val*val;
	}

	//sum/framesize

	//log of sum?

	float rmsfeature= log10(1+((maxrms)*9)); //sqrt(sum/framesize); //root mean square from 0.0 to 1.0

	//could sc_min(rmsfeature,1.0) if want clamped to 0.0 to 1

	//rmsfeature>0.01
	//printf("TARGET rms %f maxrms %f \n",rmsfeature, maxrms);


	//may have as param
	if(rmsfeature>threshold) {


		////////ZCR feature (counts - to + only)
		int zcrsize= unit->m_samplesforzcr;

		int zcrcount=0;

		float prevval=0.0;

		for (i=0; i<zcrsize; ++i) {

			val= store[i];

			if ((val>=(-0.00000001)) && (prevval<0.00000001))
				++zcrcount;

			prevval=val;
		}

		float zcrfeature= log10(zcrcount/(0.5*zcrsize*0.2)+1);

		if(zcrfeature>2) zcrfeature=2;

		zcrfeature= zcrfeature*0.5;

		//float zcrfeature= zcrcount/(0.5*zcrsize); //normalise how? divide by zcrsize/2 or more and clamp to 1? Could correct with weighting


		float scfeature=calcsc2(fftbuf, unit->m_nover4); //was m_nover2

		scfeature= sc_min(2*scfeature,1.0);

		float stfeature=calcst(fftbuf);

		//find locations to search
		float seekstart= ZIN0(3); //in seconds
		float seekdur= ZIN0(4);	  //in seconds

		int featurecounter= unit->m_featurecounter;


		int sourceframes= unit->m_sourceframes;

		int beginsearch= (featurecounter + sourceframes - ((int)((seekstart*unit->m_sr)/(unit->m_fftsize))))%(sourceframes);
		int searchlength= (int)((seekdur*unit->m_sr)/(unit->m_fftsize));

		searchlength= sc_max(searchlength,1);

		//find best match

		float * zcr= unit->m_zcr;
		float * rms= unit->m_rms;
		float * sc= unit->m_speccentroid;
		float * st= unit->m_spectilt;

		float zcrweight= ZIN0(7);
		float rmsweight= ZIN0(8);
		float scweight=	 ZIN0(9);
		float stweight=	 ZIN0(10);

		int best=(-1);
		float bestscore= 1000000000.0;

		float zcrdiff, rmsdiff, scdiff, stdiff, score;

		//not sure if I like this or not!
		float randscore= ZIN0(11);

		RGen& rgen = *unit->mParent->mRGen;

		for (i=0; i<searchlength; ++i) {

			pos= (beginsearch+i)%sourceframes;

			zcrdiff= zcrfeature- zcr[pos];

			float rmstest= rms[pos];

			if(rmstest>threshold) {

				rmsdiff= rmsfeature- rmstest;
				scdiff= scfeature- sc[pos];
				stdiff= stfeature- st[pos];

				score= zcrweight*(zcrdiff*zcrdiff) + rmsweight*(rmsdiff*rmsdiff) + scweight*(scdiff*scdiff) + stweight*(stdiff*stdiff)+(rgen.frand()*randscore);

				//could add match randomisation factor here score=score+ZIN0()

				if (score< bestscore) {
					bestscore= score;
					best=i;
				}

			}
		}

		if(best>=0) {

			int answer= (beginsearch+best)%sourceframes;

			//printf("zcr %f rms %f sc %f\n",zcrfeature,rmsfeature,scfeature);

			zcrdiff= zcrfeature- zcr[answer];
			rmsdiff= rmsfeature- rms[answer];
			scdiff= scfeature- sc[answer];

			score= zcrweight*(zcrdiff*zcrdiff) + rmsweight*(rmsdiff*rmsdiff) + scweight*(scdiff*scdiff);

			//printf("zcrdiff %f rmsdiff %f scdiff %f score %f answer %d\n",zcrdiff,rmsdiff,scdiff,score, answer);

			//store best match sample and reset read pointer and fft frame counter
			//setting read out on current sample read

			unit->m_fadeoutlocation= unit->m_matchlocation; //next sample to be read now faded

			unit->m_fadeoutamp= unit->m_matchamp;
			unit->m_matchlocation=answer*(unit->m_fftsize);
			unit->m_matchcounter=0;

			unit->m_matchamp=1.0;

			float matchlength=  ZIN0(5);

			int matchframes= (int)((matchlength*unit->m_sr)/(unit->m_fftsize));

			unit->m_matchframes= sc_max(matchframes,1);

		} else {
			matchfailure=1;

		}


		//printf("begin %d length %d answer %d\n",beginsearch, searchlength, answer);
	} else {


		matchfailure=1;

	}


	//cope with match failure- so output zeroes, must finish fade of any current material
	if(matchfailure==1) {

		//always fade out old at this point, will be silent
		unit->m_fadeoutlocation= unit->m_matchlocation; //next sample to be read now faded
		unit->m_fadeoutamp= unit->m_matchamp;

		//just read something random but at zero amp
		unit->m_matchamp=0.0;
		unit->m_matchlocation=0;
		unit->m_matchcounter=0;
		unit->m_matchframes= 1;

	}

}







//calculation function once FFT data ready, in place on fftbuf passed in
void Concat_dofft(Concat *unit,scfft * scf, float * fftbuf) {

	int i;

	scfft_dofft(scf);

	int n= unit->m_fftsize;

	//format is dc, nyquist, bin[1] ,real, bin[1].imag, etc

	//fftbuf[0] already bin 0
	fftbuf[0]= fftbuf[0]* fftbuf[0]; //get power

	float val1, val2;
	// Squared Absolute so get power
	for (i=2; i<n; i+=2) {
		val1 = fftbuf[i];
		val2 = fftbuf[i+1];
		//i>>1 is i/2
		fftbuf[i>>1] = (val1*val1)+(val2*val2);
	}

}



PluginLoad(Concat) {

	ft = inTable;

	DefineDtorUnit(Concat);
	DefineDtorUnit(Concat2);
}