MainComponent.cpp 18.6 KB
Newer Older
Michael Zbyszyński's avatar
Michael Zbyszyński 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
/*
  ==============================================================================

    This file was auto-generated!

  ==============================================================================
*/

#ifndef MAINCOMPONENT_H_INCLUDED
#define MAINCOMPONENT_H_INCLUDED

// It's important to call any headers that might
// include apple libs / headers before Juce's
// to prevent ambigious classes
#include "../../../../dependencies/Maximilian/maximilian.h"
#include "../../../../dependencies/RapidLib/src/regression.h"
#include <random>
#include <array>
#include "../JuceLibraryCode/JuceHeader.h"

class MainContentComponent;

//==============================================================================
class Oscilloscope : public Component,
                     private Timer
{
public:
	Oscilloscope(MainContentComponent* _p) : parent(_p),
		                                     writePosition(0),
	                                         bufferSize(16384),
	                                         paintSize(256)
	{
		startTimer(40);
	}

	void pushBuffer(const float* _sampleData, int _numSamples)
	{
		for (int i = 0; i < _numSamples; ++i)
		{
			size_t pos = ++writePosition % buffer.size();
			oldBuffer[pos] = buffer[pos];
			buffer[pos] = _sampleData[i];
		}
	}

	void paint(Graphics& _g) override
	{
		boundary = getLocalBounds();
		_g.fillAll(juce::Colour(0xff000000));
		Path path;
		path.startNewSubPath(0, .5 * boundary.getHeight());
		const float bufferYScale = .3f;
		int paintPos = 2;

		while (paintPos < buffer.size())
		{
			if (isZeroCrossing(paintPos))
			{
				break;
			}
			++paintPos;
		}

		const int posOffset = paintPos;
		while (paintPos < buffer.size())
		{
			float bufferPoint = buffer[paintPos];//0.5 * std::abs(buffer[paintPos] - oldBuffer[paintPos]);
			Point<float> point((paintPos - posOffset) * boundary.getWidth() / paintSize,
			                   0.5 * ((bufferYScale * bufferPoint) + 1) * boundary.getHeight());
			path.lineTo(point);
			++paintPos;
		}
		_g.setColour(juce::Colour(0xff00ff00));
		_g.strokePath(path, PathStrokeType(2.0f));
	}

	void mouseDrag(const MouseEvent& _event) override;

private:
	//==========================================================================
	void timerCallback() override
	{
		repaint();
	}

	bool isZeroCrossing(int i) const noexcept
	{
		jassert(i > 0);
		return buffer[i] > buffer[i - 1] && buffer[i] > 0 && buffer[i - 1] < 0;
	}

	//==========================================================================
	juce::Rectangle<int>                      boundary;
	std::array<float, int((float)44100 / 83)> buffer;
	std::array<float, int((float)44100 / 83)> oldBuffer;
	std::size_t                               writePosition;
	const int                                 bufferSize;
	const int                                 paintSize;
	MainContentComponent* const               parent;
};

