maxi_emscr.cpp 28.7 KB
Newer Older
Dr-Dan's avatar
Dr-Dan committed
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

/*
 *  maximilian.cpp
 *  platform independent synthesis library using portaudio or rtaudio
 *
 *  Created by Mick Grierson on 29/12/2009.
 *  Copyright 2009 Mick Grierson & Strangeloop Limited. All rights reserved.
 *	Thanks to the Goldsmiths Creative Computing Team.
 *	Special thanks to Arturo Castro for the PortAudio implementation.
 *
 *	Permission is hereby granted, free of charge, to any person
 *	obtaining a copy of this software and associated documentation
 *	files (the "Software"), to deal in the Software without
 *	restriction, including without limitation the rights to use,
 *	copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the
 *	Software is furnished to do so, subject to the following
 *	conditions:
 *	
 *	The above copyright notice and this permission notice shall be
 *	included in all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,	
 *	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 *	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 *	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 *	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *	OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include "maxi_emscr.h"
#include "maxi_embind.h"
#include "big_arrays.h"

//#include "math.h"

/*  Maximilian can be configured to load ogg vorbis format files using the 
*   loadOgg() method.
*   Uncomment the following to include Sean Barrett's Ogg Vorbis decoder.
*   If you're on windows, make sure to add the files std_vorbis.c and std_vorbis.h to your project*/

//#define VORBIS

//#ifdef VORBIS
//extern "C" {
//    #include "stb_vorbis.h"
//}
//#endif

//This used to be important for dealing with multichannel playback
float chandiv= 1;

int maxiSettings::sampleRate = 44100;
int maxiSettings::channels = 2;
int maxiSettings::bufferSize = 1024;



//void setup();//use this to do any initialisation if you want.

//void play(double *channels);//run dac! 

// --------------------------------------------------------------------------------
// MAXI OSC

maxiOsc::maxiOsc(){
    //When you create an oscillator, the constructor sets the phase of the oscillator to 0.
	phase = 0.0;
}

double maxiOsc::noise() {
    //White Noise
	//always the same unless you seed it.
	float r = rand()/(float)RAND_MAX;
	output=r*2-1;
	return(output);
}

void maxiOsc::phaseReset(double phaseIn) {
    //This allows you to set the phase of the oscillator to anything you like.
	phase=phaseIn;
}

double maxiOsc::sinewave(double frequency) {
    //This is a sinewave oscillator
	output=sin (phase*(TWOPI));
	if ( phase >= 1.0 ) phase -= 1.0;
	phase += (1./(maxiSettings::sampleRate/(frequency)));
	return(output);
}

double maxiOsc::sinebuf4(double frequency) {
    //This is a sinewave oscillator that uses 4 point interpolation on a 514 point buffer
	double remainder;
	double a,b,c,d,a1,a2,a3;
	phase += 512./(maxiSettings::sampleRate/(frequency));
	if ( phase >= 511 ) phase -=512;
	remainder = phase - floor(phase);
	
	if (phase==0) {
		a=sineBuffer[(long) 512];
		b=sineBuffer[(long) phase];
		c=sineBuffer[(long) phase+1];
		d=sineBuffer[(long) phase+2];
		
	} else {
		a=sineBuffer[(long) phase-1];
		b=sineBuffer[(long) phase];
		c=sineBuffer[(long) phase+1];
		d=sineBuffer[(long) phase+2];
		
	}
	
	a1 = 0.5f * (c - a);
	a2 = a - 2.5 * b + 2.f * c - 0.5f * d;
	a3 = 0.5f * (d - a) + 1.5f * (b - c);
	output = double (((a3 * remainder + a2) * remainder + a1) * remainder + b);
	return(output);
}

double maxiOsc::sinebuf(double frequency) { //specify the frequency of the oscillator in Hz / cps etc.
    //This is a sinewave oscillator that uses linear interpolation on a 514 point buffer
	double remainder;
 	phase += 512./(maxiSettings::sampleRate/(frequency*chandiv));
	if ( phase >= 511 ) phase -=512;
	remainder = phase - floor(phase);
	output = (double) ((1-remainder) * sineBuffer[1+ (long) phase] + remainder * sineBuffer[2+(long) phase]);
	return(output);
}

double maxiOsc::coswave(double frequency) {
    //This is a cosine oscillator
	output=cos (phase*(TWOPI));
	if ( phase >= 1.0 ) phase -= 1.0;
	phase += (1./(maxiSettings::sampleRate/(frequency)));
	return(output);
	
}

