-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAudioPluginDemo.h
More file actions
811 lines (634 loc) · 31.1 KB
/
Copy pathAudioPluginDemo.h
File metadata and controls
811 lines (634 loc) · 31.1 KB
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
/*
==============================================================================
This file is part of the JUCE examples.
Copyright (c) 2020 - Raw Material Software Limited
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
/*******************************************************************************
The block below describes the properties of this PIP. A PIP is a short snippet
of code that can be read by the Projucer and used to generate a JUCE project.
BEGIN_JUCE_PIP_METADATA
name: AudioPluginDemo
version: 1.0.0
vendor: JUCE
website: http://juce.com
description: Synthesiser audio plugin.
dependencies: juce_audio_basics, juce_audio_devices, juce_audio_formats,
juce_audio_plugin_client, juce_audio_processors,
juce_audio_utils, juce_core, juce_data_structures,
juce_events, juce_graphics, juce_gui_basics, juce_gui_extra
exporters: xcode_mac, vs2017, vs2019, linux_make, xcode_iphone, androidstudio
moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
type: AudioProcessor
mainClass: JuceDemoPluginAudioProcessor
useLocalCopy: 1
pluginCharacteristics: pluginIsSynth, pluginWantsMidiIn, pluginProducesMidiOut,
pluginEditorRequiresKeys
extraPluginFormats: AUv3
END_JUCE_PIP_METADATA
*******************************************************************************/
#pragma once
//yuh yuh yuh yuh yuh
//==============================================================================
/** A demo synth sound that's just a basic sine wave.. */
class SineWaveSound : public SynthesiserSound
{
public:
SineWaveSound() {}
bool appliesToNote (int /*midiNoteNumber*/) override { return true; }
bool appliesToChannel (int /*midiChannel*/) override { return true; }
};
//==============================================================================
/** A simple demo synth voice that just plays a sine wave.. */
class SineWaveVoice : public SynthesiserVoice
{
public:
SineWaveVoice() {}
bool canPlaySound (SynthesiserSound* sound) override
{
return dynamic_cast<SineWaveSound*> (sound) != nullptr;
}
void startNote (int midiNoteNumber, float velocity,
SynthesiserSound* /*sound*/, int) override
{
currentAngle = 0.0;
level = velocity * 0.15;
release = 0.0;
if (modRatioDen == 0) {
modRatio = 0.5;
} else {
modRatio = (modRatioNum * 1.0 / modRatioDen);
}
auto cyclesPerSecond = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
auto cyclesPerSample = (cyclesPerSecond)/ getSampleRate();
angleDelta = cyclesPerSample * MathConstants<double>::twoPi;
int modFreq = int(cyclesPerSecond * modRatio); //new
// float freqDev = 10; //new
auto modCyclesPerSample = modFreq / getSampleRate(); //new
modAngleDelta = modCyclesPerSample * MathConstants<double>::twoPi;//new
modIndex = freqDev / float(modFreq); //new
}
void stopNote (float /*velocity*/, bool allowTailOff) override
{
if (allowTailOff)
{
// start a tail-off by setting this flag. The render callback will pick up on
// this and do a fade out, calling clearCurrentNote() when it's finished.
if (release == 0.0) // we only need to begin a tail-off if it's not already doing so - the
// stopNote method could be called more than once.
release = 1.0;
}
else
{
// we're being told to stop playing immediately, so reset everything..
clearCurrentNote();
angleDelta = 0.0;
}
}
void pitchWheelMoved (int /*newValue*/) override
{
// not implemented for the purposes of this demo!
}
void controllerMoved (int paramNum, int value) override
{
if (paramNum == 0) { //freqDev
freqDev = value;
} else if (paramNum == 1) {
modRatioNum = value;
} else if (paramNum == 2) {
modRatioDen = value;
}
}
void renderNextBlock (AudioBuffer<float>& outputBuffer, int startSample, int numSamples) override
{
if (angleDelta != 0.0)
{
/*if (attack < 1) {
while (--numSamples >= 0)
{
// auto currentSample = (float) (sin (currentAngle) * level * release);
auto currentSample = (float) (sin (currentAngle + modIndex * sin( modCurrentAngle ) ) * level * attack);
for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
outputBuffer.addSample (i, startSample, currentSample);
currentAngle += angleDelta;
modCurrentAngle += modAngleDelta;
++startSample;
attack *= 1.01;
/Users/andreaspaljug/Downloads/olddownloads/JUCE 2/modules/juce_audio_plugin_client }
}
else */ if (release > 0.0)
{
while (--numSamples >= 0)
{
// auto currentSample = (float) (sin (currentAngle) * level * release);
auto currentSample = (float) (sin (currentAngle + modIndex * sin( modCurrentAngle ) ) * level * release);
for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
outputBuffer.addSample (i, startSample, currentSample);
currentAngle += angleDelta;
modCurrentAngle += modAngleDelta;
++startSample;
release *= 0.99;
if (release <= 0.005)
{
// tells the synth that this voice has stopped
clearCurrentNote();
angleDelta = 0.0;
break;
}
}
}
else
{
while (--numSamples >= 0)
{
//auto currentSample = (float) (sin (currentAngle )) * level);
auto currentSample = (float) (sin (currentAngle + modIndex * sin( modCurrentAngle )) * level);
for (auto i = outputBuffer.getNumChannels(); --i >= 0;)
outputBuffer.addSample (i, startSample, currentSample);
currentAngle += angleDelta;
modCurrentAngle += modAngleDelta;
++startSample;
}
}
}
}
using SynthesiserVoice::renderNextBlock;
private:
//sine parameters
double currentAngle = 0.0;
double angleDelta = 0.0;
double level = 0.0;
//adsr parameters
//double attack = 0.5;
//TODO: add decay, sustain, etc.
double release = 0.5;
//FM parameters
double modCurrentAngle = 0.0;
double modAngleDelta = 0.0;
double modIndex = 0.0;
int freqDev = 100;
int modRatioNum = 1;
int modRatioDen = 2;
double modRatio = 0.5;
};
//==============================================================================
/** As the name suggest, this class does the actual audio processing. */
class JuceDemoPluginAudioProcessor : public AudioProcessor
{
public:
//==============================================================================
JuceDemoPluginAudioProcessor()
: AudioProcessor (getBusesProperties()),
state (*this, nullptr, "state",
{ std::make_unique<AudioParameterFloat> ("gain", "Gain", NormalisableRange<float> (0.0f, 1.0f), 0.9f),
std::make_unique<AudioParameterFloat> ("delay", "Delay Feedback", NormalisableRange<float> (0.0f, 100.0f), 0.5f),
std::make_unique<AudioParameterFloat> ("mod", "Modulation", NormalisableRange<float> (0.0f, 100.0f), 0.5f),
std::make_unique<AudioParameterInt> ("indexNum", "Index Numerator", 1, 99, 1),
std::make_unique<AudioParameterInt> ("indexDen", "Index Denominator", 1, 20, 2), //min, max, default
std::make_unique<AudioParameterFloat> ("attack", "Attack", NormalisableRange<float> (0.0f, 100.0f), 0.5f), //min, max, default
//TODO: define variables for sustain, release
})
// std::make_unique<AudioParameterFloat> ("delay", "Delay Feedback", NormalisableRange<float> (0.0f, 1.0f), 0.5f) })
{
// Add a sub-tree to store the state of our UI
state.state.addChild ({ "uiState", { { "width", 800 }, { "height", 200 } }, {} }, -1, nullptr);
initialiseSynth();
}
~JuceDemoPluginAudioProcessor() override = default;
//==============================================================================
bool isBusesLayoutSupported (const BusesLayout& layouts) const override
{
// Only mono/stereo and input/output must have same layout
const auto& mainOutput = layouts.getMainOutputChannelSet();
const auto& mainInput = layouts.getMainInputChannelSet();
// input and output layout must either be the same or the input must be disabled altogether
if (! mainInput.isDisabled() && mainInput != mainOutput)
return false;
// do not allow disabling the main buses
if (mainOutput.isDisabled())
return false;
// only allow stereo and mono
if (mainOutput.size() > 2)
return false;
return true;
}
void prepareToPlay (double newSampleRate, int /*samplesPerBlock*/) override
{
// Use this method as the place to do any pre-playback
// initialisation that you need..
synth.setCurrentPlaybackSampleRate (newSampleRate);
keyboardState.reset();
if (isUsingDoublePrecision())
{
delayBufferDouble.setSize (2, 12000);
delayBufferFloat .setSize (1, 1);
}
else
{
delayBufferFloat .setSize (2, 12000);
delayBufferDouble.setSize (1, 1);
}
reset();
}
void releaseResources() override
{
// When playback stops, you can use this as an opportunity to free up any
// spare memory, etc.
keyboardState.reset();
}
void reset() override
{
// Use this method as the place to clear any delay lines, buffers, etc, as it
// means there's been a break in the audio's continuity.
delayBufferFloat .clear();
delayBufferDouble.clear();
}
//==============================================================================
void processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiMessages) override
{
jassert (! isUsingDoublePrecision());
process (buffer, midiMessages, delayBufferFloat);
}
void processBlock (AudioBuffer<double>& buffer, MidiBuffer& midiMessages) override
{
jassert (isUsingDoublePrecision());
process (buffer, midiMessages, delayBufferDouble);
}
//==============================================================================
bool hasEditor() const override { return true; }
AudioProcessorEditor* createEditor() override
{
return new JuceDemoPluginAudioProcessorEditor (*this);
}
//==============================================================================
const String getName() const override { return "AudioPluginDemo"; }
bool acceptsMidi() const override { return true; }
bool producesMidi() const override { return true; }
double getTailLengthSeconds() const override { return 0.0; }
//==============================================================================
int getNumPrograms() override { return 0; }
int getCurrentProgram() override { return 0; }
void setCurrentProgram (int) override {}
const String getProgramName (int) override { return {}; }
void changeProgramName (int, const String&) override {}
//==============================================================================
void getStateInformation (MemoryBlock& destData) override
{
// Store an xml representation of our state.
if (auto xmlState = state.copyState().createXml())
copyXmlToBinary (*xmlState, destData);
}
void setStateInformation (const void* data, int sizeInBytes) override
{
// Restore our plug-in's state from the xml representation stored in the above
// method.
if (auto xmlState = getXmlFromBinary (data, sizeInBytes))
state.replaceState (ValueTree::fromXml (*xmlState));
}
//==============================================================================
void updateTrackProperties (const TrackProperties& properties) override
{
{
const ScopedLock sl (trackPropertiesLock);
trackProperties = properties;
}
MessageManager::callAsync ([this]
{
if (auto* editor = dynamic_cast<JuceDemoPluginAudioProcessorEditor*> (getActiveEditor()))
editor->updateTrackProperties();
});
}
TrackProperties getTrackProperties() const
{
const ScopedLock sl (trackPropertiesLock);
return trackProperties;
}
class SpinLockedPosInfo
{
public:
SpinLockedPosInfo() { info.resetToDefault(); }
// Wait-free, but setting new info may fail if the main thread is currently
// calling `get`. This is unlikely to matter in practice because
// we'll be calling `set` much more frequently than `get`.
void set (const AudioPlayHead::CurrentPositionInfo& newInfo)
{
const juce::SpinLock::ScopedTryLockType lock (mutex);
if (lock.isLocked())
info = newInfo;
}
AudioPlayHead::CurrentPositionInfo get() const noexcept
{
const juce::SpinLock::ScopedLockType lock (mutex);
return info;
}
private:
juce::SpinLock mutex;
AudioPlayHead::CurrentPositionInfo info;
};
//==============================================================================
// These properties are public so that our editor component can access them
// A bit of a hacky way to do it, but it's only a demo! Obviously in your own
// code you'll do this much more neatly..
// this is kept up to date with the midi messages that arrive, and the UI component
// registers with it so it can represent the incoming messages
MidiKeyboardState keyboardState;
// this keeps a copy of the last set of time info that was acquired during an audio
// callback - the UI component will read this and display it.
SpinLockedPosInfo lastPosInfo;
// Our plug-in's current state
AudioProcessorValueTreeState state;
private:
//==============================================================================
/** This is the editor component that our filter will display. */
class JuceDemoPluginAudioProcessorEditor : public AudioProcessorEditor,
private Timer,
private Value::Listener
{
public:
JuceDemoPluginAudioProcessorEditor (JuceDemoPluginAudioProcessor& owner)
: AudioProcessorEditor (owner),
midiKeyboard (owner.keyboardState, MidiKeyboardComponent::horizontalKeyboard),
gainAttachment (owner.state, "gain", gainSlider),
delayAttachment (owner.state, "delay", delaySlider),
modAttachment (owner.state, "mod", modSlider),
attackAttachment (owner.state, "attack", attackSlider),
iNumAttachment (owner.state, "indexNum", iNumBox),
iDenAttachment (owner.state, "indexDen", iDenBox)
{
// add some sliders..
addAndMakeVisible (gainSlider);
gainSlider.setSliderStyle (Slider::Rotary);
addAndMakeVisible (delaySlider);
delaySlider.setSliderStyle (Slider::Rotary);
addAndMakeVisible (modSlider);
modSlider.setSliderStyle (Slider::Rotary);
addAndMakeVisible (attackSlider);
attackSlider.setSliderStyle (Slider::Rotary);
// add some checkboxes:
addAndMakeVisible(iNumBox);
for (int i = 1; i < 100; i++)
{ iNumBox.addItem(std::to_string(i), i);
}
addAndMakeVisible(iDenBox);
for (int i = 1; i <= 20; i++)
{
iDenBox.addItem(std::to_string(i), i);
}
attackLabel.attachToComponent (&attackSlider, false);
attackLabel.setFont (Font (11.0f));
// add some labels for the sliders..
gainLabel.attachToComponent (&gainSlider, false);
gainLabel.setFont (Font (11.0f));
delayLabel.attachToComponent (&delaySlider, false);
delayLabel.setFont (Font (11.0f));
modLabel.attachToComponent (&modSlider, false);
modLabel.setFont (Font (11.0f));
numLabel.attachToComponent (&iNumBox, false);
numLabel.setFont (Font (11.0f));
denLabel.attachToComponent (&iDenBox, false);
denLabel.setFont (Font (11.0f));
// add the midi keyboard component..
addAndMakeVisible (midiKeyboard);
// add a label that will display the current timecode and status..
addAndMakeVisible (timecodeDisplayLabel);
timecodeDisplayLabel.setFont (Font (Font::getDefaultMonospacedFontName(), 15.0f, Font::plain));
// set resize limits for this plug-in
setResizeLimits (400, 200, 1024, 700);
lastUIWidth .referTo (owner.state.state.getChildWithName ("uiState").getPropertyAsValue ("width", nullptr));
lastUIHeight.referTo (owner.state.state.getChildWithName ("uiState").getPropertyAsValue ("height", nullptr));
// set our component's initial size to be the last one that was stored in the filter's settings
setSize (lastUIWidth.getValue(), lastUIHeight.getValue());
lastUIWidth. addListener (this);
lastUIHeight.addListener (this);
updateTrackProperties();
// start a timer which will keep our timecode display updated
startTimerHz (30);
}
~JuceDemoPluginAudioProcessorEditor() override {}
//==============================================================================
void paint (Graphics& g) override
{
g.setColour (backgroundColour);
g.fillAll();
}
void resized() override
{
// This lays out our child components...
auto r = getLocalBounds().reduced (8);
timecodeDisplayLabel.setBounds (r.removeFromTop (26));
midiKeyboard .setBounds (r.removeFromBottom (70));
r.removeFromTop (20);
auto sliderArea = r.removeFromTop (60);
gainSlider.setBounds (sliderArea.removeFromLeft (jmin (180, sliderArea.getWidth() / 3)));
delaySlider.setBounds (sliderArea.removeFromLeft (jmin (180, sliderArea.getWidth() * 2 / 3)));
modSlider.setBounds (sliderArea.removeFromLeft (jmin (180, sliderArea.getWidth())));
iNumBox.setBounds (sliderArea.removeFromLeft (jmin (180, sliderArea.getWidth())));
iDenBox.setBounds (sliderArea.removeFromLeft (jmin (180, sliderArea.getWidth())));
//attackSlider.setBounds (sliderArea.removeFromLeft (jmin (180, sliderArea.getWidth() / 2)));
lastUIWidth = getWidth();
lastUIHeight = getHeight();
}
void timerCallback() override
{
updateTimecodeDisplay (getProcessor().lastPosInfo.get());
}
void hostMIDIControllerIsAvailable (bool controllerIsAvailable) override
{
midiKeyboard.setVisible (! controllerIsAvailable);
}
int getControlParameterIndex (Component& control) override
{
if (&control == &gainSlider)
return 0;
if (&control == &delaySlider)
return 1;
return -1;
}
void updateTrackProperties()
{
auto trackColour = getProcessor().getTrackProperties().colour;
auto& lf = getLookAndFeel();
backgroundColour = (trackColour == Colour() ? lf.findColour (ResizableWindow::backgroundColourId)
: trackColour.withAlpha (1.0f).withBrightness (0.266f));
repaint();
}
private:
MidiKeyboardComponent midiKeyboard;
Label timecodeDisplayLabel,
gainLabel { {}, "Throughput level:" },
delayLabel { {}, "Delay:" },
modLabel { {}, "Freq Mod (deviation):" },
numLabel { {}, "Index Numerator:"},
denLabel { {}, "Index Denominator:"},
attackLabel {{}, "Attack Magnitude"};
//TODO: add sustain and gain labels
Slider gainSlider, delaySlider, modSlider, attackSlider/*, iNumSlider, iDenSlider*/;
ComboBox iNumBox, iDenBox;
AudioProcessorValueTreeState::SliderAttachment gainAttachment, delayAttachment, modAttachment, attackAttachment; //Sustain attachment;
/*,indexNumAttachment, indexDenAttachment;*/
AudioProcessorValueTreeState::ComboBoxAttachment iNumAttachment, iDenAttachment;
Colour backgroundColour;
// these are used to persist the UI's size - the values are stored along with the
// filter's other parameters, and the UI component will update them when it gets
// resized.
Value lastUIWidth, lastUIHeight;
//==============================================================================
JuceDemoPluginAudioProcessor& getProcessor() const
{
return static_cast<JuceDemoPluginAudioProcessor&> (processor);
}
//==============================================================================
// quick-and-dirty function to format a timecode string
static String timeToTimecodeString (double seconds)
{
auto millisecs = roundToInt (seconds * 1000.0);
auto absMillisecs = std::abs (millisecs);
return String::formatted ("%02d:%02d:%02d.%03d",
millisecs / 3600000,
(absMillisecs / 60000) % 60,
(absMillisecs / 1000) % 60,
absMillisecs % 1000);
}
// quick-and-dirty function to format a bars/beats string
static String quarterNotePositionToBarsBeatsString (double quarterNotes, int numerator, int denominator)
{
if (numerator == 0 || denominator == 0)
return "1|1|000";
auto quarterNotesPerBar = (numerator * 4 / denominator);
auto beats = (fmod (quarterNotes, quarterNotesPerBar) / quarterNotesPerBar) * numerator;
auto bar = ((int) quarterNotes) / quarterNotesPerBar + 1;
auto beat = ((int) beats) + 1;
auto ticks = ((int) (fmod (beats, 1.0) * 960.0 + 0.5));
return String::formatted ("%d|%d|%03d", bar, beat, ticks);
}
// Updates the text in our position label.
void updateTimecodeDisplay (AudioPlayHead::CurrentPositionInfo pos)
{
MemoryOutputStream displayText;
displayText << "[" << SystemStats::getJUCEVersion() << "] "
<< String (pos.bpm, 2) << " bpm, "
<< pos.timeSigNumerator << '/' << pos.timeSigDenominator
<< " - " << timeToTimecodeString (pos.timeInSeconds)
<< " - " << quarterNotePositionToBarsBeatsString (pos.ppqPosition,
pos.timeSigNumerator,
pos.timeSigDenominator);
if (pos.isRecording)
displayText << " (recording)";
else if (pos.isPlaying)
displayText << " (playing)";
timecodeDisplayLabel.setText (displayText.toString(), dontSendNotification);
}
// called when the stored window size changes
void valueChanged (Value&) override
{
setSize (lastUIWidth.getValue(), lastUIHeight.getValue());
}
};
//==============================================================================
template <typename FloatType>
void process (AudioBuffer<FloatType>& buffer, MidiBuffer& midiMessages, AudioBuffer<FloatType>& delayBuffer)
{
auto gainParamValue = state.getParameter ("gain") ->getValue();
auto delayParamValue = state.getParameter ("delay")->getValue();
auto modParamValue = state.getParameter ("mod")->getValue();
auto numParamValue = state.getParameter ("indexNum")->getValue();
auto denParamValue = state.getParameter ("indexDen")->getValue();
auto numSamples = buffer.getNumSamples();
// In case we have more outputs than inputs, we'll clear any output
// channels that didn't contain input data, (because these aren't
// guaranteed to be empty - they may contain garbage).
for (auto i = getTotalNumInputChannels(); i < getTotalNumOutputChannels(); ++i)
buffer.clear (i, 0, numSamples);
//synth.defineModulation(1.0, delayParamValue);
// Now pass any incoming midi messages to our keyboard state object, and let it
// add messages to the buffer if the user is clicking on the on-screen keys
keyboardState.processNextMidiBuffer (midiMessages, 0, numSamples, true);
// and now get our synth to process these midi events and generate its output.
for (int i = 0; i < synth.getNumVoices(); i++) {
(synth.getVoice(i))->controllerMoved(0, 100 * modParamValue);
(synth.getVoice(i))->controllerMoved(1, 100 * numParamValue);
(synth.getVoice(i))->controllerMoved(2, 100 * denParamValue);
}
synth.renderNextBlock (buffer, midiMessages, 0, numSamples);
// Apply our delay effect to the new output..
applyDelay (buffer, delayBuffer, delayParamValue);
// Apply our gain change to the outgoing data..
applyGain (buffer, delayBuffer, gainParamValue);
// Now ask the host for the current time so we can store it to be displayed later...
updateCurrentTimeInfoFromHost();
}
template <typename FloatType>
void applyGain (AudioBuffer<FloatType>& buffer, AudioBuffer<FloatType>& delayBuffer, float gainLevel)
{
ignoreUnused (delayBuffer);
for (auto channel = 0; channel < getTotalNumOutputChannels(); ++channel)
buffer.applyGain (channel, 0, buffer.getNumSamples(), gainLevel);
}
template <typename FloatType>
void applyDelay (AudioBuffer<FloatType>& buffer, AudioBuffer<FloatType>& delayBuffer, float delayLevel)
{
auto numSamples = buffer.getNumSamples();
auto delayPos = 0;
for (auto channel = 0; channel < getTotalNumOutputChannels(); ++channel)
{
auto channelData = buffer.getWritePointer (channel);
auto delayData = delayBuffer.getWritePointer (jmin (channel, delayBuffer.getNumChannels() - 1));
delayPos = delayPosition;
for (auto i = 0; i < numSamples; ++i)
{
auto in = channelData[i];
channelData[i] += delayData[delayPos];
delayData[delayPos] = (delayData[delayPos] + in) * delayLevel;
if (++delayPos >= delayBuffer.getNumSamples())
delayPos = 0;
}
}
delayPosition = delayPos;
}
AudioBuffer<float> delayBufferFloat;
AudioBuffer<double> delayBufferDouble;
int delayPosition = 0;
Synthesiser synth;
CriticalSection trackPropertiesLock;
TrackProperties trackProperties;
void initialiseSynth()
{
auto numVoices = 8;
// Add some voices...
for (auto i = 0; i < numVoices; ++i)
synth.addVoice (new SineWaveVoice());
// ..and give the synth a sound to play
synth.addSound (new SineWaveSound());
}
void updateCurrentTimeInfoFromHost()
{
const auto newInfo = [&]
{
if (auto* ph = getPlayHead())
{
AudioPlayHead::CurrentPositionInfo result;
if (ph->getCurrentPosition (result))
return result;
}
// If the host fails to provide the current time, we'll just use default values
AudioPlayHead::CurrentPositionInfo result;
result.resetToDefault();
return result;
}();
lastPosInfo.set (newInfo);
}
static BusesProperties getBusesProperties()
{
return BusesProperties().withInput ("Input", AudioChannelSet::stereo(), true)
.withOutput ("Output", AudioChannelSet::stereo(), true);
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (JuceDemoPluginAudioProcessor)
};