//==============================================================================
class MainContentComponent : public AudioAppComponent,
	                         public Slider::Listener,
	                         public Button::Listener
{
public:
    //==========================================================================
    /* Setup */
	MainContentComponent():
		modulationFrequency(4.1),
		modulationDepth(.2),
		centreFrequency(512),
		resonance(2),
        targetModulationFrequency(4.1),
        targetModulationDepth(.2),
        targetCentreFrequency(512),
        targetResonance(2),
        trained(false),
		oscilloscope(this)
    {
		header.setColour(TextButton::buttonColourId, Colours::wheat);
		header.setColour(TextButton::textColourOffId, Colours::white);
        header.setEnabled(false);
		header.setButtonText("Rapid API Example");
		addAndMakeVisible(header);

		sidebar.setColour(TextButton::buttonColourId, Colours::white);
		sidebar.setColour(TextButton::textColourOffId, Colours::white);
        sidebar.setEnabled(false);
		addAndMakeVisible(sidebar);
		
		train.setColour(TextButton::buttonColourId, Colours::wheat);
		train.setColour(TextButton::textColourOffId, Colours::white);
		train.setButtonText("Train");
		train.addListener(this);
		addAndMakeVisible(train);

		randomise.setColour(TextButton::buttonColourId, Colours::wheat);
		randomise.setColour(TextButton::textColourOffId, Colours::white);
		randomise.setButtonText("Randomise!");
		randomise.addListener(this);
		addAndMakeVisible(randomise);

		footer.setColour(TextButton::buttonColourId, Colours::wheat);
		footer.setColour(TextButton::textColourOffId, Colours::white);
        footer.setEnabled(false);
		footer.setButtonText("Select the synth parameters you like, then move the mouse to an area and hold space to associate that space with that sound. Repeat with a few sounds");
		addAndMakeVisible(footer);
        
        modulationFrequencySlider.setRange(0, 4096);
        modulationFrequencySlider.setSkewFactorFromMidPoint (500.0);
        modulationFrequencySlider.setValue(modulationFrequency, dontSendNotification);
        modulationFrequencySlider.addListener(this);
        addAndMakeVisible(modulationFrequencySlider);
        
        modulationFrequencyLabel.setText("Mod Frequency", dontSendNotification);
		modulationFrequencyLabel.setColour(Label::ColourIds::textColourId, Colours::white);
        modulationFrequencyLabel.attachToComponent(&modulationFrequencySlider, false);
        addAndMakeVisible(modulationFrequencyLabel);
        
        modulationIndexSlider.setRange(0., 1.);
        modulationIndexSlider.setValue(modulationDepth, dontSendNotification);
        modulationIndexSlider.addListener(this);
        addAndMakeVisible(modulationIndexSlider);
        
        modulationIndexLabel.setText("Mod Index", dontSendNotification);
		modulationFrequencyLabel.setColour(Label::ColourIds::textColourId, Colours::white);
        modulationIndexLabel.attachToComponent(&modulationIndexSlider, false);
        addAndMakeVisible(modulationIndexLabel);
        
        filterFrequencySlider.setRange(0.00001, 4096);
		filterFrequencySlider.setColour(Label::ColourIds::textColourId, Colours::white);
        filterFrequencySlider.setSkewFactorFromMidPoint (500.0);
        filterFrequencySlider.setValue(centreFrequency, dontSendNotification);
        filterFrequencySlider.addListener(this);
        addAndMakeVisible(filterFrequencySlider);
        
        filterFrequencyLabel.setText("Filter Frequency", dontSendNotification);
		filterFrequencyLabel.setColour(Label::ColourIds::textColourId, Colours::white);
        filterFrequencyLabel.attachToComponent(&filterFrequencySlider, false);
        addAndMakeVisible(filterFrequencyLabel);
        
        filterResonanceSlider.setRange(0.00001, 40);
        filterResonanceSlider.setValue(resonance, dontSendNotification);
        filterResonanceSlider.addListener(this);
        addAndMakeVisible(filterResonanceSlider);
        
        filterResonanceLabel.setText("Filter Resonance", dontSendNotification);
		filterResonanceLabel.setColour(Label::ColourIds::textColourId, Colours::white);
        filterResonanceLabel.attachToComponent(&filterResonanceSlider, false);
        addAndMakeVisible(filterResonanceLabel);

		addAndMakeVisible(oscilloscope);

        setSize (800, 600);

        // No inputs, two outputs
        setAudioChannels (0, 2);
    }
    
    ~MainContentComponent()
    {
        shutdownAudio();
    }

	//==========================================================================
    /* Audio Methods */
	void prepareToPlay (int _samplesPerBlockExpected, double _sampleRate) override
    {
		// Remember this is part of the audio callback so we must be careful
		// not to do anything silly like allocating memory or dare I say wait
		// for locks!
		maxiSettings::setup(std::round(_sampleRate), 2, _samplesPerBlockExpected);
    }

    void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
    {
		int periodLength = int(maxiSettings::sampleRate / 83);
		// Get the buffers for both output channels
		float* const bufferL = bufferToFill.buffer->getWritePointer(0, bufferToFill.startSample);
		float* const bufferR = bufferToFill.buffer->getWritePointer(1, bufferToFill.startSample);
        
        const double localTargetModulationFrequency = targetModulationFrequency;
        const double localTargetModulationDepth = targetModulationDepth;
        const double localTargetCentreFrequency = targetCentreFrequency;
        const double localTargetResonance = targetResonance;
        
        const double modulationFrequencyDelta = (localTargetModulationFrequency != modulationFrequency) ? (targetModulationFrequency - modulationFrequency) / bufferToFill.numSamples : 0;
		const double modulationDepthDelta     = (localTargetModulationDepth != modulationDepth)         ? (targetModulationDepth - modulationDepth) / bufferToFill.numSamples         : 0;
        const double centreFrequencyDelta     = (localTargetCentreFrequency != centreFrequency)         ? (targetCentreFrequency - centreFrequency) / bufferToFill.numSamples         : 0;
        const double resonanceDelta           = (localTargetResonance != resonance)                     ? (targetResonance - resonance) / bufferToFill.numSamples                     : 0;
        
		// Create our FM Maximilian noises and send the mixed output to the channels
		for (int sample = 0; sample < bufferToFill.numSamples; ++sample)
		{
            modulationFrequency += modulationFrequencyDelta;
            modulationDepth += modulationDepthDelta;
            centreFrequency += centreFrequencyDelta;
            resonance += resonanceDelta;
            
			const double modulatorFrame = (modulator.sinewave(modulationFrequency) + 1.0) / 2.0 * modulationDepth + (1 - modulationDepth);
			const double carrierFrame = carrier.pulse(83, modulatorFrame);
			const double filteredFrame = filter.lores(carrierFrame, centreFrequency, resonance);

			mixer.stereo(filteredFrame, outputs, .5);
			bufferL[sample] = float(outputs[0]);
			bufferR[sample] = float(outputs[1]);
		}
        
        modulationFrequency = localTargetModulationFrequency;
        modulationDepth = localTargetModulationDepth;
        centreFrequency = localTargetCentreFrequency;
        resonance = localTargetResonance;

		oscilloscope.pushBuffer(bufferL, bufferToFill.numSamples);
    }

    void releaseResources() override {}

	//==========================================================================
    /* Graphics, GUI */
	void paint (Graphics& _g) override
    {
        // (Our component is opaque, so we must completely fill the background with a solid colour)
        _g.fillAll (Colour::fromRGB(40, 40, 40));
        
    }
    
    // This is called once at startup and then everytime the window is resized
	// Essentially all the code here just subdivides the available window space
    void resized() override
    {
		juce::Rectangle<int> area(getLocalBounds());

		const int headerFooterHeight = 36;
		header.setBounds(area.removeFromTop(headerFooterHeight));
		footer.setBounds(area.removeFromBottom(headerFooterHeight));

		const int sidebarWidth = jmax(100, area.getWidth() / 4);
		juce::Rectangle<int> sidebarArea(area.removeFromLeft(sidebarWidth));
		sidebar.setBounds(sidebarArea);

		const int drawingWidth = area.getWidth();
		drawingArea = area.removeFromRight(drawingWidth);

		oscilloscope.setBounds(drawingArea.reduced(int(sidebarWidth / 4.0)));

		const int sideItemHeight = 40;
		const int sideItemMargin = 5;

		train.setBounds(sidebarArea.removeFromTop(sideItemHeight).reduced(sideItemMargin));
		randomise.setBounds(sidebarArea.removeFromBottom(sideItemHeight).reduced(sideItemMargin));
        filterResonanceSlider.setBounds(sidebarArea.removeFromBottom(sideItemHeight).reduced(2.5*sideItemMargin));
        filterFrequencySlider.setBounds(sidebarArea.removeFromBottom(sideItemHeight).reduced(2.5*sideItemMargin));
        modulationIndexSlider.setBounds(sidebarArea.removeFromBottom(sideItemHeight).reduced(2.5*sideItemMargin));
        modulationFrequencySlider.setBounds(sidebarArea.removeFromBottom(sideItemHeight).reduced(2.5*sideItemMargin));
        
	}

	//==========================================================================
	/* Interaction events via mouse and keyboard */

	void mouseDrag(const MouseEvent& _event) override
	{
		if (trained)
		{
			std::vector<double> input = normaliseMouseSpace(_event.position.roundToInt(), drawingArea);
			std::vector<double> output = rapidRegression.run(input);
            
            targetModulationFrequency = output[0];
            targetModulationDepth     = output[1];
            targetCentreFrequency     = output[2];
            targetResonance           = output[3];
            modulationFrequencySlider.setValue(targetModulationFrequency, dontSendNotification);
            modulationIndexSlider.setValue(targetModulationDepth, dontSendNotification);
            filterFrequencySlider.setValue(targetCentreFrequency, dontSendNotification);
            filterResonanceSlider.setValue(targetResonance, dontSendNotification);
		}
		else
		{
            
			AlertWindow::showMessageBoxAsync(AlertWindow::AlertIconType::WarningIcon, "Error", "Please train the model before trying to run it!", "ok");
		}
	}

	void mouseMove(const MouseEvent& _event) override
	{
		if (KeyPress::isKeyCurrentlyDown(KeyPress::spaceKey))
		{
			std::vector<double> input = normaliseMouseSpace(_event.position.roundToInt(), drawingArea);
            trainingExample<double> example;
			example.input = { input[0], input[1] };
			example.output = { modulationFrequency, modulationDepth, centreFrequency, resonance };
			trainingSet.push_back(example);
            
            // only do once...
            if (input.size() > 0)
            {
                footer.setButtonText("When you have finished recorded the sounds you want, press train!");
            }
		}
	}

	std::vector<double> normaliseMouseSpace(const juce::Point<int>& _position, const juce::Rectangle<int>& _area)
	{
		juce::Point<int> pos = _area.getConstrainedPoint(_position);
		std::vector<double> temp;
		temp.resize(2);
		temp[0] = double(double(pos.getX() - _area.getX()) / _area.getWidth());
 		temp[1] = double(double(pos.getY() - _area.getY()) / _area.getHeight());
        return temp;
	}

	void sliderValueChanged(Slider* _slider) override
	{
        if (_slider == &modulationFrequencySlider)
            targetModulationFrequency = modulationFrequencySlider.getValue();
        else if (_slider == &modulationIndexSlider)
            targetModulationDepth = modulationIndexSlider.getValue();
        else if (_slider == &filterFrequencySlider)
            targetCentreFrequency = filterFrequencySlider.getValue();
        else if (_slider == &filterResonanceSlider)
            targetResonance = filterResonanceSlider.getValue();
	}

	void buttonClicked(Button* _button) override
	{
		if (_button == &train)
		{
			if (trainingSet.size() > 2) 
			{
				trained = rapidRegression.train(trainingSet);
                
                footer.setButtonText("Now just drag the mouse to play!");
			}
			else
			{
				AlertWindow::showMessageBoxAsync(AlertWindow::AlertIconType::WarningIcon, "Error", "Please record more audio and mouse coordinate examples before training!\n\nYou can add examples by choosing mouse coordinates with the current sound and holding space whilst wiggling the mouse", "ok");
			}
		}
		else if (_button == &randomise)
		{
			std::random_device random;
			std::default_random_engine generator(random());
			std::uniform_real_distribution<double> distribution(0.0, 1.0);

			targetModulationFrequency = 4096 * distribution(generator);
			targetModulationDepth = distribution(generator);
			targetCentreFrequency = 4096 * distribution(generator);
			targetResonance = 40 * distribution(generator);
            
            modulationFrequencySlider.setValue(targetModulationFrequency, dontSendNotification);
            modulationIndexSlider.setValue(targetModulationDepth, dontSendNotification);
            filterFrequencySlider.setValue(targetCentreFrequency, dontSendNotification);
            filterResonanceSlider.setValue(targetResonance, dontSendNotification);

		}
	}


private:
	//==========================================================================
	/*** AUDIO ***/

    // FM Synthesis private parameters
    double                       modulationFrequency;
    double                       modulationDepth;
    double                       centreFrequency;
    double                       resonance;
    double                       targetModulationFrequency;
    double                       targetModulationDepth;
    double                       targetCentreFrequency;
    double                       targetResonance;
    double                       outputs[2];

	// Maximilian objects
	maxiOsc                      carrier;
	maxiOsc                      modulator;
	maxiFilter                   filter;
	maxiMix                      mixer;

    //==========================================================================
	/*** MACHINE LEARNING ***/

	// Rapid regression
	regression<double>                   rapidRegression;
	std::vector<trainingExample<double> > trainingSet;

	// Program state
	bool                         trained;

    //==========================================================================
	/*** GUI ***/

	// Layout
	TextButton                   header;
	TextButton                   sidebar;
	TextButton                   footer;
	juce::Rectangle<int>         drawingArea;
	
	// Rapidmix
	TextButton                   train;

	// Maximilian
	Slider                       modulationFrequencySlider;
	Label                        modulationFrequencyLabel;
	Slider                       modulationIndexSlider;
	Label                        modulationIndexLabel;
	Slider                       filterFrequencySlider;
	Label                        filterFrequencyLabel;
	Slider                       filterResonanceSlider;
	Label                        filterResonanceLabel;
	TextButton                   randomise;
    
    //==========================================================================
    /*** GRAPHICS ***/
	Oscilloscope                 oscilloscope;

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainContentComponent)
};

void Oscilloscope::mouseDrag(const MouseEvent& _event)
{
	parent->mouseDrag(_event);
}

// (This function is called by the app startup code to create our main component)
Component* createMainContentComponent()     { return new MainContentComponent(); }
#endif  // MAINCOMPONENT_H_INCLUDED