double maxiOsc::phasor(double frequency) {
    //This produces a floating point linear ramp between 0 and 1 at the desired frequency 
	output=phase;
	if ( phase >= 1.0 ) phase -= 1.0;
	phase += (1./(maxiSettings::sampleRate/(frequency)));
	return(output);
} 

double maxiOsc::square(double frequency) {
    //This is a square wave
	if (phase<0.5) output=-1;
	if (phase>0.5) output=1;
	if ( phase >= 1.0 ) phase -= 1.0;
	phase += (1./(maxiSettings::sampleRate/(frequency)));
	return(output);
}

double maxiOsc::pulse(double frequency, double duty) {
    //This is a pulse generator that creates a signal between -1 and 1.
	if (duty<0.) duty=0;
	if (duty>1.) duty=1;
	if ( phase >= 1.0 ) phase -= 1.0;
	phase += (1./(maxiSettings::sampleRate/(frequency)));
	if (phase<duty) output=-1.;
	if (phase>duty) output=1.;
	return(output);
}

double maxiOsc::phasor(double frequency, double startphase, double endphase) {
    //This is a phasor that takes a value for the start and end of the ramp. 
	output=phase;
	if (phase<startphase) {
		phase=startphase;
	}
	if ( phase >= endphase ) phase = startphase;
	phase += ((endphase-startphase)/(maxiSettings::sampleRate/(frequency)));
	return(output);
}


double maxiOsc::saw(double frequency) {
	//Sawtooth generator. This is like a phasor but goes between -1 and 1
	output=phase;
	if ( phase >= 1.0 ) phase -= 2.0;
	phase += (1./(maxiSettings::sampleRate/(frequency)));
	return(output);
	
}

double maxiOsc::sawn(double frequency) {
	//Bandlimited sawtooth generator. Woohoo.
    if ( phase >= 0.5 ) phase -= 1.0;
    phase += (1./(maxiSettings::sampleRate/(frequency)));
	double temp=(8820.22/frequency)*phase;
    if (temp<-0.5) {
        temp=-0.5;
    }
    if (temp>0.5) {
        temp=0.5;
    }
    temp*=1000.0f;
    temp+=500.0f;
    double remainder = temp - floor(temp);
    output = (double) ((1.0f-remainder) * transition[(long)temp] + remainder * transition[1+(long)temp]) - phase;
	return(output);
	
}

double maxiOsc::rect(double frequency, double duty) {

    return (output);
}

double maxiOsc::triangle(double frequency) {
    //This is a triangle wave.
	if ( phase >= 1.0 ) phase -= 1.0;
	phase += (1./(maxiSettings::sampleRate/(frequency)));
	if (phase <= 0.5 ) {
		output =(phase - 0.25) * 4;
	} else {
		output =((1.0-phase) - 0.25) * 4;
	}
	return(output);
	
} 

// --------------------------------------------------------------------------------
// MAXI ENVELOPE

double maxiEnvelope::line(int numberofsegments,  std::vector<double>& segments) {
	//This is a basic multi-segment ramp generator that you can use for more or less anything.
    //However, it's not that intuitive.
    if (isPlaying==1) {//only make a sound once you've been triggered

	period=2./(segments[valindex+1]*0.004);
	nextval=segments[valindex+2];
	currentval=segments[valindex];
		
	if (currentval-amplitude > 0.0000001 && valindex < numberofsegments) {
		amplitude += ((currentval-startval)/(maxiSettings::sampleRate/period));
	} else if (currentval-amplitude < -0.0000001 && valindex < numberofsegments) {
		amplitude -= (((currentval-startval)*(-1))/(maxiSettings::sampleRate/period));
	} else if (valindex >numberofsegments-1) {
		valindex=numberofsegments-2;
	} else {
		valindex=valindex+2;
		startval=currentval;
	}
	output=amplitude;
		
	}
	else {
		output=0;
	}
	
	return(output);
}

//and this
void maxiEnvelope::trigger(int index, double amp) {
	isPlaying=1;//ok the envelope is being used now.
	valindex=index;
	SetAmplitude(amp);
//	amplitude=amp;
	
}
/*

// --------------------------------------------------------------------------------
// MAXI DELAY LINE

//Delay with feedback
maxiDelayline::maxiDelayline() {
	memset( memory, 0, 88200*sizeof (double) );	
}


double maxiDelayline::dl(double input, int size, double feedback)  {
	if ( phase >=size ) {
		phase = 0;
	}
	output=memory[phase];
	memory[phase]=(memory[phase]*feedback)+(input*feedback)*0.5;
	phase+=1;
	return(output);
	
}

double maxiDelayline::dl(double input, int size, double feedback, int position)  {
	if ( phase >=size ) phase = 0;
	if ( position >=size ) position = 0;
	output=memory[position];
	memory[phase]=(memory[phase]*feedback)+(input*feedback)*chandiv;
	phase+=1;
	return(output);
	
}
*/

// --------------------------------------------------------------------------------
// MAXI FILTER

//I particularly like these. cutoff between 0 and 1
double maxiFilter::lopass(double input, double cutoff) {
	output=outputs[0] + cutoff*(input-outputs[0]);
	outputs[0]=output;
	return(output);
}

//as above
double maxiFilter::hipass(double input, double cutoff) {
	output=input-(outputs[0] + cutoff*(input-outputs[0]));
	outputs[0]=output;
	return(output);
}
//awesome. cuttof is freq in hz. res is between 1 and whatever. Watch out!
double maxiFilter::lores(double input,double cutoff1, double resonance) {
	cutoff=cutoff1*0.5;
	if (cutoff<10) cutoff=10;
	if (cutoff>(maxiSettings::sampleRate*0.5)) cutoff=(maxiSettings::sampleRate*0.5);
	if (resonance<1.) resonance = 1.;
	z=cos(TWOPI*cutoff/maxiSettings::sampleRate);
	c=2-2*z;
	double r=(sqrt(2.0)*sqrt(-pow((z-1.0),3.0))+resonance*(z-1))/(resonance*(z-1));
	x=x+(input-y)*c;
	y=y+x;
	x=x*r;
	output=y;
	return(output);
}

//working hires filter
double maxiFilter::hires(double input,double cutoff1, double resonance) {
	cutoff=cutoff1*0.5;
	if (cutoff<10) cutoff=10;
	if (cutoff>(maxiSettings::sampleRate*0.5)) cutoff=(maxiSettings::sampleRate*0.5);
	if (resonance<1.) resonance = 1.;
	z=cos(TWOPI*cutoff/maxiSettings::sampleRate);
	c=2-2*z;
	double r=(sqrt(2.0)*sqrt(-pow((z-1.0),3.0))+resonance*(z-1))/(resonance*(z-1));
	x=x+(input-y)*c;
	y=y+x;
	x=x*r;
	output=input-y;
	return(output);
}

//This works a bit. Needs attention.
double maxiFilter::bandpass(double input,double cutoff1, double resonance) {
	cutoff=cutoff1;
	if (cutoff>(maxiSettings::sampleRate*0.5)) cutoff=(maxiSettings::sampleRate*0.5);
	if (resonance>=1.) resonance=0.999999;
	z=cos(TWOPI*cutoff/maxiSettings::sampleRate);
	inputs[0] = (1-resonance)*(sqrt(resonance*(resonance-4.0*pow(z,2.0)+2.0)+1));
	inputs[1] = 2*z*resonance;
	inputs[2] = pow((resonance*-1),2);
	
	output=inputs[0]*input+inputs[1]*outputs[1]+inputs[2]*outputs[2];
	outputs[2]=outputs[1];
	outputs[1]=output;
	return(output);
}



/*
 
 // --------------------------------------------------------------------------------
 // MAXI MIX

//stereo bus
double *maxiMix::stereo(double input,double two[2],double x) {
	if (x>1) x=1;
	if (x<0) x=0;
	two[0]=input*sqrt(1.0-x);
	two[1]=input*sqrt(x);
	return(two);
} 

//quad bus
double *maxiMix::quad(double input,double four[4],double x,double y) {
	if (x>1) x=1;
	if (x<0) x=0;
	if (y>1) y=1;
	if (y<0) y=0;
	four[0]=input*sqrt((1.0-x)*y);
	four[1]=input*sqrt((1.0-x)*(1.0-y));
	four[2]=input*sqrt(x*y);
	four[3]=input*sqrt(x*(1.0-y));
	return(four);
}

//ambisonic bus
double *maxiMix::ambisonic(double input,double eight[8],double x,double y,double z) {
	if (x>1) x=1;
	if (x<0) x=0;
	if (y>1) y=1;
	if (y<0) y=0;
	if (z>1) y=1;
	if (z<0) y=0;
	eight[0]=input*(sqrt((1.0-x)*y)*1.0-z);
	eight[1]=input*(sqrt((1.0-x)*(1.0-y))*1.0-z);
	eight[2]=input*(sqrt(x*y)*1.0-z);
	eight[3]=input*(sqrt(x*(1.0-y))*1.0-z);
	eight[4]=input*(sqrt((1.0-x)*y)*z);
	eight[5]=input*(sqrt((1.0-x)*(1.0-y))*z);
	eight[6]=input*sqrt((x*y)*z);
	eight[7]=input*sqrt((x*(1.0-y))*z);
	return(eight);
}
 */
 // --------------------------------------------------------------------------------
 // MAXI SAMPLE

//This is the maxiSample load function. It just calls read.
bool maxiSample::load(string fileName, int channel) {
	myPath = fileName;

	readChannel=channel;
	return read();
}

/*
// This is for OGG loading
bool maxiSample::loadOgg(string fileName, int channel) {
#ifdef VORBIS
    bool result;
	readChannel=channel;
    int channelx;
//    cout << fileName << endl;
    myDataSize = stb_vorbis_decode_filename(const_cast<char*>(fileName.c_str()), &channelx, &temp);
    result = myDataSize > 0;
    printf("\nchannels = %d\nlength = %d",channelx,myDataSize);
    printf("\n");
    myChannels=(short)channelx;
    length=myDataSize;
    mySampleRate=44100;
    
    if (myChannels>1) {
        int position=0;
        int channel=readChannel;
        for (int i=channel;i<myDataSize*2;i+=myChannels) {
            temp[position]=temp[i];
            position++;
        }
    }
	return result; // this should probably be something more descriptive
#endif
    return 0;
}
*/
//This sets the playback position to the start of a sample
void maxiSample::trigger() {
	position = 0;
}

/*
//This is the main read function.
bool maxiSample::read()
{
	bool result;
	ifstream inFile( myPath.c_str(), ios::in | ios::binary);
	result = (bool)inFile;
	
	if (inFile) {
		bool datafound = false;
		inFile.seekg(4, ios::beg);
		inFile.read( (char*) &myChunkSize, 4 ); // read the ChunkSize
		
		inFile.seekg(16, ios::beg);
		inFile.read( (char*) &mySubChunk1Size, 4 ); // read the SubChunk1Size
		
		//inFile.seekg(20, ios::beg);
		inFile.read( (char*) &myFormat, sizeof(short) ); // read the file format.  This should be 1 for PCM
		
		//inFile.seekg(22, ios::beg);
		inFile.read( (char*) &myChannels, sizeof(short) ); // read the # of channels (1 or 2)
		
		//inFile.seekg(24, ios::beg);
		inFile.read( (char*) &mySampleRate, sizeof(int) ); // read the samplerate
		
		//inFile.seekg(28, ios::beg);
		inFile.read( (char*) &myByteRate, sizeof(int) ); // read the byterate
		
		//inFile.seekg(32, ios::beg);
		inFile.read( (char*) &myBlockAlign, sizeof(short) ); // read the blockalign
		
		//inFile.seekg(34, ios::beg);
		inFile.read( (char*) &myBitsPerSample, sizeof(short) ); // read the bitspersample
		
		//ignore any extra chunks
		char chunkID[5]="";
		chunkID[4] = 0;
		int filePos = 36;
		while(!datafound && !inFile.eof()) {
			inFile.seekg(filePos, ios::beg);
			inFile.read((char*) &chunkID, sizeof(char) * 4);
			inFile.seekg(filePos + 4, ios::beg);
			inFile.read( (char*) &myDataSize, sizeof(int) ); // read the size of the data
			filePos += 8;
			if (strcmp(chunkID,"data") == 0) {
				datafound = true;
			}else{
				filePos += myDataSize;
			}
		}
		
		// read the data chunk
		myData = (char*) malloc(myDataSize * sizeof(char));
		inFile.seekg(filePos, ios::beg);
		inFile.read(myData, myDataSize);
		length=myDataSize*(0.5/myChannels);
		inFile.close(); // close the input file
		
        cout << "Ch: " << myChannels << ", len: " << length << endl;
		if (myChannels>1) {
			int position=0;
			int channel=readChannel*2;
			for (int i=channel;i<myDataSize+6;i+=(myChannels*2)) {
				myData[position]=myData[i];
				myData[position+1]=myData[i+1];
				position+=2;
			}
		}
        temp = (short*) malloc(myDataSize * sizeof(char));
        memcpy(temp, myData, myDataSize * sizeof(char));
        
        free(myData);
		
	}else {
//		cout << "ERROR: Could not load sample: " <<myPath << endl; //This line seems to be hated by windows 
        printf("ERROR: Could not load sample.");

	}
	
	
	return result; // this should probably be something more descriptive
}
*/


// my version for easier use with js
double maxiSample::play() {
	position++;
	if ((int) position == length) position=0;
548
	output = (double)(tempDC.at((int)position));
Dr-Dan's avatar
Dr-Dan committed
549
550
551
552
	return output;
}

void maxiSample::setSample(vector<double>& temp){
553
554
	tempDC = temp;
	length = tempDC.size();
Dr-Dan's avatar
Dr-Dan committed
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
}


//This plays back at the correct speed. Only plays once. To retrigger, you have to manually reset the position
//double maxiSample::playOnce() {
//	position++;
//	if ((long) position<length)
//        output = (double) temp[(long)position]/32767.0;
//    else {
//        output=0;
//    }
//	return output;
//
//}

//Same as above but takes a speed value specified as a ratio, with 1.0 as original speed
571
572
573
574
575
576
577
578
579
double maxiSample::playOnce(double speed) {
	position=position+((speed*chandiv)/(maxiSettings::sampleRate/mySampleRate));
	double remainder = position - (long) position;
	if ((long) position<length)
		output = (double) ((1-remainder) * tempDC.at(1+ (long) position) + remainder * tempDC.at(2+(long) position));//linear interpolation
	else 
		output=0;
	return(output);
}
Dr-Dan's avatar
Dr-Dan committed
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598

//As above but looping
double maxiSample::play(double speed) {
	double remainder;
	long a,b;
	position=position+((speed*chandiv)/(maxiSettings::sampleRate/mySampleRate));
	if (speed >=0) {
		
		if ((long) position>=length-1) position=1;
		remainder = position - floor(position);
		if (position+1<length) {
			a=position+1;
			
		}
		else {
			a=length-1;
		}
		if (position+2<length)
		{
599
			b=position+2;
Dr-Dan's avatar
Dr-Dan committed
600
601
		}
		else {
602
			b=length-1;
Dr-Dan's avatar
Dr-Dan committed
603
604
		}
		
605
606
		output = (double) ((1-remainder) * tempDC.at(a) + remainder * tempDC.at(b));//linear interpolation
	} else {
Dr-Dan's avatar
Dr-Dan committed
607
608
609
610
		if ((long) position<0) position=length;
		remainder = position - floor(position);
		if (position-1>=0) {
			a=position-1;
611
612
613
614
615
616
617
618
619
620
621
622
623
			
		}
		else {
			a=0;
		}
		if (position-2>=0) {
			b=position-2;
		}
		else {
			b=0;
		}
		output = (double) ((-1-remainder) * tempDC.at(a) + remainder * tempDC.at(b));//linear interpolation
	}
Dr-Dan's avatar
Dr-Dan committed
624
625
	return(output);
}
626
627


Dr-Dan's avatar
Dr-Dan committed
628
629
630
631
632
633
//placeholder
double maxiSample::play(double frequency, double start, double end) {
	return play(frequency, start, end, position);
}

//This allows you to say how often a second you want a specific chunk of audio to play
634
double maxiSample::play(double frequency, double start, double end, double& pos) {
Dr-Dan's avatar
Dr-Dan committed
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
	double remainder;
	if (end>=length) end=length-1;
	long a,b;

	if (frequency >0.) {
		if (pos<start) {
			pos=start;
		}
		
		if ( pos >= end ) pos = start;
		pos += ((end-start)/(maxiSettings::sampleRate/(frequency*chandiv)));
		remainder = pos - floor(pos);
		long posl = floor(pos);
		if (posl+1<length) {
			a=posl+1;
			
		}
		else {
			a=posl-1;
		}
		if (posl+2<length) {
			b=posl+2;
		}
		else {
			b=length-1;
		}

662
663
		output = (double) ((1-remainder) * tempDC.at(a) +
						   remainder * tempDC.at(b));//linear interpolation
Dr-Dan's avatar
Dr-Dan committed
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
	} else {
		frequency=frequency-(frequency+frequency);
		if ( pos <= start ) pos = end;
		pos -= ((end-start)/(maxiSettings::sampleRate/(frequency*chandiv)));
		remainder = pos - floor(pos);
		long posl = floor(pos);
		if (posl-1>=0) {
			a=posl-1;
		}
		else {
			a=0;
		}
		if (posl-2>=0) {
			b=posl-2;
		}
		else {
			b=0;
		}		
682
683
		output = (double) ((-1-remainder) * tempDC.at(a) +
						   remainder * tempDC.at(b));//linear interpolation
Dr-Dan's avatar
Dr-Dan committed
684
685
686
687
688
689
690
691
		
	}
	
	return(output);
}


//Same as above. better cubic inerpolation. Cobbled together from various (pd externals, yehar, other places).
692
// needs fixing for online version
Dr-Dan's avatar
Dr-Dan committed
693
694
695
double maxiSample::play4(double frequency, double start, double end) {
	double remainder;
	double a,b,c,d,a1,a2,a3;
696
697
	
	if (frequency > 0.) {
Dr-Dan's avatar
Dr-Dan committed
698
699
700
		if (position<start) {
			position=start;
		}
701
		
Dr-Dan's avatar
Dr-Dan committed
702
703
704
705
		if ( position >= end ) position = start;
		position += ((end-start)/(maxiSettings::sampleRate/(frequency*chandiv)));
		remainder = position - floor(position);
		if (position>0) {
706
			a=tempDC.at((long)(floor(position))-1);
Dr-Dan's avatar
Dr-Dan committed
707
708

		} else {
709
			a=tempDC.at(0);
Dr-Dan's avatar
Dr-Dan committed
710
711
712
			
		}
		
713
		b=tempDC.at((long) position);
Dr-Dan's avatar
Dr-Dan committed
714
		if (position<end-2) {
715
			c=tempDC.at((long) position+1);
Dr-Dan's avatar
Dr-Dan committed
716
717

		} else {
718
			c=tempDC.at(0);
Dr-Dan's avatar
Dr-Dan committed
719
720
721

		}
		if (position<end-3) {
722
			d=tempDC.at((long) position+2);
Dr-Dan's avatar
Dr-Dan committed
723
724

		} else {
725
			d=tempDC.at(0);
Dr-Dan's avatar
Dr-Dan committed
726
		}
727
		
Dr-Dan's avatar
Dr-Dan committed
728
729
730
		a1 = 0.5f * (c - a);
		a2 = a - 2.5 * b + 2.f * c - 0.5f * d;
		a3 = 0.5f * (d - a) + 1.5f * (b - c);
731
		output = (double) (((a3 * remainder + a2) * remainder + a1) * remainder + b);
Dr-Dan's avatar
Dr-Dan committed
732
733
734
735
736
737
738
		
	} else {
		frequency=frequency-(frequency+frequency);
		if ( position <= start ) position = end;
		position -= ((end-start)/(maxiSettings::sampleRate/(frequency*chandiv)));
		remainder = position - floor(position);
		if (position>start && position < end-1) {
739
			a=tempDC.at((long) position+1);
Dr-Dan's avatar
Dr-Dan committed
740
741
			
		} else {
742
			a=tempDC.at(0);
Dr-Dan's avatar
Dr-Dan committed
743
744
745
			
		}
		
746
		b=tempDC.at((long) position);
Dr-Dan's avatar
Dr-Dan committed
747
		if (position>start) {
748
			c=tempDC.at((long) position-1);
Dr-Dan's avatar
Dr-Dan committed
749
750
			
		} else {
751
			c=tempDC.at(0);
Dr-Dan's avatar
Dr-Dan committed
752
753
754
			
		}
		if (position>start+1) {
755
			d=tempDC.at((long) position-2);
Dr-Dan's avatar
Dr-Dan committed
756
757
			
		} else {
758
			d=tempDC.at(0);
Dr-Dan's avatar
Dr-Dan committed
759
760
761
762
		}
		a1 = 0.5f * (c - a);
		a2 = a - 2.5 * b + 2.f * c - 0.5f * d;
		a3 = 0.5f * (d - a) + 1.5f * (b - c);
763
		output = (double) (((a3 * remainder + a2) * -remainder + a1) * -remainder + b);
Dr-Dan's avatar
Dr-Dan committed
764
765
766
767
768
769
		
	}
	
	return(output);
}

770
/*
Dr-Dan's avatar
Dr-Dan committed
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
//You don't need to worry about this stuff.
double maxiSample::bufferPlay(unsigned char &bufferin,long length) {
	double remainder;
	short* buffer = (short *)&bufferin;
	position=(position+1);
	remainder = position - (long) position;
	if ((long) position>length) position=0;
	output = (double) ((1-remainder) * buffer[1+ (long) position] + remainder * buffer[2+(long) position])/32767;//linear interpolation
	return(output);
}

double maxiSample::bufferPlay(unsigned char &bufferin,double speed,long length) {
	double remainder;
	long a,b;
	short* buffer = (short *)&bufferin;
	position=position+((speed*chandiv)/(maxiSettings::sampleRate/mySampleRate));
	if (speed >=0) {
		
		if ((long) position>=length-1) position=1;
		remainder = position - floor(position);
		if (position+1<length) {
			a=position+1;
			
		}
		else {
			a=length-1;
		}
		if (position+2<length)
		{
			b=position+2;
		}
		else {
			b=length-1;
		}
		
		output = (double) ((1-remainder) * buffer[a] + remainder * buffer[b])/32767;//linear interpolation
	} else {
		if ((long) position<0) position=length;
		remainder = position - floor(position);
		if (position-1>=0) {
			a=position-1;
			
		}
		else {
			a=0;
		}
		if (position-2>=0) {
			b=position-2;
		}
		else {
			b=0;
		}
		output = (double) ((-1-remainder) * buffer[a] + remainder * buffer[b])/32767;//linear interpolation
	}	
	return(output);
}

double maxiSample::bufferPlay(unsigned char &bufferin,double frequency, double start, double end) {
	double remainder;
	length=end;
	long a,b;
	short* buffer = (short *)&bufferin;
	if (frequency >0.) {
		if (position<start) {
			position=start;
		}
		
		if ( position >= end ) position = start;
		position += ((end-start)/(maxiSettings::sampleRate/(frequency*chandiv)));
		remainder = position - floor(position);
		long pos = floor(position);
		if (pos+1<length) {
			a=pos+1;
			
		}
		else {
			a=pos-1;
		}
		if (pos+2<length) {
			b=pos+2;
		}
		else {
			b=length-1;
		}
		
		output = (double) ((1-remainder) * buffer[a] +
						   remainder * buffer[b])/32767;//linear interpolation
	} else {
		frequency=frequency-(frequency+frequency);
		if ( position <= start ) position = end;
		position -= ((end-start)/(maxiSettings::sampleRate/(frequency*chandiv)));
		remainder = position - floor(position);
		long pos = floor(position);
		if (pos-1>=0) {
			a=pos-1;
		}
		else {
			a=0;
		}
		if (pos-2>=0) {
			b=pos-2;
		}
		else {
			b=0;
		}		
		output = (double) ((-1-remainder) * buffer[a] +
						   remainder * buffer[b])/32767;//linear interpolation
		
	}
	
	return(output);
}

//better cubic inerpolation. Cobbled together from various (pd externals, yehar, other places).
double maxiSample::bufferPlay4(unsigned char &bufferin,double frequency, double start, double end) {
	double remainder;
	double a,b,c,d,a1,a2,a3;
	short* buffer = (short*)&bufferin;
	if (frequency >0.) {
		if (position<start) {
			position=start;
		}
		if ( position >= end ) position = start;
		position += ((end-start)/(maxiSettings::sampleRate/(frequency*chandiv)));
		remainder = position - floor(position);
		if (position>0) {
			a=buffer[(int)(floor(position))-1];
			
		} else {
			a=buffer[0];
			
		}
		
		b=buffer[(long) position];
		if (position<end-2) {
			c=buffer[(long) position+1];
			
		} else {
			c=buffer[0];
			
		}
		if (position<end-3) {
			d=buffer[(long) position+2];
			
		} else {
			d=buffer[0];
		}
		a1 = 0.5f * (c - a);
		a2 = a - 2.5 * b + 2.f * c - 0.5f * d;
		a3 = 0.5f * (d - a) + 1.5f * (b - c);
		output = (double) (((a3 * remainder + a2) * remainder + a1) * remainder + b) / 32767;
		
	} else {
		frequency=frequency-(frequency+frequency);
		if ( position <= start ) position = end;
		position -= ((end-start)/(maxiSettings::sampleRate/(frequency*chandiv)));
		remainder = position - floor(position);
		if (position>start && position < end-1) {
			a=buffer[(long) position+1];
			
		} else {
			a=buffer[0];
			
		}
		
		b=buffer[(long) position];
		if (position>start) {
			c=buffer[(long) position-1];
			
		} else {
			c=buffer[0];
			
		}
		if (position>start+1) {
			d=buffer[(long) position-2];
			
		} else {
			d=buffer[0];
		}
		a1 = 0.5f * (c - a);
		a2 = a - 2.5 * b + 2.f * c - 0.5f * d;
		a3 = 0.5f * (d - a) + 1.5f * (b - c);
		output = (double) (((a3 * remainder + a2) * -remainder + a1) * -remainder + b) / 32767;
		
	}
	
	return(output);
}


void maxiSample::getLength() {
	length=myDataSize*0.5;	
}

void maxiSample::setLength(unsigned long numSamples) {
    cout << "Length: " << numSamples << endl;
    short *newData = (short*) malloc(sizeof(short) * numSamples);
    if (NULL!=temp) {
        unsigned long copyLength = min((unsigned long)length, numSamples);
        memcpy(newData, temp, sizeof(short) * copyLength);
    }
    temp = newData;
    myDataSize = numSamples * 2;
    length=numSamples;
    position=0;
    recordPosition=0;
}

void maxiSample::clear() {
    memset(myData, 0, myDataSize);
}

void maxiSample::reset() {
    position=0;
}


*/


/* OK this compressor and gate are now ready to use. The envelopes, like all the envelopes in this recent update, use stupid algorithms for 
 incrementing - consequently a long attack is something like 0.0001 and a long release is like 0.9999.
 Annoyingly, a short attack is 0.1, and a short release is 0.99. I'll sort this out laters */

/*
double maxiDyn::gate(double input, double threshold, long holdtime, double attack, double release) {
	
	if (fabs(input)>threshold && attackphase!=1){ 
		holdcount=0;
		releasephase=0;
		attackphase=1;
		if(amplitude==0) amplitude=0.01;
	}
	
	if (attackphase==1 && amplitude<1) {
		amplitude*=(1+attack);
		output=input*amplitude;
	}
	
	if (amplitude>=1) {
		attackphase=0;
		holdphase=1;
	}
	
	if (holdcount<holdtime && holdphase==1) {
		output=input;
		holdcount++;
	}
	
	if (holdcount==holdtime) {
		holdphase=0;
		releasephase=1;
	}
	
	if (releasephase==1 && amplitude>0.) {
		output=input*(amplitude*=release);
		
	}
	
	return output;
}


double maxiDyn::compressor(double input, double ratio, double threshold, double attack, double release) {
	
	if (fabs(input)>threshold && attackphase!=1){ 
		holdcount=0;
		releasephase=0;
		attackphase=1;
		if(currentRatio==0) currentRatio=ratio;
	}
	
	if (attackphase==1 && currentRatio<ratio-1) {
		currentRatio*=(1+attack);
	}
	
	if (currentRatio>=ratio-1) {
		attackphase=0;
		releasephase=1;
	}
	
	if (releasephase==1 && currentRatio>0.) {
		currentRatio*=release;		
	}
	
	if (input>0.) {
		output = input/(1.+currentRatio);
	} else {
		output = input/(1.+currentRatio);
	}
	
	return output*(1+log(ratio));
}
*/

/* Lots of people struggle with the envelope generators so here's a new easy one.
 It takes mental numbers for attack and release tho. Basically, they're exponentials.
 I'll map them out later so that it's a bit more intuitive */

/*
double maxiEnv::ar(double input, double attack, double release, long holdtime, int trigger) {
	
	if (trigger==1 && attackphase!=1 && holdphase!=1){ 
		holdcount=0;
		releasephase=0;
		attackphase=1;
	}
	
	if (attackphase==1) {
		amplitude+=(1*attack);
		output=input*amplitude;
	}
	
	if (amplitude>=1) {
		amplitude=1;
		attackphase=0;
		holdphase=1;
	}
	
	if (holdcount<holdtime && holdphase==1) {
		output=input;
		holdcount++;
	}
	
	if (holdcount==holdtime && trigger==1) {
		output=input;
	}
	
	if (holdcount==holdtime && trigger!=1) {
		holdphase=0;
		releasephase=1;
	}
	
	if (releasephase==1 && amplitude>0.) {
		output=input*(amplitude*=release);
		
	}
	
	return output;
}

 // and here's a new adsr. It's not bad, very simple to use

double maxiEnv::adsr(double input, double attack, double decay, double sustain, double release, long holdtime, int trigger) {
	
	if (trigger==1 && attackphase!=1 && holdphase!=1 && decayphase!=1){ 
		holdcount=0;
		decayphase=0;
		sustainphase=0;
		releasephase=0;
		attackphase=1;
	}
	
	if (attackphase==1) {
		amplitude+=(1*attack);
		output=input*amplitude;
	}
	
	if (amplitude>=1) {
		amplitude=1;
		attackphase=0;
		decayphase=1;
	}
	
	if (decayphase==1) {
		output=input*(amplitude*=decay);	
		if (amplitude<=sustain) {
			decayphase=0;
			holdphase=1;
		}
	}
	
	if (holdcount<holdtime && holdphase==1) {
		output=input*amplitude;
		holdcount++;
	}
	
	if (holdcount==holdtime && trigger==1) {
		output=input*amplitude;
	}
	
	if (holdcount==holdtime && trigger!=1) {
		holdphase=0;
		releasephase=1;
	}
	
	if (releasephase==1 && amplitude>0.) {
		output=input*(amplitude*=release);
		
	}
	
	return output;
}

double convert::mtof(int midinote) {
	
	return mtofarray[midinote];
}


void maxiEnvelopeFollower::setAttack(double attackMS) {
    attack = pow( 0.01, 1.0 / ( attackMS * maxiSettings::sampleRate * 0.001 ) );
}

void maxiEnvelopeFollower::setRelease(double releaseMS) {
    release = pow( 0.01, 1.0 / ( releaseMS * maxiSettings::sampleRate * 0.001 ) );    
}
*/