id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
19,636
|
Lv2Instrument.cpp
|
LMMS_lmms/plugins/Lv2Instrument/Lv2Instrument.cpp
|
/*
* Lv2Instrument.cpp - implementation of LV2 instrument
*
* Copyright (c) 2018-2023 Johannes Lorenz <jlsf2013$users.sourceforge.net, $=@>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Lv2Instrument.h"
#include <QDebug>
#include <QDragEnterEvent>
#include <QPushButton>
#include "AudioEngine.h"
#include "Engine.h"
#include "InstrumentPlayHandle.h"
#include "InstrumentTrack.h"
#include "Lv2SubPluginFeatures.h"
#include "StringPairDrag.h"
#include "Clipboard.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT lv2instrument_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"LV2",
QT_TRANSLATE_NOOP("PluginBrowser",
"plugin for using arbitrary LV2 instruments inside LMMS."),
"Johannes Lorenz <jlsf2013$$$users.sourceforge.net, $$$=@>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader("logo"),
nullptr,
new Lv2SubPluginFeatures(Plugin::Type::Instrument)
};
}
/*
Lv2Instrument
*/
Lv2Instrument::Lv2Instrument(InstrumentTrack *instrumentTrackArg,
Descriptor::SubPluginFeatures::Key *key) :
Instrument(instrumentTrackArg, &lv2instrument_plugin_descriptor, key,
#ifdef LV2_INSTRUMENT_USE_MIDI
Flag::IsSingleStreamed | Flag::IsMidiBased
#else
Flag::IsSingleStreamed
#endif
),
Lv2ControlBase(this, key->attributes["uri"])
{
clearRunningNotes();
connect(instrumentTrack()->pitchRangeModel(), SIGNAL(dataChanged()),
this, SLOT(updatePitchRange()), Qt::DirectConnection);
connect(Engine::audioEngine(), &AudioEngine::sampleRateChanged,
this, &Lv2Instrument::onSampleRateChanged);
// now we need a play-handle which cares for calling play()
auto iph = new InstrumentPlayHandle(this, instrumentTrackArg);
Engine::audioEngine()->addPlayHandle(iph);
}
Lv2Instrument::~Lv2Instrument()
{
Engine::audioEngine()->removePlayHandlesOfTypes(instrumentTrack(),
PlayHandle::Type::NotePlayHandle | PlayHandle::Type::InstrumentPlayHandle);
}
void Lv2Instrument::reload()
{
Lv2ControlBase::reload();
clearRunningNotes();
emit modelChanged();
}
void Lv2Instrument::clearRunningNotes()
{
#ifdef LV2_INSTRUMENT_USE_MIDI
for (int i = 0; i < NumKeys; ++i) { m_runningNotes[i] = 0; }
#endif
}
void Lv2Instrument::onSampleRateChanged()
{
// TODO: once lv2 options are implemented,
// plugins that support it might allow changing their samplerate
// through it instead of reloading
reload();
}
void Lv2Instrument::saveSettings(QDomDocument &doc, QDomElement &that)
{
Lv2ControlBase::saveSettings(doc, that);
}
void Lv2Instrument::loadSettings(const QDomElement &that)
{
Lv2ControlBase::loadSettings(that);
}
void Lv2Instrument::loadFile(const QString &file)
{
Lv2ControlBase::loadFile(file);
}
#ifdef LV2_INSTRUMENT_USE_MIDI
bool Lv2Instrument::handleMidiEvent(
const MidiEvent &event, const TimePos &time, f_cnt_t offset)
{
// this function can be called from GUI threads while the plugin is running
// handleMidiInputEvent will use a thread-safe ringbuffer
handleMidiInputEvent(event, time, offset);
return true;
}
#endif
// not yet working
#ifndef LV2_INSTRUMENT_USE_MIDI
void Lv2Instrument::playNote(NotePlayHandle *nph, SampleFrame*)
{
}
#endif
void Lv2Instrument::play(SampleFrame* buf)
{
copyModelsFromLmms();
fpp_t fpp = Engine::audioEngine()->framesPerPeriod();
run(fpp);
copyModelsToLmms();
copyBuffersToLmms(buf, fpp);
}
gui::PluginView* Lv2Instrument::instantiateView(QWidget *parent)
{
return new gui::Lv2InsView(this, parent);
}
void Lv2Instrument::updatePitchRange()
{
qDebug() << "Lmms: Cannot update pitch range for lv2 plugin:"
"not implemented yet";
}
QString Lv2Instrument::nodeName() const
{
return Lv2ControlBase::nodeName();
}
namespace gui
{
/*
Lv2InsView
*/
Lv2InsView::Lv2InsView(Lv2Instrument *_instrument, QWidget *_parent) :
InstrumentView(_instrument, _parent),
Lv2ViewBase(this, _instrument)
{
setAutoFillBackground(true);
if (m_reloadPluginButton) {
connect(m_reloadPluginButton, &QPushButton::clicked,
this, [this](){ this->castModel<Lv2Instrument>()->reload();} );
}
if (m_toggleUIButton) {
connect(m_toggleUIButton, &QPushButton::toggled,
this, [this](){ toggleUI(); });
}
if (m_helpButton) {
connect(m_helpButton, &QPushButton::toggled,
this, [this](bool visible){ toggleHelp(visible); });
}
}
void Lv2InsView::dragEnterEvent(QDragEnterEvent *_dee)
{
// For mimeType() and MimeType enum class
using namespace Clipboard;
void (QDragEnterEvent::*reaction)() = &QDragEnterEvent::ignore;
if (_dee->mimeData()->hasFormat( mimeType( MimeType::StringPair )))
{
const QString txt =
_dee->mimeData()->data( mimeType( MimeType::StringPair ) );
if (txt.section(':', 0, 0) == "pluginpresetfile") {
reaction = &QDragEnterEvent::acceptProposedAction;
}
}
(_dee->*reaction)();
}
void Lv2InsView::dropEvent(QDropEvent *_de)
{
const QString type = StringPairDrag::decodeKey(_de);
const QString value = StringPairDrag::decodeValue(_de);
if (type == "pluginpresetfile")
{
castModel<Lv2Instrument>()->loadFile(value);
_de->accept();
return;
}
_de->ignore();
}
void Lv2InsView::hideEvent(QHideEvent *event)
{
closeHelpWindow();
QWidget::hideEvent(event);
}
void Lv2InsView::modelChanged()
{
Lv2ViewBase::modelChanged(castModel<Lv2Instrument>());
connect(castModel<Lv2Instrument>(), &Lv2Instrument::modelChanged,
this, [this](){ this->modelChanged();} );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin *lmms_plugin_main(Model *_parent, void *_data)
{
using KeyType = Plugin::Descriptor::SubPluginFeatures::Key;
try {
return new Lv2Instrument(static_cast<InstrumentTrack*>(_parent), static_cast<KeyType*>(_data));
} catch (const std::runtime_error& e) {
qCritical() << e.what();
return nullptr;
}
}
}
} // namespace lmms
| 6,646
|
C++
|
.cpp
| 227
| 27.127753
| 97
| 0.761761
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,637
|
Sfxr.cpp
|
LMMS_lmms/plugins/Sfxr/Sfxr.cpp
|
/*
* Sfxr.cpp - port of sfxr to LMMS
* Originally written by Tomas Pettersson. For the original license,
* please read readme.txt in this directory
*
* Copyright (c) 2014 Wong Cho Ching
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*/
#include <cstdlib>
#include <ctime>
#define rnd(n) (rand()%(n+1))
#define PI 3.14159265f
float frnd(float range)
{
return (float)rnd(10000)/10000*range;
}
#include <cmath>
#include <QDomElement>
#include "Sfxr.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "NotePlayHandle.h"
#include "PixmapButton.h"
#include "MidiEvent.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT sfxr_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"sfxr",
QT_TRANSLATE_NOOP( "PluginBrowser",
"LMMS port of sfxr" ),
"Wong Cho Ching",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
SfxrSynth::SfxrSynth( const SfxrInstrument * s ):
s(s),
playing_sample( true )
{
resetSample( false );
}
void SfxrSynth::resetSample( bool restart )
{
if(!restart)
{
phase=0;
}
fperiod=100.0/(s->m_startFreqModel.value()*s->m_startFreqModel.value()+0.001);
period=(int)fperiod;
fmaxperiod=100.0/(s->m_minFreqModel.value()*s->m_minFreqModel.value()+0.001);
fslide=1.0-pow((double)s->m_slideModel.value(), 3.0)*0.01;
fdslide=-pow((double)s->m_dSlideModel.value(), 3.0)*0.000001;
square_duty=0.5f-s->m_sqrDutyModel.value()*0.5f;
square_slide=-s->m_sqrSweepModel.value()*0.00005f;
if(s->m_changeAmtModel.value()>=0.0f)
arp_mod=1.0-pow((double)s->m_changeAmtModel.value(), 2.0)*0.9;
else
arp_mod=1.0+pow((double)s->m_changeAmtModel.value(), 2.0)*10.0;
arp_time=0;
arp_limit=(int)(pow(1.0f-s->m_changeSpeedModel.value(), 2.0f)*20000+32);
if(s->m_changeSpeedModel.value()==1.0f)
arp_limit=0;
if(!restart)
{
// reset filter
fltp=0.0f;
fltdp=0.0f;
fltw=pow(s->m_lpFilCutModel.value(), 3.0f)*0.1f;
fltw_d=1.0f+s->m_lpFilCutSweepModel.value()*0.0001f;
fltdmp=5.0f/(1.0f+pow(s->m_lpFilResoModel.value(), 2.0f)*20.0f)*(0.01f+fltw);
if(fltdmp>0.8f) fltdmp=0.8f;
fltphp=0.0f;
flthp=pow(s->m_hpFilCutModel.value(), 2.0f)*0.1f;
flthp_d=1.0+s->m_hpFilCutSweepModel.value()*0.0003f;
// reset vibrato
vib_phase=0.0f;
vib_speed=pow(s->m_vibSpeedModel.value(), 2.0f)*0.01f;
vib_amp=s->m_vibDepthModel.value()*0.5f;
// reset envelope
env_vol=0.0f;
env_stage=0;
env_time=0;
env_length[0]=(int)(s->m_attModel.value()*s->m_attModel.value()*99999.0f)+1;
env_length[1]=(int)(s->m_holdModel.value()*s->m_holdModel.value()*99999.0f)+1;
env_length[2]=(int)(s->m_decModel.value()*s->m_decModel.value()*99999.0f)+1;
fphase=pow(s->m_phaserOffsetModel.value(), 2.0f)*1020.0f;
if(s->m_phaserOffsetModel.value()<0.0f) fphase=-fphase;
fdphase=pow(s->m_phaserSweepModel.value(), 2.0f)*1.0f;
if(s->m_phaserSweepModel.value()<0.0f) fdphase=-fdphase;
iphase=abs((int)fphase);
ipp=0;
phaser_buffer.fill(0.0f);
for (auto& noiseSample : noise_buffer)
{
noiseSample = frnd(2.0f) - 1.0f;
}
rep_time=0;
rep_limit=(int)(pow(1.0f-s->m_repeatSpeedModel.value(), 2.0f)*20000+32);
if(s->m_repeatSpeedModel.value()==0.0f)
rep_limit=0;
}
}
void SfxrSynth::update( SampleFrame* buffer, const int32_t frameNum )
{
for(int i=0;i<frameNum;i++)
{
if(!playing_sample)
{
for( ch_cnt_t j=0; j < DEFAULT_CHANNELS; j++ )
{
buffer[i][j]=0.0f;
}
}
rep_time++;
if(rep_limit!=0 && rep_time>=rep_limit)
{
rep_limit=0;
resetSample(true);
}
// frequency envelopes/arpeggios
arp_time++;
if(arp_limit!=0 && arp_time>=arp_limit)
{
arp_limit=0;
fperiod*=arp_mod;
}
fslide+=fdslide;
fperiod*=fslide;
if(fperiod>fmaxperiod)
{
fperiod=fmaxperiod;
if(s->m_minFreqModel.value()>0.0f)
playing_sample=false;
}
float rfperiod=fperiod;
if(vib_amp>0.0f)
{
vib_phase+=vib_speed;
rfperiod=fperiod*(1.0+sin(vib_phase)*vib_amp);
}
period=(int)rfperiod;
if(period<8) period=8;
square_duty+=square_slide;
if(square_duty<0.0f) square_duty=0.0f;
if(square_duty>0.5f) square_duty=0.5f;
// volume envelope
env_time++;
if(env_time>env_length[env_stage])
{
env_time=0;
env_stage++;
if(env_stage==3)
playing_sample=false;
}
if(env_stage==0)
env_vol=(float)env_time/env_length[0];
if(env_stage==1)
env_vol=1.0f+pow(1.0f-(float)env_time/env_length[1], 1.0f)*2.0f*s->m_susModel.value();
if(env_stage==2)
env_vol=1.0f-(float)env_time/env_length[2];
// phaser step
fphase+=fdphase;
iphase=abs((int)fphase);
if(iphase>1023) iphase=1023;
if(flthp_d!=0.0f)
{
flthp*=flthp_d;
if(flthp<0.00001f) flthp=0.00001f;
if(flthp>0.1f) flthp=0.1f;
}
float ssample=0.0f;
for(int si=0;si<8;si++) // 8x supersampling
{
float sample=0.0f;
phase++;
if(phase>=period)
{
// phase=0;
phase%=period;
if(s->m_waveFormModel.value()==3)
for (auto& noiseSample : noise_buffer)
{
noiseSample = frnd(2.0f) - 1.0f;
}
}
// base waveform
float fp=(float)phase/period;
switch(s->m_waveFormModel.value())
{
case 0: // square
if(fp<square_duty)
sample=0.5f;
else
sample=-0.5f;
break;
case 1: // sawtooth
sample=1.0f-fp*2;
break;
case 2: // sine
sample=(float)sin(fp*2*PI);
break;
case 3: // noise
sample=noise_buffer[phase*32/period];
break;
}
// lp filter
float pp=fltp;
fltw*=fltw_d;
if(fltw<0.0f) fltw=0.0f;
if(fltw>0.1f) fltw=0.1f;
if(s->m_lpFilCutModel.value()!=1.0f)
{
fltdp+=(sample-fltp)*fltw;
fltdp-=fltdp*fltdmp;
}
else
{
fltp=sample;
fltdp=0.0f;
}
fltp+=fltdp;
// hp filter
fltphp+=fltp-pp;
fltphp-=fltphp*flthp;
sample=fltphp;
// phaser
phaser_buffer[ipp&1023]=sample;
sample+=phaser_buffer[(ipp-iphase+1024)&1023];
ipp=(ipp+1)&1023;
// final accumulation and envelope application
ssample+=sample*env_vol;
}
//ssample=ssample/8*master_vol;
//ssample*=2.0f*sound_vol;
ssample*=0.025f;
if(buffer!=nullptr)
{
if(ssample>1.0f) ssample=1.0f;
if(ssample<-1.0f) ssample=-1.0f;
for( ch_cnt_t j=0; j<DEFAULT_CHANNELS; j++ )
{
buffer[i][j]=ssample;
}
}
}
}
bool SfxrSynth::isPlaying() const
{
return playing_sample;
}
SfxrInstrument::SfxrInstrument( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &sfxr_plugin_descriptor ),
m_attModel(0.0f, this, "Attack Time"),
m_holdModel(0.3f, this, "Sustain Time"),
m_susModel(0.0f, this, "Sustain Punch"),
m_decModel(0.4f, this, "Decay Time"),
m_startFreqModel(0.3f, this, "Start Frequency"),
m_minFreqModel(0.0f, this, "Min Frequency"),
m_slideModel(0.0f, this, "Slide"),
m_dSlideModel(0.0f, this, "Delta Slide"),
m_vibDepthModel(0.0f, this, "Vibrato Depth"),
m_vibSpeedModel(0.0f, this, "Vibrato Speed"),
m_changeAmtModel(0.0f, this, "Change Amount"),
m_changeSpeedModel(0.0f, this, "Change Speed"),
m_sqrDutyModel(0.0f, this, "Square Duty"),
m_sqrSweepModel(0.0f, this, "Duty Sweep"),
m_repeatSpeedModel(0.0f, this, "Repeat Speed"),
m_phaserOffsetModel(0.0f, this, "Phaser Offset"),
m_phaserSweepModel(0.0f, this, "Phaser Sweep"),
m_lpFilCutModel(1.0f, this, "LP Filter Cutoff"),
m_lpFilCutSweepModel(0.0f, this, "LP Filter Cutoff Sweep"),
m_lpFilResoModel(0.0f, this, "LP Filter Resonance"),
m_hpFilCutModel(0.0f, this, "HP Filter Cutoff"),
m_hpFilCutSweepModel(0.0f, this, "HP Filter Cutoff Sweep"),
m_waveFormModel( static_cast<int>(SfxrWave::Square), 0, NumSfxrWaves-1, this, tr( "Wave" ) )
{
}
void SfxrInstrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
_this.setAttribute( "version", "1" );
m_attModel.saveSettings( _doc, _this, "att" );
m_holdModel.saveSettings( _doc, _this, "hold" );
m_susModel.saveSettings( _doc, _this, "sus" );
m_decModel.saveSettings( _doc, _this, "dec" );
m_startFreqModel.saveSettings( _doc, _this, "startFreq" );
m_minFreqModel.saveSettings( _doc, _this, "minFreq" );
m_slideModel.saveSettings( _doc, _this, "slide" );
m_dSlideModel.saveSettings( _doc, _this, "dSlide" );
m_vibDepthModel.saveSettings( _doc, _this, "vibDepth" );
m_vibSpeedModel.saveSettings( _doc, _this, "vibSpeed" );
m_changeAmtModel.saveSettings( _doc, _this, "changeAmt" );
m_changeSpeedModel.saveSettings( _doc, _this, "changeSpeed" );
m_sqrDutyModel.saveSettings( _doc, _this, "sqrDuty" );
m_sqrSweepModel.saveSettings( _doc, _this, "sqrSweep" );
m_repeatSpeedModel.saveSettings( _doc, _this, "repeatSpeed" );
m_phaserOffsetModel.saveSettings( _doc, _this, "phaserOffset" );
m_phaserSweepModel.saveSettings( _doc, _this, "phaserSweep" );
m_lpFilCutModel.saveSettings( _doc, _this, "lpFilCut" );
m_lpFilCutSweepModel.saveSettings( _doc, _this, "lpFilCutSweep" );
m_lpFilResoModel.saveSettings( _doc, _this, "lpFilReso" );
m_hpFilCutModel.saveSettings( _doc, _this, "hpFilCut" );
m_hpFilCutSweepModel.saveSettings( _doc, _this, "hpFilCutSweep" );
m_waveFormModel.saveSettings( _doc, _this, "waveForm" );
}
void SfxrInstrument::loadSettings( const QDomElement & _this )
{
m_attModel.loadSettings(_this, "att" );
m_holdModel.loadSettings( _this, "hold" );
m_susModel.loadSettings( _this, "sus" );
m_decModel.loadSettings( _this, "dec" );
m_startFreqModel.loadSettings( _this, "startFreq" );
m_minFreqModel.loadSettings( _this, "minFreq" );
m_slideModel.loadSettings( _this, "slide" );
m_dSlideModel.loadSettings( _this, "dSlide" );
m_vibDepthModel.loadSettings( _this, "vibDepth" );
m_vibSpeedModel.loadSettings( _this, "vibSpeed" );
m_changeAmtModel.loadSettings( _this, "changeAmt" );
m_changeSpeedModel.loadSettings( _this, "changeSpeed" );
m_sqrDutyModel.loadSettings( _this, "sqrDuty" );
m_sqrSweepModel.loadSettings( _this, "sqrSweep" );
m_repeatSpeedModel.loadSettings( _this, "repeatSpeed" );
m_phaserOffsetModel.loadSettings( _this, "phaserOffset" );
m_phaserSweepModel.loadSettings( _this, "phaserSweep" );
m_lpFilCutModel.loadSettings( _this, "lpFilCut" );
m_lpFilCutSweepModel.loadSettings( _this, "lpFilCutSweep" );
m_lpFilResoModel.loadSettings( _this, "lpFilReso" );
m_hpFilCutModel.loadSettings( _this, "hpFilCut" );
m_hpFilCutSweepModel.loadSettings( _this, "hpFilCutSweep" );
m_waveFormModel.loadSettings( _this, "waveForm" );
}
QString SfxrInstrument::nodeName() const
{
return( sfxr_plugin_descriptor.name );
}
void SfxrInstrument::playNote( NotePlayHandle * _n, SampleFrame* _working_buffer )
{
float currentSampleRate = Engine::audioEngine()->outputSampleRate();
fpp_t frameNum = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
if (!_n->m_pluginData)
{
_n->m_pluginData = new SfxrSynth( this );
}
else if( static_cast<SfxrSynth*>(_n->m_pluginData)->isPlaying() == false )
{
zeroSampleFrames(_working_buffer + offset, frameNum);
_n->noteOff();
return;
}
const auto baseFreq = instrumentTrack()->baseFreq();
int32_t pitchedFrameNum = (_n->frequency() / baseFreq) * frameNum;
pitchedFrameNum /= ( currentSampleRate / 44100 );
// debug code
// qDebug( "pFN %d", pitchedFrameNum );
auto pitchedBuffer = new SampleFrame[pitchedFrameNum];
static_cast<SfxrSynth*>(_n->m_pluginData)->update( pitchedBuffer, pitchedFrameNum );
for( fpp_t i=0; i<frameNum; i++ )
{
for( ch_cnt_t j=0; j<DEFAULT_CHANNELS; j++ )
{
_working_buffer[i+offset][j] = pitchedBuffer[i*pitchedFrameNum/frameNum][j];
}
}
delete[] pitchedBuffer;
applyRelease( _working_buffer, _n );
}
void SfxrInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<SfxrSynth *>( _n->m_pluginData );
}
gui::PluginView * SfxrInstrument::instantiateView( QWidget * _parent )
{
return( new gui::SfxrInstrumentView( this, _parent ) );
}
void SfxrInstrument::resetModels()
{
m_attModel.reset();
m_holdModel.reset();
m_susModel.reset();
m_decModel.reset();
m_startFreqModel.reset();
m_minFreqModel.reset();
m_slideModel.reset();
m_dSlideModel.reset();
m_vibDepthModel.reset();
m_vibSpeedModel.reset();
m_changeAmtModel.reset();
m_changeSpeedModel.reset();
m_sqrDutyModel.reset();
m_sqrSweepModel.reset();
m_repeatSpeedModel.reset();
m_phaserOffsetModel.reset();
m_phaserSweepModel.reset();
m_lpFilCutModel.reset();
m_lpFilCutSweepModel.reset();
m_lpFilResoModel.reset();
m_hpFilCutModel.reset();
m_hpFilCutSweepModel.reset();
m_waveFormModel.reset();
}
namespace gui
{
class SfxrKnob : public Knob
{
public:
SfxrKnob( QWidget * _parent ) :
Knob( KnobType::Styled, _parent )
{
setFixedSize( 20, 20 );
setCenterPointX( 10.0 );
setCenterPointY( 10.0 );
setTotalAngle( 270.0 );
setLineWidth( 1 );
}
};
#define createKnob( _knob, _x, _y, _name )\
_knob = new SfxrKnob( this ); \
_knob->setHintText( tr( _name ":" ), "" ); \
_knob->move( _x, _y ); \
_knob->setToolTip(tr(_name));
#define createButton( _button, _x, _y, _name, _resName )\
_button = new PixmapButton( this, tr( _name ) );\
_button->move( _x, _y );\
_button->setActiveGraphic( embed::getIconPixmap( _resName "_active" ) );\
_button->setInactiveGraphic( embed::getIconPixmap( _resName "_inactive" ) );\
_button->setToolTip(tr(_name));
#define createButtonLocalGraphic( _button, _x, _y, _name, _resName )\
_button = new PixmapButton( this, tr( _name ) );\
_button->move( _x, _y );\
_button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( _resName "_active" ) );\
_button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( _resName "_inactive" ) );\
_button->setToolTip(tr(_name));
SfxrInstrumentView::SfxrInstrumentView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
srand(time(nullptr));
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
createKnob(m_attKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*0, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*0, "Attack Time");
createKnob(m_holdKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*1, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*0, "Sustain Time");
createKnob(m_susKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*2, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*0, "Sustain Punch");
createKnob(m_decKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*3, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*0, "Decay Time");
m_attKnob ->setObjectName( "envKnob" );
m_holdKnob ->setObjectName( "envKnob" );
m_susKnob ->setObjectName( "envKnob" );
m_decKnob ->setObjectName( "envKnob" );
createKnob(m_startFreqKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*0, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*1, "Start Frequency");
createKnob(m_minFreqKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*1, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*1, "Min Frequency");
createKnob(m_slideKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*2, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*1, "Slide");
createKnob(m_dSlideKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*3, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*1, "Delta Slide");
createKnob(m_vibDepthKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*4, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*1, "Vibrato Depth");
createKnob(m_vibSpeedKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*5, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*1, "Vibrato Speed");
m_startFreqKnob ->setObjectName( "freqKnob" );
m_minFreqKnob ->setObjectName( "freqKnob" );
m_slideKnob ->setObjectName( "freqKnob" );
m_dSlideKnob ->setObjectName( "freqKnob" );
m_vibDepthKnob ->setObjectName( "freqKnob" );
m_vibSpeedKnob ->setObjectName( "freqKnob" );
createKnob(m_changeAmtKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*0, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*2, "Change Amount");
createKnob(m_changeSpeedKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*1, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*2, "Change Speed");
m_changeAmtKnob ->setObjectName( "changeKnob" );
m_changeSpeedKnob ->setObjectName( "changeKnob" );
createKnob(m_sqrDutyKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*3, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*2, "Square Duty (Square wave only)");
createKnob(m_sqrSweepKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*4, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*2, "Duty Sweep (Square wave only)");
m_sqrDutyKnob ->setObjectName( "sqrKnob" );
m_sqrSweepKnob ->setObjectName( "sqrKnob" );
createKnob(m_repeatSpeedKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*0, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*3, "Repeat Speed");
m_repeatSpeedKnob ->setObjectName( "repeatKnob" );
createKnob(m_phaserOffsetKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*3, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*3, "Phaser Offset");
createKnob(m_phaserSweepKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*4, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*3, "Phaser Sweep");
m_phaserOffsetKnob ->setObjectName( "phaserKnob" );
m_phaserSweepKnob ->setObjectName( "phaserKnob" );
createKnob(m_lpFilCutKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*0, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*4, "LP Filter Cutoff");
createKnob(m_lpFilCutSweepKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*1, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*4, "LP Filter Cutoff Sweep");
createKnob(m_lpFilResoKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*2, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*4, "LP Filter Resonance");
createKnob(m_hpFilCutKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*3, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*4, "HP Filter Cutoff");
createKnob(m_hpFilCutSweepKnob, KNOBS_BASE_X+KNOB_BLOCK_SIZE_X*4, KNOBS_BASE_Y+KNOB_BLOCK_SIZE_Y*4, "HP Filter Cutoff Sweep");
m_lpFilCutKnob ->setObjectName( "filterKnob" );
m_lpFilCutSweepKnob ->setObjectName( "filterKnob" );
m_lpFilResoKnob ->setObjectName( "filterKnob" );
m_hpFilCutKnob ->setObjectName( "filterKnob" );
m_hpFilCutSweepKnob ->setObjectName( "filterKnob" );
createButtonLocalGraphic(m_sqrWaveBtn, KNOBS_BASE_X+WAVEFORM_BUTTON_WIDTH*0, WAVEFORM_BASE_Y, "Square Wave", "sfxr_square_wave");
createButtonLocalGraphic(m_sawWaveBtn, KNOBS_BASE_X+WAVEFORM_BUTTON_WIDTH*1, WAVEFORM_BASE_Y, "Saw Wave", "sfxr_saw_wave");
createButtonLocalGraphic(m_sinWaveBtn, KNOBS_BASE_X+WAVEFORM_BUTTON_WIDTH*2, WAVEFORM_BASE_Y, "Sine Wave", "sfxr_sin_wave");
createButtonLocalGraphic(m_noiseWaveBtn, KNOBS_BASE_X+WAVEFORM_BUTTON_WIDTH*3, WAVEFORM_BASE_Y, "Noise", "sfxr_white_noise_wave");
m_waveBtnGroup = new automatableButtonGroup( this );
m_waveBtnGroup->addButton(m_sqrWaveBtn);
m_waveBtnGroup->addButton(m_sawWaveBtn);
m_waveBtnGroup->addButton(m_sinWaveBtn);
m_waveBtnGroup->addButton(m_noiseWaveBtn);
createButtonLocalGraphic(m_pickupBtn, GENERATOR_BASE_X+GENERATOR_BUTTON_WIDTH*0, GENERATOR_BASE_Y, "Generate pick up/coin sfx", "pickup");
createButtonLocalGraphic(m_laserBtn, GENERATOR_BASE_X+GENERATOR_BUTTON_WIDTH*1, GENERATOR_BASE_Y, "Generate laser/shoot sfx", "laser");
createButtonLocalGraphic(m_explosionBtn, GENERATOR_BASE_X+GENERATOR_BUTTON_WIDTH*2, GENERATOR_BASE_Y, "Generate explosion sfx", "explosion");
createButtonLocalGraphic(m_powerupBtn, GENERATOR_BASE_X+GENERATOR_BUTTON_WIDTH*3, GENERATOR_BASE_Y, "Generate power up sfx", "powerup");
createButtonLocalGraphic(m_hitBtn, GENERATOR_BASE_X+GENERATOR_BUTTON_WIDTH*4, GENERATOR_BASE_Y, "Generate hit/hurt sfx", "hit");
createButtonLocalGraphic(m_jumpBtn, GENERATOR_BASE_X+GENERATOR_BUTTON_WIDTH*5, GENERATOR_BASE_Y, "Generate jump sfx", "jump");
createButtonLocalGraphic(m_blipBtn, GENERATOR_BASE_X+GENERATOR_BUTTON_WIDTH*6, GENERATOR_BASE_Y, "Generate blip/select sfx", "blip");
connect( m_pickupBtn, SIGNAL ( clicked() ), this, SLOT ( genPickup() ) );
connect( m_laserBtn, SIGNAL ( clicked() ), this, SLOT ( genLaser() ) );
connect( m_explosionBtn, SIGNAL ( clicked() ), this, SLOT ( genExplosion() ) );
connect( m_powerupBtn, SIGNAL ( clicked() ), this, SLOT ( genPowerup() ) );
connect( m_hitBtn, SIGNAL ( clicked() ), this, SLOT ( genHit() ) );
connect( m_jumpBtn, SIGNAL ( clicked() ), this, SLOT ( genJump() ) );
connect( m_blipBtn, SIGNAL ( clicked() ), this, SLOT ( genBlip() ) );
createButtonLocalGraphic(m_randomizeBtn, RAND_BUTTON_X, RAND_BUTTON_Y, "Generate random sfx", "randomize");
createButtonLocalGraphic(m_mutateBtn, MUTA_BUTTON_X, MUTA_BUTTON_Y, "Mutate sfx", "mutate");
connect( m_randomizeBtn, SIGNAL ( clicked() ), this, SLOT ( randomize() ) );
connect( m_mutateBtn, SIGNAL ( clicked() ), this, SLOT ( mutate() ) );
//preview sound on generator/random/mutate button clicked
/* // disabled for now
connect( m_pickupBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
connect( m_laserBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
connect( m_explosionBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
connect( m_powerupBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
connect( m_hitBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
connect( m_jumpBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
connect( m_blipBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
connect( m_randomizeBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
connect( m_mutateBtn, SIGNAL ( clicked() ), this, SLOT ( previewSound() ) );
*/
}
void SfxrInstrumentView::modelChanged()
{
auto s = castModel<SfxrInstrument>();
m_attKnob->setModel( &s->m_attModel );
m_holdKnob->setModel( &s->m_holdModel );
m_susKnob->setModel( &s->m_susModel );
m_decKnob->setModel( &s->m_decModel );
m_startFreqKnob->setModel( &s->m_startFreqModel );
m_minFreqKnob->setModel( &s->m_minFreqModel );
m_slideKnob->setModel( &s->m_slideModel );
m_dSlideKnob->setModel( &s->m_dSlideModel );
m_vibDepthKnob->setModel( &s->m_vibDepthModel );
m_vibSpeedKnob->setModel( &s->m_vibSpeedModel );
m_changeAmtKnob->setModel( &s->m_changeAmtModel );
m_changeSpeedKnob->setModel( &s->m_changeSpeedModel );
m_sqrDutyKnob->setModel( &s->m_sqrDutyModel );
m_sqrSweepKnob->setModel( &s->m_sqrSweepModel );
m_repeatSpeedKnob->setModel( &s->m_repeatSpeedModel );
m_phaserOffsetKnob->setModel( &s->m_phaserOffsetModel );
m_phaserSweepKnob->setModel( &s->m_phaserSweepModel );
m_lpFilCutKnob->setModel( &s->m_lpFilCutModel );
m_lpFilCutSweepKnob->setModel( &s->m_lpFilCutSweepModel );
m_lpFilResoKnob->setModel( &s->m_lpFilResoModel );
m_hpFilCutKnob->setModel( &s->m_hpFilCutModel );
m_hpFilCutSweepKnob->setModel( &s->m_hpFilCutSweepModel );
m_waveBtnGroup->setModel( &s->m_waveFormModel );
}
void SfxrInstrumentView::genPickup()
{
auto s = castModel<SfxrInstrument>();
s->resetModels();
s->m_startFreqModel.setValue( 0.4f+frnd(0.5f) );
s->m_attModel.setValue( 0.0f );
s->m_holdModel.setValue( frnd(0.1f) );
s->m_decModel.setValue( 0.1f+frnd(0.4f) );
s->m_susModel.setValue( 0.3f+frnd(0.3f) );
if(rnd(1))
{
s->m_changeSpeedModel.setValue( 0.5f+frnd(0.2f) );
s->m_changeAmtModel.setValue( 0.2f+frnd(0.4f) );
}
}
void SfxrInstrumentView::genLaser()
{
auto s = castModel<SfxrInstrument>();
s->resetModels();
s->m_waveFormModel.setValue( rnd(2) );
if(s->m_waveFormModel.value()==2 && rnd(1))
s->m_waveFormModel.setValue( rnd(1) );
s->m_startFreqModel.setValue( 0.5f+frnd(0.5f) );
s->m_minFreqModel.setValue( s->m_startFreqModel.value()-0.2f-frnd(0.6f) );
if(s->m_minFreqModel.value()<0.2f)
{
s->m_minFreqModel.setValue(0.2f);
}
s->m_slideModel.setValue( -0.15f-frnd(0.2f) );
if(rnd(2)==0)
{
s->m_startFreqModel.setValue( 0.3f+frnd(0.6f) );
s->m_minFreqModel.setValue( frnd(0.1f) );
s->m_slideModel.setValue( -0.35f-frnd(0.3f) );
}
if(rnd(1))
{
s->m_sqrDutyModel.setValue( frnd(0.5f) );
s->m_sqrSweepModel.setValue( 0.2f );
}
else
{
s->m_sqrDutyModel.setValue( 0.4f+frnd(0.5f) );
s->m_sqrSweepModel.setValue( -frnd(0.7f) );
}
s->m_attModel.setValue( 0.0f );
s->m_holdModel.setValue( 0.1f+frnd(0.2f) );
s->m_decModel.setValue( frnd(0.4f) );
if(rnd(1))
{
s->m_susModel.setValue( frnd(0.3f) );
}
if(rnd(2)==0)
{
s->m_phaserOffsetModel.setValue( frnd(0.2f) );
s->m_phaserSweepModel.setValue( -frnd(0.2f) );
}
if(rnd(1))
s->m_hpFilCutModel.setValue( frnd(0.3f) );
}
void SfxrInstrumentView::genExplosion()
{
auto s = castModel<SfxrInstrument>();
s->resetModels();
s->m_waveFormModel.setValue( 3 );
if(rnd(1))
{
s->m_startFreqModel.setValue( 0.1f+frnd(0.4f) );
s->m_slideModel.setValue( -0.1f+frnd(0.4f) );
}
else
{
s->m_startFreqModel.setValue( 0.2f+frnd(0.7f) );
s->m_slideModel.setValue( -0.2f-frnd(0.2f) );
}
s->m_startFreqModel.setValue( s->m_startFreqModel.value()*s->m_startFreqModel.value() );
if(rnd(4)==0)
{
s->m_slideModel.setValue( 0.0f );
}
if(rnd(2)==0)
{
s->m_repeatSpeedModel.setValue( 0.3f+frnd(0.5f) );
}
s->m_attModel.setValue( 0.0f );
s->m_holdModel.setValue( 0.1f+frnd(0.3f) );
s->m_decModel.setValue( 0.5f );
if(rnd(1)==0)
{
s->m_phaserOffsetModel.setValue( -0.3f+frnd(0.9f) );
s->m_phaserSweepModel.setValue( -frnd(0.3f) );
}
s->m_susModel.setValue( 0.2f+frnd(0.6f) );
if(rnd(1))
{
s->m_vibDepthModel.setValue( frnd(0.7f) );
s->m_vibSpeedModel.setValue( frnd(0.6f) );
}
if(rnd(2)==0)
{
s->m_changeSpeedModel.setValue( 0.6f+frnd(0.3f) );
s->m_changeAmtModel.setValue( 0.8f-frnd(1.6f) );
}
}
void SfxrInstrumentView::genPowerup()
{
auto s = castModel<SfxrInstrument>();
s->resetModels();
if(rnd(1))
s->m_waveFormModel.setValue( 1 );
else
s->m_sqrDutyModel.setValue( frnd(0.6f) );
if(rnd(1))
{
s->m_startFreqModel.setValue( 0.2f+frnd(0.3f) );
s->m_slideModel.setValue( 0.1f+frnd(0.4f) );
s->m_repeatSpeedModel.setValue( 0.4f+frnd(0.4f) );
}
else
{
s->m_startFreqModel.setValue( 0.2f+frnd(0.3f) );
s->m_slideModel.setValue( 0.05f+frnd(0.2f) );
if(rnd(1))
{
s->m_vibDepthModel.setValue( frnd(0.7f) );
s->m_vibSpeedModel.setValue( frnd(0.6f) );
}
}
s->m_attModel.setValue( 0.0f );
s->m_holdModel.setValue( frnd(0.4f) );
s->m_decModel.setValue( 0.1f+frnd(0.4f) );
}
void SfxrInstrumentView::genHit()
{
auto s = castModel<SfxrInstrument>();
s->resetModels();
s->m_waveFormModel.setValue( rnd(2) );
if(s->m_waveFormModel.value()==2)
{
s->m_waveFormModel.setValue( 3 );
}
if(s->m_waveFormModel.value()==0)
{
s->m_sqrDutyModel.setValue( frnd(0.6f) );
}
s->m_startFreqModel.setValue( 0.2f+frnd(0.6f) );
s->m_slideModel.setValue( -0.3f-frnd(0.4f) );
s->m_attModel.setValue( 0.0f );
s->m_holdModel.setValue( frnd(0.1f) );
s->m_decModel.setValue( 0.1f+frnd(0.2f) );
if(rnd(1))
{
s->m_hpFilCutModel.setValue( frnd(0.3f) );
}
}
void SfxrInstrumentView::genJump()
{
auto s = castModel<SfxrInstrument>();
s->resetModels();
s->m_waveFormModel.setValue( 0 );
s->m_sqrDutyModel.setValue( frnd(0.6f) );
s->m_startFreqModel.setValue( 0.3f+frnd(0.3f) );
s->m_slideModel.setValue( 0.1f+frnd(0.2f) );
s->m_attModel.setValue( 0.0f );
s->m_holdModel.setValue( 0.1f+frnd(0.3f) );
s->m_decModel.setValue( 0.1f+frnd(0.2f) );
if(rnd(1))
{
s->m_hpFilCutModel.setValue( frnd(0.3f) );
}
if(rnd(1))
{
s->m_lpFilCutModel.setValue( 1.0f-frnd(0.6f) );
}
}
void SfxrInstrumentView::genBlip()
{
auto s = castModel<SfxrInstrument>();
s->resetModels();
s->m_waveFormModel.setValue( rnd(1) );
if( s->m_waveFormModel.value()==0 )
{
s->m_sqrDutyModel.setValue( frnd(0.6f) );
}
s->m_startFreqModel.setValue( 0.2f+frnd(0.4f) );
s->m_attModel.setValue( 0.0f );
s->m_holdModel.setValue( 0.1f+frnd(0.1f) );
s->m_decModel.setValue( frnd(0.2f) );
s->m_hpFilCutModel.setValue( 0.1f );
}
void SfxrInstrumentView::randomize()
{
auto s = castModel<SfxrInstrument>();
s->m_startFreqModel.setValue( pow(frnd(2.0f)-1.0f, 2.0f) );
if(rnd(1))
{
s->m_startFreqModel.setValue( pow(frnd(2.0f)-1.0f, 3.0f)+0.5f );
}
s->m_minFreqModel.setValue( 0.0f );
s->m_slideModel.setValue( pow(frnd(2.0f)-1.0f, 5.0f) );
if( s->m_startFreqModel.value()>0.7f && s->m_slideModel.value()>0.2f )
{
s->m_slideModel.setValue( -s->m_slideModel.value() );
}
if( s->m_startFreqModel.value()<0.2f && s->m_slideModel.value()<-0.05f )
{
s->m_slideModel.setValue( -s->m_slideModel.value() );
}
s->m_dSlideModel.setValue( pow(frnd(2.0f)-1.0f, 3.0f) );
s->m_sqrDutyModel.setValue( frnd(2.0f)-1.0f );
s->m_sqrSweepModel.setValue( pow(frnd(2.0f)-1.0f, 3.0f) );
s->m_vibDepthModel.setValue( pow(frnd(2.0f)-1.0f, 3.0f) );
s->m_vibSpeedModel.setValue( frnd(2.0f)-1.0f );
//s->m_vibDelayModel.setValue( frnd(2.0f)-1.0f );
s->m_attModel.setValue( pow(frnd(2.0f)-1.0f, 3.0f) );
s->m_holdModel.setValue( pow(frnd(2.0f)-1.0f, 2.0f) );
s->m_decModel.setValue( frnd(2.0f)-1.0f );
s->m_susModel.setValue( pow(frnd(0.8f), 2.0f) );
if(s->m_attModel.value()+s->m_holdModel.value()+s->m_decModel.value()<0.2f)
{
s->m_holdModel.setValue( s->m_holdModel.value()+0.2f+frnd(0.3f) );
s->m_decModel.setValue( s->m_decModel.value()+0.2f+frnd(0.3f) );
}
s->m_lpFilResoModel.setValue( frnd(2.0f)-1.0f );
s->m_lpFilCutModel.setValue( 1.0f-pow(frnd(1.0f), 3.0f) );
s->m_lpFilCutSweepModel.setValue( pow(frnd(2.0f)-1.0f, 3.0f) );
if(s->m_lpFilCutModel.value()<0.1f && s->m_lpFilCutSweepModel.value()<-0.05f)
{
s->m_lpFilCutSweepModel.setValue( -s->m_lpFilCutSweepModel.value() );
}
s->m_hpFilCutModel.setValue( pow(frnd(1.0f), 5.0f) );
s->m_hpFilCutSweepModel.setValue( pow(frnd(2.0f)-1.0f, 5.0f) );
s->m_phaserOffsetModel.setValue( pow(frnd(2.0f)-1.0f, 3.0f) );
s->m_phaserSweepModel.setValue( pow(frnd(2.0f)-1.0f, 3.0f) );
s->m_repeatSpeedModel.setValue( frnd(2.0f)-1.0f );
s->m_changeSpeedModel.setValue( frnd(2.0f)-1.0f );
s->m_changeAmtModel.setValue( frnd(2.0f)-1.0f );
}
void SfxrInstrumentView::mutate()
{
auto s = castModel<SfxrInstrument>();
if(rnd(1)) s->m_startFreqModel.setValue( s->m_startFreqModel.value()+frnd(0.1f)-0.05f );
// if(rnd(1)) s->m_minFreqModel.setValue( s->m_minFreqModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_slideModel.setValue( s->m_slideModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_dSlideModel.setValue( s->m_dSlideModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_sqrDutyModel.setValue( s->m_sqrDutyModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_sqrSweepModel.setValue( s->m_sqrSweepModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_vibDepthModel.setValue( s->m_vibDepthModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_vibSpeedModel.setValue( s->m_vibSpeedModel.value()+frnd(0.1f)-0.05f );
// if(rnd(1)) s->m_vibDelayModel.setValue( s->m_vibDelayModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_attModel.setValue( s->m_attModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_holdModel.setValue( s->m_holdModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_decModel.setValue( s->m_decModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_susModel.setValue( s->m_susModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_lpFilResoModel.setValue( s->m_lpFilResoModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_lpFilCutModel.setValue( s->m_lpFilCutModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_lpFilCutSweepModel.setValue( s->m_lpFilCutSweepModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_hpFilCutModel.setValue( s->m_hpFilCutModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_hpFilCutSweepModel.setValue( s->m_hpFilCutSweepModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_phaserOffsetModel.setValue( s->m_phaserOffsetModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_phaserSweepModel.setValue( s->m_phaserSweepModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_repeatSpeedModel.setValue( s->m_repeatSpeedModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_changeSpeedModel.setValue( s->m_changeSpeedModel.value()+frnd(0.1f)-0.05f );
if(rnd(1)) s->m_changeAmtModel.setValue( s->m_changeAmtModel.value()+frnd(0.1f)-0.05f );
}
void SfxrInstrumentView::previewSound()
{
auto s = castModel<SfxrInstrument>();
InstrumentTrack* it = s->instrumentTrack();
it->silenceAllNotes();
it->processInEvent( MidiEvent( MidiNoteOn, 0, it->baseNoteModel()->value(), MidiDefaultVelocity ) );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* m, void* )
{
return new SfxrInstrument( static_cast<InstrumentTrack *>( m ) );
}
}
} // namespace lmms
| 32,790
|
C++
|
.cpp
| 861
| 35.39489
| 142
| 0.69945
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,638
|
TripleOscillator.cpp
|
LMMS_lmms/plugins/TripleOscillator/TripleOscillator.cpp
|
/*
* TripleOscillator.cpp - powerful instrument with three oscillators
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include <QFileInfo>
#include "TripleOscillator.h"
#include "AudioEngine.h"
#include "AutomatableButton.h"
#include "debug.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "NotePlayHandle.h"
#include "Oscillator.h"
#include "PathUtil.h"
#include "PixmapButton.h"
#include "SampleBuffer.h"
#include "SampleLoader.h"
#include "Song.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT tripleoscillator_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"TripleOscillator",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Three powerful oscillators you can modulate "
"in several ways" ),
"Tobias Doerffel <tobydox/at/users.sf.net>",
0x0110,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
OscillatorObject::OscillatorObject( Model * _parent, int _idx ) :
Model( _parent ),
m_volumeModel( DefaultVolume / NUM_OF_OSCILLATORS, MinVolume,
MaxVolume, 1.0f, this, tr( "Osc %1 volume" ).arg( _idx+1 ) ),
m_panModel( DefaultPanning, PanningLeft, PanningRight, 1.0f, this,
tr( "Osc %1 panning" ).arg( _idx+1 ) ),
m_coarseModel( -_idx*KeysPerOctave,
-2 * KeysPerOctave, 2 * KeysPerOctave, 1.0f, this,
tr( "Osc %1 coarse detuning" ).arg( _idx+1 ) ),
m_fineLeftModel( 0.0f, -100.0f, 100.0f, 1.0f, this,
tr( "Osc %1 fine detuning left" ).arg( _idx+1 ) ),
m_fineRightModel( 0.0f, -100.0f, 100.0f, 1.0f, this,
tr( "Osc %1 fine detuning right" ).arg( _idx + 1 ) ),
m_phaseOffsetModel( 0.0f, 0.0f, 360.0f, 1.0f, this,
tr( "Osc %1 phase-offset" ).arg( _idx+1 ) ),
m_stereoPhaseDetuningModel( 0.0f, 0.0f, 360.0f, 1.0f, this,
tr( "Osc %1 stereo phase-detuning" ).arg( _idx+1 ) ),
m_waveShapeModel( static_cast<int>(Oscillator::WaveShape::Sine), 0,
Oscillator::NumWaveShapes-1, this,
tr( "Osc %1 wave shape" ).arg( _idx+1 ) ),
m_modulationAlgoModel( static_cast<int>(Oscillator::ModulationAlgo::SignalMix), 0,
Oscillator::NumModulationAlgos-1, this,
tr( "Modulation type %1" ).arg( _idx+1 ) ),
m_useWaveTableModel(true),
m_sampleBuffer( new SampleBuffer ),
m_volumeLeft( 0.0f ),
m_volumeRight( 0.0f ),
m_detuningLeft( 0.0f ),
m_detuningRight( 0.0f ),
m_phaseOffsetLeft( 0.0f ),
m_phaseOffsetRight( 0.0f ),
m_useWaveTable( true )
{
// Connect knobs with Oscillators' inputs
connect( &m_volumeModel, SIGNAL( dataChanged() ),
this, SLOT( updateVolume() ), Qt::DirectConnection );
connect( &m_panModel, SIGNAL( dataChanged() ),
this, SLOT( updateVolume() ), Qt::DirectConnection );
updateVolume();
connect( &m_coarseModel, SIGNAL( dataChanged() ),
this, SLOT( updateDetuningLeft() ), Qt::DirectConnection );
connect( &m_coarseModel, SIGNAL( dataChanged() ),
this, SLOT( updateDetuningRight() ), Qt::DirectConnection );
connect( &m_fineLeftModel, SIGNAL( dataChanged() ),
this, SLOT( updateDetuningLeft() ), Qt::DirectConnection );
connect( &m_fineRightModel, SIGNAL( dataChanged() ),
this, SLOT( updateDetuningRight() ), Qt::DirectConnection );
updateDetuningLeft();
updateDetuningRight();
connect( &m_phaseOffsetModel, SIGNAL( dataChanged() ),
this, SLOT( updatePhaseOffsetLeft() ), Qt::DirectConnection );
connect( &m_phaseOffsetModel, SIGNAL( dataChanged() ),
this, SLOT( updatePhaseOffsetRight() ), Qt::DirectConnection );
connect( &m_stereoPhaseDetuningModel, SIGNAL( dataChanged() ),
this, SLOT( updatePhaseOffsetLeft() ), Qt::DirectConnection );
connect ( &m_useWaveTableModel, SIGNAL(dataChanged()),
this, SLOT( updateUseWaveTable()));
updatePhaseOffsetLeft();
updatePhaseOffsetRight();
}
void OscillatorObject::oscUserDefWaveDblClick()
{
auto af = gui::SampleLoader::openWaveformFile();
if( af != "" )
{
m_sampleBuffer = gui::SampleLoader::createBufferFromFile(af);
m_userAntiAliasWaveTable = Oscillator::generateAntiAliasUserWaveTable(m_sampleBuffer.get());
// TODO:
//m_usrWaveBtn->setToolTip(m_sampleBuffer->audioFile());
}
}
void OscillatorObject::updateVolume()
{
if( m_panModel.value() >= 0.0f )
{
const float panningFactorLeft = 1.0f - m_panModel.value()
/ (float)PanningRight;
m_volumeLeft = panningFactorLeft * m_volumeModel.value() /
100.0f;
m_volumeRight = m_volumeModel.value() / 100.0f;
}
else
{
m_volumeLeft = m_volumeModel.value() / 100.0f;
const float panningFactorRight = 1.0f + m_panModel.value()
/ (float)PanningRight;
m_volumeRight = panningFactorRight * m_volumeModel.value() /
100.0f;
}
}
void OscillatorObject::updateDetuningLeft()
{
m_detuningLeft = powf( 2.0f, ( (float)m_coarseModel.value() * 100.0f
+ (float)m_fineLeftModel.value() ) / 1200.0f )
/ Engine::audioEngine()->outputSampleRate();
}
void OscillatorObject::updateDetuningRight()
{
m_detuningRight = powf( 2.0f, ( (float)m_coarseModel.value() * 100.0f
+ (float)m_fineRightModel.value() ) / 1200.0f )
/ Engine::audioEngine()->outputSampleRate();
}
void OscillatorObject::updatePhaseOffsetLeft()
{
m_phaseOffsetLeft = ( m_phaseOffsetModel.value() +
m_stereoPhaseDetuningModel.value() ) / 360.0f;
}
void OscillatorObject::updatePhaseOffsetRight()
{
m_phaseOffsetRight = m_phaseOffsetModel.value() / 360.0f;
}
void OscillatorObject::updateUseWaveTable()
{
m_useWaveTable = m_useWaveTableModel.value();
}
TripleOscillator::TripleOscillator( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &tripleoscillator_plugin_descriptor )
{
for( int i = 0; i < NUM_OF_OSCILLATORS; ++i )
{
m_osc[i] = new OscillatorObject( this, i );
}
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ),
this, SLOT( updateAllDetuning() ) );
}
void TripleOscillator::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
for( int i = 0; i < NUM_OF_OSCILLATORS; ++i )
{
QString is = QString::number( i );
m_osc[i]->m_volumeModel.saveSettings( _doc, _this, "vol" + is );
m_osc[i]->m_panModel.saveSettings( _doc, _this, "pan" + is );
m_osc[i]->m_coarseModel.saveSettings( _doc, _this, "coarse"
+ is );
m_osc[i]->m_fineLeftModel.saveSettings( _doc, _this, "finel" +
is );
m_osc[i]->m_fineRightModel.saveSettings( _doc, _this, "finer" +
is );
m_osc[i]->m_phaseOffsetModel.saveSettings( _doc, _this,
"phoffset" + is );
m_osc[i]->m_stereoPhaseDetuningModel.saveSettings( _doc, _this,
"stphdetun" + is );
m_osc[i]->m_waveShapeModel.saveSettings( _doc, _this,
"wavetype" + is );
m_osc[i]->m_modulationAlgoModel.saveSettings( _doc, _this,
"modalgo" + QString::number( i+1 ) );
m_osc[i]->m_useWaveTableModel.saveSettings( _doc, _this,
"useWaveTable" + QString::number (i+1 ) );
_this.setAttribute( "userwavefile" + is,
m_osc[i]->m_sampleBuffer->audioFile() );
}
}
void TripleOscillator::loadSettings( const QDomElement & _this )
{
for( int i = 0; i < NUM_OF_OSCILLATORS; ++i )
{
const QString is = QString::number( i );
m_osc[i]->m_volumeModel.loadSettings( _this, "vol" + is );
m_osc[i]->m_panModel.loadSettings( _this, "pan" + is );
m_osc[i]->m_coarseModel.loadSettings( _this, "coarse" + is );
m_osc[i]->m_fineLeftModel.loadSettings( _this, "finel" + is );
m_osc[i]->m_fineRightModel.loadSettings( _this, "finer" + is );
m_osc[i]->m_phaseOffsetModel.loadSettings( _this,
"phoffset" + is );
m_osc[i]->m_stereoPhaseDetuningModel.loadSettings( _this,
"stphdetun" + is );
m_osc[i]->m_waveShapeModel.loadSettings( _this, "wavetype" +
is );
m_osc[i]->m_modulationAlgoModel.loadSettings( _this,
"modalgo" + QString::number( i+1 ) );
m_osc[i]->m_useWaveTableModel.loadSettings( _this,
"useWaveTable" + QString::number (i+1 ) );
if (auto userWaveFile = _this.attribute("userwavefile" + is); !userWaveFile.isEmpty())
{
if (QFileInfo(PathUtil::toAbsolute(userWaveFile)).exists())
{
m_osc[i]->m_sampleBuffer = gui::SampleLoader::createBufferFromFile(userWaveFile);
m_osc[i]->m_userAntiAliasWaveTable = Oscillator::generateAntiAliasUserWaveTable(m_osc[i]->m_sampleBuffer.get());
}
else { Engine::getSong()->collectError(QString("%1: %2").arg(tr("Sample not found"), userWaveFile)); }
}
}
}
QString TripleOscillator::nodeName() const
{
return( tripleoscillator_plugin_descriptor.name );
}
void TripleOscillator::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
if (!_n->m_pluginData)
{
auto oscs_l = std::array<Oscillator*, NUM_OF_OSCILLATORS>{};
auto oscs_r = std::array<Oscillator*, NUM_OF_OSCILLATORS>{};
for( int i = NUM_OF_OSCILLATORS - 1; i >= 0; --i )
{
// the last oscs needs no sub-oscs...
if( i == NUM_OF_OSCILLATORS - 1 )
{
oscs_l[i] = new Oscillator(
&m_osc[i]->m_waveShapeModel,
&m_osc[i]->m_modulationAlgoModel,
_n->frequency(),
m_osc[i]->m_detuningLeft,
m_osc[i]->m_phaseOffsetLeft,
m_osc[i]->m_volumeLeft );
oscs_l[i]->setUseWaveTable(m_osc[i]->m_useWaveTable);
oscs_r[i] = new Oscillator(
&m_osc[i]->m_waveShapeModel,
&m_osc[i]->m_modulationAlgoModel,
_n->frequency(),
m_osc[i]->m_detuningRight,
m_osc[i]->m_phaseOffsetRight,
m_osc[i]->m_volumeRight );
oscs_r[i]->setUseWaveTable(m_osc[i]->m_useWaveTable);
}
else
{
oscs_l[i] = new Oscillator(
&m_osc[i]->m_waveShapeModel,
&m_osc[i]->m_modulationAlgoModel,
_n->frequency(),
m_osc[i]->m_detuningLeft,
m_osc[i]->m_phaseOffsetLeft,
m_osc[i]->m_volumeLeft,
oscs_l[i + 1] );
oscs_l[i]->setUseWaveTable(m_osc[i]->m_useWaveTable);
oscs_r[i] = new Oscillator(
&m_osc[i]->m_waveShapeModel,
&m_osc[i]->m_modulationAlgoModel,
_n->frequency(),
m_osc[i]->m_detuningRight,
m_osc[i]->m_phaseOffsetRight,
m_osc[i]->m_volumeRight,
oscs_r[i + 1] );
oscs_r[i]->setUseWaveTable(m_osc[i]->m_useWaveTable);
}
oscs_l[i]->setUserWave( m_osc[i]->m_sampleBuffer );
oscs_r[i]->setUserWave( m_osc[i]->m_sampleBuffer );
oscs_l[i]->setUserAntiAliasWaveTable(m_osc[i]->m_userAntiAliasWaveTable);
oscs_r[i]->setUserAntiAliasWaveTable(m_osc[i]->m_userAntiAliasWaveTable);
}
_n->m_pluginData = new oscPtr;
static_cast<oscPtr *>( _n->m_pluginData )->oscLeft = oscs_l[0];
static_cast< oscPtr *>( _n->m_pluginData )->oscRight =
oscs_r[0];
}
Oscillator * osc_l = static_cast<oscPtr *>( _n->m_pluginData )->oscLeft;
Oscillator * osc_r = static_cast<oscPtr *>( _n->m_pluginData )->oscRight;
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
osc_l->update( _working_buffer + offset, frames, 0 );
osc_r->update( _working_buffer + offset, frames, 1 );
applyFadeIn(_working_buffer, _n);
applyRelease( _working_buffer, _n );
}
void TripleOscillator::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<Oscillator *>( static_cast<oscPtr *>(
_n->m_pluginData )->oscLeft );
delete static_cast<Oscillator *>( static_cast<oscPtr *>(
_n->m_pluginData )->oscRight );
delete static_cast<oscPtr *>( _n->m_pluginData );
}
gui::PluginView* TripleOscillator::instantiateView( QWidget * _parent )
{
return new gui::TripleOscillatorView( this, _parent );
}
void TripleOscillator::updateAllDetuning()
{
for (const auto& osc : m_osc)
{
osc->updateDetuningLeft();
osc->updateDetuningRight();
}
}
namespace gui
{
class TripleOscKnob : public Knob
{
public:
TripleOscKnob( QWidget * _parent ) :
Knob( KnobType::Styled, _parent )
{
setFixedSize( 28, 35 );
}
};
// 82, 109
TripleOscillatorView::TripleOscillatorView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(),
PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
const int mod_x = 66;
const int mod1_y = 58;
const int mod2_y = 75;
const int osc_y = 109;
const int osc_h = 52;
// TODO: clean rewrite using layouts and all that...
auto pm_osc1_btn = new PixmapButton(this, nullptr);
pm_osc1_btn->move( mod_x, mod1_y );
pm_osc1_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"pm_active" ) );
pm_osc1_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"pm_inactive" ) );
pm_osc1_btn->setToolTip(tr("Modulate phase of oscillator 1 by oscillator 2"));
auto am_osc1_btn = new PixmapButton(this, nullptr);
am_osc1_btn->move( mod_x + 35, mod1_y );
am_osc1_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"am_active" ) );
am_osc1_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"am_inactive" ) );
am_osc1_btn->setToolTip(tr("Modulate amplitude of oscillator 1 by oscillator 2"));
auto mix_osc1_btn = new PixmapButton(this, nullptr);
mix_osc1_btn->move( mod_x + 70, mod1_y );
mix_osc1_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"mix_active" ) );
mix_osc1_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"mix_inactive" ) );
mix_osc1_btn->setToolTip(tr("Mix output of oscillators 1 & 2"));
auto sync_osc1_btn = new PixmapButton(this, nullptr);
sync_osc1_btn->move( mod_x + 105, mod1_y );
sync_osc1_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"sync_active" ) );
sync_osc1_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"sync_inactive" ) );
sync_osc1_btn->setToolTip(tr("Synchronize oscillator 1 with "
"oscillator 2" ) );
auto fm_osc1_btn = new PixmapButton(this, nullptr);
fm_osc1_btn->move( mod_x + 140, mod1_y );
fm_osc1_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"fm_active" ) );
fm_osc1_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"fm_inactive" ) );
fm_osc1_btn->setToolTip(tr("Modulate frequency of oscillator 1 by oscillator 2"));
m_mod1BtnGrp = new automatableButtonGroup( this );
m_mod1BtnGrp->addButton( pm_osc1_btn );
m_mod1BtnGrp->addButton( am_osc1_btn );
m_mod1BtnGrp->addButton( mix_osc1_btn );
m_mod1BtnGrp->addButton( sync_osc1_btn );
m_mod1BtnGrp->addButton( fm_osc1_btn );
auto pm_osc2_btn = new PixmapButton(this, nullptr);
pm_osc2_btn->move( mod_x, mod2_y );
pm_osc2_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"pm_active" ) );
pm_osc2_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"pm_inactive" ) );
pm_osc2_btn->setToolTip(tr("Modulate phase of oscillator 2 by oscillator 3"));
auto am_osc2_btn = new PixmapButton(this, nullptr);
am_osc2_btn->move( mod_x + 35, mod2_y );
am_osc2_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"am_active" ) );
am_osc2_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"am_inactive" ) );
am_osc2_btn->setToolTip(tr("Modulate amplitude of oscillator 2 by oscillator 3"));
auto mix_osc2_btn = new PixmapButton(this, nullptr);
mix_osc2_btn->move( mod_x + 70, mod2_y );
mix_osc2_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"mix_active" ) );
mix_osc2_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"mix_inactive" ) );
mix_osc2_btn->setToolTip(tr("Mix output of oscillators 2 & 3"));
auto sync_osc2_btn = new PixmapButton(this, nullptr);
sync_osc2_btn->move( mod_x + 105, mod2_y );
sync_osc2_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"sync_active" ) );
sync_osc2_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"sync_inactive" ) );
sync_osc2_btn->setToolTip(tr("Synchronize oscillator 2 with oscillator 3"));
auto fm_osc2_btn = new PixmapButton(this, nullptr);
fm_osc2_btn->move( mod_x + 140, mod2_y );
fm_osc2_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"fm_active" ) );
fm_osc2_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"fm_inactive" ) );
fm_osc2_btn->setToolTip(tr("Modulate frequency of oscillator 2 by oscillator 3"));
m_mod2BtnGrp = new automatableButtonGroup( this );
m_mod2BtnGrp->addButton( pm_osc2_btn );
m_mod2BtnGrp->addButton( am_osc2_btn );
m_mod2BtnGrp->addButton( mix_osc2_btn );
m_mod2BtnGrp->addButton( sync_osc2_btn );
m_mod2BtnGrp->addButton( fm_osc2_btn );
for( int i = 0; i < NUM_OF_OSCILLATORS; ++i )
{
int knob_y = osc_y + i * osc_h;
// setup volume-knob
auto vk = new Knob(KnobType::Styled, this);
vk->setVolumeKnob( true );
vk->setFixedSize( 28, 35 );
vk->move( 6, knob_y );
vk->setHintText( tr( "Osc %1 volume:" ).arg(
i+1 ), "%" );
// setup panning-knob
Knob * pk = new TripleOscKnob( this );
pk->move( 35, knob_y );
pk->setHintText( tr("Osc %1 panning:").arg( i + 1 ), "" );
// setup coarse-knob
Knob * ck = new TripleOscKnob( this );
ck->move( 82, knob_y );
ck->setHintText( tr( "Osc %1 coarse detuning:" ).arg( i + 1 )
, " " + tr( "semitones" ) );
// setup knob for left fine-detuning
Knob * flk = new TripleOscKnob( this );
flk->move( 111, knob_y );
flk->setHintText( tr( "Osc %1 fine detuning left:" ).
arg( i + 1 ),
" " + tr( "cents" ) );
// setup knob for right fine-detuning
Knob * frk = new TripleOscKnob( this );
frk->move( 140, knob_y );
frk->setHintText( tr( "Osc %1 fine detuning right:" ).
arg( i + 1 ),
" " + tr( "cents" ) );
// setup phase-offset-knob
Knob * pok = new TripleOscKnob( this );
pok->move( 188, knob_y );
pok->setHintText( tr( "Osc %1 phase-offset:" ).
arg( i + 1 ),
" " + tr( "degrees" ) );
// setup stereo-phase-detuning-knob
Knob * spdk = new TripleOscKnob( this );
spdk->move( 217, knob_y );
spdk->setHintText( tr("Osc %1 stereo phase-detuning:" ).
arg( i + 1 ),
" " + tr( "degrees" ) );
int btn_y = 96 + i * osc_h;
auto sin_wave_btn = new PixmapButton(this, nullptr);
sin_wave_btn->move( 128, btn_y );
sin_wave_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"sin_shape_active" ) );
sin_wave_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"sin_shape_inactive" ) );
sin_wave_btn->setToolTip(
tr( "Sine wave" ) );
auto triangle_wave_btn = new PixmapButton(this, nullptr);
triangle_wave_btn->move( 143, btn_y );
triangle_wave_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "triangle_shape_active" ) );
triangle_wave_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "triangle_shape_inactive" ) );
triangle_wave_btn->setToolTip(
tr( "Triangle wave") );
auto saw_wave_btn = new PixmapButton(this, nullptr);
saw_wave_btn->move( 158, btn_y );
saw_wave_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"saw_shape_active" ) );
saw_wave_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"saw_shape_inactive" ) );
saw_wave_btn->setToolTip(
tr( "Saw wave" ) );
auto sqr_wave_btn = new PixmapButton(this, nullptr);
sqr_wave_btn->move( 173, btn_y );
sqr_wave_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"square_shape_active" ) );
sqr_wave_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"square_shape_inactive" ) );
sqr_wave_btn->setToolTip(
tr( "Square wave" ) );
auto moog_saw_wave_btn = new PixmapButton(this, nullptr);
moog_saw_wave_btn->move( 188, btn_y );
moog_saw_wave_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "moog_saw_shape_active" ) );
moog_saw_wave_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "moog_saw_shape_inactive" ) );
moog_saw_wave_btn->setToolTip(
tr( "Moog-like saw wave" ) );
auto exp_wave_btn = new PixmapButton(this, nullptr);
exp_wave_btn->move( 203, btn_y );
exp_wave_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"exp_shape_active" ) );
exp_wave_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"exp_shape_inactive" ) );
exp_wave_btn->setToolTip(
tr( "Exponential wave" ) );
auto white_noise_btn = new PixmapButton(this, nullptr);
white_noise_btn->move( 218, btn_y );
white_noise_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "white_noise_shape_active" ) );
white_noise_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "white_noise_shape_inactive" ) );
white_noise_btn->setToolTip(
tr( "White noise" ) );
auto uwb = new PixmapButton(this, nullptr);
uwb->move( 233, btn_y );
uwb->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"usr_shape_active" ) );
uwb->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"usr_shape_inactive" ) );
uwb->setToolTip(tr("User-defined wave"));
auto uwt = new PixmapButton(this, nullptr);
uwt->move( 110, btn_y );
uwt->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"wavetable_active" ) );
uwt->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"wavetable_inactive" ) );
uwt->setCheckable(true);
uwt->setToolTip(tr("Use alias-free wavetable oscillators."));
auto wsbg = new automatableButtonGroup(this);
wsbg->addButton( sin_wave_btn );
wsbg->addButton( triangle_wave_btn );
wsbg->addButton( saw_wave_btn );
wsbg->addButton( sqr_wave_btn );
wsbg->addButton( moog_saw_wave_btn );
wsbg->addButton( exp_wave_btn );
wsbg->addButton( white_noise_btn );
wsbg->addButton( uwb );
m_oscKnobs[i] = OscillatorKnobs( vk, pk, ck, flk, frk, pok,
spdk, uwb, wsbg, uwt );
}
}
void TripleOscillatorView::modelChanged()
{
auto t = castModel<TripleOscillator>();
m_mod1BtnGrp->setModel( &t->m_osc[0]->m_modulationAlgoModel );
m_mod2BtnGrp->setModel( &t->m_osc[1]->m_modulationAlgoModel );
for( int i = 0; i < NUM_OF_OSCILLATORS; ++i )
{
m_oscKnobs[i].m_volKnob->setModel(
&t->m_osc[i]->m_volumeModel );
m_oscKnobs[i].m_panKnob->setModel(
&t->m_osc[i]->m_panModel );
m_oscKnobs[i].m_coarseKnob->setModel(
&t->m_osc[i]->m_coarseModel );
m_oscKnobs[i].m_fineLeftKnob->setModel(
&t->m_osc[i]->m_fineLeftModel );
m_oscKnobs[i].m_fineRightKnob->setModel(
&t->m_osc[i]->m_fineRightModel );
m_oscKnobs[i].m_phaseOffsetKnob->setModel(
&t->m_osc[i]->m_phaseOffsetModel );
m_oscKnobs[i].m_stereoPhaseDetuningKnob->setModel(
&t->m_osc[i]->m_stereoPhaseDetuningModel );
m_oscKnobs[i].m_waveShapeBtnGrp->setModel(
&t->m_osc[i]->m_waveShapeModel );
m_oscKnobs[i].m_multiBandWaveTableButton->setModel(
&t->m_osc[i]->m_useWaveTableModel );
connect( m_oscKnobs[i].m_userWaveButton,
SIGNAL( doubleClicked() ),
t->m_osc[i], SLOT( oscUserDefWaveDblClick() ) );
}
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* model, void * )
{
return new TripleOscillator( static_cast<InstrumentTrack *>( model ) );
}
}
} // namespace lmms
| 23,536
|
C++
|
.cpp
| 614
| 34.786645
| 116
| 0.685835
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,639
|
FreeBoy.cpp
|
LMMS_lmms/plugins/FreeBoy/FreeBoy.cpp
|
/*
* FreeBoy.cpp - GameBoy papu based instrument
*
* Copyright (c) 2008 Attila Herman <attila589/at/gmail.com>
* Csaba Hruska <csaba.hruska/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "FreeBoy.h"
#include <cmath>
#include <QDomElement>
#include "GbApuWrapper.h"
#include "base64.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "AudioEngine.h"
#include "NotePlayHandle.h"
#include "PixmapButton.h"
#include "Engine.h"
#include "Graph.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
namespace
{
constexpr blip_time_t FRAME_LENGTH = 70224;
constexpr long CLOCK_RATE = 4194304;
}
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT freeboy_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"FreeBoy",
QT_TRANSLATE_NOOP( "PluginBrowser", "Emulation of GameBoy (TM) APU" ),
"Attila Herman <attila589/at/gmail.com>"
"Csaba Hruska <csaba.hruska/at/gmail.com>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
} ;
}
FreeBoyInstrument::FreeBoyInstrument( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &freeboy_plugin_descriptor ),
m_ch1SweepTimeModel( 4.0f, 0.0f, 7.0f, 1.0f, this, tr( "Sweep time" ) ),
m_ch1SweepDirModel( false, this, tr( "Sweep direction" ) ),
m_ch1SweepRtShiftModel( 4.0f, 0.0f, 7.0f, 1.0f, this,
tr( "Sweep rate shift amount" ) ),
m_ch1WavePatternDutyModel( 2.0f, 0.0f, 3.0f, 1.0f, this,
tr( "Wave pattern duty cycle" ) ),
m_ch1VolumeModel( 15.0f, 0.0f, 15.0f, 1.0f, this,
tr( "Channel 1 volume" ) ),
m_ch1VolSweepDirModel( false, this,
tr( "Volume sweep direction" ) ),
m_ch1SweepStepLengthModel( 0.0f, 0.0f, 7.0f, 1.0f, this,
tr( "Length of each step in sweep" ) ),
m_ch2WavePatternDutyModel( 2.0f, 0.0f, 3.0f, 1.0f, this,
tr( "Wave pattern duty cycle" ) ),
m_ch2VolumeModel( 15.0f, 0.0f, 15.0f, 1.0f, this,
tr( "Channel 2 volume" ) ),
m_ch2VolSweepDirModel( false, this,
tr( "Volume sweep direction" ) ),
m_ch2SweepStepLengthModel( 0.0f, 0.0f, 7.0f, 1.0f, this,
tr( "Length of each step in sweep" ) ),
//m_ch3OnModel( true, this, tr( "Channel 3 Master on/off" ) ),
m_ch3VolumeModel( 3.0f, 0.0f, 3.0f, 1.0f, this,
tr( "Channel 3 volume" ) ),
m_ch4VolumeModel( 15.0f, 0.0f, 15.0f, 1.0f, this,
tr( "Channel 4 volume" ) ),
m_ch4VolSweepDirModel( false, this,
tr( "Volume sweep direction" ) ),
m_ch4SweepStepLengthModel( 0.0f, 0.0f, 7.0f, 1.0f, this,
tr( "Length of each step in sweep" ) ),
m_ch4ShiftRegWidthModel( false, this,
tr( "Shift Register width" ) ),
m_so1VolumeModel( 7.0f, 0.0f, 7.0f, 1.0f, this, tr( "Right output level") ),
m_so2VolumeModel( 7.0f, 0.0f, 7.0f, 1.0f, this, tr( "Left output level" ) ),
m_ch1So1Model( true, this, tr( "Channel 1 to SO2 (Left)" ) ),
m_ch2So1Model( true, this, tr( "Channel 2 to SO2 (Left)" ) ),
m_ch3So1Model( true, this, tr( "Channel 3 to SO2 (Left)" ) ),
m_ch4So1Model( false, this, tr( "Channel 4 to SO2 (Left)" ) ),
m_ch1So2Model( true, this, tr( "Channel 1 to SO1 (Right)" ) ),
m_ch2So2Model( true, this, tr( "Channel 2 to SO1 (Right)" ) ),
m_ch3So2Model( true, this, tr( "Channel 3 to SO1 (Right)" ) ),
m_ch4So2Model( false, this, tr( "Channel 4 to SO1 (Right)" ) ),
m_trebleModel( -20.0f, -100.0f, 200.0f, 1.0f, this, tr( "Treble" ) ),
m_bassModel( 461.0f, -1.0f, 600.0f, 1.0f, this, tr( "Bass" ) ),
m_graphModel( 0, 15, 32, this, false, 1 )
{
}
void FreeBoyInstrument::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
m_ch1SweepTimeModel.saveSettings( _doc, _this, "st" );
m_ch1SweepDirModel.saveSettings( _doc, _this, "sd" );
m_ch1SweepRtShiftModel.saveSettings( _doc, _this, "srs" );
m_ch1WavePatternDutyModel.saveSettings( _doc, _this, "ch1wpd" );
m_ch1VolumeModel.saveSettings( _doc, _this, "ch1vol" );
m_ch1VolSweepDirModel.saveSettings( _doc, _this, "ch1vsd" );
m_ch1SweepStepLengthModel.saveSettings( _doc, _this, "ch1ssl" );
m_ch2WavePatternDutyModel.saveSettings( _doc, _this, "ch2wpd" );
m_ch2VolumeModel.saveSettings( _doc, _this, "ch2vol" );
m_ch2VolSweepDirModel.saveSettings( _doc, _this, "ch2vsd" );
m_ch2SweepStepLengthModel.saveSettings( _doc, _this, "ch2ssl" );
//m_ch3OnModel.saveSettings( _doc, _this, "ch3on" );
m_ch3VolumeModel.saveSettings( _doc, _this, "ch3vol" );
m_ch4VolumeModel.saveSettings( _doc, _this, "ch4vol" );
m_ch4VolSweepDirModel.saveSettings( _doc, _this, "ch4vsd" );
m_ch4SweepStepLengthModel.saveSettings( _doc, _this, "ch4ssl" );
m_ch4ShiftRegWidthModel.saveSettings( _doc, _this, "srw" );
m_so1VolumeModel.saveSettings( _doc, _this, "so1vol" );
m_so2VolumeModel.saveSettings( _doc, _this, "so2vol" );
m_ch1So1Model.saveSettings( _doc, _this, "ch1so2" );
m_ch2So1Model.saveSettings( _doc, _this, "ch2so2" );
m_ch3So1Model.saveSettings( _doc, _this, "ch3so2" );
m_ch4So1Model.saveSettings( _doc, _this, "ch4so2" );
m_ch1So2Model.saveSettings( _doc, _this, "ch1so1" );
m_ch2So2Model.saveSettings( _doc, _this, "ch2so1" );
m_ch3So2Model.saveSettings( _doc, _this, "ch3so1" );
m_ch4So2Model.saveSettings( _doc, _this, "ch4so1" );
m_trebleModel.saveSettings( _doc, _this, "Treble" );
m_bassModel.saveSettings( _doc, _this, "Bass" );
QString sampleString;
base64::encode( (const char *)m_graphModel.samples(),
m_graphModel.length() * sizeof(float), sampleString );
_this.setAttribute( "sampleShape", sampleString );
}
void FreeBoyInstrument::loadSettings( const QDomElement & _this )
{
m_ch1SweepTimeModel.loadSettings( _this, "st" );
m_ch1SweepDirModel.loadSettings( _this, "sd" );
m_ch1SweepRtShiftModel.loadSettings( _this, "srs" );
m_ch1WavePatternDutyModel.loadSettings( _this, "ch1wpd" );
m_ch1VolumeModel.loadSettings( _this, "ch1vol" );
m_ch1VolSweepDirModel.loadSettings( _this, "ch1vsd" );
m_ch1SweepStepLengthModel.loadSettings( _this, "ch1ssl" );
m_ch2WavePatternDutyModel.loadSettings( _this, "ch2wpd" );
m_ch2VolumeModel.loadSettings( _this, "ch2vol" );
m_ch2VolSweepDirModel.loadSettings( _this, "ch2vsd" );
m_ch2SweepStepLengthModel.loadSettings( _this, "ch2ssl" );
//m_ch3OnModel.loadSettings( _this, "ch3on" );
m_ch3VolumeModel.loadSettings( _this, "ch3vol" );
m_ch4VolumeModel.loadSettings( _this, "ch4vol" );
m_ch4VolSweepDirModel.loadSettings( _this, "ch4vsd" );
m_ch4SweepStepLengthModel.loadSettings( _this, "ch4ssl" );
m_ch4ShiftRegWidthModel.loadSettings( _this, "srw" );
m_so1VolumeModel.loadSettings( _this, "so1vol" );
m_so2VolumeModel.loadSettings( _this, "so2vol" );
m_ch1So1Model.loadSettings( _this, "ch1so2" );
m_ch2So1Model.loadSettings( _this, "ch2so2" );
m_ch3So1Model.loadSettings( _this, "ch3so2" );
m_ch4So1Model.loadSettings( _this, "ch4so2" );
m_ch1So2Model.loadSettings( _this, "ch1so1" );
m_ch2So2Model.loadSettings( _this, "ch2so1" );
m_ch3So2Model.loadSettings( _this, "ch3so1" );
m_ch4So2Model.loadSettings( _this, "ch4so1" );
m_trebleModel.loadSettings( _this, "Treble" );
m_bassModel.loadSettings( _this, "Bass" );
int size = 0;
char * dst = 0;
base64::decode( _this.attribute( "sampleShape"), &dst, &size );
m_graphModel.setSamples( (float*) dst );
}
QString FreeBoyInstrument::nodeName() const
{
return( freeboy_plugin_descriptor.name );
}
float FreeBoyInstrument::desiredReleaseTimeMs() const
{
// Previous implementation was 1000 samples. At 44.1 kHz this is somewhat shy of 23. ms.
return 23.f;
}
void FreeBoyInstrument::playNote(NotePlayHandle* nph, SampleFrame* workingBuffer)
{
const f_cnt_t tfp = nph->totalFramesPlayed();
const int samplerate = Engine::audioEngine()->outputSampleRate();
const fpp_t frames = nph->framesLeftForCurrentPeriod();
const f_cnt_t offset = nph->noteOffset();
int data = 0;
int freq = nph->frequency();
if (!nph->m_pluginData)
{
auto papu = new GbApuWrapper{};
papu->setSampleRate(samplerate, CLOCK_RATE);
// Master sound circuitry power control
papu->writeRegister(0xff26, 0x80);
data = m_ch1VolumeModel.value();
data = data << 1;
data += m_ch1VolSweepDirModel.value();
data = data << 3;
data += m_ch1SweepStepLengthModel.value();
papu->writeRegister(0xff12, data);
data = m_ch2VolumeModel.value();
data = data << 1;
data += m_ch2VolSweepDirModel.value();
data = data << 3;
data += m_ch2SweepStepLengthModel.value();
papu->writeRegister(0xff17, data);
//channel 4 - noise
data = m_ch4VolumeModel.value();
data = data << 1;
data += m_ch4VolSweepDirModel.value();
data = data << 3;
data += m_ch4SweepStepLengthModel.value();
papu->writeRegister(0xff21, data);
nph->m_pluginData = papu;
}
auto papu = static_cast<GbApuWrapper*>(nph->m_pluginData);
papu->trebleEq(m_trebleModel.value());
papu->bassFreq(m_bassModel.value());
//channel 1 - square
data = m_ch1SweepTimeModel.value();
data = data << 1;
data += m_ch1SweepDirModel.value();
data = data << 3;
data += m_ch1SweepRtShiftModel.value();
papu->writeRegister(0xff10, data);
data = m_ch1WavePatternDutyModel.value();
data = data << 6;
papu->writeRegister(0xff11, data);
//channel 2 - square
data = m_ch2WavePatternDutyModel.value();
data = data << 6;
papu->writeRegister(0xff16, data);
//channel 3 - wave
//data = m_ch3OnModel.value() ? 128 : 0;
data = 128;
papu->writeRegister(0xff1a, data);
auto ch3voldata = std::array{0, 3, 2, 1};
data = ch3voldata[(int)m_ch3VolumeModel.value()];
data = data << 5;
papu->writeRegister(0xff1c, data);
//controls
data = m_so1VolumeModel.value();
data = data << 4;
data += m_so2VolumeModel.value();
papu->writeRegister(0xff24, data);
data = m_ch4So2Model.value() ? 128 : 0;
data += m_ch3So2Model.value() ? 64 : 0;
data += m_ch2So2Model.value() ? 32 : 0;
data += m_ch1So2Model.value() ? 16 : 0;
data += m_ch4So1Model.value() ? 8 : 0;
data += m_ch3So1Model.value() ? 4 : 0;
data += m_ch2So1Model.value() ? 2 : 0;
data += m_ch1So1Model.value() ? 1 : 0;
papu->writeRegister(0xff25, data);
const float* wpm = m_graphModel.samples();
for (char i = 0; i < 16; ++i)
{
data = static_cast<int>(std::floor(wpm[i * 2])) << 4;
data += static_cast<int>(std::floor(wpm[(i * 2) + 1]));
papu->writeRegister(0xff30 + i, data);
}
if ((freq >= 65) && (freq <= 4000))
{
int initFlag = (tfp == 0) ? 128 : 0;
// Hz = 4194304 / ((2048 - (11-bit-freq)) << 5)
data = 2048 - ((4194304 / freq) >> 5);
if (tfp == 0)
{
papu->writeRegister(0xff13, data & 0xff);
papu->writeRegister(0xff14, (data >> 8) | initFlag);
}
papu->writeRegister(0xff18, data & 0xff);
papu->writeRegister(0xff19, (data >> 8) | initFlag);
papu->writeRegister(0xff1d, data & 0xff);
papu->writeRegister(0xff1e, (data >> 8) | initFlag);
}
if (tfp == 0)
{
// Initialize noise channel...
// PRNG Frequency = (1048576 Hz / (ratio + 1)) / 2 ^ (shiftclockfreq + 1)
// When div_ratio = 0 the ratio should be 0.5. Since s = 0 is the only case where r = 0 gives
// a unique frequency, we can start by guessing s = r = 0 here and then skip r = 0 in the loop.
char clock_freq = 0;
char div_ratio = 0;
float closest_freq = 524288.0 / (0.5 * std::pow(2.0, clock_freq + 1.0));
// This nested for loop iterates over all possible combinations of clock frequency and dividing
// ratio and chooses the combination whose resulting frequency is closest to the note frequency
for (char s = 0; s < 16; ++s)
{
for (char r = 1; r < 8; ++r)
{
float f = 524288.0 / (r * std::pow(2.0, s + 1.0));
if (std::fabs(freq - closest_freq) > std::fabs(freq - f))
{
closest_freq = f;
div_ratio = r;
clock_freq = s;
}
}
}
data = clock_freq;
data = data << 1;
data += m_ch4ShiftRegWidthModel.value();
data = data << 3;
data += div_ratio;
papu->writeRegister(0xff22, data);
//channel 4 init
papu->writeRegister(0xff23, 128);
}
constexpr auto bufSize = f_cnt_t{2048};
auto framesLeft = frames;
auto buf = std::array<blip_sample_t, bufSize * 2>{};
while (framesLeft > 0)
{
int avail = papu->samplesAvail();
if (avail <= 0)
{
papu->endFrame(FRAME_LENGTH);
avail = papu->samplesAvail();
}
const auto dataLen = std::min({static_cast<f_cnt_t>(avail), framesLeft, bufSize});
const auto count = static_cast<f_cnt_t>(papu->readSamples(buf.data(), dataLen * 2) / 2);
for (auto frame = std::size_t{0}; frame < count; ++frame)
{
for (ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch)
{
sample_t s = static_cast<float>(buf[(frame * 2) + ch]) / 32768.0f;
workingBuffer[frames - framesLeft + frame + offset][ch] = s;
}
}
framesLeft -= count;
}
}
void FreeBoyInstrument::deleteNotePluginData(NotePlayHandle* nph)
{
delete static_cast<GbApuWrapper*>(nph->m_pluginData);
}
gui::PluginView * FreeBoyInstrument::instantiateView( QWidget * _parent )
{
return( new gui::FreeBoyInstrumentView( this, _parent ) );
}
namespace gui
{
class FreeBoyKnob : public Knob
{
public:
FreeBoyKnob( QWidget * _parent ) :
Knob( KnobType::Styled, _parent )
{
setFixedSize( 30, 30 );
setCenterPointX( 15.0 );
setCenterPointY( 15.0 );
setInnerRadius( 8 );
setOuterRadius( 13 );
setTotalAngle( 270.0 );
setLineWidth( 1 );
setOuterColor( QColor( 0xF1, 0xFF, 0x93 ) );
}
};
FreeBoyInstrumentView::FreeBoyInstrumentView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
m_ch1SweepTimeKnob = new FreeBoyKnob( this );
m_ch1SweepTimeKnob->setHintText( tr( "Sweep time:" ), "" );
m_ch1SweepTimeKnob->move( 5 + 4*32, 106 );
m_ch1SweepTimeKnob->setToolTip(tr("Sweep time"));
m_ch1SweepRtShiftKnob = new FreeBoyKnob( this );
m_ch1SweepRtShiftKnob->setHintText( tr( "Sweep rate shift amount:" )
, "" );
m_ch1SweepRtShiftKnob->move( 5 + 3*32, 106 );
m_ch1SweepRtShiftKnob->setToolTip(tr("Sweep rate shift amount"));
m_ch1WavePatternDutyKnob = new FreeBoyKnob( this );
m_ch1WavePatternDutyKnob->setHintText( tr( "Wave pattern duty cycle:" )
, "" );
m_ch1WavePatternDutyKnob->move( 5 + 2*32, 106 );
m_ch1WavePatternDutyKnob->setToolTip(tr("Wave pattern duty cycle"));
m_ch1VolumeKnob = new FreeBoyKnob( this );
m_ch1VolumeKnob->setHintText( tr( "Square channel 1 volume:" )
, "" );
m_ch1VolumeKnob->move( 5, 106 );
m_ch1VolumeKnob->setToolTip(tr("Square channel 1 volume"));
m_ch1SweepStepLengthKnob = new FreeBoyKnob( this );
m_ch1SweepStepLengthKnob->setHintText( tr( "Length of each step in sweep:" )
, "" );
m_ch1SweepStepLengthKnob->move( 5 + 32, 106 );
m_ch1SweepStepLengthKnob->setToolTip(tr("Length of each step in sweep"));
m_ch2WavePatternDutyKnob = new FreeBoyKnob( this );
m_ch2WavePatternDutyKnob->setHintText( tr( "Wave pattern duty cycle:" )
, "" );
m_ch2WavePatternDutyKnob->move( 5 + 2*32, 155 );
m_ch2WavePatternDutyKnob->setToolTip(tr("Wave pattern duty cycle"));
m_ch2VolumeKnob = new FreeBoyKnob( this );
m_ch2VolumeKnob->setHintText( tr( "Square channel 2 volume:" )
, "" );
m_ch2VolumeKnob->move( 5, 155 );
m_ch2VolumeKnob->setToolTip(tr("Square channel 2 volume"));
m_ch2SweepStepLengthKnob = new FreeBoyKnob( this );
m_ch2SweepStepLengthKnob->setHintText( tr( "Length of each step in sweep:" )
, "" );
m_ch2SweepStepLengthKnob->move( 5 + 32, 155 );
m_ch2SweepStepLengthKnob->setToolTip(tr("Length of each step in sweep"));
m_ch3VolumeKnob = new FreeBoyKnob( this );
m_ch3VolumeKnob->setHintText( tr( "Wave pattern channel volume:" ), "" );
m_ch3VolumeKnob->move( 5, 204 );
m_ch3VolumeKnob->setToolTip(tr("Wave pattern channel volume"));
m_ch4VolumeKnob = new FreeBoyKnob( this );
m_ch4VolumeKnob->setHintText( tr( "Noise channel volume:" ), "" );
m_ch4VolumeKnob->move( 144, 155 );
m_ch4VolumeKnob->setToolTip(tr("Noise channel volume"));
m_ch4SweepStepLengthKnob = new FreeBoyKnob( this );
m_ch4SweepStepLengthKnob->setHintText( tr( "Length of each step in sweep:" )
, "" );
m_ch4SweepStepLengthKnob->move( 144 + 32, 155 );
m_ch4SweepStepLengthKnob->setToolTip(tr("Length of each step in sweep"));
m_so1VolumeKnob = new FreeBoyKnob( this );
m_so1VolumeKnob->setHintText( tr( "SO1 volume (Right):" ), "" );
m_so1VolumeKnob->move( 5, 58 );
m_so1VolumeKnob->setToolTip(tr("SO1 volume (Right)"));
m_so2VolumeKnob = new FreeBoyKnob( this );
m_so2VolumeKnob->setHintText( tr( "SO2 volume (Left):" ), "" );
m_so2VolumeKnob->move( 5 + 32, 58 );
m_so2VolumeKnob->setToolTip(tr("SO2 volume (Left)"));
m_trebleKnob = new FreeBoyKnob( this );
m_trebleKnob->setHintText( tr( "Treble:" ), "" );
m_trebleKnob->move( 5 + 2*32, 58 );
m_trebleKnob->setToolTip(tr("Treble"));
m_bassKnob = new FreeBoyKnob( this );
m_bassKnob->setHintText( tr( "Bass:" ), "" );
m_bassKnob->move( 5 + 3*32, 58 );
m_bassKnob->setToolTip(tr("Bass"));
m_ch1SweepDirButton = new PixmapButton( this, nullptr );
m_ch1SweepDirButton->setCheckable( true );
m_ch1SweepDirButton->move( 167, 108 );
m_ch1SweepDirButton->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_down" ) );
m_ch1SweepDirButton->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_up" ) );
m_ch1SweepDirButton->setToolTip(tr("Sweep direction"));
m_ch1VolSweepDirButton = new PixmapButton( this, nullptr );
m_ch1VolSweepDirButton->setCheckable( true );
m_ch1VolSweepDirButton->move( 207, 108 );
m_ch1VolSweepDirButton->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_up" ) );
m_ch1VolSweepDirButton->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_down" ) );
m_ch1VolSweepDirButton->setToolTip(tr("Volume sweep direction"));
m_ch2VolSweepDirButton = new PixmapButton( this,
tr( "Volume sweep direction" ) );
m_ch2VolSweepDirButton->setCheckable( true );
m_ch2VolSweepDirButton->move( 102, 156 );
m_ch2VolSweepDirButton->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_up" ) );
m_ch2VolSweepDirButton->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_down" ) );
m_ch2VolSweepDirButton->setToolTip(tr("Volume sweep direction"));
//m_ch3OnButton = new PixmapButton( this, NULL );
//m_ch3OnButton->move( 176, 53 );
m_ch4VolSweepDirButton = new PixmapButton( this,
tr( "Volume sweep direction" ) );
m_ch4VolSweepDirButton->setCheckable( true );
m_ch4VolSweepDirButton->move( 207, 157 );
m_ch4VolSweepDirButton->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_up" ) );
m_ch4VolSweepDirButton->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_down" ) );
m_ch4VolSweepDirButton->setToolTip(tr("Volume sweep direction"));
m_ch4ShiftRegWidthButton = new PixmapButton( this, nullptr );
m_ch4ShiftRegWidthButton->setCheckable( true );
m_ch4ShiftRegWidthButton->move( 207, 171 );
m_ch4ShiftRegWidthButton->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_7" ) );
m_ch4ShiftRegWidthButton->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "btn_15" ) );
m_ch4ShiftRegWidthButton->setToolTip(tr("Shift register width"));
m_ch1So1Button = new PixmapButton( this, nullptr );
m_ch1So1Button->setCheckable( true );
m_ch1So1Button->move( 208, 51 );
m_ch1So1Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "btn_on" ) );
m_ch1So1Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap("btn_off") );
m_ch1So1Button->setToolTip(tr("Channel 1 to SO1 (Right)"));
m_ch2So1Button = new PixmapButton( this, nullptr );
m_ch2So1Button->setCheckable( true );
m_ch2So1Button->move( 208, 51 + 12 );
m_ch2So1Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "btn_on" ) );
m_ch2So1Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap("btn_off") );
m_ch2So1Button->setToolTip(tr("Channel 2 to SO1 (Right)"));
m_ch3So1Button = new PixmapButton( this, nullptr );
m_ch3So1Button->setCheckable( true );
m_ch3So1Button->move( 208, 51 + 2*12 );
m_ch3So1Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "btn_on" ) );
m_ch3So1Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap("btn_off") );
m_ch3So1Button->setToolTip(tr("Channel 3 to SO1 (Right)"));
m_ch4So1Button = new PixmapButton( this, nullptr );
m_ch4So1Button->setCheckable( true );
m_ch4So1Button->setChecked( false );
m_ch4So1Button->move( 208, 51 + 3*12 );
m_ch4So1Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "btn_on" ) );
m_ch4So1Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap("btn_off") );
m_ch4So1Button->setToolTip(tr("Channel 4 to SO1 (Right)"));
m_ch1So2Button = new PixmapButton( this, nullptr );
m_ch1So2Button->setCheckable( true );
m_ch1So2Button->move( 148, 51 );
m_ch1So2Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "btn_on" ) );
m_ch1So2Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap("btn_off") );
m_ch1So2Button->setToolTip(tr("Channel 1 to SO2 (Left)"));
m_ch2So2Button = new PixmapButton( this, nullptr );
m_ch2So2Button->setCheckable( true );
m_ch2So2Button->move( 148, 51 + 12 );
m_ch2So2Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "btn_on" ) );
m_ch2So2Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap("btn_off") );
m_ch2So2Button->setToolTip(tr("Channel 2 to SO2 (Left)"));
m_ch3So2Button = new PixmapButton( this, nullptr );
m_ch3So2Button->setCheckable( true );
m_ch3So2Button->move( 148, 51 + 2*12 );
m_ch3So2Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "btn_on" ) );
m_ch3So2Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap("btn_off") );
m_ch3So2Button->setToolTip(tr("Channel 3 to SO2 (Left)"));
m_ch4So2Button = new PixmapButton( this, nullptr );
m_ch4So2Button->setCheckable( true );
m_ch4So2Button->setChecked( false );
m_ch4So2Button->move( 148, 51 + 3*12 );
m_ch4So2Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "btn_on" ) );
m_ch4So2Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap("btn_off") );
m_ch4So2Button->setToolTip(tr("Channel 4 to SO2 (Left)"));
m_graph = new Graph( this );
m_graph->setGraphStyle( Graph::Style::Nearest );
m_graph->setGraphColor( QColor(0x4E, 0x83, 0x2B) );
m_graph->move( 37, 199 );
m_graph->resize(208, 47);
m_graph->setToolTip(tr("Wave pattern graph"));
}
void FreeBoyInstrumentView::modelChanged()
{
auto p = castModel<FreeBoyInstrument>();
m_ch1SweepTimeKnob->setModel( &p->m_ch1SweepTimeModel );
m_ch1SweepDirButton->setModel( &p->m_ch1SweepDirModel );
m_ch1SweepRtShiftKnob->setModel( &p->m_ch1SweepRtShiftModel );
m_ch1WavePatternDutyKnob->setModel( &p->m_ch1WavePatternDutyModel );
m_ch1VolumeKnob->setModel( &p->m_ch1VolumeModel );
m_ch1VolSweepDirButton->setModel( &p->m_ch1VolSweepDirModel );
m_ch1SweepStepLengthKnob->setModel( &p->m_ch1SweepStepLengthModel );
m_ch2WavePatternDutyKnob->setModel( &p->m_ch2WavePatternDutyModel );
m_ch2VolumeKnob->setModel( &p->m_ch2VolumeModel );
m_ch2VolSweepDirButton->setModel( &p->m_ch2VolSweepDirModel );
m_ch2SweepStepLengthKnob->setModel( &p->m_ch2SweepStepLengthModel );
//m_ch3OnButton->setModel( &p->m_ch3OnModel );
m_ch3VolumeKnob->setModel( &p->m_ch3VolumeModel );
m_ch4VolumeKnob->setModel( &p->m_ch4VolumeModel );
m_ch4VolSweepDirButton->setModel( &p->m_ch4VolSweepDirModel );
m_ch4SweepStepLengthKnob->setModel( &p->m_ch4SweepStepLengthModel );
m_ch4ShiftRegWidthButton->setModel( &p->m_ch4ShiftRegWidthModel );
m_so1VolumeKnob->setModel( &p->m_so1VolumeModel );
m_so2VolumeKnob->setModel( &p->m_so2VolumeModel );
m_ch1So1Button->setModel( &p->m_ch1So1Model );
m_ch2So1Button->setModel( &p->m_ch2So1Model );
m_ch3So1Button->setModel( &p->m_ch3So1Model );
m_ch4So1Button->setModel( &p->m_ch4So1Model );
m_ch1So2Button->setModel( &p->m_ch1So2Model );
m_ch2So2Button->setModel( &p->m_ch2So2Model );
m_ch3So2Button->setModel( &p->m_ch3So2Model );
m_ch4So2Button->setModel( &p->m_ch4So2Model );
m_trebleKnob->setModel( &p->m_trebleModel );
m_bassKnob->setModel( &p->m_bassModel );
m_graph->setModel( &p->m_graphModel );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return( new FreeBoyInstrument(
static_cast<InstrumentTrack *>( m ) ) );
}
}
} // namespace lmms
| 24,947
|
C++
|
.cpp
| 591
| 39.485618
| 97
| 0.707643
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,640
|
GbApuWrapper.cpp
|
LMMS_lmms/plugins/FreeBoy/GbApuWrapper.cpp
|
/*
* GbApuWrapper.cpp - Gb_Apu subclass which allows direct buffer access
* Copyright (c) 2017 Tres Finocchiaro <tres.finocchiaro/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "GbApuWrapper.h"
namespace lmms
{
// Sets specified sample rate and clock rate in Stereo_Buffer
blargg_err_t GbApuWrapper::setSampleRate(long sampleRate, long clockRate)
{
Gb_Apu::output(m_buf.center(), m_buf.left(), m_buf.right());
m_buf.clock_rate(clockRate);
return m_buf.set_sample_rate(sampleRate);
}
// Wrap Stereo_Buffer::samples_avail()
long GbApuWrapper::samplesAvail() const
{
return m_buf.samples_avail();
}
// Wrap Stereo_Buffer::read_samples(...)
long GbApuWrapper::readSamples(blip_sample_t* out, long count)
{
return m_buf.read_samples(out, count);
}
// Wrap Stereo_Buffer::bass_freq(...)
void GbApuWrapper::bassFreq(int freq)
{
m_buf.bass_freq(freq);
}
void GbApuWrapper::endFrame(blip_time_t endTime)
{
m_time = 0;
Gb_Apu::end_frame(endTime);
m_buf.end_frame(endTime);
}
} // namespace lmms
| 1,776
|
C++
|
.cpp
| 54
| 31.148148
| 73
| 0.753505
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,641
|
BitInvader.cpp
|
LMMS_lmms/plugins/BitInvader/BitInvader.cpp
|
/*
* BitInvader.cpp - instrument which uses a usereditable wavetable
*
* Copyright (c) 2006-2008 Andreas Brandmaier <andy/at/brandmaier/dot/de>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "BitInvader.h"
#include "AudioEngine.h"
#include "base64.h"
#include "Engine.h"
#include "Graph.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "NotePlayHandle.h"
#include "PixmapButton.h"
#include "Song.h"
#include "interpolation.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
static const int wavetableSize = 200;
static const float defaultNormalizationFactor = 1.0f;
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT bitinvader_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"BitInvader",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Customizable wavetable synthesizer" ),
"Andreas Brandmaier <andreas/at/brandmaier/dot/de>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
BSynth::BSynth( float * _shape, NotePlayHandle * _nph, bool _interpolation,
float _factor, const sample_rate_t _sample_rate ) :
sample_index( 0 ),
sample_realindex( 0 ),
nph( _nph ),
sample_rate( _sample_rate ),
interpolation( _interpolation)
{
sample_shape = new float[wavetableSize];
for (int i=0; i < wavetableSize; ++i)
{
float buf = _shape[i] * _factor;
/* Double check that normalization has been performed correctly,
i.e., the absolute value of all samples is <= 1.0 if _factor
is different to the default normalization factor. If there is
a value > 1.0, clip the sample to 1.0 to limit the range. */
if ((_factor != defaultNormalizationFactor) && (fabsf(buf) > 1.0f))
{
buf = (buf < 0) ? -1.0f : 1.0f;
}
sample_shape[i] = buf;
}
}
BSynth::~BSynth()
{
delete[] sample_shape;
}
sample_t BSynth::nextStringSample( float sample_length )
{
auto sample_step = static_cast<float>(sample_length / (sample_rate / nph->frequency()));
// check overflow
while (sample_realindex >= sample_length) {
sample_realindex -= sample_length;
}
const auto currentRealIndex = sample_realindex;
const auto currentIndex = static_cast<int>(sample_realindex);
sample_realindex += sample_step;
if (!interpolation)
{
sample_index = currentIndex;
return sample_shape[sample_index];
}
const auto nextIndex = currentIndex < sample_length - 1 ? currentIndex + 1 : 0;
return linearInterpolate(sample_shape[currentIndex], sample_shape[nextIndex], fraction(currentRealIndex));
}
/***********************************************************************
*
* class BitInvader
*
* lmms - plugin
*
***********************************************************************/
BitInvader::BitInvader( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &bitinvader_plugin_descriptor ),
m_sampleLength(wavetableSize, 4, wavetableSize, 1, this, tr("Sample length")),
m_graph(-1.0f, 1.0f, wavetableSize, this),
m_interpolation(false, this, tr("Interpolation")),
m_normalize(false, this, tr("Normalize"))
{
m_graph.setWaveToSine();
lengthChanged();
connect( &m_sampleLength, SIGNAL( dataChanged() ),
this, SLOT( lengthChanged() ), Qt::DirectConnection );
connect( &m_graph, SIGNAL( samplesChanged( int, int ) ),
this, SLOT( samplesChanged( int, int ) ) );
}
void BitInvader::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
// Save plugin version
_this.setAttribute( "version", "0.1" );
// Save sample length
m_sampleLength.saveSettings( _doc, _this, "sampleLength" );
// Save sample shape base64-encoded
QString sampleString;
base64::encode((const char *)m_graph.samples(),
wavetableSize * sizeof(float), sampleString);
_this.setAttribute( "sampleShape", sampleString );
// save LED normalize
m_interpolation.saveSettings( _doc, _this, "interpolation" );
// save LED
m_normalize.saveSettings( _doc, _this, "normalize" );
}
void BitInvader::loadSettings( const QDomElement & _this )
{
// Clear wavetable before loading a new
m_graph.clear();
// Load sample length
m_sampleLength.loadSettings( _this, "sampleLength" );
int sampleLength = (int)m_sampleLength.value();
// Load sample shape
int size = 0;
char * dst = 0;
base64::decode( _this.attribute( "sampleShape"), &dst, &size );
m_graph.setLength(size / sizeof(float));
m_graph.setSamples(reinterpret_cast<float*>(dst));
m_graph.setLength(sampleLength);
delete[] dst;
// Load LED normalize
m_interpolation.loadSettings( _this, "interpolation" );
// Load LED
m_normalize.loadSettings( _this, "normalize" );
}
void BitInvader::lengthChanged()
{
m_graph.setLength( (int) m_sampleLength.value() );
normalize();
}
void BitInvader::samplesChanged( int _begin, int _end )
{
normalize();
//engine::getSongEditor()->setModified();
}
void BitInvader::normalize()
{
// analyze
float max = std::numeric_limits<float>::epsilon();
const float* samples = m_graph.samples();
for(int i=0; i < m_graph.length(); i++)
{
const float f = fabsf( samples[i] );
if (f > max) { max = f; }
}
m_normalizeFactor = 1.0 / max;
}
QString BitInvader::nodeName() const
{
return( bitinvader_plugin_descriptor.name );
}
void BitInvader::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
if (!_n->m_pluginData)
{
float factor = !m_normalize.value() ? defaultNormalizationFactor : m_normalizeFactor;
_n->m_pluginData = new BSynth(
const_cast<float*>( m_graph.samples() ),
_n,
m_interpolation.value(), factor,
Engine::audioEngine()->outputSampleRate() );
}
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
auto ps = static_cast<BSynth*>(_n->m_pluginData);
for( fpp_t frame = offset; frame < frames + offset; ++frame )
{
_working_buffer[frame] = SampleFrame(ps->nextStringSample(m_graph.length()));
}
applyRelease( _working_buffer, _n );
}
void BitInvader::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<BSynth *>( _n->m_pluginData );
}
gui::PluginView * BitInvader::instantiateView( QWidget * _parent )
{
return( new gui::BitInvaderView( this, _parent ) );
}
namespace gui
{
BitInvaderView::BitInvaderView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap(
"artwork" ) );
setPalette( pal );
m_sampleLengthKnob = new Knob( KnobType::Dark28, this );
m_sampleLengthKnob->move( 6, 201 );
m_sampleLengthKnob->setHintText( tr( "Sample length" ), "" );
m_graph = new Graph( this, Graph::Style::Nearest, 204, 134 );
m_graph->move(23,59); // 55,120 - 2px border
m_graph->setAutoFillBackground( true );
m_graph->setGraphColor( QColor( 255, 255, 255 ) );
m_graph->setToolTip(tr("Draw your own waveform here "
"by dragging your mouse on this graph."
));
pal = QPalette();
pal.setBrush( backgroundRole(),
PLUGIN_NAME::getIconPixmap("wavegraph") );
m_graph->setPalette( pal );
m_sinWaveBtn = new PixmapButton( this, tr( "Sine wave" ) );
m_sinWaveBtn->move( 131, 205 );
m_sinWaveBtn->setActiveGraphic( embed::getIconPixmap(
"sin_wave_active" ) );
m_sinWaveBtn->setInactiveGraphic( embed::getIconPixmap(
"sin_wave_inactive" ) );
m_sinWaveBtn->setToolTip(
tr( "Sine wave" ) );
m_triangleWaveBtn = new PixmapButton( this, tr( "Triangle wave" ) );
m_triangleWaveBtn->move( 131 + 14, 205 );
m_triangleWaveBtn->setActiveGraphic(
embed::getIconPixmap( "triangle_wave_active" ) );
m_triangleWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "triangle_wave_inactive" ) );
m_triangleWaveBtn->setToolTip(
tr( "Triangle wave" ) );
m_sawWaveBtn = new PixmapButton( this, tr( "Saw wave" ) );
m_sawWaveBtn->move( 131 + 14*2, 205 );
m_sawWaveBtn->setActiveGraphic( embed::getIconPixmap(
"saw_wave_active" ) );
m_sawWaveBtn->setInactiveGraphic( embed::getIconPixmap(
"saw_wave_inactive" ) );
m_sawWaveBtn->setToolTip(
tr( "Saw wave" ) );
m_sqrWaveBtn = new PixmapButton( this, tr( "Square wave" ) );
m_sqrWaveBtn->move( 131 + 14*3, 205 );
m_sqrWaveBtn->setActiveGraphic( embed::getIconPixmap(
"square_wave_active" ) );
m_sqrWaveBtn->setInactiveGraphic( embed::getIconPixmap(
"square_wave_inactive" ) );
m_sqrWaveBtn->setToolTip(
tr( "Square wave" ) );
m_whiteNoiseWaveBtn = new PixmapButton( this,
tr( "White noise" ) );
m_whiteNoiseWaveBtn->move( 131 + 14*4, 205 );
m_whiteNoiseWaveBtn->setActiveGraphic(
embed::getIconPixmap( "white_noise_wave_active" ) );
m_whiteNoiseWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "white_noise_wave_inactive" ) );
m_whiteNoiseWaveBtn->setToolTip(
tr( "White noise" ) );
m_usrWaveBtn = new PixmapButton( this, tr( "User-defined wave" ) );
m_usrWaveBtn->move( 131 + 14*5, 205 );
m_usrWaveBtn->setActiveGraphic( embed::getIconPixmap(
"usr_wave_active" ) );
m_usrWaveBtn->setInactiveGraphic( embed::getIconPixmap(
"usr_wave_inactive" ) );
m_usrWaveBtn->setToolTip(
tr( "User-defined wave" ) );
m_smoothBtn = new PixmapButton( this, tr( "Smooth waveform" ) );
m_smoothBtn->move( 131 + 14*6, 205 );
m_smoothBtn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"smooth_active" ) );
m_smoothBtn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"smooth_inactive" ) );
m_smoothBtn->setToolTip(
tr( "Smooth waveform" ) );
m_interpolationToggle = new LedCheckBox( "Interpolation", this,
tr( "Interpolation" ), LedCheckBox::LedColor::Yellow );
m_interpolationToggle->move( 131, 221 );
m_normalizeToggle = new LedCheckBox( "Normalize", this,
tr( "Normalize" ), LedCheckBox::LedColor::Green );
m_normalizeToggle->move( 131, 236 );
connect( m_sinWaveBtn, SIGNAL (clicked () ),
this, SLOT ( sinWaveClicked() ) );
connect( m_triangleWaveBtn, SIGNAL ( clicked () ),
this, SLOT ( triangleWaveClicked() ) );
connect( m_sawWaveBtn, SIGNAL (clicked () ),
this, SLOT ( sawWaveClicked() ) );
connect( m_sqrWaveBtn, SIGNAL ( clicked () ),
this, SLOT ( sqrWaveClicked() ) );
connect( m_whiteNoiseWaveBtn, SIGNAL ( clicked () ),
this, SLOT ( noiseWaveClicked() ) );
connect( m_usrWaveBtn, SIGNAL ( clicked () ),
this, SLOT ( usrWaveClicked() ) );
connect( m_smoothBtn, SIGNAL ( clicked () ),
this, SLOT ( smoothClicked() ) );
connect( m_interpolationToggle, SIGNAL( toggled( bool ) ),
this, SLOT ( interpolationToggled( bool ) ) );
connect( m_normalizeToggle, SIGNAL( toggled( bool ) ),
this, SLOT ( normalizeToggled( bool ) ) );
}
void BitInvaderView::modelChanged()
{
auto b = castModel<BitInvader>();
m_graph->setModel( &b->m_graph );
m_sampleLengthKnob->setModel( &b->m_sampleLength );
m_interpolationToggle->setModel( &b->m_interpolation );
m_normalizeToggle->setModel( &b->m_normalize );
}
void BitInvaderView::sinWaveClicked()
{
m_graph->model()->clearInvisible();
m_graph->model()->setWaveToSine();
Engine::getSong()->setModified();
}
void BitInvaderView::triangleWaveClicked()
{
m_graph->model()->clearInvisible();
m_graph->model()->setWaveToTriangle();
Engine::getSong()->setModified();
}
void BitInvaderView::sawWaveClicked()
{
m_graph->model()->clearInvisible();
m_graph->model()->setWaveToSaw();
Engine::getSong()->setModified();
}
void BitInvaderView::sqrWaveClicked()
{
m_graph->model()->clearInvisible();
m_graph->model()->setWaveToSquare();
Engine::getSong()->setModified();
}
void BitInvaderView::noiseWaveClicked()
{
m_graph->model()->clearInvisible();
m_graph->model()->setWaveToNoise();
Engine::getSong()->setModified();
}
void BitInvaderView::usrWaveClicked()
{
QString fileName = m_graph->model()->setWaveToUser();
if (!fileName.isEmpty())
{
m_usrWaveBtn->setToolTip(fileName);
m_graph->model()->clearInvisible();
Engine::getSong()->setModified();
}
}
void BitInvaderView::smoothClicked()
{
m_graph->model()->smooth();
Engine::getSong()->setModified();
}
void BitInvaderView::interpolationToggled( bool value )
{
m_graph->setGraphStyle( value ? Graph::Style::Linear : Graph::Style::Nearest);
Engine::getSong()->setModified();
}
void BitInvaderView::normalizeToggled( bool value )
{
Engine::getSong()->setModified();
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return( new BitInvader( static_cast<InstrumentTrack *>( m ) ) );
}
}
} // namespace lmms
| 13,335
|
C++
|
.cpp
| 394
| 31.258883
| 107
| 0.708839
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,642
|
LOMMControls.cpp
|
LMMS_lmms/plugins/LOMM/LOMMControls.cpp
|
/*
* LOMMControls.cpp
*
* Copyright (c) 2023 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LOMMControls.h"
#include "LOMM.h"
#include <QDomElement>
#include <QMessageBox>
namespace lmms
{
LOMMControls::LOMMControls(LOMMEffect* effect) :
EffectControls(effect),
m_effect(effect),
m_depthModel(0.4f, 0, 1, 0.00001f, this, tr("Depth")),
m_timeModel(1, 0, 10, 0.00001f, this, tr("Time")),
m_inVolModel(0, -48, 48, 0.00001f, this, tr("Input Volume")),
m_outVolModel(8, -48, 48, 0.00001f, this, tr("Output Volume")),
m_upwardModel(1, 0, 2, 0.00001f, this, tr("Upward Depth")),
m_downwardModel(1, 0, 2, 0.00001f, this, tr("Downward Depth")),
m_split1Model(2500, 20, 20000, 0.01f, this, tr("High/Mid Split")),
m_split2Model(88.3f, 20, 20000, 0.01f, this, tr("Mid/Low Split")),
m_split1EnabledModel(true, this, tr("Enable High/Mid Split")),
m_split2EnabledModel(true, this, tr("Enable Mid/Low Split")),
m_band1EnabledModel(true, this, tr("Enable High Band")),
m_band2EnabledModel(true, this, tr("Enable Mid Band")),
m_band3EnabledModel(true, this, tr("Enable Low Band")),
m_inHighModel(0, -48, 48, 0.00001f, this, tr("High Input Volume")),
m_inMidModel(0, -48, 48, 0.00001f, this, tr("Mid Input Volume")),
m_inLowModel(0, -48, 48, 0.00001f, this, tr("Low Input Volume")),
m_outHighModel(4.6f, -48, 48, 0.00001f, this, tr("High Output Volume")),
m_outMidModel(0.f, -48, 48, 0.00001f, this, tr("Mid Output Volume")),
m_outLowModel(4.6f, -48, 48, 0.00001f, this, tr("Low Output Volume")),
m_aThreshHModel(-30.3f, LOMM_DISPLAY_MIN, LOMM_DISPLAY_MAX, 0.001f, this, tr("Above Threshold High")),
m_aThreshMModel(-25.f, LOMM_DISPLAY_MIN, LOMM_DISPLAY_MAX, 0.001f, this, tr("Above Threshold Mid")),
m_aThreshLModel(-28.6f, LOMM_DISPLAY_MIN, LOMM_DISPLAY_MAX, 0.001f, this, tr("Above Threshold Low")),
m_aRatioHModel(99.99f, 1, 99.99f, 0.01f, this, tr("Above Ratio High")),
m_aRatioMModel(66.7f, 1, 99.99f, 0.01f, this, tr("Above Ratio Mid")),
m_aRatioLModel(66.7f, 1, 99.99f, 0.01f, this, tr("Above Ratio Low")),
m_bThreshHModel(-35.6f, LOMM_DISPLAY_MIN, LOMM_DISPLAY_MAX, 0.001f, this, tr("Below Threshold High")),
m_bThreshMModel(-36.6f, LOMM_DISPLAY_MIN, LOMM_DISPLAY_MAX, 0.001f, this, tr("Below Threshold Mid")),
m_bThreshLModel(-35.6f, LOMM_DISPLAY_MIN, LOMM_DISPLAY_MAX, 0.001f, this, tr("Below Threshold Low")),
m_bRatioHModel(4.17f, 1, 99.99f, 0.01f, this, tr("Below Ratio High")),
m_bRatioMModel(4.17f, 1, 99.99f, 0.01f, this, tr("Below Ratio Mid")),
m_bRatioLModel(4.17f, 1, 99.99f, 0.01f, this, tr("Below Ratio Low")),
m_atkHModel(13.5f, 0, 1000, 0.001f, this, tr("Attack High")),
m_atkMModel(22.4f, 0, 1000, 0.001f, this, tr("Attack Mid")),
m_atkLModel(47.8f, 0, 1000, 0.001f, this, tr("Attack Low")),
m_relHModel(132, 0, 1000, 0.001f, this, tr("Release High")),
m_relMModel(282, 0, 1000, 0.001f, this, tr("Release Mid")),
m_relLModel(282, 0, 1000, 0.001f, this, tr("Release Low")),
m_rmsTimeModel(10, 0, 500, 0.001f, this, tr("RMS Time")),
m_kneeModel(6, 0, 36, 0.00001f, this, tr("Knee")),
m_rangeModel(36, 0, 96, 0.00001f, this, tr("Range")),
m_balanceModel(0, -18, 18, 0.00001f, this, tr("Balance")),
m_depthScalingModel(true, this, tr("Scale output volume with Depth")),
m_stereoLinkModel(false, this, tr("Stereo Link")),
m_autoTimeModel(0, 0, 1, 0.00001f, this, tr("Auto Time")),
m_mixModel(1, 0, 1, 0.00001f, this, tr("Mix")),
m_feedbackModel(false, this, tr("Feedback")),
m_midsideModel(false, this, tr("Mid/Side")),
m_lookaheadEnableModel(false, this, tr("Lookahead")),
m_lookaheadModel(0.f, 0.f, LOMM_MAX_LOOKAHEAD, 0.01f, this, tr("Lookahead Length")),
m_lowSideUpwardSuppressModel(false, this, tr("Suppress upward compression for side band"))
{
auto models = {&m_timeModel, &m_inVolModel, &m_outVolModel, &m_inHighModel, &m_inMidModel,
&m_inLowModel, &m_outHighModel, &m_outMidModel, &m_outLowModel, &m_aRatioHModel,
&m_aRatioMModel, &m_aRatioLModel, &m_bRatioHModel, &m_bRatioMModel, &m_bRatioLModel,
&m_atkHModel, &m_atkMModel, &m_atkLModel, &m_relHModel, &m_relMModel, &m_relLModel,
&m_rmsTimeModel, &m_balanceModel};
for (auto model : models) { model->setScaleLogarithmic(true); }
}
void LOMMControls::resetAllParameters()
{
int choice = QMessageBox::question(m_view, "Clear Plugin Settings", "Are you sure you want to clear all parameters?\n(This wipes LOMM to a clean slate, not the default preset.)", QMessageBox::Yes | QMessageBox::No);
if (choice != QMessageBox::Yes) { return; }
// give the user a chance to beg LMMS for forgiveness
addJournalCheckPoint();
// This plugin's normal default values are fairly close to what they'd want in most applications.
// The Init button is there so the user can start from a clean slate instead.
// These are those values.
setInitAndReset(m_depthModel, 1);
setInitAndReset(m_timeModel, 1);
setInitAndReset(m_inVolModel, 0);
setInitAndReset(m_outVolModel, 0);
setInitAndReset(m_upwardModel, 1);
setInitAndReset(m_downwardModel, 1);
setInitAndReset(m_split1Model, 2500);
setInitAndReset(m_split2Model, 88);
setInitAndReset(m_split1EnabledModel, true);
setInitAndReset(m_split2EnabledModel, true);
setInitAndReset(m_band1EnabledModel, true);
setInitAndReset(m_band2EnabledModel, true);
setInitAndReset(m_band3EnabledModel, true);
setInitAndReset(m_inHighModel, 0);
setInitAndReset(m_inMidModel, 0);
setInitAndReset(m_inLowModel, 0);
setInitAndReset(m_outHighModel, 0);
setInitAndReset(m_outMidModel, 0);
setInitAndReset(m_outLowModel, 0);
setInitAndReset(m_aThreshHModel, m_aThreshHModel.maxValue());
setInitAndReset(m_aThreshMModel, m_aThreshMModel.maxValue());
setInitAndReset(m_aThreshLModel, m_aThreshLModel.maxValue());
setInitAndReset(m_aRatioHModel, 1);
setInitAndReset(m_aRatioMModel, 1);
setInitAndReset(m_aRatioLModel, 1);
setInitAndReset(m_bThreshHModel, m_bThreshHModel.minValue());
setInitAndReset(m_bThreshMModel, m_bThreshMModel.minValue());
setInitAndReset(m_bThreshLModel, m_bThreshLModel.minValue());
setInitAndReset(m_bRatioHModel, 1);
setInitAndReset(m_bRatioMModel, 1);
setInitAndReset(m_bRatioLModel, 1);
setInitAndReset(m_atkHModel, 13.5);
setInitAndReset(m_atkMModel, 22.4);
setInitAndReset(m_atkLModel, 47.8);
setInitAndReset(m_relHModel, 132);
setInitAndReset(m_relMModel, 282);
setInitAndReset(m_relLModel, 282);
setInitAndReset(m_rmsTimeModel, 10);
setInitAndReset(m_kneeModel, 6);
setInitAndReset(m_rangeModel, 36);
setInitAndReset(m_balanceModel, 0);
setInitAndReset(m_depthScalingModel, true);
setInitAndReset(m_stereoLinkModel, false);
setInitAndReset(m_autoTimeModel, 0);
setInitAndReset(m_mixModel, 1);
setInitAndReset(m_feedbackModel, false);
setInitAndReset(m_midsideModel, false);
setInitAndReset(m_lookaheadEnableModel, false);
setInitAndReset(m_lookaheadModel, 0.f);
setInitAndReset(m_lowSideUpwardSuppressModel, false);
}
void LOMMControls::loadSettings(const QDomElement& parent)
{
m_depthModel.loadSettings(parent, "depth");
m_timeModel.loadSettings(parent, "time");
m_inVolModel.loadSettings(parent, "inVol");
m_outVolModel.loadSettings(parent, "outVol");
m_upwardModel.loadSettings(parent, "upward");
m_downwardModel.loadSettings(parent, "downward");
m_split1Model.loadSettings(parent, "split1");
m_split2Model.loadSettings(parent, "split2");
m_split1EnabledModel.loadSettings(parent, "split1Enabled");
m_split2EnabledModel.loadSettings(parent, "split2Enabled");
m_band1EnabledModel.loadSettings(parent, "band1Enabled");
m_band2EnabledModel.loadSettings(parent, "band2Enabled");
m_band3EnabledModel.loadSettings(parent, "band3Enabled");
m_inHighModel.loadSettings(parent, "inHigh");
m_inMidModel.loadSettings(parent, "inMid");
m_inLowModel.loadSettings(parent, "inLow");
m_outHighModel.loadSettings(parent, "outHigh");
m_outMidModel.loadSettings(parent, "outMid");
m_outLowModel.loadSettings(parent, "outLow");
m_aThreshHModel.loadSettings(parent, "aThreshH");
m_aThreshMModel.loadSettings(parent, "aThreshM");
m_aThreshLModel.loadSettings(parent, "aThreshL");
m_aRatioHModel.loadSettings(parent, "aRatioH");
m_aRatioMModel.loadSettings(parent, "aRatioM");
m_aRatioLModel.loadSettings(parent, "aRatioL");
m_bThreshHModel.loadSettings(parent, "bThreshH");
m_bThreshMModel.loadSettings(parent, "bThreshM");
m_bThreshLModel.loadSettings(parent, "bThreshL");
m_bRatioHModel.loadSettings(parent, "bRatioH");
m_bRatioMModel.loadSettings(parent, "bRatioM");
m_bRatioLModel.loadSettings(parent, "bRatioL");
m_atkHModel.loadSettings(parent, "atkH");
m_atkMModel.loadSettings(parent, "atkM");
m_atkLModel.loadSettings(parent, "atkL");
m_relHModel.loadSettings(parent, "relH");
m_relMModel.loadSettings(parent, "relM");
m_relLModel.loadSettings(parent, "relL");
m_rmsTimeModel.loadSettings(parent, "rmsTime");
m_kneeModel.loadSettings(parent, "knee");
m_rangeModel.loadSettings(parent, "range");
m_balanceModel.loadSettings(parent, "balance");
m_depthScalingModel.loadSettings(parent, "depthScaling");
m_stereoLinkModel.loadSettings(parent, "stereoLink");
m_autoTimeModel.loadSettings(parent, "autoTime");
m_mixModel.loadSettings(parent, "mix");
m_feedbackModel.loadSettings(parent, "feedback");
m_midsideModel.loadSettings(parent, "midside");
m_lookaheadEnableModel.loadSettings(parent, "lookaheadEnable");
m_lookaheadModel.loadSettings(parent, "lookahead");
m_lowSideUpwardSuppressModel.loadSettings(parent, "lowSideUpwardSuppress");
}
void LOMMControls::saveSettings(QDomDocument& doc, QDomElement& parent)
{
m_depthModel.saveSettings(doc, parent, "depth");
m_timeModel.saveSettings(doc, parent, "time");
m_inVolModel.saveSettings(doc, parent, "inVol");
m_outVolModel.saveSettings(doc, parent, "outVol");
m_upwardModel.saveSettings(doc, parent, "upward");
m_downwardModel.saveSettings(doc, parent, "downward");
m_split1Model.saveSettings(doc, parent, "split1");
m_split2Model.saveSettings(doc, parent, "split2");
m_split1EnabledModel.saveSettings(doc, parent, "split1Enabled");
m_split2EnabledModel.saveSettings(doc, parent, "split2Enabled");
m_band1EnabledModel.saveSettings(doc, parent, "band1Enabled");
m_band2EnabledModel.saveSettings(doc, parent, "band2Enabled");
m_band3EnabledModel.saveSettings(doc, parent, "band3Enabled");
m_inHighModel.saveSettings(doc, parent, "inHigh");
m_inMidModel.saveSettings(doc, parent, "inMid");
m_inLowModel.saveSettings(doc, parent, "inLow");
m_outHighModel.saveSettings(doc, parent, "outHigh");
m_outMidModel.saveSettings(doc, parent, "outMid");
m_outLowModel.saveSettings(doc, parent, "outLow");
m_aThreshHModel.saveSettings(doc, parent, "aThreshH");
m_aThreshMModel.saveSettings(doc, parent, "aThreshM");
m_aThreshLModel.saveSettings(doc, parent, "aThreshL");
m_aRatioHModel.saveSettings(doc, parent, "aRatioH");
m_aRatioMModel.saveSettings(doc, parent, "aRatioM");
m_aRatioLModel.saveSettings(doc, parent, "aRatioL");
m_bThreshHModel.saveSettings(doc, parent, "bThreshH");
m_bThreshMModel.saveSettings(doc, parent, "bThreshM");
m_bThreshLModel.saveSettings(doc, parent, "bThreshL");
m_bRatioHModel.saveSettings(doc, parent, "bRatioH");
m_bRatioMModel.saveSettings(doc, parent, "bRatioM");
m_bRatioLModel.saveSettings(doc, parent, "bRatioL");
m_atkHModel.saveSettings(doc, parent, "atkH");
m_atkMModel.saveSettings(doc, parent, "atkM");
m_atkLModel.saveSettings(doc, parent, "atkL");
m_relHModel.saveSettings(doc, parent, "relH");
m_relMModel.saveSettings(doc, parent, "relM");
m_relLModel.saveSettings(doc, parent, "relL");
m_rmsTimeModel.saveSettings(doc, parent, "rmsTime");
m_kneeModel.saveSettings(doc, parent, "knee");
m_rangeModel.saveSettings(doc, parent, "range");
m_balanceModel.saveSettings(doc, parent, "balance");
m_depthScalingModel.saveSettings(doc, parent, "depthScaling");
m_stereoLinkModel.saveSettings(doc, parent, "stereoLink");
m_autoTimeModel.saveSettings(doc, parent, "autoTime");
m_mixModel.saveSettings(doc, parent, "mix");
m_feedbackModel.saveSettings(doc, parent, "feedback");
m_midsideModel.saveSettings(doc, parent, "midside");
m_lookaheadEnableModel.saveSettings(doc, parent, "lookaheadEnable");
m_lookaheadModel.saveSettings(doc, parent, "lookahead");
m_lowSideUpwardSuppressModel.saveSettings(doc, parent, "lowSideUpwardSuppress");
}
} // namespace lmms
| 13,053
|
C++
|
.cpp
| 257
| 48.766537
| 216
| 0.758102
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,643
|
LOMMControlDialog.cpp
|
LMMS_lmms/plugins/LOMM/LOMMControlDialog.cpp
|
/*
* LOMMControlDialog.cpp
*
* Copyright (c) 2023 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LOMM.h"
#include "LOMMControlDialog.h"
#include "LOMMControls.h"
namespace lmms::gui
{
LOMMControlDialog::LOMMControlDialog(LOMMControls* controls) :
EffectControlDialog(controls),
m_controls(controls)
{
setAutoFillBackground(true);
QPalette pal;
pal.setBrush(backgroundRole(), PLUGIN_NAME::getIconPixmap("artwork"));
setPalette(pal);
setFixedSize(400, 256);
createKnob(KnobType::Bright26, this, 10, 4, &controls->m_depthModel, tr("Depth:"), "", tr("Compression amount for all bands"));
createKnob(KnobType::Bright26, this, 10, 41, &controls->m_timeModel, tr("Time:"), "", tr("Attack/release scaling for all bands"));
createKnob(KnobType::Bright26, this, 10, 220, &controls->m_inVolModel, tr("Input Volume:"), " dB", tr("Input volume"));
createKnob(KnobType::Bright26, this, 363, 220, &controls->m_outVolModel, tr("Output Volume:"), " dB", tr("Output volume"));
createKnob(KnobType::Bright26, this, 10, 179, &controls->m_upwardModel, tr("Upward Depth:"), "", tr("Upward compression amount for all bands"));
createKnob(KnobType::Bright26, this, 363, 179, &controls->m_downwardModel, tr("Downward Depth:"), "", tr("Downward compression amount for all bands"));
createLcdFloatSpinBox(5, 2, "11green", tr("High/Mid Crossover"), this, 352, 76, &controls->m_split1Model, tr("High/Mid Crossover"));
createLcdFloatSpinBox(5, 2, "11green", tr("Mid/Low Crossover"), this, 352, 156, &controls->m_split2Model, tr("Mid/Low Crossover"));
createPixmapButton(tr("High/mid band split"), this, 369, 104, &controls->m_split1EnabledModel, "crossover_led_green", "crossover_led_off", tr("High/mid band split"));
createPixmapButton(tr("Mid/low band split"), this, 369, 126, &controls->m_split2EnabledModel, "crossover_led_green", "crossover_led_off", tr("Mid/low band split"));
createPixmapButton(tr("Enable High Band"), this, 143, 66, &controls->m_band1EnabledModel, "high_band_active", "high_band_inactive", tr("Enable High Band"));
createPixmapButton(tr("Enable Mid Band"), this, 143, 146, &controls->m_band2EnabledModel, "mid_band_active", "mid_band_inactive", tr("Enable Mid Band"));
createPixmapButton(tr("Enable Low Band"), this, 143, 226, &controls->m_band3EnabledModel, "low_band_active", "low_band_inactive", tr("Enable Low Band"));
createKnob(KnobType::Bright26, this, 53, 43, &controls->m_inHighModel, tr("High Input Volume:"), " dB", tr("Input volume for high band"));
createKnob(KnobType::Bright26, this, 53, 123, &controls->m_inMidModel, tr("Mid Input Volume:"), " dB", tr("Input volume for mid band"));
createKnob(KnobType::Bright26, this, 53, 203, &controls->m_inLowModel, tr("Low Input Volume:"), " dB", tr("Input volume for low band"));
createKnob(KnobType::Bright26, this, 320, 43, &controls->m_outHighModel, tr("High Output Volume:"), " dB", tr("Output volume for high band"));
createKnob(KnobType::Bright26, this, 320, 123, &controls->m_outMidModel, tr("Mid Output Volume:"), " dB", tr("Output volume for mid band"));
createKnob(KnobType::Bright26, this, 320, 203, &controls->m_outLowModel, tr("Low Output Volume:"), " dB", tr("Output volume for low band"));
createLcdFloatSpinBox(3, 3, "11green", tr("Above Threshold High"), this, 300, 13, &controls->m_aThreshHModel, tr("Downward compression threshold for high band"));
createLcdFloatSpinBox(3, 3, "11green", tr("Above Threshold Mid"), this, 300, 93, &controls->m_aThreshMModel, tr("Downward compression threshold for mid band"));
createLcdFloatSpinBox(3, 3, "11green", tr("Above Threshold Low"), this, 300, 173, &controls->m_aThreshLModel, tr("Downward compression threshold for low band"));
createLcdFloatSpinBox(2, 2, "11green", tr("Above Ratio High"), this, 284, 44, &controls->m_aRatioHModel, tr("Downward compression ratio for high band"));
createLcdFloatSpinBox(2, 2, "11green", tr("Above Ratio Mid"), this, 284, 124, &controls->m_aRatioMModel, tr("Downward compression ratio for mid band"));
createLcdFloatSpinBox(2, 2, "11green", tr("Above Ratio Low"), this, 284, 204, &controls->m_aRatioLModel, tr("Downward compression ratio for low band"));
createLcdFloatSpinBox(3, 3, "11green", tr("Below Threshold High"), this, 59, 13, &controls->m_bThreshHModel, tr("Upward compression threshold for high band"));
createLcdFloatSpinBox(3, 3, "11green", tr("Below Threshold Mid"), this, 59, 93, &controls->m_bThreshMModel, tr("Upward compression threshold for mid band"));
createLcdFloatSpinBox(3, 3, "11green", tr("Below Threshold Low"), this, 59, 173, &controls->m_bThreshLModel, tr("Upward compression threshold for low band"));
createLcdFloatSpinBox(2, 2, "11green", tr("Below Ratio High"), this, 87, 44, &controls->m_bRatioHModel, tr("Upward compression ratio for high band"));
createLcdFloatSpinBox(2, 2, "11green", tr("Below Ratio Mid"), this, 87, 124, &controls->m_bRatioMModel, tr("Upward compression ratio for mid band"));
createLcdFloatSpinBox(2, 2, "11green", tr("Below Ratio Low"), this, 87, 204, &controls->m_bRatioLModel, tr("Upward compression ratio for low band"));
createKnob(KnobType::Small17, this, 120, 61, &controls->m_atkHModel, tr("Attack High:"), " ms", tr("Attack time for high band"));
createKnob(KnobType::Small17, this, 120, 141, &controls->m_atkMModel, tr("Attack Mid:"), " ms", tr("Attack time for mid band"));
createKnob(KnobType::Small17, this, 120, 221, &controls->m_atkLModel, tr("Attack Low:"), " ms", tr("Attack time for low band"));
createKnob(KnobType::Small17, this, 261, 61, &controls->m_relHModel, tr("Release High:"), " ms", tr("Release time for high band"));
createKnob(KnobType::Small17, this, 261, 141, &controls->m_relMModel, tr("Release Mid:"), " ms", tr("Release time for mid band"));
createKnob(KnobType::Small17, this, 261, 221, &controls->m_relLModel, tr("Release Low:"), " ms", tr("Release time for low band"));
createKnob(KnobType::Small17, this, 380, 42, &controls->m_rmsTimeModel, tr("RMS Time:"), " ms", tr("RMS size for sidechain signal (set to 0 for Peak mode)"));
createKnob(KnobType::Small17, this, 356, 42, &controls->m_kneeModel, tr("Knee:"), " dB", tr("Knee size for all compressors"));
createKnob(KnobType::Small17, this, 24, 146, &controls->m_rangeModel, tr("Range:"), " dB", tr("Maximum gain increase for all bands"));
createKnob(KnobType::Small17, this, 13, 114, &controls->m_balanceModel, tr("Balance:"), " dB", tr("Bias input volume towards one channel"));
createPixmapButton(tr("Scale output volume with Depth"), this, 51, 0, &controls->m_depthScalingModel, "depthScaling_active", "depthScaling_inactive",
tr("Scale output volume with Depth parameter"));
createPixmapButton(tr("Stereo Link"), this, 52, 237, &controls->m_stereoLinkModel, "stereoLink_active", "stereoLink_inactive",
tr("Apply same gain change to both channels"));
createKnob(KnobType::Small17, this, 24, 80, &controls->m_autoTimeModel, tr("Auto Time:"), "", tr("Speed up attack and release times when transients occur"));
createKnob(KnobType::Bright26, this, 363, 4, &controls->m_mixModel, tr("Mix:"), "", tr("Wet/Dry of all bands"));
m_feedbackButton = createPixmapButton(tr("Feedback"), this, 317, 238, &controls->m_feedbackModel, "feedback_active", "feedback_inactive",
tr("Use output as sidechain signal instead of input"));
createPixmapButton(tr("Mid/Side"), this, 285, 238, &controls->m_midsideModel, "midside_active", "midside_inactive", tr("Compress mid/side channels instead of left/right"));
m_lowSideUpwardSuppressButton = createPixmapButton(tr("Suppress upward compression for side band"), this, 106, 180, &controls->m_lowSideUpwardSuppressModel,
"lowSideUpwardSuppress_active", "lowSideUpwardSuppress_inactive", tr("Suppress upward compression for side band"));
createPixmapButton(tr("Lookahead"), this, 147, 0, &controls->m_lookaheadEnableModel, "lookahead_active", "lookahead_inactive",
tr(("Enable lookahead with fixed " + std::to_string(int(LOMM_MAX_LOOKAHEAD)) + " ms latency").c_str()));
createLcdFloatSpinBox(2, 2, "11green", tr("Lookahead"), this, 214, 2, &controls->m_lookaheadModel, tr("Lookahead length"));
PixmapButton* initButton = createPixmapButton(tr("Clear all parameters"), this, 84, 237, nullptr, "init_active", "init_inactive", tr("Clear all parameters"));
connect(initButton, SIGNAL(clicked()), m_controls, SLOT(resetAllParameters()));
connect(&controls->m_lookaheadEnableModel, SIGNAL(dataChanged()), this, SLOT(updateFeedbackVisibility()));
connect(&controls->m_midsideModel, SIGNAL(dataChanged()), this, SLOT(updateLowSideUpwardSuppressVisibility()));
connect(getGUI()->mainWindow(), SIGNAL(periodicUpdate()), this, SLOT(updateDisplay()));
emit updateFeedbackVisibility();
emit updateLowSideUpwardSuppressVisibility();
}
void LOMMControlDialog::updateFeedbackVisibility()
{
m_feedbackButton->setVisible(!m_controls->m_lookaheadEnableModel.value());
}
void LOMMControlDialog::updateLowSideUpwardSuppressVisibility()
{
m_lowSideUpwardSuppressButton->setVisible(m_controls->m_midsideModel.value());
}
void LOMMControlDialog::updateDisplay()
{
update();
}
void LOMMControlDialog::paintEvent(QPaintEvent *event)
{
if (!isVisible()) { return; }
QPainter p;
p.begin(this);
// Draw threshold lines
QColor aColor(255, 255, 0, 31);
QColor bColor(255, 0, 0, 31);
QPen aPen(QColor(255, 255, 0, 255), 1);
QPen bPen(QColor(255, 0, 0, 255), 1);
int thresholdsX[] = {dbfsToX(m_controls->m_aThreshHModel.value()),
dbfsToX(m_controls->m_aThreshMModel.value()),
dbfsToX(m_controls->m_aThreshLModel.value()),
dbfsToX(m_controls->m_bThreshHModel.value()),
dbfsToX(m_controls->m_bThreshMModel.value()),
dbfsToX(m_controls->m_bThreshLModel.value())};
for (int i = 0; i < 3; ++i) {
p.setPen(aPen);
p.fillRect(thresholdsX[i], LOMM_DISPLAY_Y[2 * i], LOMM_DISPLAY_X + LOMM_DISPLAY_WIDTH - thresholdsX[i], LOMM_DISPLAY_Y[2 * i + 1] + LOMM_DISPLAY_HEIGHT - LOMM_DISPLAY_Y[2 * i], aColor);
p.drawLine(thresholdsX[i], LOMM_DISPLAY_Y[2 * i], thresholdsX[i], LOMM_DISPLAY_Y[2 * i + 1] + LOMM_DISPLAY_HEIGHT);
p.setPen(bPen);
p.fillRect(LOMM_DISPLAY_X, LOMM_DISPLAY_Y[2 * i], thresholdsX[i + 3] - LOMM_DISPLAY_X, LOMM_DISPLAY_Y[2 * i + 1] + LOMM_DISPLAY_HEIGHT - LOMM_DISPLAY_Y[2 * i], bColor);
p.drawLine(thresholdsX[i + 3], LOMM_DISPLAY_Y[2 * i], thresholdsX[i + 3], LOMM_DISPLAY_Y[2 * i + 1] + LOMM_DISPLAY_HEIGHT);
}
QPen inputPen(QColor(200, 200, 200, 80), 1);
QPen outputPen(QColor(255, 255, 255, 255), 1);
for (int i = 0; i < 3; ++i) {
// Draw input lines
p.setPen(inputPen);
int inL = dbfsToX(m_controls->m_effect->m_displayIn[i][0]);
p.drawLine(inL, LOMM_DISPLAY_Y[2 * i] + 4, inL, LOMM_DISPLAY_Y[2 * i] + LOMM_DISPLAY_HEIGHT);
int inR = dbfsToX(m_controls->m_effect->m_displayIn[i][1]);
p.drawLine(inR, LOMM_DISPLAY_Y[2 * i + 1], inR, LOMM_DISPLAY_Y[2 * i + 1] + LOMM_DISPLAY_HEIGHT - 4);
// Draw output lines
p.setPen(outputPen);
int outL = dbfsToX(m_controls->m_effect->m_displayOut[i][0]);
p.drawLine(outL, LOMM_DISPLAY_Y[2 * i], outL, LOMM_DISPLAY_Y[2 * i] + LOMM_DISPLAY_HEIGHT);
int outR = dbfsToX(m_controls->m_effect->m_displayOut[i][1]);
p.drawLine(outR, LOMM_DISPLAY_Y[2 * i + 1], outR, LOMM_DISPLAY_Y[2 * i + 1] + LOMM_DISPLAY_HEIGHT);
}
p.end();
}
int LOMMControlDialog::dbfsToX(float dbfs)
{
float returnX = (dbfs - LOMM_DISPLAY_MIN) / (LOMM_DISPLAY_MAX - LOMM_DISPLAY_MIN);
returnX = qBound(LOMM_DISPLAY_X, LOMM_DISPLAY_X + returnX * LOMM_DISPLAY_WIDTH, LOMM_DISPLAY_X + LOMM_DISPLAY_WIDTH);
return returnX;
}
float LOMMControlDialog::xToDbfs(int x)
{
float xNorm = static_cast<float>(x - LOMM_DISPLAY_X) / LOMM_DISPLAY_WIDTH;
float dbfs = xNorm * (LOMM_DISPLAY_MAX - LOMM_DISPLAY_MIN) + LOMM_DISPLAY_MIN;
return dbfs;
}
void LOMMControlDialog::mousePressEvent(QMouseEvent* event)
{
if ((event->button() == Qt::LeftButton || event->button() == Qt::MiddleButton) && !(event->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier)))
{
const QPoint& p = event->pos();
if (LOMM_DISPLAY_X - 10 <= p.x() && p.x() <= LOMM_DISPLAY_X + LOMM_DISPLAY_WIDTH + 10)
{
FloatModel* aThresh[] = {&m_controls->m_aThreshHModel, &m_controls->m_aThreshMModel, &m_controls->m_aThreshLModel};
FloatModel* bThresh[] = {&m_controls->m_bThreshHModel, &m_controls->m_bThreshMModel, &m_controls->m_bThreshLModel};
for (int i = 0; i < 3; ++i)
{
if (LOMM_DISPLAY_Y[i * 2] <= p.y() && p.y() <= LOMM_DISPLAY_Y[i * 2 + 1] + LOMM_DISPLAY_HEIGHT)
{
int behavior = (p.x() < dbfsToX(bThresh[i]->value())) ? 0 : (p.x() > dbfsToX(aThresh[i]->value())) ? 1 : 2;
if (event->button() == Qt::MiddleButton)
{
if (behavior == 0 || behavior == 2) {bThresh[i]->reset();}
if (behavior == 1 || behavior == 2) {aThresh[i]->reset();}
return;
}
m_bandDrag = i;
m_lastMousePos = p;
m_buttonPressed = true;
m_dragType = behavior;
return;
}
}
}
}
}
void LOMMControlDialog::mouseMoveEvent(QMouseEvent * event)
{
if (m_buttonPressed && event->pos() != m_lastMousePos)
{
const float distance = event->pos().x() - m_lastMousePos.x();
float dbDistance = distance * LOMM_DISPLAY_DB_PER_PIXEL;
m_lastMousePos = event->pos();
FloatModel* aModel[] = {&m_controls->m_aThreshHModel, &m_controls->m_aThreshMModel, &m_controls->m_aThreshLModel};
FloatModel* bModel[] = {&m_controls->m_bThreshHModel, &m_controls->m_bThreshMModel, &m_controls->m_bThreshLModel};
float bVal = bModel[m_bandDrag]->value();
float aVal = aModel[m_bandDrag]->value();
if (m_dragType == 0)
{
bModel[m_bandDrag]->setValue(bVal + dbDistance);
}
else if (m_dragType == 1)
{
aModel[m_bandDrag]->setValue(aVal + dbDistance);
}
else
{
dbDistance = qBound(bModel[m_bandDrag]->minValue(), bVal + dbDistance, bModel[m_bandDrag]->maxValue()) - bVal;
dbDistance = qBound(aModel[m_bandDrag]->minValue(), aVal + dbDistance, aModel[m_bandDrag]->maxValue()) - aVal;
bModel[m_bandDrag]->setValue(bVal + dbDistance);
aModel[m_bandDrag]->setValue(aVal + dbDistance);
}
}
}
void LOMMControlDialog::mouseReleaseEvent(QMouseEvent* event)
{
if (event && event->button() == Qt::LeftButton)
{
m_buttonPressed = false;
}
}
} // namespace lmms::gui
| 15,057
|
C++
|
.cpp
| 232
| 62.008621
| 187
| 0.708277
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,644
|
LOMM.cpp
|
LMMS_lmms/plugins/LOMM/LOMM.cpp
|
/*
* LOMM.cpp
*
* Copyright (c) 2023 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LOMM.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT lomm_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"LOMM",
QT_TRANSLATE_NOOP("PluginBrowser", "Upwards/downwards multiband compression plugin powered by the eldritch elder god LOMMUS."),
"Lost Robot <r94231/at/gmail/dot/com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr
};
}
LOMMEffect::LOMMEffect(Model* parent, const Descriptor::SubPluginFeatures::Key* key) :
Effect(&lomm_plugin_descriptor, parent, key),
m_lommControls(this),
m_sampleRate(Engine::audioEngine()->outputSampleRate()),
m_lp1(m_sampleRate),
m_lp2(m_sampleRate),
m_hp1(m_sampleRate),
m_hp2(m_sampleRate),
m_ap(m_sampleRate),
m_needsUpdate(true),
m_coeffPrecalc(-0.05f),
m_crestTimeConst(0.999f),
m_lookWrite(0),
m_lookBufLength(2)
{
autoQuitModel()->setValue(autoQuitModel()->maxValue());
m_ap.setFilterType(BasicFilters<2>::FilterType::AllPass);
connect(Engine::audioEngine(), SIGNAL(sampleRateChanged()), this, SLOT(changeSampleRate()));
changeSampleRate();
}
void LOMMEffect::changeSampleRate()
{
m_sampleRate = Engine::audioEngine()->outputSampleRate();
m_lp1.setSampleRate(m_sampleRate);
m_lp2.setSampleRate(m_sampleRate);
m_hp1.setSampleRate(m_sampleRate);
m_hp2.setSampleRate(m_sampleRate);
m_ap.setSampleRate(m_sampleRate);
m_coeffPrecalc = -2.2f / (m_sampleRate * 0.001f);
m_needsUpdate = true;
m_crestTimeConst = exp(-1.f / (0.2f * m_sampleRate));
m_lookBufLength = std::ceil((LOMM_MAX_LOOKAHEAD / 1000.f) * m_sampleRate) + 2;
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
m_inLookBuf[j][i].resize(m_lookBufLength);
m_scLookBuf[j][i].resize(m_lookBufLength, LOMM_MIN_FLOOR);
}
}
std::fill(m_yL.begin(), m_yL.end(), std::array<float, 2>{LOMM_MIN_FLOOR, LOMM_MIN_FLOOR});
m_rms = m_gainResult = m_displayIn = m_displayOut = m_prevOut = m_yL;
m_crestPeakVal[0] = m_crestPeakVal[1] = LOMM_MIN_FLOOR;
m_crestRmsVal = m_crestFactorVal = m_crestPeakVal;
}
Effect::ProcessStatus LOMMEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
if (m_needsUpdate || m_lommControls.m_split1Model.isValueChanged())
{
m_lp1.setLowpass(m_lommControls.m_split1Model.value());
m_hp1.setHighpass(m_lommControls.m_split1Model.value());
m_ap.calcFilterCoeffs(m_lommControls.m_split1Model.value(), 0.70710678118f);
}
if (m_needsUpdate || m_lommControls.m_split2Model.isValueChanged())
{
m_lp2.setLowpass(m_lommControls.m_split2Model.value());
m_hp2.setHighpass(m_lommControls.m_split2Model.value());
}
m_needsUpdate = false;
const float d = dryLevel();
const float w = wetLevel();
const float depth = m_lommControls.m_depthModel.value();
const float time = m_lommControls.m_timeModel.value();
const float inVol = dbfsToAmp(m_lommControls.m_inVolModel.value());
const float outVol = dbfsToAmp(m_lommControls.m_outVolModel.value());
const float upward = m_lommControls.m_upwardModel.value();
const float downward = m_lommControls.m_downwardModel.value();
const bool split1Enabled = m_lommControls.m_split1EnabledModel.value();
const bool split2Enabled = m_lommControls.m_split2EnabledModel.value();
const bool band1Enabled = m_lommControls.m_band1EnabledModel.value();
const bool band2Enabled = m_lommControls.m_band2EnabledModel.value();
const bool band3Enabled = m_lommControls.m_band3EnabledModel.value();
const float inHigh = dbfsToAmp(m_lommControls.m_inHighModel.value());
const float inMid = dbfsToAmp(m_lommControls.m_inMidModel.value());
const float inLow = dbfsToAmp(m_lommControls.m_inLowModel.value());
float inBandVol[3] = {inHigh, inMid, inLow};
const float outHigh = dbfsToAmp(m_lommControls.m_outHighModel.value());
const float outMid = dbfsToAmp(m_lommControls.m_outMidModel.value());
const float outLow = dbfsToAmp(m_lommControls.m_outLowModel.value());
float outBandVol[3] = {outHigh, outMid, outLow};
const float aThreshH = m_lommControls.m_aThreshHModel.value();
const float aThreshM = m_lommControls.m_aThreshMModel.value();
const float aThreshL = m_lommControls.m_aThreshLModel.value();
float aThresh[3] = {aThreshH, aThreshM, aThreshL};
const float aRatioH = m_lommControls.m_aRatioHModel.value();
const float aRatioM = m_lommControls.m_aRatioMModel.value();
const float aRatioL = m_lommControls.m_aRatioLModel.value();
float aRatio[3] = {1.f / aRatioH, 1.f / aRatioM, 1.f / aRatioL};
const float bThreshH = m_lommControls.m_bThreshHModel.value();
const float bThreshM = m_lommControls.m_bThreshMModel.value();
const float bThreshL = m_lommControls.m_bThreshLModel.value();
float bThresh[3] = {bThreshH, bThreshM, bThreshL};
const float bRatioH = m_lommControls.m_bRatioHModel.value();
const float bRatioM = m_lommControls.m_bRatioMModel.value();
const float bRatioL = m_lommControls.m_bRatioLModel.value();
float bRatio[3] = {1.f / bRatioH, 1.f / bRatioM, 1.f / bRatioL};
const float atkH = m_lommControls.m_atkHModel.value() * time;
const float atkM = m_lommControls.m_atkMModel.value() * time;
const float atkL = m_lommControls.m_atkLModel.value() * time;
const float atkCoefH = msToCoeff(atkH);
const float atkCoefM = msToCoeff(atkM);
const float atkCoefL = msToCoeff(atkL);
float atk[3] = {atkH, atkM, atkL};
float atkCoef[3] = {atkCoefH, atkCoefM, atkCoefL};
const float relH = m_lommControls.m_relHModel.value() * time;
const float relM = m_lommControls.m_relMModel.value() * time;
const float relL = m_lommControls.m_relLModel.value() * time;
const float relCoefH = msToCoeff(relH);
const float relCoefM = msToCoeff(relM);
const float relCoefL = msToCoeff(relL);
float rel[3] = {relH, relM, relL};
float relCoef[3] = {relCoefH, relCoefM, relCoefL};
const float rmsTime = m_lommControls.m_rmsTimeModel.value();
const float rmsTimeConst = (rmsTime == 0) ? 0 : exp(-1.f / (rmsTime * 0.001f * m_sampleRate));
const float knee = m_lommControls.m_kneeModel.value() * 0.5f;
const float range = m_lommControls.m_rangeModel.value();
const float rangeAmp = dbfsToAmp(range);
const float balance = m_lommControls.m_balanceModel.value();
const float balanceAmpTemp = dbfsToAmp(balance);
const float balanceAmp[2] = {1.f / balanceAmpTemp, balanceAmpTemp};
const bool depthScaling = m_lommControls.m_depthScalingModel.value();
const bool stereoLink = m_lommControls.m_stereoLinkModel.value();
const float autoTime = m_lommControls.m_autoTimeModel.value() * m_lommControls.m_autoTimeModel.value();
const float mix = m_lommControls.m_mixModel.value();
const bool midside = m_lommControls.m_midsideModel.value();
const bool lookaheadEnable = m_lommControls.m_lookaheadEnableModel.value();
const int lookahead = std::ceil((m_lommControls.m_lookaheadModel.value() / 1000.f) * m_sampleRate);
const bool feedback = m_lommControls.m_feedbackModel.value() && !lookaheadEnable;
const bool lowSideUpwardSuppress = m_lommControls.m_lowSideUpwardSuppressModel.value() && midside;
for (fpp_t f = 0; f < frames; ++f)
{
std::array<sample_t, 2> s = {buf[f][0], buf[f][1]};
// Convert left/right to mid/side. Side channel is intentionally made
// to be 6 dB louder to bring it into volume ranges comparable to the mid channel.
if (midside)
{
float tempS0 = s[0];
s[0] = (s[0] + s[1]) * 0.5f;
s[1] = tempS0 - s[1];
}
std::array<std::array<float, 2>, 3> bands = {{}};
std::array<std::array<float, 2>, 3> bandsDry = {{}};
for (int i = 0; i < 2; ++i)// Channels
{
// These values are for the Auto time knob. Higher crest factor allows for faster attack/release.
float inSquared = s[i] * s[i];
m_crestPeakVal[i] = std::max(std::max(LOMM_MIN_FLOOR, inSquared), m_crestTimeConst * m_crestPeakVal[i] + (1 - m_crestTimeConst) * (inSquared));
m_crestRmsVal[i] = std::max(LOMM_MIN_FLOOR, m_crestTimeConst * m_crestRmsVal[i] + ((1 - m_crestTimeConst) * (inSquared)));
m_crestFactorVal[i] = m_crestPeakVal[i] / m_crestRmsVal[i];
float crestFactorValTemp = ((m_crestFactorVal[i] - LOMM_AUTO_TIME_ADJUST) * autoTime) + LOMM_AUTO_TIME_ADJUST;
// Crossover filters
bands[2][i] = m_lp2.update(s[i], i);
bands[1][i] = m_hp2.update(s[i], i);
bands[0][i] = m_hp1.update(bands[1][i], i);
bands[1][i] = m_lp1.update(bands[1][i], i);
bands[2][i] = m_ap.update(bands[2][i], i);
if (!split1Enabled)
{
bands[1][i] += bands[0][i];
bands[0][i] = 0;
}
if (!split2Enabled)
{
bands[1][i] += bands[2][i];
bands[2][i] = 0;
}
// Mute disabled bands
bands[0][i] *= band1Enabled;
bands[1][i] *= band2Enabled;
bands[2][i] *= band3Enabled;
std::array<float, 3> detect = {0, 0, 0};
for (int j = 0; j < 3; ++j)// Bands
{
bandsDry[j][i] = bands[j][i];
if (feedback && !lookaheadEnable)
{
bands[j][i] = m_prevOut[j][i];
}
bands[j][i] *= inBandVol[j] * inVol * balanceAmp[i];
if (rmsTime > 0)// RMS
{
m_rms[j][i] = rmsTimeConst * m_rms[j][i] + ((1 - rmsTimeConst) * (bands[j][i] * bands[j][i]));
detect[j] = std::max(LOMM_MIN_FLOOR, std::sqrt(m_rms[j][i]));
}
else// Peak
{
detect[j] = std::max(LOMM_MIN_FLOOR, std::abs(bands[j][i]));
}
if (detect[j] > m_yL[j][i])// Attack phase
{
// Calculate attack value depending on crest factor
const float currentAttack = autoTime
? msToCoeff(LOMM_AUTO_TIME_ADJUST * atk[j] / crestFactorValTemp)
: atkCoef[j];
m_yL[j][i] = m_yL[j][i] * currentAttack + (1 - currentAttack) * detect[j];
}
else// Release phase
{
// Calculate release value depending on crest factor
const float currentRelease = autoTime
? msToCoeff(LOMM_AUTO_TIME_ADJUST * rel[j] / crestFactorValTemp)
: relCoef[j];
m_yL[j][i] = m_yL[j][i] * currentRelease + (1 - currentRelease) * detect[j];
}
m_yL[j][i] = std::max(LOMM_MIN_FLOOR, m_yL[j][i]);
float yAmp = m_yL[j][i];
if (lookaheadEnable)
{
float temp = yAmp;
// Lookahead is calculated by picking the largest value between
// the current sidechain signal and the delayed sidechain signal.
yAmp = std::max(m_scLookBuf[j][i][m_lookWrite], m_scLookBuf[j][i][(m_lookWrite + m_lookBufLength - lookahead) % m_lookBufLength]);
m_scLookBuf[j][i][m_lookWrite] = temp;
}
const float yDbfs = ampToDbfs(yAmp);
float aboveGain = 0;
float belowGain = 0;
// Downward compression
if (yDbfs - aThresh[j] < -knee)// Below knee
{
aboveGain = yDbfs;
}
else if (yDbfs - aThresh[j] < knee)// Within knee
{
const float temp = yDbfs - aThresh[j] + knee;
aboveGain = yDbfs + (aRatio[j] - 1) * temp * temp / (4 * knee);
}
else// Above knee
{
aboveGain = aThresh[j] + (yDbfs - aThresh[j]) * aRatio[j];
}
if (aboveGain < yDbfs)
{
if (downward * depth <= 1)
{
aboveGain = linearInterpolate(yDbfs, aboveGain, downward * depth);
}
else
{
aboveGain = linearInterpolate(aboveGain, aThresh[j], downward * depth - 1);
}
}
// Upward compression
if (yDbfs - bThresh[j] > knee)// Above knee
{
belowGain = yDbfs;
}
else if (bThresh[j] - yDbfs < knee)// Within knee
{
const float temp = bThresh[j] - yDbfs + knee;
belowGain = yDbfs + (1 - bRatio[j]) * temp * temp / (4 * knee);
}
else// Below knee
{
belowGain = bThresh[j] + (yDbfs - bThresh[j]) * bRatio[j];
}
if (belowGain > yDbfs)
{
if (upward * depth <= 1)
{
belowGain = linearInterpolate(yDbfs, belowGain, upward * depth);
}
else
{
belowGain = linearInterpolate(belowGain, bThresh[j], upward * depth - 1);
}
}
m_displayIn[j][i] = yDbfs;
m_gainResult[j][i] = (dbfsToAmp(aboveGain) / yAmp) * (dbfsToAmp(belowGain) / yAmp);
if (lowSideUpwardSuppress && m_gainResult[j][i] > 1 && j == 2 && i == 1) //undo upward compression if low side band
{
m_gainResult[j][i] = 1;
}
m_gainResult[j][i] = std::min(m_gainResult[j][i], rangeAmp);
m_displayOut[j][i] = ampToDbfs(std::max(LOMM_MIN_FLOOR, yAmp * m_gainResult[j][i]));
// Apply the same gain reduction to both channels if stereo link is enabled.
if (stereoLink && i == 1)
{
if (m_gainResult[j][1] < m_gainResult[j][0])
{
m_gainResult[j][0] = m_gainResult[j][1];
m_displayOut[j][0] = m_displayIn[j][0] - (m_displayIn[j][1] - m_displayOut[j][1]);
}
else
{
m_gainResult[j][1] = m_gainResult[j][0];
m_displayOut[j][1] = m_displayIn[j][1] - (m_displayIn[j][0] - m_displayOut[j][0]);
}
}
}
}
for (int i = 0; i < 2; ++i)// Channels
{
for (int j = 0; j < 3; ++j)// Bands
{
if (lookaheadEnable)
{
float temp = bands[j][i];
bands[j][i] = m_inLookBuf[j][i][m_lookWrite];
m_inLookBuf[j][i][m_lookWrite] = temp;
bandsDry[j][i] = bands[j][i];
}
else if (feedback)
{
bands[j][i] = bandsDry[j][i] * inBandVol[j] * inVol * balanceAmp[i];
}
// Apply gain reduction
bands[j][i] *= m_gainResult[j][i];
// Store for Feedback
m_prevOut[j][i] = bands[j][i];
bands[j][i] *= outBandVol[j];
bands[j][i] = linearInterpolate(bandsDry[j][i], bands[j][i], mix);
}
s[i] = bands[0][i] + bands[1][i] + bands[2][i];
s[i] *= linearInterpolate(1.f, outVol, mix * (depthScaling ? depth : 1));
}
// Convert mid/side back to left/right.
// Note that the side channel was intentionally made to be 6 dB louder prior to compression.
if (midside)
{
float tempS0 = s[0];
s[0] = s[0] + (s[1] * 0.5f);
s[1] = tempS0 - (s[1] * 0.5f);
}
if (--m_lookWrite < 0) { m_lookWrite = m_lookBufLength - 1; }
buf[f][0] = d * buf[f][0] + w * s[0];
buf[f][1] = d * buf[f][1] + w * s[1];
}
return ProcessStatus::ContinueIfNotQuiet;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main(Model* parent, void* data)
{
return new LOMMEffect(parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(data));
}
}
} // namespace lmms
| 15,112
|
C++
|
.cpp
| 382
| 35.625654
| 146
| 0.674995
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,645
|
MonoDelay.cpp
|
LMMS_lmms/plugins/Flanger/MonoDelay.cpp
|
/*
* monodelay.cpp - defination of MonoDelay class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "MonoDelay.h"
#include "string.h"
namespace lmms
{
MonoDelay::MonoDelay( int maxTime , int sampleRate )
{
m_buffer = 0;
m_maxTime = static_cast<float>(maxTime);
m_maxLength = maxTime * sampleRate;
m_length = static_cast<float>(m_maxLength);
m_writeIndex = 0;
m_feedback = 0.0f;
setSampleRate( sampleRate );
}
MonoDelay::~MonoDelay()
{
if( m_buffer )
{
delete m_buffer;
}
}
void MonoDelay::tick( sample_t* sample )
{
m_writeIndex = ( m_writeIndex + 1 ) % ( int )m_maxLength;
int readIndex = m_writeIndex - static_cast<int>(m_length);
if (readIndex < 0 ) { readIndex += m_maxLength; }
float out = m_buffer[ readIndex ];
m_buffer[ m_writeIndex ] = *sample + ( out * m_feedback );
*sample = out;
}
void MonoDelay::setSampleRate( int sampleRate )
{
if( m_buffer )
{
delete m_buffer;
}
m_buffer = new sample_t[( int )( sampleRate * m_maxTime ) ];
memset( m_buffer, 0, sizeof(float) * ( int )( sampleRate * m_maxTime ) );
}
} // namespace lmms
| 1,917
|
C++
|
.cpp
| 63
| 28.365079
| 75
| 0.717012
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,646
|
FlangerControlsDialog.cpp
|
LMMS_lmms/plugins/Flanger/FlangerControlsDialog.cpp
|
/*
* flangercontrolsdialog.cpp - defination of FlangerControlsDialog class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "FlangerControlsDialog.h"
#include "embed.h"
#include "FlangerControls.h"
#include "LedCheckBox.h"
#include "TempoSyncKnob.h"
namespace lmms::gui
{
FlangerControlsDialog::FlangerControlsDialog( FlangerControls *controls ) :
EffectControlDialog( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 233, 75 );
auto delayKnob = new Knob(KnobType::Bright26, this);
delayKnob->move( 10,10 );
delayKnob->setVolumeKnob( false );
delayKnob->setModel( &controls->m_delayTimeModel );
delayKnob->setLabel( tr( "DELAY" ) );
delayKnob->setHintText( tr( "Delay time:" ) + " ", "s" );
auto lfoFreqKnob = new TempoSyncKnob(KnobType::Bright26, this);
lfoFreqKnob->move( 48,10 );
lfoFreqKnob->setVolumeKnob( false );
lfoFreqKnob->setModel( &controls->m_lfoFrequencyModel );
lfoFreqKnob->setLabel( tr( "RATE" ) );
lfoFreqKnob->setHintText( tr( "Period:" ) , " Sec" );
auto lfoAmtKnob = new Knob(KnobType::Bright26, this);
lfoAmtKnob->move( 85,10 );
lfoAmtKnob->setVolumeKnob( false );
lfoAmtKnob->setModel( &controls->m_lfoAmountModel );
lfoAmtKnob->setLabel( tr( "AMNT" ) );
lfoAmtKnob->setHintText( tr( "Amount:" ) , "" );
auto lfoPhaseKnob = new Knob(KnobType::Bright26, this);
lfoPhaseKnob->move( 123,10 );
lfoPhaseKnob->setVolumeKnob( false );
lfoPhaseKnob->setModel( &controls->m_lfoPhaseModel );
lfoPhaseKnob->setLabel( tr( "PHASE" ) );
lfoPhaseKnob->setHintText( tr( "Phase:" ) , " degrees" );
auto feedbackKnob = new Knob(KnobType::Bright26, this);
feedbackKnob->move( 160,10 );
feedbackKnob->setVolumeKnob( true) ;
feedbackKnob->setModel( &controls->m_feedbackModel );
feedbackKnob->setLabel( tr( "FDBK" ) );
feedbackKnob->setHintText( tr( "Feedback amount:" ) , "" );
auto whiteNoiseKnob = new Knob(KnobType::Bright26, this);
whiteNoiseKnob->move( 196,10 );
whiteNoiseKnob->setVolumeKnob( true) ;
whiteNoiseKnob->setModel( &controls->m_whiteNoiseAmountModel );
whiteNoiseKnob->setLabel( tr( "NOISE" ) );
whiteNoiseKnob->setHintText( tr( "White noise amount:" ) , "" );
auto invertCb = new LedCheckBox(tr("Invert"), this);
invertCb->move( 10,53 );
}
} // namespace lmms::gui
| 3,200
|
C++
|
.cpp
| 78
| 38.961538
| 75
| 0.738486
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,647
|
FlangerControls.cpp
|
LMMS_lmms/plugins/Flanger/FlangerControls.cpp
|
/*
* flangercontrols.cpp - defination of FlangerControls class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "FlangerControls.h"
#include "FlangerEffect.h"
#include "Engine.h"
#include "Song.h"
namespace lmms
{
FlangerControls::FlangerControls( FlangerEffect *effect ) :
EffectControls ( effect ),
m_effect ( effect ),
m_delayTimeModel(0.001f, 0.0001f, 0.050f, 0.0001f, this, tr("Delay samples")),
m_lfoFrequencyModel(0.25f, 0.01f, 60, 0.0001f, 60000.f, this, tr("LFO frequency")),
m_lfoAmountModel(0.f, 0.f, 0.0025f, 0.0001f, this, tr("Amount")),
m_lfoPhaseModel(90.f, 0.f, 360.f, 0.0001f, this, tr("Stereo phase")),
m_feedbackModel(0.f, -1.f, 1.f, 0.0001f, this, tr("Feedback")),
m_whiteNoiseAmountModel(0.f, 0.f, 0.05f, 0.0001f, this, tr("Noise")),
m_invertFeedbackModel ( false, this, tr( "Invert" ) )
{
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( changedSampleRate() ) );
connect( Engine::getSong(), SIGNAL( playbackStateChanged() ), this, SLOT( changedPlaybackState() ) );
}
void FlangerControls::loadSettings( const QDomElement &_this )
{
m_delayTimeModel.loadSettings( _this, "DelayTimeSamples" );
m_lfoFrequencyModel.loadSettings( _this, "LfoFrequency" );
m_lfoAmountModel.loadSettings( _this, "LfoAmount" );
m_lfoPhaseModel.loadSettings( _this, "LfoPhase" );
m_feedbackModel.loadSettings( _this, "Feedback" );
m_whiteNoiseAmountModel.loadSettings( _this, "WhiteNoise" );
m_invertFeedbackModel.loadSettings( _this, "Invert" );
}
void FlangerControls::saveSettings( QDomDocument &doc, QDomElement &parent )
{
m_delayTimeModel.saveSettings( doc , parent, "DelayTimeSamples" );
m_lfoFrequencyModel.saveSettings( doc, parent , "LfoFrequency" );
m_lfoAmountModel.saveSettings( doc, parent , "LfoAmount" );
m_lfoPhaseModel.saveSettings( doc, parent , "LfoPhase" );
m_feedbackModel.saveSettings( doc, parent, "Feedback" ) ;
m_whiteNoiseAmountModel.saveSettings( doc, parent , "WhiteNoise" ) ;
m_invertFeedbackModel.saveSettings( doc, parent, "Invert" );
}
void FlangerControls::changedSampleRate()
{
m_effect->changeSampleRate();
}
void FlangerControls::changedPlaybackState()
{
m_effect->restartLFO();
}
} // namespace lmms
| 3,071
|
C++
|
.cpp
| 73
| 40.054795
| 102
| 0.747057
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,648
|
FlangerEffect.cpp
|
LMMS_lmms/plugins/Flanger/FlangerEffect.cpp
|
/*
* flangereffect.cpp - defination of FlangerEffect class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "FlangerEffect.h"
#include "Engine.h"
#include "MonoDelay.h"
#include "QuadratureLfo.h"
#include "embed.h"
#include "lmms_math.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT flanger_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Flanger",
QT_TRANSLATE_NOOP( "PluginBrowser", "A native flanger plugin" ),
"Dave French <contact/dot/dave/dot/french3/at/googlemail/dot/com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
FlangerEffect::FlangerEffect( Model *parent, const Plugin::Descriptor::SubPluginFeatures::Key *key ) :
Effect( &flanger_plugin_descriptor, parent, key ),
m_flangerControls( this )
{
m_lfo = new QuadratureLfo( Engine::audioEngine()->outputSampleRate() );
m_lDelay = new MonoDelay( 1, Engine::audioEngine()->outputSampleRate() );
m_rDelay = new MonoDelay( 1, Engine::audioEngine()->outputSampleRate() );
}
FlangerEffect::~FlangerEffect()
{
if(m_lDelay )
{
delete m_lDelay;
}
if( m_rDelay )
{
delete m_rDelay;
}
if( m_lfo )
{
delete m_lfo;
}
}
Effect::ProcessStatus FlangerEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const float d = dryLevel();
const float w = wetLevel();
const float length = m_flangerControls.m_delayTimeModel.value() * Engine::audioEngine()->outputSampleRate();
const float noise = m_flangerControls.m_whiteNoiseAmountModel.value();
float amplitude = m_flangerControls.m_lfoAmountModel.value() * Engine::audioEngine()->outputSampleRate();
bool invertFeedback = m_flangerControls.m_invertFeedbackModel.value();
m_lfo->setFrequency( 1.0/m_flangerControls.m_lfoFrequencyModel.value() );
m_lfo->setOffset( m_flangerControls.m_lfoPhaseModel.value() / 180 * D_PI );
m_lDelay->setFeedback( m_flangerControls.m_feedbackModel.value() );
m_rDelay->setFeedback( m_flangerControls.m_feedbackModel.value() );
auto dryS = std::array<sample_t, 2>{};
for( fpp_t f = 0; f < frames; ++f )
{
float leftLfo;
float rightLfo;
buf[f][0] += (fastRandf(2.0f) - 1.0f) * noise;
buf[f][1] += (fastRandf(2.0f) - 1.0f) * noise;
dryS[0] = buf[f][0];
dryS[1] = buf[f][1];
m_lfo->tick(&leftLfo, &rightLfo);
m_lDelay->setLength( ( float )length + amplitude * (leftLfo+1.0) );
m_rDelay->setLength( ( float )length + amplitude * (rightLfo+1.0) );
if(invertFeedback)
{
m_lDelay->tick( &buf[f][1] );
m_rDelay->tick(&buf[f][0] );
} else
{
m_lDelay->tick( &buf[f][0] );
m_rDelay->tick( &buf[f][1] );
}
buf[f][0] = ( d * dryS[0] ) + ( w * buf[f][0] );
buf[f][1] = ( d * dryS[1] ) + ( w * buf[f][1] );
}
return ProcessStatus::ContinueIfNotQuiet;
}
void FlangerEffect::changeSampleRate()
{
m_lfo->setSampleRate( Engine::audioEngine()->outputSampleRate() );
m_lDelay->setSampleRate( Engine::audioEngine()->outputSampleRate() );
m_rDelay->setSampleRate( Engine::audioEngine()->outputSampleRate() );
}
void FlangerEffect::restartLFO()
{
m_lfo->restart();
}
extern "C"
{
//needed for getting plugin out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new FlangerEffect( parent , static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( data ) );
}
}}
} // namespace lmms
| 4,194
|
C++
|
.cpp
| 126
| 31.079365
| 110
| 0.716696
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,649
|
DynamicsProcessor.cpp
|
LMMS_lmms/plugins/DynamicsProcessor/DynamicsProcessor.cpp
|
/*
* DynamicsProcessor.cpp - DynamicsProcessor effect-plugin
*
* Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "DynamicsProcessor.h"
#include "lmms_math.h"
#include "interpolation.h"
#include "RmsHelper.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT dynamicsprocessor_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Dynamics Processor",
QT_TRANSLATE_NOOP( "PluginBrowser",
"plugin for processing dynamics in a flexible way" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
const float DYN_NOISE_FLOOR = 0.00001f; // -100dBFS noise floor
const double DNF_LOG = -1.0;
DynProcEffect::DynProcEffect( Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Effect( &dynamicsprocessor_plugin_descriptor, _parent, _key ),
m_dpControls( this )
{
m_currentPeak[0] = m_currentPeak[1] = DYN_NOISE_FLOOR;
m_rms[0] = new RmsHelper( 64 * Engine::audioEngine()->outputSampleRate() / 44100 );
m_rms[1] = new RmsHelper( 64 * Engine::audioEngine()->outputSampleRate() / 44100 );
calcAttack();
calcRelease();
}
DynProcEffect::~DynProcEffect()
{
delete m_rms[0];
delete m_rms[1];
}
inline void DynProcEffect::calcAttack()
{
m_attCoeff = std::exp((DNF_LOG / (m_dpControls.m_attackModel.value() * 0.001)) / Engine::audioEngine()->outputSampleRate());
}
inline void DynProcEffect::calcRelease()
{
m_relCoeff = std::exp((DNF_LOG / (m_dpControls.m_releaseModel.value() * 0.001)) / Engine::audioEngine()->outputSampleRate());
}
Effect::ProcessStatus DynProcEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
//qDebug( "%f %f", m_currentPeak[0], m_currentPeak[1] );
// variables for effect
int i = 0;
auto sm_peak = std::array{0.0f, 0.0f};
const float d = dryLevel();
const float w = wetLevel();
const int stereoMode = m_dpControls.m_stereomodeModel.value();
const float inputGain = m_dpControls.m_inputModel.value();
const float outputGain = m_dpControls.m_outputModel.value();
const float * samples = m_dpControls.m_wavegraphModel.samples();
// debug code
// qDebug( "peaks %f %f", m_currentPeak[0], m_currentPeak[1] );
if( m_needsUpdate )
{
m_rms[0]->setSize( 64 * Engine::audioEngine()->outputSampleRate() / 44100 );
m_rms[1]->setSize( 64 * Engine::audioEngine()->outputSampleRate() / 44100 );
calcAttack();
calcRelease();
m_needsUpdate = false;
}
else
{
if( m_dpControls.m_attackModel.isValueChanged() )
{
calcAttack();
}
if( m_dpControls.m_releaseModel.isValueChanged() )
{
calcRelease();
}
}
for (fpp_t f = 0; f < frames; ++f)
{
auto s = std::array{buf[f][0], buf[f][1]};
// apply input gain
s[0] *= inputGain;
s[1] *= inputGain;
// update peak values
for ( i=0; i <= 1; i++ )
{
const double t = m_rms[i]->update( s[i] );
if( t > m_currentPeak[i] )
{
m_currentPeak[i] = m_currentPeak[i] * m_attCoeff + (1 - m_attCoeff) * t;
}
else
if( t < m_currentPeak[i] )
{
m_currentPeak[i] = m_currentPeak[i] * m_relCoeff + (1 - m_relCoeff) * t;
}
m_currentPeak[i] = std::max(DYN_NOISE_FLOOR, m_currentPeak[i]);
}
// account for stereo mode
switch( static_cast<DynProcControls::StereoMode>(stereoMode) )
{
case DynProcControls::StereoMode::Maximum:
{
sm_peak[0] = sm_peak[1] = qMax( m_currentPeak[0], m_currentPeak[1] );
break;
}
case DynProcControls::StereoMode::Average:
{
sm_peak[0] = sm_peak[1] = ( m_currentPeak[0] + m_currentPeak[1] ) * 0.5;
break;
}
case DynProcControls::StereoMode::Unlinked:
{
sm_peak[0] = m_currentPeak[0];
sm_peak[1] = m_currentPeak[1];
break;
}
}
// start effect
for ( i=0; i <= 1; i++ )
{
const int lookup = static_cast<int>( sm_peak[i] * 200.0f );
const float frac = fraction( sm_peak[i] * 200.0f );
if( sm_peak[i] > DYN_NOISE_FLOOR )
{
float gain;
if (lookup < 1) { gain = frac * samples[0]; }
else if (lookup < 200) { gain = linearInterpolate(samples[lookup - 1], samples[lookup], frac); }
else { gain = samples[199]; }
s[i] *= gain;
s[i] /= sm_peak[i];
}
}
// apply output gain
s[0] *= outputGain;
s[1] *= outputGain;
// mix wet/dry signals
buf[f][0] = d * buf[f][0] + w * s[0];
buf[f][1] = d * buf[f][1] + w * s[1];
}
return ProcessStatus::ContinueIfNotQuiet;
}
void DynProcEffect::processBypassedImpl()
{
// Apparently we can't keep running after the decay value runs out so we'll just set the peaks to zero
m_currentPeak[0] = m_currentPeak[1] = DYN_NOISE_FLOOR;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * _parent, void * _data )
{
return( new DynProcEffect( _parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(
_data ) ) );
}
}
} // namespace lmms
| 5,831
|
C++
|
.cpp
| 188
| 28.319149
| 126
| 0.686148
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,650
|
DynamicsProcessorControls.cpp
|
LMMS_lmms/plugins/DynamicsProcessor/DynamicsProcessorControls.cpp
|
/*
* DynamicsProcessorControls.cpp - controls for DynamicsProcessor-effect
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "DynamicsProcessorControls.h"
#include "DynamicsProcessor.h"
#include "base64.h"
#include "Graph.h"
#include "Engine.h"
#include "Song.h"
namespace lmms
{
#define onedB 1.1220184543019633f
DynProcControls::DynProcControls( DynProcEffect * _eff ) :
EffectControls( _eff ),
m_effect( _eff ),
m_inputModel( 1.0f, 0.0f, 5.0f, 0.01f, this, tr( "Input gain" ) ),
m_outputModel( 1.0f, 0.0f, 5.0f, 0.01f, this, tr( "Output gain" ) ),
m_attackModel( 10.0f, 1.0f, 500.0f, 1.0f, this, tr( "Attack time" ) ),
m_releaseModel( 100.0f, 1.0f, 500.0f, 1.0f, this, tr( "Release time" ) ),
m_wavegraphModel( 0.0f, 1.0f, 200, this ),
m_stereomodeModel( 0, 0, 2, this, tr( "Stereo mode" ) )
{
connect( &m_wavegraphModel, SIGNAL( samplesChanged( int, int ) ),
this, SLOT( samplesChanged( int, int ) ) );
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( sampleRateChanged() ) );
setDefaultShape();
}
void DynProcControls::sampleRateChanged()
{
m_effect->m_needsUpdate = true;
}
void DynProcControls::samplesChanged( int _begin, int _end)
{
Engine::getSong()->setModified();
}
void DynProcControls::loadSettings( const QDomElement & _this )
{
//load knobs, stereomode
m_inputModel.loadSettings( _this, "inputGain" );
m_outputModel.loadSettings( _this, "outputGain" );
m_attackModel.loadSettings( _this, "attack" );
m_releaseModel.loadSettings( _this, "release" );
m_stereomodeModel.loadSettings( _this, "stereoMode" );
//load waveshape
int size = 0;
char * dst = 0;
base64::decode( _this.attribute( "waveShape"), &dst, &size );
m_wavegraphModel.setSamples( (float*) dst );
delete[] dst;
}
void DynProcControls::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
//save input, output knobs
m_inputModel.saveSettings( _doc, _this, "inputGain" );
m_outputModel.saveSettings( _doc, _this, "outputGain" );
m_attackModel.saveSettings( _doc, _this, "attack" );
m_releaseModel.saveSettings( _doc, _this, "release" );
m_stereomodeModel.saveSettings( _doc, _this, "stereoMode" );
//save waveshape
QString sampleString;
base64::encode( (const char *)m_wavegraphModel.samples(),
m_wavegraphModel.length() * sizeof(float), sampleString );
_this.setAttribute( "waveShape", sampleString );
}
void DynProcControls::setDefaultShape()
{
auto shp = std::array<float, 200>{};
for ( int i = 0; i<200; i++)
{
shp[i] = ((float)i + 1.0f) / 200.0f;
}
m_wavegraphModel.setLength( 200 );
m_wavegraphModel.setSamples( (float*)&shp );
}
void DynProcControls::resetClicked()
{
setDefaultShape();
Engine::getSong()->setModified();
}
void DynProcControls::smoothClicked()
{
m_wavegraphModel.smoothNonCyclic();
Engine::getSong()->setModified();
}
void DynProcControls::addOneClicked()
{
for( int i=0; i<200; i++ )
{
m_wavegraphModel.setSampleAt( i, qBound( 0.0f, m_wavegraphModel.samples()[i] * onedB, 1.0f ) );
}
Engine::getSong()->setModified();
}
void DynProcControls::subOneClicked()
{
for( int i=0; i<200; i++ )
{
m_wavegraphModel.setSampleAt( i, qBound( 0.0f, m_wavegraphModel.samples()[i] / onedB, 1.0f ) );
}
Engine::getSong()->setModified();
}
} // namespace lmms
| 4,204
|
C++
|
.cpp
| 124
| 31.870968
| 100
| 0.721425
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,651
|
DynamicsProcessorControlDialog.cpp
|
LMMS_lmms/plugins/DynamicsProcessor/DynamicsProcessorControlDialog.cpp
|
/*
* DynamicsProcessorControlDialog.cpp - control-dialog for DynamicsProcessor-effect
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "DynamicsProcessorControlDialog.h"
#include "DynamicsProcessorControls.h"
#include "embed.h"
#include "Graph.h"
#include "Knob.h"
#include "PixmapButton.h"
namespace lmms::gui
{
DynProcControlDialog::DynProcControlDialog(
DynProcControls * _controls ) :
EffectControlDialog( _controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(),
PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 224, 319 );
auto waveGraph = new Graph(this, Graph::Style::LinearNonCyclic, 204, 205);
waveGraph -> move( 10, 6 );
waveGraph -> setModel( &_controls -> m_wavegraphModel );
waveGraph -> setAutoFillBackground( true );
pal = QPalette();
pal.setBrush( backgroundRole(),
PLUGIN_NAME::getIconPixmap("wavegraph") );
waveGraph->setPalette( pal );
waveGraph->setGraphColor( QColor( 85, 204, 145 ) );
waveGraph -> setMaximumSize( 204, 205 );
auto inputKnob = new Knob(KnobType::Bright26, this);
inputKnob -> setVolumeKnob( true );
inputKnob -> setVolumeRatio( 1.0 );
inputKnob -> move( 26, 223 );
inputKnob->setModel( &_controls->m_inputModel );
inputKnob->setLabel( tr( "INPUT" ) );
inputKnob->setHintText( tr( "Input gain:" ) , "" );
auto outputKnob = new Knob(KnobType::Bright26, this);
outputKnob -> setVolumeKnob( true );
outputKnob -> setVolumeRatio( 1.0 );
outputKnob -> move( 76, 223 );
outputKnob->setModel( &_controls->m_outputModel );
outputKnob->setLabel( tr( "OUTPUT" ) );
outputKnob->setHintText( tr( "Output gain:" ) , "" );
auto attackKnob = new Knob(KnobType::Bright26, this);
attackKnob -> move( 24, 268 );
attackKnob->setModel( &_controls->m_attackModel );
attackKnob->setLabel( tr( "ATTACK" ) );
attackKnob->setHintText( tr( "Peak attack time:" ) , "ms" );
auto releaseKnob = new Knob(KnobType::Bright26, this);
releaseKnob -> move( 74, 268 );
releaseKnob->setModel( &_controls->m_releaseModel );
releaseKnob->setLabel( tr( "RELEASE" ) );
releaseKnob->setHintText( tr( "Peak release time:" ) , "ms" );
//wavegraph control buttons
auto resetButton = new PixmapButton(this, tr("Reset wavegraph"));
resetButton -> move( 162, 223 );
resetButton -> resize( 13, 48 );
resetButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "reset_active" ) );
resetButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "reset_inactive" ) );
resetButton->setToolTip(tr("Reset wavegraph"));
auto smoothButton = new PixmapButton(this, tr("Smooth wavegraph"));
smoothButton -> move( 162, 239 );
smoothButton -> resize( 13, 48 );
smoothButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "smooth_active" ) );
smoothButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "smooth_inactive" ) );
smoothButton->setToolTip(tr("Smooth wavegraph"));
auto addOneButton = new PixmapButton(this, tr("Increase wavegraph amplitude by 1 dB"));
addOneButton -> move( 131, 223 );
addOneButton -> resize( 13, 29 );
addOneButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "add1_active" ) );
addOneButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "add1_inactive" ) );
addOneButton->setToolTip(tr("Increase wavegraph amplitude by 1 dB"));
auto subOneButton = new PixmapButton(this, tr("Decrease wavegraph amplitude by 1 dB"));
subOneButton -> move( 131, 239 );
subOneButton -> resize( 13, 29 );
subOneButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "sub1_active" ) );
subOneButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "sub1_inactive" ) );
subOneButton->setToolTip(tr("Decrease wavegraph amplitude by 1 dB"));
//stereomode switches
auto smMaxButton = new PixmapButton(this, tr("Stereo mode: maximum"));
smMaxButton -> move( 131, 257 );
smMaxButton -> resize( 78, 17 );
smMaxButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "max_active" ) );
smMaxButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "max_inactive" ) );
smMaxButton->setToolTip(tr("Process based on the maximum of both stereo channels"));
auto smAvgButton = new PixmapButton(this, tr("Stereo mode: average"));
smAvgButton -> move( 131, 274 );
smAvgButton -> resize( 78, 16 );
smAvgButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "avg_active" ) );
smAvgButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "avg_inactive" ) );
smAvgButton->setToolTip(tr("Process based on the average of both stereo channels"));
auto smUnlButton = new PixmapButton(this, tr("Stereo mode: unlinked"));
smUnlButton -> move( 131, 290 );
smUnlButton -> resize( 78, 17 );
smUnlButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "unl_active" ) );
smUnlButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "unl_inactive" ) );
smUnlButton->setToolTip(tr("Process each stereo channel independently"));
auto smGroup = new automatableButtonGroup(this);
smGroup -> addButton( smMaxButton );
smGroup -> addButton( smAvgButton );
smGroup -> addButton( smUnlButton );
smGroup -> setModel( &_controls -> m_stereomodeModel );
connect( resetButton, SIGNAL (clicked () ),
_controls, SLOT ( resetClicked() ) );
connect( smoothButton, SIGNAL (clicked () ),
_controls, SLOT ( smoothClicked() ) );
connect( addOneButton, SIGNAL( clicked() ),
_controls, SLOT( addOneClicked() ) );
connect( subOneButton, SIGNAL( clicked() ),
_controls, SLOT( subOneClicked() ) );
}
} // namespace lmms::gui
| 6,384
|
C++
|
.cpp
| 135
| 45.103704
| 88
| 0.732894
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,652
|
Compressor.cpp
|
LMMS_lmms/plugins/Compressor/Compressor.cpp
|
/*
* Compressor.cpp
*
* Copyright (c) 2020 Lost Robot <r94231@gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Compressor.h"
#include "embed.h"
#include "interpolation.h"
#include "lmms_math.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT compressor_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"Compressor",
QT_TRANSLATE_NOOP("PluginBrowser", "A dynamic range compressor."),
"Lost Robot <r94231@gmail.com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
CompressorEffect::CompressorEffect(Model* parent, const Descriptor::SubPluginFeatures::Key* key) :
Effect(&compressor_plugin_descriptor, parent, key),
m_compressorControls(this)
{
m_sampleRate = Engine::audioEngine()->outputSampleRate();
m_yL[0] = m_yL[1] = COMP_NOISE_FLOOR;
// 200 ms
m_crestTimeConst = exp(-1.f / (0.2f * m_sampleRate));
connect(&m_compressorControls.m_attackModel, SIGNAL(dataChanged()), this, SLOT(calcAttack()), Qt::DirectConnection);
connect(&m_compressorControls.m_releaseModel, SIGNAL(dataChanged()), this, SLOT(calcRelease()), Qt::DirectConnection);
connect(&m_compressorControls.m_holdModel, SIGNAL(dataChanged()), this, SLOT(calcHold()), Qt::DirectConnection);
connect(&m_compressorControls.m_ratioModel, SIGNAL(dataChanged()), this, SLOT(calcRatio()), Qt::DirectConnection);
connect(&m_compressorControls.m_rangeModel, SIGNAL(dataChanged()), this, SLOT(calcRange()), Qt::DirectConnection);
connect(&m_compressorControls.m_rmsModel, SIGNAL(dataChanged()), this, SLOT(resizeRMS()), Qt::DirectConnection);
connect(&m_compressorControls.m_lookaheadLengthModel, SIGNAL(dataChanged()), this, SLOT(calcLookaheadLength()), Qt::DirectConnection);
connect(&m_compressorControls.m_thresholdModel, SIGNAL(dataChanged()), this, SLOT(calcThreshold()), Qt::DirectConnection);
connect(&m_compressorControls.m_kneeModel, SIGNAL(dataChanged()), this, SLOT(calcKnee()), Qt::DirectConnection);
connect(&m_compressorControls.m_outGainModel, SIGNAL(dataChanged()), this, SLOT(calcOutGain()), Qt::DirectConnection);
connect(&m_compressorControls.m_inGainModel, SIGNAL(dataChanged()), this, SLOT(calcInGain()), Qt::DirectConnection);
connect(&m_compressorControls.m_tiltModel, SIGNAL(dataChanged()), this, SLOT(calcTiltCoeffs()), Qt::DirectConnection);
connect(&m_compressorControls.m_tiltFreqModel, SIGNAL(dataChanged()), this, SLOT(calcTiltCoeffs()), Qt::DirectConnection);
connect(&m_compressorControls.m_limiterModel, SIGNAL(dataChanged()), this, SLOT(redrawKnee()), Qt::DirectConnection);
connect(&m_compressorControls.m_mixModel, SIGNAL(dataChanged()), this, SLOT(calcMix()), Qt::DirectConnection);
connect(&m_compressorControls.m_autoAttackModel, SIGNAL(dataChanged()), this, SLOT(calcAutoAttack()), Qt::DirectConnection);
connect(&m_compressorControls.m_autoReleaseModel, SIGNAL(dataChanged()), this, SLOT(calcAutoRelease()), Qt::DirectConnection);
connect(&m_compressorControls.m_thresholdModel, SIGNAL(dataChanged()), this, SLOT(calcAutoMakeup()), Qt::DirectConnection);
connect(&m_compressorControls.m_ratioModel, SIGNAL(dataChanged()), this, SLOT(calcAutoMakeup()), Qt::DirectConnection);
connect(&m_compressorControls.m_kneeModel, SIGNAL(dataChanged()), this, SLOT(calcAutoMakeup()), Qt::DirectConnection);
connect(&m_compressorControls.m_autoMakeupModel, SIGNAL(dataChanged()), this, SLOT(calcAutoMakeup()), Qt::DirectConnection);
connect(Engine::audioEngine(), SIGNAL(sampleRateChanged()), this, SLOT(changeSampleRate()));
changeSampleRate();
}
float CompressorEffect::msToCoeff(float ms)
{
// Convert time in milliseconds to applicable lowpass coefficient
return exp(m_coeffPrecalc / ms);
}
void CompressorEffect::calcAutoMakeup()
{
// Formulas using the compressor's Threshold, Ratio, and Knee values to estimate a good makeup gain value
float tempGainResult;
if (-m_thresholdVal < m_kneeVal)
{
const float temp = -m_thresholdVal + m_kneeVal;
tempGainResult = ((m_compressorControls.m_limiterModel.value() ? 0 : m_ratioVal) - 1) * temp * temp / (4 * m_kneeVal);
}
else// Above knee
{
tempGainResult = m_compressorControls.m_limiterModel.value()
? m_thresholdVal
: m_thresholdVal - m_thresholdVal * m_ratioVal;
}
m_autoMakeupVal = 1.f / dbfsToAmp(tempGainResult);
}
void CompressorEffect::calcAttack()
{
m_attCoeff = msToCoeff(m_compressorControls.m_attackModel.value());
}
void CompressorEffect::calcRelease()
{
m_relCoeff = msToCoeff(m_compressorControls.m_releaseModel.value());
}
void CompressorEffect::calcAutoAttack()
{
m_autoAttVal = m_compressorControls.m_autoAttackModel.value() * 0.01f;
}
void CompressorEffect::calcAutoRelease()
{
m_autoRelVal = m_compressorControls.m_autoReleaseModel.value() * 0.01f;
}
void CompressorEffect::calcHold()
{
m_holdLength = m_compressorControls.m_holdModel.value() * 0.001f * m_sampleRate;
m_holdTimer[0] = 0;
m_holdTimer[1] = 0;
}
void CompressorEffect::calcOutGain()
{
// 0.999 is needed to keep the values from crossing the threshold all the time
// (most commonly for limiters specifically), and is kept across all modes for consistency.
m_outGainVal = dbfsToAmp(m_compressorControls.m_outGainModel.value()) * 0.999;
}
void CompressorEffect::calcRatio()
{
m_ratioVal = 1.f / m_compressorControls.m_ratioModel.value();
m_redrawKnee = true;
}
void CompressorEffect::calcRange()
{
// Range is inactive when turned all the way down
m_rangeVal = (m_compressorControls.m_rangeModel.value() > m_compressorControls.m_rangeModel.minValue())
? dbfsToAmp(m_compressorControls.m_rangeModel.value())
: 0;
}
void CompressorEffect::resizeRMS()
{
const float rmsValue = m_compressorControls.m_rmsModel.value();
m_rmsTimeConst = (rmsValue > 0) ? exp(-1.f / (rmsValue * 0.001f * m_sampleRate)) : 0;
}
void CompressorEffect::calcLookaheadLength()
{
m_lookaheadLength = std::ceil((m_compressorControls.m_lookaheadLengthModel.value() / 1000.f) * m_sampleRate);
}
void CompressorEffect::calcThreshold()
{
m_thresholdVal = m_compressorControls.m_thresholdModel.value();
m_thresholdAmpVal = dbfsToAmp(m_thresholdVal);
m_redrawKnee = true;
m_redrawThreshold = true;
}
void CompressorEffect::calcKnee()
{
m_kneeVal = m_compressorControls.m_kneeModel.value() * 0.5f;
m_redrawKnee = true;
}
void CompressorEffect::calcInGain()
{
m_inGainVal = dbfsToAmp(m_compressorControls.m_inGainModel.value());
}
void CompressorEffect::redrawKnee()
{
m_redrawKnee = true;
}
void CompressorEffect::calcTiltCoeffs()
{
m_tiltVal = m_compressorControls.m_tiltModel.value();
const float amp = 6 / log(2);
const float gfactor = 5;
const float g1 = m_tiltVal > 0 ? -gfactor * m_tiltVal : -m_tiltVal;
const float g2 = m_tiltVal > 0 ? m_tiltVal : gfactor * m_tiltVal;
m_lgain = exp(g1 / amp) - 1;
m_hgain = exp(g2 / amp) - 1;
const float omega = 2 * F_PI * m_compressorControls.m_tiltFreqModel.value();
const float n = 1 / (m_sampleRate * 3 + omega);
m_a0 = 2 * omega * n;
m_b1 = (m_sampleRate * 3 - omega) * n;
}
void CompressorEffect::calcMix()
{
m_mixVal = m_compressorControls.m_mixModel.value() * 0.01;
}
Effect::ProcessStatus CompressorEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
m_cleanedBuffers = false;
const float d = dryLevel();
const float w = wetLevel();
float lOutPeak = 0.0;
float rOutPeak = 0.0;
float lInPeak = 0.0;
float rInPeak = 0.0;
const bool midside = m_compressorControls.m_midsideModel.value();
const bool peakmode = m_compressorControls.m_peakmodeModel.value();
const float inBalance = m_compressorControls.m_inBalanceModel.value();
const float outBalance = m_compressorControls.m_outBalanceModel.value();
const bool limiter = m_compressorControls.m_limiterModel.value();
const float blend = m_compressorControls.m_blendModel.value();
const float stereoBalance = m_compressorControls.m_stereoBalanceModel.value();
const bool autoMakeup = m_compressorControls.m_autoMakeupModel.value();
const int stereoLink = m_compressorControls.m_stereoLinkModel.value();
const bool audition = m_compressorControls.m_auditionModel.value();
const bool feedback = m_compressorControls.m_feedbackModel.value();
const bool lookahead = m_compressorControls.m_lookaheadModel.value();
for(fpp_t f = 0; f < frames; ++f)
{
auto drySignal = std::array{buf[f][0], buf[f][1]};
auto s = std::array{drySignal[0] * m_inGainVal, drySignal[1] * m_inGainVal};
// Calculate tilt filters, to bias the sidechain to the low or high frequencies
if (m_tiltVal)
{
calcTiltFilter(s[0], s[0], 0);
calcTiltFilter(s[1], s[1], 1);
}
if (midside)// Convert left/right to mid/side
{
const float temp = s[0];
s[0] = (temp + s[1]) * 0.5;
s[1] = temp - s[1];
}
s[0] *= inBalance > 0 ? 1 - inBalance : 1;
s[1] *= inBalance < 0 ? 1 + inBalance : 1;
m_gainResult[0] = 0;
m_gainResult[1] = 0;
for (int i = 0; i < 2; i++)
{
float inputValue = (feedback && !lookahead) ? m_prevOut[i] : s[i];
// Calculate the crest factor of the audio by diving the peak by the RMS
m_crestPeakVal[i] = qMax(qMax(COMP_NOISE_FLOOR, inputValue * inputValue), m_crestTimeConst * m_crestPeakVal[i] + (1 - m_crestTimeConst) * (inputValue * inputValue));
m_crestRmsVal[i] = qMax(COMP_NOISE_FLOOR, m_crestTimeConst * m_crestRmsVal[i] + ((1 - m_crestTimeConst) * (inputValue * inputValue)));
m_crestFactorVal[i] = m_crestPeakVal[i] / m_crestRmsVal[i];
m_rmsVal[i] = m_rmsTimeConst * m_rmsVal[i] + ((1 - m_rmsTimeConst) * (inputValue * inputValue));
// Grab the peak or RMS value
inputValue = qMax(COMP_NOISE_FLOOR, peakmode ? std::abs(inputValue) : std::sqrt(m_rmsVal[i]));
float t = inputValue;
if (t > m_yL[i])// Attack phase
{
// We want the "resting value" of our crest factor to be with a sine wave,
// which with this variable has a value of 2.
// So, we pull this value down to 0, and multiply it by the percentage of
// automatic attack control that is applied. We then add 2 back to it.
float crestFactorValTemp = ((m_crestFactorVal[i] - 2.f) * m_autoAttVal) + 2.f;
// Calculate attack value depending on crest factor
const float att = m_autoAttVal
? msToCoeff(2.f * m_compressorControls.m_attackModel.value() / (crestFactorValTemp))
: m_attCoeff;
m_yL[i] = m_yL[i] * att + (1 - att) * t;
m_holdTimer[i] = m_holdLength;// Reset hold timer
}
else// Release phase
{
float crestFactorValTemp = ((m_crestFactorVal[i] - 2.f) * m_autoRelVal) + 2.f;
const float rel = m_autoRelVal
? msToCoeff(2.f * m_compressorControls.m_releaseModel.value() / (crestFactorValTemp))
: m_relCoeff;
if (m_holdTimer[i])// Don't change peak if hold is being applied
{
--m_holdTimer[i];
}
else
{
m_yL[i] = m_yL[i] * rel + (1 - rel) * t;
}
}
// Keep it above the noise floor
m_yL[i] = qMax(COMP_NOISE_FLOOR, m_yL[i]);
float scVal = m_yL[i];
if (lookahead)
{
const float temp = scVal;
// Lookahead is calculated by picking the largest value between
// the current sidechain signal and the delayed sidechain signal.
scVal = std::max(m_scLookBuf[i][m_lookWrite], m_scLookBuf[i][(m_lookWrite + m_lookBufLength - m_lookaheadLength) % m_lookBufLength]);
m_scLookBuf[i][m_lookWrite] = temp;
}
// For the visualizer
m_displayPeak[i] = qMax(scVal, m_displayPeak[i]);
const float currentPeakDbfs = ampToDbfs(scVal);
// Now find the gain change that should be applied,
// depending on the measured input value.
if (currentPeakDbfs - m_thresholdVal < -m_kneeVal)// Below knee
{
m_gainResult[i] = currentPeakDbfs;
}
else if (currentPeakDbfs - m_thresholdVal < m_kneeVal)// Within knee
{
const float temp = currentPeakDbfs - m_thresholdVal + m_kneeVal;
m_gainResult[i] = currentPeakDbfs + ((limiter ? 0 : m_ratioVal) - 1) * temp * temp / (4 * m_kneeVal);
}
else// Above knee
{
m_gainResult[i] = limiter
? m_thresholdVal
: m_thresholdVal + (currentPeakDbfs - m_thresholdVal) * m_ratioVal;
}
m_gainResult[i] = dbfsToAmp(m_gainResult[i]) / scVal;
m_gainResult[i] = qMax(m_rangeVal, m_gainResult[i]);
}
switch (static_cast<StereoLinkMode>(stereoLink))
{
case StereoLinkMode::Unlinked:
{
break;
}
case StereoLinkMode::Maximum:
{
m_gainResult[0] = m_gainResult[1] = qMin(m_gainResult[0], m_gainResult[1]);
break;
}
case StereoLinkMode::Average:
{
m_gainResult[0] = m_gainResult[1] = (m_gainResult[0] + m_gainResult[1]) * 0.5f;
break;
}
case StereoLinkMode::Minimum:
{
m_gainResult[0] = m_gainResult[1] = qMax(m_gainResult[0], m_gainResult[1]);
break;
}
case StereoLinkMode::Blend:
{
if (blend > 0)// 0 is unlinked
{
if (blend <= 1)// Blend to minimum volume
{
const float temp1 = qMin(m_gainResult[0], m_gainResult[1]);
m_gainResult[0] = linearInterpolate(m_gainResult[0], temp1, blend);
m_gainResult[1] = linearInterpolate(m_gainResult[1], temp1, blend);
}
else if (blend <= 2)// Blend to average volume
{
const float temp1 = qMin(m_gainResult[0], m_gainResult[1]);
const float temp2 = (m_gainResult[0] + m_gainResult[1]) * 0.5f;
m_gainResult[0] = linearInterpolate(temp1, temp2, blend - 1);
m_gainResult[1] = m_gainResult[0];
}
else// Blend to maximum volume
{
const float temp1 = (m_gainResult[0] + m_gainResult[1]) * 0.5f;
const float temp2 = qMax(m_gainResult[0], m_gainResult[1]);
m_gainResult[0] = linearInterpolate(temp1, temp2, blend - 2);
m_gainResult[1] = m_gainResult[0];
}
}
break;
}
}
// Bias compression to the left or right (or mid or side)
if (stereoBalance != 0)
{
m_gainResult[0] = 1 - ((1 - m_gainResult[0]) * (stereoBalance > 0 ? 1 - stereoBalance : 1));
m_gainResult[1] = 1 - ((1 - m_gainResult[1]) * (stereoBalance < 0 ? 1 + stereoBalance : 1));
}
// For visualizer
m_displayGain[0] = qMax(m_gainResult[0], m_displayGain[0]);
m_displayGain[1] = qMax(m_gainResult[1], m_displayGain[1]);
// Delay the signal by 20 ms via ring buffer if lookahead is enabled
if (lookahead)
{
s[0] = m_inLookBuf[0][m_lookWrite];
s[1] = m_inLookBuf[1][m_lookWrite];
m_inLookBuf[0][m_lookWrite] = drySignal[0];
m_inLookBuf[1][m_lookWrite] = drySignal[1];
}
else
{
s[0] = drySignal[0];
s[1] = drySignal[1];
}
auto delayedDrySignal = std::array{s[0], s[1]};
if (midside)// Convert left/right to mid/side
{
const float temp = s[0];
s[0] = (temp + s[1]) * 0.5;
s[1] = temp - s[1];
}
s[0] *= inBalance > 0 ? 1 - inBalance : 1;
s[1] *= inBalance < 0 ? 1 + inBalance : 1;
s[0] *= m_gainResult[0] * m_inGainVal * m_outGainVal * (outBalance > 0 ? 1 - outBalance : 1);
s[1] *= m_gainResult[1] * m_inGainVal * m_outGainVal * (outBalance < 0 ? 1 + outBalance : 1);
if (midside)// Convert mid/side back to left/right
{
const float temp1 = s[0];
const float temp2 = s[1] * 0.5;
s[0] = temp1 + temp2;
s[1] = temp1 - temp2;
}
m_prevOut[0] = s[0];
m_prevOut[1] = s[1];
// Negate wet signal from dry signal
if (audition)
{
s[0] = (-s[0] + delayedDrySignal[0] * m_outGainVal * m_inGainVal);
s[1] = (-s[1] + delayedDrySignal[1] * m_outGainVal * m_inGainVal);
}
else if (autoMakeup)
{
s[0] *= m_autoMakeupVal;
s[1] *= m_autoMakeupVal;
}
// Calculate wet/dry value results
const float temp1 = delayedDrySignal[0];
const float temp2 = delayedDrySignal[1];
buf[f][0] = d * temp1 + w * s[0];
buf[f][1] = d * temp2 + w * s[1];
buf[f][0] = (1 - m_mixVal) * temp1 + m_mixVal * buf[f][0];
buf[f][1] = (1 - m_mixVal) * temp2 + m_mixVal * buf[f][1];
if (--m_lookWrite < 0) { m_lookWrite = m_lookBufLength - 1; }
lInPeak = drySignal[0] > lInPeak ? drySignal[0] : lInPeak;
rInPeak = drySignal[1] > rInPeak ? drySignal[1] : rInPeak;
lOutPeak = s[0] > lOutPeak ? s[0] : lOutPeak;
rOutPeak = s[1] > rOutPeak ? s[1] : rOutPeak;
}
m_compressorControls.m_outPeakL = lOutPeak;
m_compressorControls.m_outPeakR = rOutPeak;
m_compressorControls.m_inPeakL = lInPeak;
m_compressorControls.m_inPeakR = rInPeak;
return ProcessStatus::ContinueIfNotQuiet;
}
void CompressorEffect::processBypassedImpl()
{
// Clear lookahead buffers and other values when needed
if (!m_cleanedBuffers)
{
m_yL[0] = m_yL[1] = COMP_NOISE_FLOOR;
m_gainResult[0] = m_gainResult[1] = 1;
m_displayPeak[0] = m_displayPeak[1] = COMP_NOISE_FLOOR;
m_displayGain[0] = m_displayGain[1] = COMP_NOISE_FLOOR;
std::fill(std::begin(m_scLookBuf[0]), std::end(m_scLookBuf[0]), COMP_NOISE_FLOOR);
std::fill(std::begin(m_scLookBuf[1]), std::end(m_scLookBuf[1]), COMP_NOISE_FLOOR);
std::fill(std::begin(m_inLookBuf[0]), std::end(m_inLookBuf[0]), 0);
std::fill(std::begin(m_inLookBuf[1]), std::end(m_inLookBuf[1]), 0);
m_cleanedBuffers = true;
}
}
// Regular modulo doesn't handle negative numbers correctly. This does.
inline int CompressorEffect::realmod(int k, int n)
{
return (k %= n) < 0 ? k+n : k;
}
// Regular fmod doesn't handle negative numbers correctly. This does.
inline float CompressorEffect::realfmod(float k, float n)
{
return (k = fmod(k, n)) < 0 ? k+n : k;
}
inline void CompressorEffect::calcTiltFilter(sample_t inputSample, sample_t &outputSample, int filtNum)
{
m_tiltOut[filtNum] = m_a0 * inputSample + m_b1 * m_tiltOut[filtNum];
outputSample = inputSample + m_lgain * m_tiltOut[filtNum] + m_hgain * (inputSample - m_tiltOut[filtNum]);
}
void CompressorEffect::changeSampleRate()
{
m_sampleRate = Engine::audioEngine()->outputSampleRate();
m_coeffPrecalc = COMP_LOG / (m_sampleRate * 0.001f);
// 200 ms
m_crestTimeConst = exp(-1.f / (0.2f * m_sampleRate));
m_lookBufLength = std::ceil((20.f / 1000.f) * m_sampleRate) + 2;
for (int i = 0; i < 2; ++i)
{
m_inLookBuf[i].resize(m_lookBufLength);
m_scLookBuf[i].resize(m_lookBufLength, COMP_NOISE_FLOOR);
}
m_lookWrite = 0;
calcThreshold();
calcKnee();
calcRatio();
calcAutoMakeup();// This should be after Threshold, Knee, and Ratio
calcAttack();
calcRelease();
calcRange();
calcLookaheadLength();
calcHold();
resizeRMS();
calcOutGain();
calcInGain();
calcTiltCoeffs();
calcMix();
calcAutoAttack();
calcAutoRelease();
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main(Model* parent, void* data)
{
return new CompressorEffect(parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(data));
}
}
} // namespace lmms
| 19,381
|
C++
|
.cpp
| 492
| 36.392276
| 168
| 0.704598
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,653
|
CompressorControls.cpp
|
LMMS_lmms/plugins/Compressor/CompressorControls.cpp
|
/*
* CompressorControls.cpp
*
* Copyright (c) 2020 Lost Robot <r94231@gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "CompressorControls.h"
#include "Compressor.h"
#include <QDomElement>
namespace lmms
{
CompressorControls::CompressorControls(CompressorEffect* effect) :
EffectControls(effect),
m_effect(effect),
m_thresholdModel(-8.0f, -60.0f, 0.0f, 0.001f, this, tr("Threshold")),
m_ratioModel(1.8f, 1.0f, 20.0f, 0.001f, this, tr("Ratio")),
m_attackModel(10.0f, 0.005f, 250.f, 0.001f, this, tr("Attack")),
m_releaseModel(100.0f, 1.f, 2500.f, 0.001f, this, tr("Release")),
m_kneeModel(12.0f, 0.0f, 96.0f, 0.01f, this, tr("Knee")),
m_holdModel(0.0f, 0.0f, 500.0f, 0.01f, this, tr("Hold")),
m_rangeModel(-240.0f, -240.0f, 0.0f, 0.01f, this, tr("Range")),
m_rmsModel(1.0f, 0.0f, 250.0f, 0.01f, this, tr("RMS Size")),
m_midsideModel(0.0f, 0.0f, 1.0f, this, tr("Mid/Side")),
m_peakmodeModel(0.0f, 0.0f, 1.0f, this, tr("Peak Mode")),
m_lookaheadLengthModel(0.0f, 0.0f, 20.0f, 0.0001f, this, tr("Lookahead Length")),
m_inBalanceModel(0.0f, -1.0f, 1.0f, 0.0001f, this, tr("Input Balance")),
m_outBalanceModel(0.0f, -1.0f, 1.0f, 0.0001f, this, tr("Output Balance")),
m_limiterModel(0.f, 0.f, 1.0f, this, tr("Limiter")),
m_outGainModel(0.f, -60.f, 30.f, 0.01f, this, tr("Output Gain")),
m_inGainModel(0.f, -60.f, 30.f, 0.01f, this, tr("Input Gain")),
m_blendModel(1.f, 0.f, 3.f, 0.0001f, this, tr("Blend")),
m_stereoBalanceModel(0.0f, -1.0f, 1.0f, 0.0001f, this, tr("Stereo Balance")),
m_autoMakeupModel(false, this, tr("Auto Makeup Gain")),
m_auditionModel(false, this, tr("Audition")),
m_feedbackModel(false, this, tr("Feedback")),
m_autoAttackModel(0.0f, 0.f, 100.0f, 0.01f, this, tr("Auto Attack")),
m_autoReleaseModel(0.0f, 0.f, 100.0f, 0.01f, this, tr("Auto Release")),
m_lookaheadModel(false, this, tr("Lookahead")),
m_tiltModel(0.0f, -6.0f, 6.0f, 0.0001f, this, tr("Tilt")),
m_tiltFreqModel(150.0f, 20.0f, 20000.0f, 0.1f, this, tr("Tilt Frequency")),
m_stereoLinkModel(1.0f, 0.0f, 4.0f, this, tr("Stereo Link")),
m_mixModel(100.0f, 0.f, 100.0f, 0.01f, this, tr("Mix"))
{
m_ratioModel.setScaleLogarithmic(true);
m_holdModel.setScaleLogarithmic(true);
m_attackModel.setScaleLogarithmic(true);
m_releaseModel.setScaleLogarithmic(true);
m_thresholdModel.setScaleLogarithmic(true);
m_rangeModel.setScaleLogarithmic(true);
m_lookaheadLengthModel.setScaleLogarithmic(true);
m_rmsModel.setScaleLogarithmic(true);
m_kneeModel.setScaleLogarithmic(true);
m_tiltFreqModel.setScaleLogarithmic(true);
m_rangeModel.setScaleLogarithmic(true);
}
void CompressorControls::saveSettings(QDomDocument& doc, QDomElement& _this)
{
m_thresholdModel.saveSettings(doc, _this, "threshold");
m_ratioModel.saveSettings(doc, _this, "ratio");
m_attackModel.saveSettings(doc, _this, "attack");
m_releaseModel.saveSettings(doc, _this, "release");
m_kneeModel.saveSettings(doc, _this, "knee");
m_holdModel.saveSettings(doc, _this, "hold");
m_rangeModel.saveSettings(doc, _this, "range");
m_rmsModel.saveSettings(doc, _this, "rms");
m_midsideModel.saveSettings(doc, _this, "midside");
m_peakmodeModel.saveSettings(doc, _this, "peakmode");
m_lookaheadLengthModel.saveSettings(doc, _this, "lookaheadLength");
m_inBalanceModel.saveSettings(doc, _this, "inBalance");
m_outBalanceModel.saveSettings(doc, _this, "outBalance");
m_limiterModel.saveSettings(doc, _this, "limiter");
m_outGainModel.saveSettings(doc, _this, "outGain");
m_inGainModel.saveSettings(doc, _this, "inGain");
m_blendModel.saveSettings(doc, _this, "blend");
m_stereoBalanceModel.saveSettings(doc, _this, "stereoBalance");
m_autoMakeupModel.saveSettings(doc, _this, "autoMakeup");
m_auditionModel.saveSettings(doc, _this, "audition");
m_feedbackModel.saveSettings(doc, _this, "feedback");
m_autoAttackModel.saveSettings(doc, _this, "autoAttack");
m_autoReleaseModel.saveSettings(doc, _this, "autoRelease");
m_lookaheadModel.saveSettings(doc, _this, "lookahead");
m_tiltModel.saveSettings(doc, _this, "tilt");
m_tiltFreqModel.saveSettings(doc, _this, "tiltFreq");
m_stereoLinkModel.saveSettings(doc, _this, "stereoLink");
m_mixModel.saveSettings(doc, _this, "mix");
}
void CompressorControls::loadSettings(const QDomElement& _this)
{
m_thresholdModel.loadSettings(_this, "threshold");
m_ratioModel.loadSettings(_this, "ratio");
m_attackModel.loadSettings(_this, "attack");
m_releaseModel.loadSettings(_this, "release");
m_kneeModel.loadSettings(_this, "knee");
m_holdModel.loadSettings(_this, "hold");
m_rangeModel.loadSettings(_this, "range");
m_rmsModel.loadSettings(_this, "rms");
m_midsideModel.loadSettings(_this, "midside");
m_peakmodeModel.loadSettings(_this, "peakmode");
m_lookaheadLengthModel.loadSettings(_this, "lookaheadLength");
m_inBalanceModel.loadSettings(_this, "inBalance");
m_outBalanceModel.loadSettings(_this, "outBalance");
m_limiterModel.loadSettings(_this, "limiter");
m_outGainModel.loadSettings(_this, "outGain");
m_inGainModel.loadSettings(_this, "inGain");
m_blendModel.loadSettings(_this, "blend");
m_stereoBalanceModel.loadSettings(_this, "stereoBalance");
m_autoMakeupModel.loadSettings(_this, "autoMakeup");
m_auditionModel.loadSettings(_this, "audition");
m_feedbackModel.loadSettings(_this, "feedback");
m_autoAttackModel.loadSettings(_this, "autoAttack");
m_autoReleaseModel.loadSettings(_this, "autoRelease");
m_lookaheadModel.loadSettings(_this, "lookahead");
m_tiltModel.loadSettings(_this, "tilt");
m_tiltFreqModel.loadSettings(_this, "tiltFreq");
m_stereoLinkModel.loadSettings(_this, "stereoLink");
m_mixModel.loadSettings(_this, "mix");
}
} // namespace lmms
| 6,409
|
C++
|
.cpp
| 135
| 45.496296
| 82
| 0.739061
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,654
|
CompressorControlDialog.cpp
|
LMMS_lmms/plugins/Compressor/CompressorControlDialog.cpp
|
/*
* CompressorControlDialog.cpp
*
* Copyright (c) 2020 Lost Robot <r94231@gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Compressor.h"
#include "CompressorControlDialog.h"
#include "CompressorControls.h"
#include <QLabel>
#include <QPainter>
#include <QWheelEvent>
#include "AutomatableButton.h"
#include "embed.h"
#include "../Eq/EqFader.h"
#include "GuiApplication.h"
#include "interpolation.h"
#include "Knob.h"
#include "MainWindow.h"
#include "PixmapButton.h"
namespace lmms::gui
{
CompressorControlDialog::CompressorControlDialog(CompressorControls* controls) :
EffectControlDialog(controls),
m_controls(controls)
{
setAutoFillBackground(false);
setAttribute(Qt::WA_OpaquePaintEvent, true);
setAttribute(Qt::WA_NoSystemBackground, true);
setMinimumSize(MIN_COMP_SCREEN_X, MIN_COMP_SCREEN_Y);
resize(COMP_SCREEN_X, COMP_SCREEN_Y);
m_graphPixmap.fill(QColor("transparent"));
m_visPixmap.fill(QColor("transparent"));
m_kneePixmap.fill(QColor("transparent"));
m_kneePixmap2.fill(QColor("transparent"));
m_miscPixmap.fill(QColor("transparent"));
m_controlsBoxLabel = new QLabel(this);
m_controlsBoxLabel->setPixmap(PLUGIN_NAME::getIconPixmap("controlsBox"));
m_controlsBoxLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
m_rmsEnabledLabel = new QLabel(this);
m_rmsEnabledLabel->setPixmap(PLUGIN_NAME::getIconPixmap("knob_enabled"));
m_rmsEnabledLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
m_blendEnabledLabel = new QLabel(this);
m_blendEnabledLabel->setPixmap(PLUGIN_NAME::getIconPixmap("knob_enabled"));
m_blendEnabledLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
m_lookaheadEnabledLabel = new QLabel(this);
m_lookaheadEnabledLabel->setPixmap(PLUGIN_NAME::getIconPixmap("knob_enabled"));
m_lookaheadEnabledLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
m_ratioEnabledLabel = new QLabel(this);
m_ratioEnabledLabel->setPixmap(PLUGIN_NAME::getIconPixmap("knob_enabled_large"));
m_ratioEnabledLabel->setAttribute(Qt::WA_TransparentForMouseEvents);
m_thresholdKnob = new Knob(KnobType::Styled, this);
makeLargeKnob(m_thresholdKnob, tr("Threshold:") , " dBFS");
m_thresholdKnob->setModel(&controls->m_thresholdModel);
m_thresholdKnob->setToolTip(tr("Volume at which the compression begins to take place"));
m_ratioKnob = new Knob(KnobType::Styled, this);
makeLargeKnob(m_ratioKnob, tr("Ratio:") , ":1");
m_ratioKnob->setModel(&controls->m_ratioModel);
m_ratioKnob->setToolTip(tr("How far the compressor must turn the volume down after crossing the threshold"));
m_attackKnob = new Knob(KnobType::Styled, this);
makeLargeKnob(m_attackKnob, tr("Attack:") , " ms");
m_attackKnob->setModel(&controls->m_attackModel);
m_attackKnob->setToolTip(tr("Speed at which the compressor starts to compress the audio"));
m_releaseKnob = new Knob(KnobType::Styled, this);
makeLargeKnob(m_releaseKnob, tr("Release:") , " ms");
m_releaseKnob->setModel(&controls->m_releaseModel);
m_releaseKnob->setToolTip(tr("Speed at which the compressor ceases to compress the audio"));
m_kneeKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_kneeKnob, tr("Knee:") , " dB");
m_kneeKnob->setModel(&controls->m_kneeModel);
m_kneeKnob->setToolTip(tr("Smooth out the gain reduction curve around the threshold"));
m_rangeKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_rangeKnob, tr("Range:") , " dBFS");
m_rangeKnob->setModel(&controls->m_rangeModel);
m_rangeKnob->setToolTip(tr("Maximum gain reduction"));
m_lookaheadLengthKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_lookaheadLengthKnob, tr("Lookahead Length:") , " ms");
m_lookaheadLengthKnob->setModel(&controls->m_lookaheadLengthModel);
m_lookaheadLengthKnob->setToolTip(tr("How long the compressor has to react to the sidechain signal ahead of time"));
m_holdKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_holdKnob, tr("Hold:") , " ms");
m_holdKnob->setModel(&controls->m_holdModel);
m_holdKnob->setToolTip(tr("Delay between attack and release stages"));
m_rmsKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_rmsKnob, tr("RMS Size:") , "");
m_rmsKnob->setModel(&controls->m_rmsModel);
m_rmsKnob->setToolTip(tr("Size of the RMS buffer"));
m_inBalanceKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_inBalanceKnob, tr("Input Balance:") , "");
m_inBalanceKnob->setModel(&controls->m_inBalanceModel);
m_inBalanceKnob->setToolTip(tr("Bias the input audio to the left/right or mid/side"));
m_outBalanceKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_outBalanceKnob, tr("Output Balance:") , "");
m_outBalanceKnob->setModel(&controls->m_outBalanceModel);
m_outBalanceKnob->setToolTip(tr("Bias the output audio to the left/right or mid/side"));
m_stereoBalanceKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_stereoBalanceKnob, tr("Stereo Balance:") , "");
m_stereoBalanceKnob->setModel(&controls->m_stereoBalanceModel);
m_stereoBalanceKnob->setToolTip(tr("Bias the sidechain signal to the left/right or mid/side"));
m_blendKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_blendKnob, tr("Stereo Link Blend:") , "");
m_blendKnob->setModel(&controls->m_blendModel);
m_blendKnob->setToolTip(tr("Blend between unlinked/maximum/average/minimum stereo linking modes"));
m_tiltKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_tiltKnob, tr("Tilt Gain:") , " dB");
m_tiltKnob->setModel(&controls->m_tiltModel);
m_tiltKnob->setToolTip(tr("Bias the sidechain signal to the low or high frequencies. -6 db is lowpass, 6 db is highpass."));
m_tiltFreqKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_tiltFreqKnob, tr("Tilt Frequency:") , " Hz");
m_tiltFreqKnob->setModel(&controls->m_tiltFreqModel);
m_tiltFreqKnob->setToolTip(tr("Center frequency of sidechain tilt filter"));
m_mixKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_mixKnob, tr("Mix:") , "%");
m_mixKnob->setModel(&controls->m_mixModel);
m_mixKnob->setToolTip(tr("Balance between wet and dry signals"));
m_autoAttackKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_autoAttackKnob, tr("Auto Attack:") , "%");
m_autoAttackKnob->setModel(&controls->m_autoAttackModel);
m_autoAttackKnob->setToolTip(tr("Automatically control attack value depending on crest factor"));
m_autoReleaseKnob = new Knob(KnobType::Styled, this);
makeSmallKnob(m_autoReleaseKnob, tr("Auto Release:") , "%");
m_autoReleaseKnob->setModel(&controls->m_autoReleaseModel);
m_autoReleaseKnob->setToolTip(tr("Automatically control release value depending on crest factor"));
m_outFader = new EqFader(&controls->m_outGainModel,tr("Output gain"),
this, &controls->m_outPeakL, &controls->m_outPeakR);
m_outFader->setDisplayConversion(false);
m_outFader->setHintText(tr("Gain"), "dBFS");
m_outFader->setToolTip(tr("Output volume"));
m_inFader = new EqFader(&controls->m_inGainModel,tr("Input gain"),
this, &controls->m_inPeakL, &controls->m_inPeakR);
m_inFader->setDisplayConversion(false);
m_inFader->setHintText(tr("Gain"), "dBFS");
m_inFader->setToolTip(tr("Input volume"));
rmsButton = new PixmapButton(this, tr("Root Mean Square"));
rmsButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("rms_sel"));
rmsButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("rms_unsel"));
rmsButton->setToolTip(tr("Use RMS of the input"));
peakButton = new PixmapButton(this, tr("Peak"));
peakButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("peak_sel"));
peakButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("peak_unsel"));
peakButton->setToolTip(tr("Use absolute value of the input"));
rmsPeakGroup = new automatableButtonGroup(this);
rmsPeakGroup->addButton(rmsButton);
rmsPeakGroup->addButton(peakButton);
rmsPeakGroup->setModel(&controls->m_peakmodeModel);
leftRightButton = new PixmapButton(this, tr("Left/Right"));
leftRightButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("leftright_sel"));
leftRightButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("leftright_unsel"));
leftRightButton->setToolTip(tr("Compress left and right audio"));
midSideButton = new PixmapButton(this, tr("Mid/Side"));
midSideButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("midside_sel"));
midSideButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("midside_unsel"));
midSideButton->setToolTip(tr("Compress mid and side audio"));
leftRightMidSideGroup = new automatableButtonGroup(this);
leftRightMidSideGroup->addButton(leftRightButton);
leftRightMidSideGroup->addButton(midSideButton);
leftRightMidSideGroup->setModel(&controls->m_midsideModel);
compressButton = new PixmapButton(this, tr("Compressor"));
compressButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("compressor_sel"));
compressButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("compressor_unsel"));
compressButton->setToolTip(tr("Compress the audio"));
limitButton = new PixmapButton(this, tr("Limiter"));
limitButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("limiter_sel"));
limitButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("limiter_unsel"));
limitButton->setToolTip(tr("Set Ratio to infinity (is not guaranteed to limit audio volume)"));
compressLimitGroup = new automatableButtonGroup(this);
compressLimitGroup->addButton(compressButton);
compressLimitGroup->addButton(limitButton);
compressLimitGroup->setModel(&controls->m_limiterModel);
unlinkedButton = new PixmapButton(this, tr("Unlinked"));
unlinkedButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("unlinked_sel"));
unlinkedButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("unlinked_unsel"));
unlinkedButton->setToolTip(tr("Compress each channel separately"));
maximumButton = new PixmapButton(this, tr("Maximum"));
maximumButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("maximum_sel"));
maximumButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("maximum_unsel"));
maximumButton->setToolTip(tr("Compress based on the loudest channel"));
averageButton = new PixmapButton(this, tr("Average"));
averageButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("average_sel"));
averageButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("average_unsel"));
averageButton->setToolTip(tr("Compress based on the averaged channel volume"));
minimumButton = new PixmapButton(this, tr("Minimum"));
minimumButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("minimum_sel"));
minimumButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("minimum_unsel"));
minimumButton->setToolTip(tr("Compress based on the quietest channel"));
blendButton = new PixmapButton(this, tr("Blend"));
blendButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("blend_sel"));
blendButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("blend_unsel"));
blendButton->setToolTip(tr("Blend between stereo linking modes"));
stereoLinkGroup = new automatableButtonGroup(this);
stereoLinkGroup->addButton(unlinkedButton);
stereoLinkGroup->addButton(maximumButton);
stereoLinkGroup->addButton(averageButton);
stereoLinkGroup->addButton(minimumButton);
stereoLinkGroup->addButton(blendButton);
stereoLinkGroup->setModel(&controls->m_stereoLinkModel);
autoMakeupButton = new PixmapButton(this, tr("Auto Makeup Gain"));
autoMakeupButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("autogain_sel"));
autoMakeupButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("autogain_unsel"));
autoMakeupButton->setToolTip(tr("Automatically change makeup gain depending on threshold, knee, and ratio settings"));
autoMakeupButton->setCheckable(true);
autoMakeupButton->setModel(&controls->m_autoMakeupModel);
auditionButton = new PixmapButton(this, tr("Soft Clip"));
auditionButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("audition_sel"));
auditionButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("audition_unsel"));
auditionButton->setToolTip(tr("Play the delta signal"));
auditionButton->setCheckable(true);
auditionButton->setModel(&controls->m_auditionModel);
feedbackButton = new PixmapButton(this, tr("Soft Clip"));
feedbackButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("feedback_sel"));
feedbackButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("feedback_unsel"));
feedbackButton->setToolTip(tr("Use the compressor's output as the sidechain input"));
feedbackButton->setCheckable(true);
feedbackButton->setModel(&controls->m_feedbackModel);
lookaheadButton = new PixmapButton(this, tr("Lookahead Enabled"));
lookaheadButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("lookahead_sel"));
lookaheadButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("lookahead_unsel"));
lookaheadButton->setToolTip(tr("Enable Lookahead, which introduces 20 milliseconds of latency"));
lookaheadButton->setCheckable(true);
lookaheadButton->setModel(&controls->m_lookaheadModel);
connect(getGUI()->mainWindow(), SIGNAL(periodicUpdate()), this, SLOT(updateDisplay()));
connect(&m_controls->m_peakmodeModel, SIGNAL(dataChanged()), this, SLOT(peakmodeChanged()));
connect(&m_controls->m_stereoLinkModel, SIGNAL(dataChanged()), this, SLOT(stereoLinkChanged()));
connect(&m_controls->m_lookaheadModel, SIGNAL(dataChanged()), this, SLOT(lookaheadChanged()));
connect(&m_controls->m_limiterModel, SIGNAL(dataChanged()), this, SLOT(limiterChanged()));
m_timeElapsed.start();
peakmodeChanged();
stereoLinkChanged();
lookaheadChanged();
limiterChanged();
}
void CompressorControlDialog::makeLargeKnob(Knob * knob, QString hint, QString unit)
{
knob->setHintText(hint, unit);
knob->setFixedSize(56, 56);
knob->setOuterRadius(23);
knob->setInnerRadius(15);
knob->setCenterPointX(28);
knob->setCenterPointY(28);
}
void CompressorControlDialog::makeSmallKnob(Knob * knob, QString hint, QString unit)
{
knob->setHintText(hint, unit);
knob->setFixedSize(30, 30);
knob->setOuterRadius(10);
knob->setInnerRadius(4);
knob->setCenterPointX(15);
knob->setCenterPointY(15);
}
void CompressorControlDialog::peakmodeChanged()
{
m_rmsKnob->setVisible(!m_controls->m_peakmodeModel.value());
m_rmsEnabledLabel->setVisible(!m_controls->m_peakmodeModel.value());
}
void CompressorControlDialog::stereoLinkChanged()
{
m_blendKnob->setVisible(m_controls->m_stereoLinkModel.value() == 4);
m_blendEnabledLabel->setVisible(m_controls->m_stereoLinkModel.value() == 4);
}
void CompressorControlDialog::lookaheadChanged()
{
m_lookaheadLengthKnob->setVisible(m_controls->m_lookaheadModel.value());
m_lookaheadEnabledLabel->setVisible(m_controls->m_lookaheadModel.value());
feedbackButton->setVisible(!m_controls->m_lookaheadModel.value());
}
void CompressorControlDialog::limiterChanged()
{
m_ratioKnob->setVisible(!m_controls->m_limiterModel.value());
m_ratioEnabledLabel->setVisible(!m_controls->m_limiterModel.value());
}
void CompressorControlDialog::updateDisplay()
{
if (!isVisible())
{
m_timeElapsed.restart();
return;
}
int elapsedMil = m_timeElapsed.elapsed();
m_timeElapsed.restart();
m_timeSinceLastUpdate += elapsedMil;
m_compPixelMovement = int(m_timeSinceLastUpdate / COMP_MILLI_PER_PIXEL);
m_timeSinceLastUpdate %= COMP_MILLI_PER_PIXEL;
// Time Change / Daylight Savings Time protection
if (!m_compPixelMovement || m_compPixelMovement <= 0)
{
return;
}
if (!m_controls->m_effect->isEnabled() || !m_controls->m_effect->isRunning())
{
m_controls->m_effect->m_displayPeak[0] = COMP_NOISE_FLOOR;
m_controls->m_effect->m_displayPeak[1] = COMP_NOISE_FLOOR;
m_controls->m_effect->m_displayGain[0] = 1;
m_controls->m_effect->m_displayGain[1] = 1;
}
m_peakAvg = (m_controls->m_effect->m_displayPeak[0] + m_controls->m_effect->m_displayPeak[1]) * 0.5f;
m_gainAvg = (m_controls->m_effect->m_displayGain[0] + m_controls->m_effect->m_displayGain[1]) * 0.5f;
m_controls->m_effect->m_displayPeak[0] = m_controls->m_effect->m_yL[0];
m_controls->m_effect->m_displayPeak[1] = m_controls->m_effect->m_yL[1];
m_controls->m_effect->m_displayGain[0] = m_controls->m_effect->m_gainResult[0];
m_controls->m_effect->m_displayGain[1] = m_controls->m_effect->m_gainResult[1];
m_yPoint = dbfsToYPoint(ampToDbfs(m_peakAvg));
m_yGainPoint = dbfsToYPoint(ampToDbfs(m_gainAvg));
m_threshYPoint = dbfsToYPoint(m_controls->m_effect->m_thresholdVal);
m_threshXPoint = m_kneeWindowSizeY - m_threshYPoint;
drawVisPixmap();
if (m_controls->m_effect->m_redrawKnee)
{
redrawKnee();
}
drawKneePixmap2();
if (m_controls->m_effect->m_redrawThreshold)
{
drawMiscPixmap();
}
m_lastPoint = m_yPoint;
m_lastGainPoint = m_yGainPoint;
update();
}
void CompressorControlDialog::drawVisPixmap()
{
m_p.begin(&m_visPixmap);
// Move entire display to the left
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.drawPixmap(-m_compPixelMovement, 0, m_visPixmap);
m_p.fillRect(m_windowSizeX-m_compPixelMovement, 0, m_windowSizeX, m_windowSizeY, QColor("transparent"));
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
m_p.setRenderHint(QPainter::Antialiasing, true);
// Draw translucent portion of input volume line
m_p.setPen(QPen(m_inVolAreaColor, 1));
for (int i = 0; i < m_compPixelMovement; ++i)
{
const int temp = linearInterpolate(m_lastPoint, m_yPoint, float(i) / float(m_compPixelMovement));
m_p.drawLine(m_windowSizeX-m_compPixelMovement+i, temp, m_windowSizeX-m_compPixelMovement+i, m_windowSizeY);
}
// Draw input volume line
m_p.setPen(QPen(m_inVolColor, 1));
m_p.drawLine(m_windowSizeX-m_compPixelMovement-1, m_lastPoint, m_windowSizeX, m_yPoint);
// Draw translucent portion of output volume line
m_p.setPen(QPen(m_outVolAreaColor, 1));
for (int i = 0; i < m_compPixelMovement; ++i)
{
const int temp = linearInterpolate(m_lastPoint+m_lastGainPoint, m_yPoint+m_yGainPoint, float(i) / float(m_compPixelMovement));
m_p.drawLine(m_windowSizeX-m_compPixelMovement+i, temp, m_windowSizeX-m_compPixelMovement+i, m_windowSizeY);
}
// Draw output volume line
m_p.setPen(QPen(m_outVolColor, 1));
m_p.drawLine(m_windowSizeX-m_compPixelMovement-1, m_lastPoint+m_lastGainPoint, m_windowSizeX, m_yPoint+m_yGainPoint);
// Draw gain reduction line
m_p.setPen(QPen(m_gainReductionColor, 2));
m_p.drawLine(m_windowSizeX-m_compPixelMovement-1, m_lastGainPoint, m_windowSizeX, m_yGainPoint);
m_p.end();
}
void CompressorControlDialog::redrawKnee()
{
m_controls->m_effect->m_redrawKnee = false;
// Start drawing knee visualizer
m_p.begin(&m_kneePixmap);
m_p.setRenderHint(QPainter::Antialiasing, false);
// Clear display
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.fillRect(0, 0, m_windowSizeX, m_kneeWindowSizeY, QColor("transparent"));
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
m_p.setRenderHint(QPainter::Antialiasing, true);
m_p.setPen(QPen(m_kneeColor, 3));
// Limiter = infinite ratio
float actualRatio = m_controls->m_limiterModel.value() ? 0 : m_controls->m_effect->m_ratioVal;
// Calculate endpoints for the two straight lines
const float thresholdVal = m_controls->m_effect->m_thresholdVal;
const float kneeVal = m_controls->m_effect->m_kneeVal;
float kneePoint1 = thresholdVal - kneeVal;
float kneePoint2X = thresholdVal + kneeVal;
float kneePoint2Y = thresholdVal + kneeVal * actualRatio;
float ratioPoint = thresholdVal + (-thresholdVal * actualRatio);
// Draw two straight lines
m_p.drawLine(0, m_kneeWindowSizeY, dbfsToXPoint(kneePoint1), dbfsToYPoint(kneePoint1));
if (dbfsToXPoint(kneePoint2X) < m_kneeWindowSizeY)
{
m_p.drawLine(dbfsToXPoint(kneePoint2X), dbfsToYPoint(kneePoint2Y), m_kneeWindowSizeY, dbfsToYPoint(ratioPoint));
}
// Draw knee section
if (kneeVal)
{
m_p.setPen(QPen(m_kneeColor2, 3));
auto prevPoint = std::array{kneePoint1, kneePoint1};
auto newPoint = std::array{0.f, 0.f};
// Draw knee curve using many straight lines.
for (int i = 0; i < COMP_KNEE_LINES; ++i)
{
newPoint[0] = linearInterpolate(kneePoint1, kneePoint2X, (i + 1) / (float)COMP_KNEE_LINES);
const float temp = newPoint[0] - thresholdVal + kneeVal;
newPoint[1] = (newPoint[0] + (actualRatio - 1) * temp * temp / (4 * kneeVal));
m_p.drawLine(dbfsToXPoint(prevPoint[0]), dbfsToYPoint(prevPoint[1]), dbfsToXPoint(newPoint[0]), dbfsToYPoint(newPoint[1]));
prevPoint[0] = newPoint[0];
prevPoint[1] = newPoint[1];
}
}
m_p.setRenderHint(QPainter::Antialiasing, false);
// Erase right portion
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.fillRect(m_kneeWindowSizeX + 1, 0, m_windowSizeX, m_kneeWindowSizeY, QColor("transparent"));
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
m_p.end();
m_p.begin(&m_kneePixmap2);
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.fillRect(0, 0, m_windowSizeX, m_kneeWindowSizeY, QColor("transparent"));
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
m_p.end();
m_lastKneePoint = 0;
}
void CompressorControlDialog::drawKneePixmap2()
{
m_p.begin(&m_kneePixmap2);
m_p.setRenderHint(QPainter::Antialiasing, false);
int kneePoint = dbfsToXPoint(ampToDbfs(m_peakAvg));
if (kneePoint > m_lastKneePoint)
{
QRectF knee2Rect = QRect(m_lastKneePoint, 0, kneePoint - m_lastKneePoint, m_kneeWindowSizeY);
m_p.drawPixmap(knee2Rect, m_kneePixmap, knee2Rect);
}
else
{
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.fillRect(kneePoint, 0, m_lastKneePoint, m_kneeWindowSizeY, QColor("transparent"));
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
}
m_lastKneePoint = kneePoint;
m_p.end();
}
void CompressorControlDialog::drawMiscPixmap()
{
m_p.begin(&m_miscPixmap);
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.fillRect(0, 0, m_windowSizeX, m_windowSizeY, QColor("transparent"));
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
m_p.setRenderHint(QPainter::Antialiasing, true);
// Draw threshold lines
m_p.setPen(QPen(m_threshColor, 2, Qt::DotLine));
m_p.drawLine(0, m_threshYPoint, m_windowSizeX, m_threshYPoint);
m_p.drawLine(m_threshXPoint, 0, m_threshXPoint, m_kneeWindowSizeY);
m_p.end();
m_controls->m_effect->m_redrawThreshold = false;
}
void CompressorControlDialog::paintEvent(QPaintEvent *event)
{
if (!isVisible())
{
return;
}
m_p.begin(this);
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.fillRect(0, 0, m_windowSizeX, m_windowSizeY, m_backgroundColor);
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
m_p.drawPixmap(0, 0, m_graphPixmap);
m_p.drawPixmap(0, 0, m_visPixmap);
m_p.setOpacity(0.25);
m_p.drawPixmap(0, 0, m_kneePixmap);
m_p.setOpacity(1);
if (m_controls->m_effect->isEnabled() && m_controls->m_effect->isRunning())
{
m_p.drawPixmap(0, 0, m_kneePixmap2);
}
m_p.drawPixmap(0, 0, m_miscPixmap);
m_p.end();
}
inline int CompressorControlDialog::dbfsToYPoint(float inDbfs)
{
return (-((inDbfs + m_dbRange) / m_dbRange) + 1) * m_windowSizeY;
}
inline int CompressorControlDialog::dbfsToXPoint(float inDbfs)
{
return m_kneeWindowSizeY - dbfsToYPoint(inDbfs);
}
void CompressorControlDialog::resizeEvent(QResizeEvent *event)
{
resetCompressorView();
}
void CompressorControlDialog::wheelEvent(QWheelEvent * event)
{
const float temp = m_dbRange;
const float dbRangeNew = m_dbRange - copysignf(COMP_GRID_SPACING, event->angleDelta().y());
m_dbRange = round(qBound(COMP_GRID_SPACING, dbRangeNew, COMP_GRID_MAX) / COMP_GRID_SPACING) * COMP_GRID_SPACING;
// Only reset view if the scolling had an effect
if (m_dbRange != temp)
{
drawGraph();
m_controls->m_effect->m_redrawKnee = true;
m_controls->m_effect->m_redrawThreshold = true;
}
}
void CompressorControlDialog::drawGraph()
{
m_p.begin(&m_graphPixmap);
m_p.setRenderHint(QPainter::Antialiasing, false);
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.fillRect(0, 0, m_windowSizeX, m_windowSizeY, QColor("transparent"));
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
m_p.setPen(QPen(m_textColor, 1));
// Arbitrary formula for increasing font size when window size increases
m_p.setFont(QFont("Arial", qMax(int(m_windowSizeY / 1080.f * 24), 12)));
// Redraw graph
m_p.setPen(QPen(m_graphColor, 1));
for (int i = 0; i < m_dbRange / COMP_GRID_SPACING + 1; ++i)
{
m_p.drawLine(0, dbfsToYPoint(-COMP_GRID_SPACING * i), m_windowSizeX, dbfsToYPoint(-COMP_GRID_SPACING * i));
m_p.drawLine(dbfsToXPoint(-COMP_GRID_SPACING * i), 0, dbfsToXPoint(-COMP_GRID_SPACING * i), m_kneeWindowSizeY);
m_p.drawText(QRectF(m_windowSizeX - 50, dbfsToYPoint(-COMP_GRID_SPACING * i), 50, 50), Qt::AlignRight | Qt::AlignTop, QString::number(i * -COMP_GRID_SPACING));
}
m_p.end();
}
void CompressorControlDialog::mouseDoubleClickEvent(QMouseEvent* event)
{
setGuiVisibility(!m_guiVisibility);
}
void CompressorControlDialog::setGuiVisibility(bool isVisible)
{
if (!isVisible)
{
m_rmsKnob->setVisible(isVisible);
m_rmsEnabledLabel->setVisible(isVisible);
m_lookaheadLengthKnob->setVisible(isVisible);
m_lookaheadEnabledLabel->setVisible(isVisible);
m_blendKnob->setVisible(isVisible);
m_blendEnabledLabel->setVisible(isVisible);
m_ratioKnob->setVisible(isVisible);
m_ratioEnabledLabel->setVisible(isVisible);
}
else
{
m_rmsKnob->setVisible(!m_controls->m_peakmodeModel.value());
m_rmsEnabledLabel->setVisible(!m_controls->m_peakmodeModel.value());
m_blendKnob->setVisible(m_controls->m_stereoLinkModel.value() == 4);
m_blendEnabledLabel->setVisible(m_controls->m_stereoLinkModel.value() == 4);
m_lookaheadLengthKnob->setVisible(m_controls->m_lookaheadModel.value());
m_lookaheadEnabledLabel->setVisible(m_controls->m_lookaheadModel.value());
m_ratioKnob->setVisible(!m_controls->m_limiterModel.value());
m_ratioEnabledLabel->setVisible(!m_controls->m_limiterModel.value());
}
m_controlsBoxLabel->setVisible(isVisible);
m_thresholdKnob->setVisible(isVisible);
m_attackKnob->setVisible(isVisible);
m_releaseKnob->setVisible(isVisible);
m_kneeKnob->setVisible(isVisible);
m_rangeKnob->setVisible(isVisible);
m_holdKnob->setVisible(isVisible);
m_inBalanceKnob->setVisible(isVisible);
m_outBalanceKnob->setVisible(isVisible);
m_stereoBalanceKnob->setVisible(isVisible);
m_tiltKnob->setVisible(isVisible);
m_tiltFreqKnob->setVisible(isVisible);
m_mixKnob->setVisible(isVisible);
m_autoAttackKnob->setVisible(isVisible);
m_autoReleaseKnob->setVisible(isVisible);
m_outFader->setVisible(isVisible);
m_inFader->setVisible(isVisible);
rmsButton->setVisible(isVisible);
peakButton->setVisible(isVisible);
rmsPeakGroup->setVisible(isVisible);
leftRightButton->setVisible(isVisible);
midSideButton->setVisible(isVisible);
compressButton->setVisible(isVisible);
limitButton->setVisible(isVisible);
unlinkedButton->setVisible(isVisible);
maximumButton->setVisible(isVisible);
averageButton->setVisible(isVisible);
minimumButton->setVisible(isVisible);
blendButton->setVisible(isVisible);
autoMakeupButton->setVisible(isVisible);
auditionButton->setVisible(isVisible);
feedbackButton->setVisible(isVisible);
lookaheadButton->setVisible(isVisible);
m_guiVisibility = isVisible;
}
void CompressorControlDialog::resetCompressorView()
{
m_windowSizeX = size().width();
m_windowSizeY = size().height();
m_kneeWindowSizeX = m_windowSizeY;
m_kneeWindowSizeY = m_windowSizeY;
m_controlsBoxX = (m_windowSizeX - COMP_BOX_X) * 0.5;
m_controlsBoxY = m_windowSizeY - 40 - COMP_BOX_Y;
m_controls->m_effect->m_redrawKnee = true;
m_controls->m_effect->m_redrawThreshold = true;
m_lastKneePoint = 0;
drawGraph();
m_p.begin(&m_visPixmap);
m_p.setCompositionMode(QPainter::CompositionMode_Source);
m_p.fillRect(0, 0, m_windowSizeX, m_windowSizeY, QColor("transparent"));
m_p.setCompositionMode(QPainter::CompositionMode_SourceOver);
// Draw line at right side, so the sudden
// content that the visualizer will display
// later on won't look too ugly
m_p.setPen(QPen(m_resetColor, 3));
m_p.drawLine(m_windowSizeX, 0, m_windowSizeX, m_windowSizeY);
m_p.end();
m_controlsBoxLabel->move(m_controlsBoxX, m_controlsBoxY);
m_rmsEnabledLabel->move(m_controlsBoxX + 429, m_controlsBoxY + 209);
m_blendEnabledLabel->move(m_controlsBoxX + 587, m_controlsBoxY + 197);
m_lookaheadEnabledLabel->move(m_controlsBoxX + 221, m_controlsBoxY + 135);
m_ratioEnabledLabel->move(m_controlsBoxX + 267, m_controlsBoxY + 21);
m_thresholdKnob->move(m_controlsBoxX + 137, m_controlsBoxY + 21);
m_ratioKnob->move(m_controlsBoxX + 267, m_controlsBoxY + 21);
m_attackKnob->move(m_controlsBoxX + 397, m_controlsBoxY + 21);
m_releaseKnob->move(m_controlsBoxX + 527, m_controlsBoxY + 21);
m_kneeKnob->move(m_controlsBoxX + 97, m_controlsBoxY + 135);
m_rangeKnob->move(m_controlsBoxX + 159, m_controlsBoxY + 135);
m_lookaheadLengthKnob->move(m_controlsBoxX + 221, m_controlsBoxY + 135);
m_holdKnob->move(m_controlsBoxX + 283, m_controlsBoxY + 135);
m_rmsKnob->move(m_controlsBoxX + 429, m_controlsBoxY + 209);
m_inBalanceKnob->move(m_controlsBoxX + 27, m_controlsBoxY + 219);
m_outBalanceKnob->move(m_controlsBoxX + 662, m_controlsBoxY + 219);
m_stereoBalanceKnob->move(m_controlsBoxX + 522, m_controlsBoxY + 137);
m_blendKnob->move(m_controlsBoxX + 587, m_controlsBoxY + 197);
m_tiltKnob->move(m_controlsBoxX + 364, m_controlsBoxY + 138);
m_tiltFreqKnob->move(m_controlsBoxX + 415, m_controlsBoxY + 138);
m_mixKnob->move(m_controlsBoxX + 27, m_controlsBoxY + 13);
m_outFader->move(m_controlsBoxX + 666, m_controlsBoxY + 91);
m_inFader->move(m_controlsBoxX + 31, m_controlsBoxY + 91);
rmsButton->move(m_controlsBoxX + 337, m_controlsBoxY + 231);
peakButton->move(m_controlsBoxX + 337, m_controlsBoxY + 248);
leftRightButton->move(m_controlsBoxX + 220, m_controlsBoxY + 231);
midSideButton->move(m_controlsBoxX + 220, m_controlsBoxY + 248);
compressButton->move(m_controlsBoxX + 98, m_controlsBoxY + 231);
limitButton->move(m_controlsBoxX + 98, m_controlsBoxY + 248);
unlinkedButton->move(m_controlsBoxX + 495, m_controlsBoxY + 180);
maximumButton->move(m_controlsBoxX + 495, m_controlsBoxY + 197);
averageButton->move(m_controlsBoxX + 495, m_controlsBoxY + 214);
minimumButton->move(m_controlsBoxX + 495, m_controlsBoxY + 231);
blendButton->move(m_controlsBoxX + 495, m_controlsBoxY + 248);
autoMakeupButton->move(m_controlsBoxX + 220, m_controlsBoxY + 206);
auditionButton->move(m_controlsBoxX + 658, m_controlsBoxY + 14);
feedbackButton->move(m_controlsBoxX + 98, m_controlsBoxY + 206);
m_autoAttackKnob->move(m_controlsBoxX + 460, m_controlsBoxY + 38);
m_autoReleaseKnob->move(m_controlsBoxX + 590, m_controlsBoxY + 38);
lookaheadButton->move(m_controlsBoxX + 202, m_controlsBoxY + 171);
}
} // namespace lmms::gui
| 31,388
|
C++
|
.cpp
| 653
| 45.811639
| 161
| 0.769304
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,655
|
vst_base.cpp
|
LMMS_lmms/plugins/VstBase/vst_base.cpp
|
/*
* vst_base.cpp - VST-base-code to be used by any LMMS plugins dealing with VST-
* plugins
*
* Copyright (c) 2006-2010 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Plugin.h"
#include "vstbase_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor VSTBASE_EXPORT vstbase_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"VST Base",
"library for all LMMS plugins dealing with VST-plugins",
"Tobias Doerffel <tobydox/at/users/dot/sf/dot/net>",
0x0100,
Plugin::Type::Library,
nullptr,
nullptr,
} ;
}
} // namespace lmms
| 1,372
|
C++
|
.cpp
| 43
| 29.976744
| 80
| 0.743182
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,656
|
RemoteVstPlugin.cpp
|
LMMS_lmms/plugins/VstBase/RemoteVstPlugin.cpp
|
/*
* RemoteVstPlugin.cpp - LMMS VST Support Layer (RemotePlugin client)
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* Code partly taken from (X)FST:
* Copyright (c) 2004 Paul Davis
* Copyright (c) 2004 Torben Hohn
* Copyright (c) 2002 Kjetil S. Matheussen
*
* X11 code partly taken from https://github.com/ekenberg/vstminihost:
* Copyright (c) 2012 Johan Ekenberg
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "lmmsconfig.h"
#include "RemotePluginClient.h"
#ifdef LMMS_HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef LMMS_BUILD_LINUX
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifdef LMMS_HAVE_SCHED_H
#include <sched.h>
#endif
#ifndef NATIVE_LINUX_VST
#include <wine/exception.h>
#endif
#endif // LMMS_BUILD_LINUX
#ifndef NATIVE_LINUX_VST
#define USE_WS_PREFIX
#include <windows.h>
#else
#include <dlfcn.h>
#include <pthread.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xos.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <sstream>
#include <time.h>
// https://stackoverflow.com/questions/22476110/c-compiling-error-including-x11-x-h-x11-xlib-h
#undef Bool
#undef CursorShape
#undef Expose
#undef KeyPress
#undef KeyRelease
#undef FocusIn
#undef FocusOut
#undef FontChange
#undef None
#undef Status
#undef Unsorted
#endif
#include <mutex>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
#include <iostream>
#include <string>
#include <cstring>
#include <aeffectx.h>
#if kVstVersion < 2400
#define OLD_VST_SDK
struct ERect
{
short top;
short left;
short bottom;
short right;
} ;
#endif
#include "lmms_basics.h"
#include "Midi.h"
#include "communication.h"
#include "IoHelper.h"
#include "VstSyncData.h"
using namespace std;
static lmms::VstHostLanguage hlang = lmms::VstHostLanguage::English;
static bool EMBED = false;
static bool EMBED_X11 = false;
static bool EMBED_WIN32 = false;
static bool HEADLESS = false;
namespace lmms
{
class RemoteVstPlugin;
}
lmms::RemoteVstPlugin * __plugin = nullptr;
#ifndef NATIVE_LINUX_VST
HWND __MessageHwnd = nullptr;
DWORD __processingThreadId = 0;
#else
pthread_t __processingThreadId = 0;
#endif
namespace lmms
{
#ifdef _WIN32
//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetErrorAsString(DWORD errorMessageID)
{
//Get the error message, if any.
if(errorMessageID == 0)
return std::string(); //No error message has been recorded
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, nullptr);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
#endif
class RemoteVstPlugin : public RemotePluginClient
{
public:
#ifdef SYNC_WITH_SHM_FIFO
RemoteVstPlugin( const std::string& _shm_in, const std::string& _shm_out );
#else
RemoteVstPlugin( const char * socketPath );
#endif
virtual ~RemoteVstPlugin();
virtual bool processMessage( const message & _m );
void init( const std::string & _plugin_file );
void initEditor();
void showEditor();
void hideEditor();
void destroyEditor();
virtual void process( const SampleFrame* _in, SampleFrame* _out );
virtual void processMidiEvent( const MidiEvent& event, const f_cnt_t offset );
// set given sample-rate for plugin
virtual void updateSampleRate()
{
SuspendPlugin suspend( this );
pluginDispatch( effSetSampleRate, 0, 0,
nullptr, (float) sampleRate() );
}
// set given buffer-size for plugin
virtual void updateBufferSize()
{
SuspendPlugin suspend( this );
pluginDispatch( effSetBlockSize, 0, bufferSize() );
}
void setResumed( bool resumed )
{
m_resumed = resumed;
pluginDispatch( effMainsChanged, 0, resumed ? 1 : 0 );
}
inline bool isResumed() const
{
return m_resumed;
}
inline bool isInitialized() const
{
return m_initialized;
}
// set given tempo
void setBPM( const bpm_t _bpm )
{
m_bpm = _bpm;
}
// determine VST-version the plugin uses
inline int pluginVersion()
{
return pluginDispatch( effGetVendorVersion );
}
// determine name of plugin
const char * pluginName();
// determine vendor of plugin
const char * pluginVendorString();
// determine product-string of plugin
const char * pluginProductString();
// determine name of current program
const char * programName();
void getParameterDisplays();
void getParameterLabels();
// send name of current program back to host
void sendCurrentProgramName();
// do a complete parameter-dump and post it
void getParameterDump();
// read parameter-dump and set it for plugin
void setParameterDump( const message & _m );
// save settings chunk of plugin into file
void saveChunkToFile( const std::string & _file );
// restore settings chunk of plugin from file
void loadChunkFromFile(const std::string& _file, std::size_t _len);
// restore settings chunk of plugin from file
void loadPresetFile( const std::string & _file );
// sets given program index
void setProgram( int index );
// rotate current program by given offset
void rotateProgram( int offset );
// Load names of presets/programs
void getProgramNames();
// Save presets/programs
void savePreset( const std::string & _file );
// number of inputs
virtual int inputCount() const
{
if( m_plugin )
{
return m_plugin->numInputs;
}
return 0;
}
// number of outputs
virtual int outputCount() const
{
if( m_plugin )
{
return m_plugin->numOutputs;
}
return 0;
}
// has to be called as soon as input- or output-count changes
int updateInOutCount();
inline void lockShm()
{
m_shmLock.lock();
}
inline bool tryLockShm()
{
return m_shmLock.try_lock();
}
inline void unlockShm()
{
m_shmLock.unlock();
}
inline bool isShmValid()
{
return m_shmValid;
}
inline void setShmIsValid( bool valid )
{
m_shmValid = valid;
}
inline bool isProcessing() const
{
return m_processing;
}
inline void setProcessing( bool processing )
{
m_processing = processing;
}
inline void queueMessage( const message & m ) {
#ifdef NATIVE_LINUX_VST
pthread_mutex_lock(&message_mutex);
#endif
m_messageList.push( m );
#ifdef NATIVE_LINUX_VST
pthread_mutex_unlock(&message_mutex);
#endif
}
inline bool shouldGiveIdle() const
{
return m_shouldGiveIdle;
}
inline void setShouldGiveIdle( bool shouldGiveIdle )
{
m_shouldGiveIdle = shouldGiveIdle;
}
void idle();
void processUIThreadMessages();
#ifdef NATIVE_LINUX_VST
void sendX11Idle();
#endif
#ifndef NATIVE_LINUX_VST
static DWORD WINAPI processingThread( LPVOID _param );
#else
static void * processingThread( void * _param );
#endif
static bool setupMessageWindow();
#ifndef NATIVE_LINUX_VST
static DWORD WINAPI guiEventLoop();
#else
void guiEventLoop();
#endif
#ifndef NATIVE_LINUX_VST
static LRESULT CALLBACK wndProc( HWND hwnd, UINT uMsg,
WPARAM wParam, LPARAM lParam );
#endif
private:
enum class GuiThreadMessage
{
None,
ProcessPluginMessage,
GiveIdle,
ClosePlugin
} ;
struct SuspendPlugin {
SuspendPlugin( RemoteVstPlugin * plugin ) :
m_plugin( plugin ),
m_resumed( plugin->isResumed() )
{
if( m_resumed ) { m_plugin->setResumed( false ); }
}
~SuspendPlugin()
{
if( m_resumed ) { m_plugin->setResumed( true ); }
}
private:
RemoteVstPlugin * m_plugin;
bool m_resumed;
};
// callback used by plugin for being able to communicate with it's host
static intptr_t VST_CALL_CONV hostCallback( AEffect * _effect, int32_t _opcode,
int32_t _index, intptr_t _value,
void * _ptr, float _opt );
bool load( const std::string & _plugin_file );
int pluginDispatch( int cmd, int param1 = 0, int param2 = 0,
void * p = nullptr, float f = 0 )
{
if( m_plugin )
{
return m_plugin->dispatcher( m_plugin, cmd, param1, param2, p, f );
}
return 0;
}
std::string m_shortName;
#ifndef NATIVE_LINUX_VST
HINSTANCE m_libInst;
#else
void* m_libInst = nullptr;
#endif
AEffect * m_plugin;
#ifndef NATIVE_LINUX_VST
HWND m_window = nullptr;
#else
Window m_window = 0;
Display* m_display = nullptr;
Atom m_wmDeleteMessage;
bool m_x11WindowVisible = false;
#endif
intptr_t m_windowID;
int m_windowWidth;
int m_windowHeight;
bool m_initialized;
bool m_resumed;
bool m_processing;
#ifdef NATIVE_LINUX_VST
pthread_mutex_t message_mutex = PTHREAD_MUTEX_INITIALIZER;
bool m_shouldQuit = false;
#endif
std::queue<message> m_messageList;
bool m_shouldGiveIdle;
float * * m_inputs;
float * * m_outputs;
std::mutex m_shmLock;
bool m_shmValid;
using VstMidiEventList = std::vector<VstMidiEvent>;
VstMidiEventList m_midiEvents;
bpm_t m_bpm;
double m_currentSamplePos;
int m_currentProgram;
// host to plugin synchronisation data structure
struct in
{
double lastppqPos;
double m_Timestamp;
int32_t m_lastFlags;
} ;
in * m_in;
};
#ifdef SYNC_WITH_SHM_FIFO
RemoteVstPlugin::RemoteVstPlugin( const std::string& _shm_in, const std::string& _shm_out ) :
RemotePluginClient( _shm_in, _shm_out ),
#else
RemoteVstPlugin::RemoteVstPlugin( const char * socketPath ) :
RemotePluginClient( socketPath ),
#endif
m_libInst( nullptr ),
m_plugin( nullptr ),
m_windowID( 0 ),
m_windowWidth( 0 ),
m_windowHeight( 0 ),
m_initialized( false ),
m_resumed( false ),
m_processing( false ),
m_messageList(),
m_shouldGiveIdle( false ),
m_inputs( nullptr ),
m_outputs( nullptr ),
m_shmValid( false ),
m_midiEvents(),
m_bpm( 0 ),
m_currentSamplePos( 0 ),
m_currentProgram( -1 ),
m_in( nullptr )
{
__plugin = this;
m_in = ( in* ) new char[ sizeof( in ) ];
m_in->lastppqPos = 0;
m_in->m_Timestamp = -1;
m_in->m_lastFlags = 0;
// process until we have loaded the plugin
while( 1 )
{
message m = receiveMessage();
processMessage( m );
if( m.id == IdVstLoadPlugin || m.id == IdQuit )
{
break;
}
}
}
RemoteVstPlugin::~RemoteVstPlugin()
{
destroyEditor();
setResumed( false );
pluginDispatch( effClose );
if( m_libInst != nullptr )
{
#ifndef NATIVE_LINUX_VST
FreeLibrary( m_libInst );
#else
dlclose(m_libInst);
#endif
m_libInst = nullptr;
}
delete[] m_inputs;
delete[] m_outputs;
}
bool RemoteVstPlugin::processMessage( const message & _m )
{
if (! EMBED)
{
switch( _m.id )
{
case IdShowUI:
showEditor();
return true;
case IdHideUI:
hideEditor();
return true;
case IdToggleUI:
#ifndef NATIVE_LINUX_VST
if( m_window && IsWindowVisible( m_window ) )
#else
if (m_window && m_x11WindowVisible)
#endif
{
hideEditor();
}
else
{
showEditor();
}
return true;
case IdIsUIVisible:
#ifndef NATIVE_LINUX_VST
bool visible = m_window && IsWindowVisible( m_window );
#else
bool visible = m_window && m_x11WindowVisible;
#endif
sendMessage( message( IdIsUIVisible )
.addInt( visible ? 1 : 0 ) );
return true;
}
}
else if (EMBED && _m.id == IdShowUI)
{
#ifndef NATIVE_LINUX_VST
ShowWindow( m_window, SW_SHOWNORMAL );
UpdateWindow( m_window );
#endif
return true;
}
switch( _m.id )
{
case IdVstLoadPlugin:
init( _m.getString() );
break;
case IdVstSetTempo:
setBPM( _m.getInt() );
break;
case IdVstSetLanguage:
hlang = static_cast<VstHostLanguage>( _m.getInt() );
break;
case IdVstGetParameterDump:
getParameterDump();
break;
case IdVstSetParameterDump:
setParameterDump( _m );
break;
case IdSaveSettingsToFile:
saveChunkToFile( _m.getString() );
sendMessage( IdSaveSettingsToFile );
break;
case IdLoadSettingsFromFile:
loadChunkFromFile( _m.getString( 0 ), _m.getInt( 1 ) );
sendMessage( IdLoadSettingsFromFile );
break;
case IdLoadPresetFile:
loadPresetFile( _m.getString( 0 ) );
sendMessage( IdLoadPresetFile );
break;
case IdVstSetProgram:
setProgram( _m.getInt( 0 ) );
sendMessage( IdVstSetProgram );
break;
case IdVstCurrentProgram:
sendMessage( message( IdVstCurrentProgram ).addInt( m_currentProgram ) );
break;
case IdVstRotateProgram:
rotateProgram( _m.getInt( 0 ) );
sendMessage( IdVstRotateProgram );
break;
case IdVstProgramNames:
getProgramNames();
break;
case IdSavePresetFile:
savePreset( _m.getString( 0 ) );
sendMessage( IdSavePresetFile );
break;
case IdVstSetParameter:
m_plugin->setParameter( m_plugin, _m.getInt( 0 ), _m.getFloat( 1 ) );
//sendMessage( IdVstSetParameter );
break;
case IdVstParameterDisplays:
getParameterDisplays();
break;
case IdVstParameterLabels:
getParameterLabels();
break;
case IdVstIdleUpdate:
{
int newCurrentProgram = pluginDispatch( effGetProgram );
if( newCurrentProgram != m_currentProgram )
{
m_currentProgram = newCurrentProgram;
sendCurrentProgramName();
}
break;
}
case IdIdle:
{
#ifdef NATIVE_LINUX_VST
idle();
#endif
break;
}
#ifdef NATIVE_LINUX_VST
case IdQuit:
{
m_shouldQuit = true;
break;
}
#endif
default:
return RemotePluginClient::processMessage( _m );
}
return true;
}
void RemoteVstPlugin::init( const std::string & _plugin_file )
{
if( load( _plugin_file ) == false )
{
sendMessage( IdVstFailedLoadingPlugin );
return;
}
updateInOutCount();
updateBufferSize();
updateSampleRate();
/* set program to zero */
/* i comment this out because it breaks dfx Geometer
* looks like we cant set programs for it
*
pluginDispatch( effSetProgram, 0, 0 ); */
// request rate and blocksize
setResumed( true );
debugMessage( "creating editor\n" );
initEditor();
debugMessage( "editor successfully created\n" );
// now post some information about our plugin
sendMessage( message( IdVstPluginWindowID ).addInt( m_windowID ) );
sendMessage( message( IdVstPluginEditorGeometry ).
addInt( m_windowWidth ).
addInt( m_windowHeight ) );
sendMessage( message( IdVstPluginName ).addString( pluginName() ) );
debugMessage( std::string("plugin name: ") + pluginName() + "\n" );
sendMessage( message( IdVstPluginVersion ).addInt( pluginVersion() ) );
sendMessage( message( IdVstPluginVendorString ).
addString( pluginVendorString() ) );
sendMessage( message( IdVstPluginProductString ).
addString( pluginProductString() ) );
sendMessage( message( IdVstParameterCount ).
addInt( m_plugin->numParams ) );
sendMessage( IdInitDone );
debugMessage( "initialization done\n" );
m_initialized = true;
}
static void close_check( FILE* fp )
{
if (!fp) {return;}
if( fclose( fp ) )
{
perror( "fclose" );
}
}
void RemoteVstPlugin::initEditor()
{
if( HEADLESS || m_window || !( m_plugin->flags & effFlagsHasEditor ) )
{
return;
}
#ifndef NATIVE_LINUX_VST
HMODULE hInst = GetModuleHandle( nullptr );
if( hInst == nullptr )
{
debugMessage( "initEditor(): can't get module handle\n" );
return;
}
DWORD dwStyle;
if (EMBED) {
dwStyle = WS_POPUP | WS_SYSMENU | WS_BORDER;
} else {
dwStyle = WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX;
}
m_window = CreateWindowEx( WS_EX_APPWINDOW, "LVSL", pluginName(),
dwStyle,
0, 0, 10, 10, nullptr, nullptr, hInst, nullptr );
if( m_window == nullptr )
{
debugMessage( "initEditor(): cannot create editor window\n" );
return;
}
pluginDispatch( effEditOpen, 0, 0, m_window );
ERect * er;
pluginDispatch( effEditGetRect, 0, 0, &er );
m_windowWidth = er->right - er->left;
m_windowHeight = er->bottom - er->top;
RECT windowSize = { 0, 0, m_windowWidth, m_windowHeight };
AdjustWindowRect( &windowSize, dwStyle, false );
SetWindowPos( m_window, 0, 0, 0, windowSize.right - windowSize.left,
windowSize.bottom - windowSize.top, SWP_NOACTIVATE |
SWP_NOMOVE | SWP_NOZORDER );
pluginDispatch( effEditTop );
#ifdef LMMS_BUILD_LINUX
m_windowID = (intptr_t) GetProp( m_window, "__wine_x11_whole_window" );
#else
// 64-bit versions of Windows use 32-bit handles for interoperability
m_windowID = (intptr_t) m_window;
#endif
#else
Atom prop_atom, val_atom;
if (m_display == nullptr)
{
m_display = XOpenDisplay(nullptr);
}
m_window = XCreateSimpleWindow(m_display, DefaultRootWindow(m_display), 0, 0, 400, 400, 0, 0, 0);
m_wmDeleteMessage = XInternAtom(m_display, "WM_DELETE_WINDOW", false);
XSetWMProtocols(m_display, m_window, &m_wmDeleteMessage, 1);
// make tool window
prop_atom = XInternAtom(m_display, "_NET_WM_WINDOW_TYPE", False);
val_atom = XInternAtom(m_display, "_NET_WM_WINDOW_TYPE_DIALOG", False);
XChangeProperty(m_display, m_window, prop_atom, XA_ATOM, 32, PropModeReplace, (unsigned char *)&val_atom, 1);
// change name
XStoreName(m_display, m_window, pluginName());
ERect * er;
pluginDispatch(effEditGetRect, 0, 0, &er);
m_windowWidth = er->right - er->left;
m_windowHeight = er->bottom - er->top;
XResizeWindow(m_display, m_window, m_windowWidth, m_windowHeight);
XMapWindow(m_display, m_window);
XFlush(m_display);
pluginDispatch(effEditOpen, 0, (intptr_t) m_display, (void*) m_window);
XSelectInput(m_display, m_window, SubstructureNotifyMask | ButtonPressMask | ButtonReleaseMask
| ButtonMotionMask | ExposureMask | KeyPressMask);
pluginDispatch(effEditTop);
m_x11WindowVisible = true;
#endif // NATIVE_LINUX_VST
}
void RemoteVstPlugin::showEditor() {
if( !EMBED && !HEADLESS && m_window )
{
#ifndef NATIVE_LINUX_VST
ShowWindow( m_window, SW_SHOWNORMAL );
#else
if (!m_x11WindowVisible)
{
XMapWindow(m_display, m_window);
XFlush(m_display);
m_x11WindowVisible = true;
}
#endif
}
}
void RemoteVstPlugin::hideEditor() {
if( !EMBED && !HEADLESS && m_window )
{
#ifndef NATIVE_LINUX_VST
ShowWindow( m_window, SW_HIDE );
#else
if (m_x11WindowVisible)
{
XUnmapWindow(m_display, m_window);
XFlush(m_display);
m_x11WindowVisible = false;
}
#endif
}
}
void RemoteVstPlugin::destroyEditor()
{
if( !m_window )
{
return;
}
pluginDispatch( effEditClose );
#ifndef NATIVE_LINUX_VST
// Destroying the window takes some time in Wine 1.8.5
DestroyWindow( m_window );
m_window = nullptr;
#else
if (m_display)
{
XCloseDisplay(m_display);
}
m_display = nullptr;
m_window = 0;
#endif
}
bool RemoteVstPlugin::load( const std::string & _plugin_file )
{
#ifndef NATIVE_LINUX_VST
if( ( m_libInst = LoadLibraryW( toWString(_plugin_file).c_str() ) ) == nullptr )
{
DWORD error = GetLastError();
debugMessage( "LoadLibrary failed: " + GetErrorAsString(error) );
return false;
}
#else
m_libInst = dlopen(_plugin_file.c_str(), RTLD_LAZY);
if ( m_libInst == nullptr) {
debugMessage( std::string("LoadLibrary failed: ") + dlerror() );
return false;
}
#endif
using mainEntryPointer = AEffect* (VST_CALL_CONV*) (audioMasterCallback);
#ifndef NATIVE_LINUX_VST
mainEntryPointer mainEntry = (mainEntryPointer)
GetProcAddress( m_libInst, "VSTPluginMain" );
if( mainEntry == nullptr )
{
mainEntry = (mainEntryPointer)
GetProcAddress( m_libInst, "VstPluginMain" );
}
if( mainEntry == nullptr )
{
mainEntry = (mainEntryPointer)
GetProcAddress( m_libInst, "main" );
}
#else
mainEntryPointer mainEntry = (mainEntryPointer) dlsym(m_libInst, "VSTPluginMain");
if( mainEntry == nullptr )
mainEntry = (mainEntryPointer) dlsym(m_libInst, "VstPluginMain");
if( mainEntry == nullptr )
mainEntry = (mainEntryPointer) dlsym(m_libInst, "main");
#endif
if( mainEntry == nullptr )
{
debugMessage( "could not find entry point\n" );
return false;
}
m_plugin = mainEntry( hostCallback );
if( m_plugin == nullptr )
{
debugMessage( "mainEntry procedure returned nullptr\n" );
return false;
}
if( m_plugin->magic != kEffectMagic )
{
debugMessage( "File is not a VST plugin\n" );
return false;
}
char id[5];
sprintf( id, "%c%c%c%c", ((char *)&m_plugin->uniqueID)[3],
((char *)&m_plugin->uniqueID)[2],
((char *)&m_plugin->uniqueID)[1],
((char *)&m_plugin->uniqueID)[0] );
id[4] = 0;
sendMessage( message( IdVstPluginUniqueID ).addString( id ) );
pluginDispatch( effOpen );
return true;
}
void RemoteVstPlugin::process( const SampleFrame* _in, SampleFrame* _out )
{
// first we gonna post all MIDI-events we enqueued so far
if( m_midiEvents.size() )
{
// since MIDI-events are not received immediately, we
// have to have them stored somewhere even after
// dispatcher-call, so we create static copies of the
// data and post them
#define MIDI_EVENT_BUFFER_COUNT 1024
static char eventsBuffer[sizeof( VstEvents ) + sizeof( VstMidiEvent * ) * MIDI_EVENT_BUFFER_COUNT];
static VstMidiEvent vme[MIDI_EVENT_BUFFER_COUNT];
// first sort events chronologically, since some plugins
// (e.g. Sinnah) can hang if they're out of order
std::stable_sort( m_midiEvents.begin(), m_midiEvents.end(),
[]( const VstMidiEvent &a, const VstMidiEvent &b )
{
return a.deltaFrames < b.deltaFrames;
} );
auto events = (VstEvents*)eventsBuffer;
events->reserved = 0;
events->numEvents = m_midiEvents.size();
int idx = 0;
for( VstMidiEventList::iterator it = m_midiEvents.begin(); it != m_midiEvents.end(); ++it, ++idx )
{
memcpy( &vme[idx], &*it, sizeof( VstMidiEvent ) );
events->events[idx] = (VstEvent *) &vme[idx];
}
m_midiEvents.clear();
pluginDispatch( effProcessEvents, 0, 0, events );
}
// now we're ready to fetch sound from VST-plugin
if( !tryLockShm() )
{
return;
}
if( !isShmValid() )
{
unlockShm();
return;
}
for( int i = 0; i < inputCount(); ++i )
{
m_inputs[i] = &((float *) _in)[i * bufferSize()];
}
for( int i = 0; i < outputCount(); ++i )
{
m_outputs[i] = &((float *) _out)[i * bufferSize()];
memset( m_outputs[i], 0, bufferSize() * sizeof( float ) );
}
#ifdef OLD_VST_SDK
if( m_plugin->flags & effFlagsCanReplacing )
{
m_plugin->processReplacing( m_plugin, m_inputs, m_outputs,
bufferSize() );
}
else
{
m_plugin->process( m_plugin, m_inputs, m_outputs,
bufferSize() );
}
#else
m_plugin->processReplacing(m_plugin, m_inputs, m_outputs, bufferSize());
#endif
unlockShm();
m_currentSamplePos += bufferSize();
}
void RemoteVstPlugin::processMidiEvent( const MidiEvent& event, const f_cnt_t offset )
{
VstMidiEvent vme;
vme.type = kVstMidiType;
vme.byteSize = 24;
vme.deltaFrames = offset;
vme.flags = 0;
vme.detune = 0;
vme.noteLength = 0;
vme.noteOffset = 0;
vme.noteOffVelocity = 0;
vme.reserved1 = 0;
vme.reserved2 = 0;
vme.midiData[0] = event.type() + event.channel();
switch( event.type() )
{
case MidiPitchBend:
vme.midiData[1] = event.pitchBend() & 0x7f;
vme.midiData[2] = event.pitchBend() >> 7;
break;
// TODO: handle more special cases
default:
vme.midiData[1] = event.key();
vme.midiData[2] = event.velocity();
break;
}
vme.midiData[3] = 0;
m_midiEvents.push_back( vme );
}
const char * RemoteVstPlugin::pluginName()
{
static char buf[32];
buf[0] = 0;
pluginDispatch( effGetEffectName, 0, 0, buf );
buf[31] = 0;
return buf;
}
const char * RemoteVstPlugin::pluginVendorString()
{
static char buf[64];
buf[0] = 0;
pluginDispatch( effGetVendorString, 0, 0, buf );
buf[63] = 0;
return buf;
}
const char * RemoteVstPlugin::pluginProductString()
{
static char buf[64];
buf[0] = 0;
pluginDispatch( effGetProductString, 0, 0, buf );
buf[63] = 0;
return buf;
}
const char * RemoteVstPlugin::programName()
{
static char buf[24];
memset( buf, 0, sizeof( buf ) );
pluginDispatch( effGetProgramName, 0, 0, buf );
buf[23] = 0;
return buf;
}
// join the ParameterDisplays (stringified values without units) and send them to host
void RemoteVstPlugin::getParameterDisplays()
{
std::string paramDisplays;
static char buf[9]; // buffer for getting string
for (int i=0; i< m_plugin->numParams; ++i)
{
memset( buf, 0, sizeof( buf ) ); // fill with '\0' because got string may not to be ended with '\0'
pluginDispatch( effGetParamDisplay, i, 0, buf );
buf[8] = 0;
// each field shaped like: [length:number][content:string]
paramDisplays += '0' + strlen(buf); // add length descriptor (length is up to 8)
paramDisplays += buf;
}
sendMessage( message( IdVstParameterDisplays ).addString( paramDisplays.c_str() ) );
}
// join the ParameterLabels (units) and send them to host
void RemoteVstPlugin::getParameterLabels()
{
std::string paramLabels;
static char buf[9]; // buffer for getting string
for (int i=0; i< m_plugin->numParams; ++i)
{
memset( buf, 0, sizeof( buf ) ); // fill with '\0' because got string may not to be ended with '\0'
pluginDispatch( effGetParamLabel, i, 0, buf );
buf[8] = 0;
// each field shaped like: [length:number][content:string]
paramLabels += '0' + strlen(buf); // add length descriptor (length is up to 8)
paramLabels += buf;
}
sendMessage( message( IdVstParameterLabels ).addString( paramLabels.c_str() ) );
}
void RemoteVstPlugin::sendCurrentProgramName()
{
char presName[64];
sprintf( presName, "%d/%d: %s", pluginDispatch( effGetProgram ) + 1, m_plugin->numPrograms, programName() );
sendMessage( message( IdVstCurrentProgramName ).addString( presName ) );
}
void RemoteVstPlugin::getParameterDump()
{
message m( IdVstParameterDump );
m.addInt( m_plugin->numParams );
for( int i = 0; i < m_plugin->numParams; ++i )
{
char paramName[256];
memset( paramName, 0, sizeof( paramName ) );
pluginDispatch( effGetParamName, i, 0, paramName );
paramName[sizeof(paramName)-1] = 0;
m.addInt( i );
m.addString( paramName );
m.addFloat( m_plugin->getParameter( m_plugin, i ) );
}
sendMessage( m );
}
void RemoteVstPlugin::setParameterDump( const message & _m )
{
const int n = _m.getInt( 0 );
const int params = ( n > m_plugin->numParams ) ?
m_plugin->numParams : n;
int p = 0;
for( int i = 0; i < params; ++i )
{
VstParameterDumpItem item;
item.index = _m.getInt( ++p );
item.shortLabel = _m.getString( ++p );
item.value = _m.getFloat( ++p );
m_plugin->setParameter( m_plugin, item.index, item.value );
}
}
void RemoteVstPlugin::saveChunkToFile( const std::string & _file )
{
if( m_plugin->flags & 32 )
{
void * chunk = nullptr;
const int len = pluginDispatch( 23, 0, 0, &chunk );
if( len > 0 )
{
FILE* fp = F_OPEN_UTF8( _file, "wb" );
if (!fp)
{
fprintf( stderr,
"Error opening file for saving chunk.\n" );
return;
}
if (fwrite(chunk, 1, len, fp) != static_cast<std::size_t>(len))
{
fprintf( stderr,
"Error saving chunk to file.\n" );
}
close_check( fp );
}
}
}
void RemoteVstPlugin::setProgram( int program )
{
if( isInitialized() == false )
{
return;
}
if( program < 0 )
{
program = 0;
}
else if( program >= m_plugin->numPrograms )
{
program = m_plugin->numPrograms - 1;
}
pluginDispatch( effSetProgram, 0, program );
sendCurrentProgramName();
}
void RemoteVstPlugin::rotateProgram( int offset )
{
if( isInitialized() == false )
{
return;
}
int newProgram = pluginDispatch( effGetProgram ) + offset;
if( newProgram < 0 )
{
newProgram = 0;
}
else if( newProgram >= m_plugin->numPrograms )
{
newProgram = m_plugin->numPrograms - 1;
}
pluginDispatch( effSetProgram, 0, newProgram );
sendCurrentProgramName();
}
void RemoteVstPlugin::getProgramNames()
{
char presName[1024+256*30];
char curProgName[30];
if (isInitialized() == false) return;
bool progNameIndexed = ( pluginDispatch( 29, 0, -1, curProgName ) == 1 );
if (m_plugin->numPrograms > 1) {
if (progNameIndexed) {
for (int i = 0; i< (m_plugin->numPrograms >= 256?256:m_plugin->numPrograms); i++)
{
pluginDispatch( 29, i, -1, curProgName );
if (i == 0) sprintf( presName, "%s", curProgName );
else sprintf( presName + strlen(presName), "|%s", curProgName );
}
}
else
{
int currProgram = pluginDispatch( effGetProgram );
for (int i = 0; i< (m_plugin->numPrograms >= 256?256:m_plugin->numPrograms); i++)
{
pluginDispatch( effSetProgram, 0, i );
if (i == 0) sprintf( presName, "%s", programName() );
else sprintf( presName + strlen(presName), "|%s", programName() );
}
pluginDispatch( effSetProgram, 0, currProgram );
}
} else sprintf( presName, "%s", programName() );
presName[sizeof(presName)-1] = 0;
sendMessage( message( IdVstProgramNames ).addString( presName ) );
}
inline unsigned int endian_swap(unsigned int& x)
{
return (x>>24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF00) | (x<<24);
}
struct sBank
{
unsigned int chunkMagic;
unsigned int byteSize;
unsigned int fxMagic;
unsigned int version;
unsigned int fxID;
unsigned int fxVersion;
unsigned int numPrograms;
char prgName[28];
};
void RemoteVstPlugin::savePreset( const std::string & _file )
{
unsigned int chunk_size = 0;
auto pBank = (sBank*)new char[sizeof(sBank)];
char progName[ 128 ] = { 0 };
char* data = nullptr;
const bool chunky = ( m_plugin->flags & ( 1 << 5 ) ) != 0;
bool isPreset = _file.substr( _file.find_last_of( "." ) + 1 ) == "fxp";
int presNameLen = _file.find_last_of( "/" ) + _file.find_last_of( "\\" ) + 2;
if (isPreset)
{
for (size_t i = 0; i < _file.length() - 4 - presNameLen; i++)
progName[i] = i < 23 ? _file[presNameLen + i] : 0;
pluginDispatch( 4, 0, 0, progName );
}
if ( chunky )
chunk_size = pluginDispatch( 23, isPreset, 0, &data );
else {
if (isPreset) {
chunk_size = m_plugin->numParams * sizeof( float );
data = new char[ chunk_size ];
auto toUIntArray = reinterpret_cast<unsigned int*>(data);
for ( int i = 0; i < m_plugin->numParams; i++ )
{
float value = m_plugin->getParameter( m_plugin, i );
auto pValue = (unsigned int*)&value;
toUIntArray[ i ] = endian_swap( *pValue );
}
} else chunk_size = (((m_plugin->numParams * sizeof( float )) + 56)*m_plugin->numPrograms);
}
pBank->chunkMagic = 0x4B6E6343;
pBank->byteSize = chunk_size + ( chunky ? sizeof( int ) : 0 ) + 48;
if (!isPreset) pBank->byteSize += 100;
pBank->byteSize = endian_swap( pBank->byteSize );
pBank->fxMagic = chunky ? 0x68435046 : 0x6B437846;
if (!isPreset && chunky) pBank->fxMagic = 0x68434246;
if (!isPreset &&!chunky) pBank->fxMagic = 0x6B427846;
pBank->version = 0x01000000;
auto uIntToFile = (unsigned int)m_plugin->uniqueID;
pBank->fxID = endian_swap( uIntToFile );
uIntToFile = (unsigned int) pluginVersion();
pBank->fxVersion = endian_swap( uIntToFile );
uIntToFile = (unsigned int) chunky ? m_plugin->numPrograms : m_plugin->numParams;
if (!isPreset &&!chunky) uIntToFile = (unsigned int) m_plugin->numPrograms;
pBank->numPrograms = endian_swap( uIntToFile );
FILE * stream = F_OPEN_UTF8( _file, "wb" );
if (!stream)
{
fprintf( stderr,
"Error opening file for saving preset.\n" );
return;
}
fwrite ( pBank, 1, 28, stream );
fwrite ( progName, 1, isPreset ? 28 : 128, stream );
if ( chunky ) {
uIntToFile = endian_swap( chunk_size );
fwrite ( &uIntToFile, 1, 4, stream );
}
if (pBank->fxMagic != 0x6B427846 )
fwrite ( data, 1, chunk_size, stream );
else {
int numPrograms = m_plugin->numPrograms;
int currProgram = pluginDispatch( effGetProgram );
chunk_size = (m_plugin->numParams * sizeof( float ));
pBank->byteSize = chunk_size + 48;
pBank->byteSize = endian_swap( pBank->byteSize );
pBank->fxMagic = 0x6B437846;
uIntToFile = (unsigned int) m_plugin->numParams;
pBank->numPrograms = endian_swap( uIntToFile );
data = new char[ chunk_size ];
unsigned int* pValue,* toUIntArray = reinterpret_cast<unsigned int*>( data );
float value;
for (int j = 0; j < numPrograms; j++) {
pluginDispatch( effSetProgram, 0, j );
pluginDispatch( effGetProgramName, 0, 0, pBank->prgName );
fwrite ( pBank, 1, 56, stream );
for ( int i = 0; i < m_plugin->numParams; i++ )
{
value = m_plugin->getParameter( m_plugin, i );
pValue = ( unsigned int * ) &value;
toUIntArray[ i ] = endian_swap( *pValue );
}
fwrite ( data, 1, chunk_size, stream );
}
pluginDispatch( effSetProgram, 0, currProgram );
}
fclose( stream );
if ( !chunky )
delete[] data;
delete[] (sBank*)pBank;
}
void RemoteVstPlugin::loadPresetFile( const std::string & _file )
{
void * chunk = nullptr;
auto pLen = new unsigned int[1];
unsigned int len = 0;
auto pBank = (sBank*)new char[sizeof(sBank)];
FILE * stream = F_OPEN_UTF8( _file, "rb" );
if (!stream)
{
fprintf( stderr,
"Error opening file for loading preset.\n" );
return;
}
if ( fread ( pBank, 1, 56, stream ) != 56 )
{
fprintf( stderr, "Error loading preset file.\n" );
}
pBank->fxID = endian_swap( pBank->fxID );
pBank->numPrograms = endian_swap( pBank->numPrograms );
unsigned int toUInt;
float * pFloat;
if (static_cast<std::uint_fast32_t>(m_plugin->uniqueID) != pBank->fxID) {
sendMessage( message( IdVstCurrentProgramName ).
addString( "Error: Plugin UniqID not match" ) );
fclose( stream );
delete[] (unsigned int*)pLen;
delete[] (sBank*)pBank;
return;
}
if( _file.substr( _file.find_last_of( "." ) + 1 ) != "fxp" )
fseek ( stream , 156 , SEEK_SET );
if(pBank->fxMagic != 0x6B427846) {
if(pBank->fxMagic != 0x6B437846) {
if ( fread (pLen, 1, 4, stream) != 4 )
{
fprintf( stderr,
"Error loading preset file.\n" );
}
chunk = new char[len = endian_swap(*pLen)];
} else chunk = new char[len = sizeof(float)*pBank->numPrograms];
if ( fread (chunk, len, 1, stream) != 1 )
{
fprintf( stderr, "Error loading preset file.\n" );
}
fclose( stream );
}
if(_file.substr(_file.find_last_of(".") + 1) == "fxp") {
pBank->prgName[23] = 0;
pluginDispatch( 4, 0, 0, pBank->prgName );
if(pBank->fxMagic != 0x6B437846)
pluginDispatch( 24, 1, len, chunk );
else
{
auto toUIntArray = reinterpret_cast<unsigned int*>(chunk);
for (auto i = 0u; i < pBank->numPrograms; i++)
{
toUInt = endian_swap( toUIntArray[ i ] );
pFloat = ( float* ) &toUInt;
m_plugin->setParameter( m_plugin, i, *pFloat );
}
}
} else {
if(pBank->fxMagic != 0x6B427846) {
pluginDispatch( 24, 0, len, chunk );
} else {
int numPrograms = pBank->numPrograms;
unsigned int * toUIntArray;
int currProgram = pluginDispatch( effGetProgram );
chunk = new char[ len = sizeof(float)*m_plugin->numParams ];
toUIntArray = reinterpret_cast<unsigned int *>( chunk );
for (int i =0; i < numPrograms; i++) {
if ( fread (pBank, 1, 56, stream) != 56 )
{
fprintf( stderr,
"Error loading preset file.\n" );
}
if ( fread (chunk, len, 1, stream) != 1 )
{
fprintf( stderr,
"Error loading preset file.\n" );
}
pluginDispatch( effSetProgram, 0, i );
pBank->prgName[23] = 0;
pluginDispatch( 4, 0, 0, pBank->prgName );
for (int j = 0; j < m_plugin->numParams; j++ ) {
toUInt = endian_swap( toUIntArray[ j ] );
pFloat = ( float* ) &toUInt;
m_plugin->setParameter( m_plugin, j, *pFloat );
}
}
pluginDispatch( effSetProgram, 0, currProgram );
fclose( stream );
}
}
sendCurrentProgramName();
delete[] (unsigned int*)pLen;
delete[] (sBank*)pBank;
delete[] (char*)chunk;
}
void RemoteVstPlugin::loadChunkFromFile(const std::string& _file, std::size_t _len)
{
auto chunk = new char[_len];
FILE* fp = F_OPEN_UTF8( _file, "rb" );
if (!fp)
{
fprintf( stderr,
"Error opening file for loading chunk.\n" );
return;
}
if ( fread( chunk, 1, _len, fp ) != _len )
{
fprintf( stderr, "Error loading chunk from file.\n" );
}
close_check( fp );
pluginDispatch( effSetChunk, 0, _len, chunk );
delete[] chunk;
}
int RemoteVstPlugin::updateInOutCount()
{
if( inputCount() == RemotePluginClient::inputCount() &&
outputCount() == RemotePluginClient::outputCount() )
{
return 1;
}
#ifndef NATIVE_LINUX_VST
if( GetCurrentThreadId() == __processingThreadId )
#else
if( pthread_equal(pthread_self(), __processingThreadId) )
#endif
{
debugMessage( "Plugin requested I/O change from processing "
"thread. Request denied; stability may suffer.\n" );
return 0;
}
lockShm();
setShmIsValid( false );
unlockShm();
delete[] m_inputs;
delete[] m_outputs;
m_inputs = nullptr;
m_outputs = nullptr;
setInputOutputCount( inputCount(), outputCount() );
char buf[64];
sprintf( buf, "inputs: %d output: %d\n", inputCount(), outputCount() );
debugMessage( buf );
if( inputCount() > 0 )
{
m_inputs = new float * [inputCount()];
}
if( outputCount() > 0 )
{
m_outputs = new float * [outputCount()];
}
return 1;
}
//#define DEBUG_CALLBACKS
#ifdef DEBUG_CALLBACKS
#define SHOW_CALLBACK __plugin->debugMessage
#else
#define SHOW_CALLBACK(...)
#endif
/* TODO:
* - complete audioMasterGetTime-handling (bars etc.)
* - implement audioMasterProcessEvents
* - audioMasterGetVendorVersion: return LMMS-version (config.h!)
* - audioMasterGetDirectory: return either VST-plugin-dir or LMMS-workingdir
* - audioMasterOpenFileSelector: show QFileDialog?
*/
intptr_t RemoteVstPlugin::hostCallback( AEffect * _effect, int32_t _opcode,
int32_t _index, intptr_t _value,
void * _ptr, float _opt )
{
static VstTimeInfo _timeInfo;
#ifdef DEBUG_CALLBACKS
char buf[64];
sprintf( buf, "host-callback, opcode = %d\n", (int) _opcode );
SHOW_CALLBACK( buf );
#endif
// workaround for early callbacks by some plugins
if( __plugin && __plugin->m_plugin == nullptr )
{
__plugin->m_plugin = _effect;
}
switch( _opcode )
{
case audioMasterAutomate:
SHOW_CALLBACK( "amc: audioMasterAutomate\n" );
// index, value, returns 0
return 0;
case audioMasterVersion:
SHOW_CALLBACK( "amc: audioMasterVersion\n" );
return 2300;
case audioMasterCurrentId:
SHOW_CALLBACK( "amc: audioMasterCurrentId\n" );
// returns the unique id of a plug that's currently
// loading
return 0;
case audioMasterIdle:
SHOW_CALLBACK ("amc: audioMasterIdle\n" );
// call application idle routine (this will
// call effEditIdle for all open editors too)
#ifndef NATIVE_LINUX_VST
PostMessage( __MessageHwnd, WM_USER, static_cast<WPARAM>(GuiThreadMessage::GiveIdle), 0 );
#else
__plugin->sendX11Idle();
#endif
return 0;
case audioMasterPinConnected:
SHOW_CALLBACK( "amc: audioMasterPinConnected\n" );
// inquire if an input or output is beeing connected;
// index enumerates input or output counting from zero:
// value is 0 for input and != 0 otherwise. note: the
// return value is 0 for <true> such that older versions
// will always return true.
return 0;
case audioMasterGetTime:
{
SHOW_CALLBACK( "amc: audioMasterGetTime\n" );
// returns const VstTimeInfo* (or 0 if not supported)
// <value> should contain a mask indicating which
// fields are required (see valid masks above), as some
// items may require extensive conversions
const auto syncData = __plugin->getVstSyncData();
assert(syncData != nullptr);
memset( &_timeInfo, 0, sizeof( _timeInfo ) );
_timeInfo.samplePos = __plugin->m_currentSamplePos;
_timeInfo.sampleRate = syncData->m_sampleRate;
_timeInfo.flags = 0;
_timeInfo.tempo = syncData->m_bpm;
_timeInfo.timeSigNumerator = syncData->timeSigNumer;
_timeInfo.timeSigDenominator = syncData->timeSigDenom;
_timeInfo.flags |= kVstTempoValid;
_timeInfo.flags |= kVstTimeSigValid;
if (syncData->isCycle)
{
_timeInfo.cycleStartPos = syncData->cycleStart;
_timeInfo.cycleEndPos = syncData->cycleEnd;
_timeInfo.flags |= kVstCyclePosValid;
_timeInfo.flags |= kVstTransportCycleActive;
}
if (syncData->ppqPos != __plugin->m_in->m_Timestamp)
{
_timeInfo.ppqPos = syncData->ppqPos;
__plugin->m_in->lastppqPos = syncData->ppqPos;
__plugin->m_in->m_Timestamp = syncData->ppqPos;
}
else if (syncData->isPlaying)
{
__plugin->m_in->lastppqPos +=
syncData->m_bpm / 60.0
* syncData->m_bufferSize
/ syncData->m_sampleRate;
_timeInfo.ppqPos = __plugin->m_in->lastppqPos;
}
// _timeInfo.ppqPos = syncData->ppqPos;
_timeInfo.flags |= kVstPpqPosValid;
if (syncData->isPlaying)
{
_timeInfo.flags |= kVstTransportPlaying;
}
_timeInfo.barStartPos = ((int) (_timeInfo.ppqPos
/ (4 * syncData->timeSigNumer / (float) syncData->timeSigDenom)))
* (4 * syncData->timeSigNumer / (float) syncData->timeSigDenom);
_timeInfo.flags |= kVstBarsValid;
if ((_timeInfo.flags & (kVstTransportPlaying | kVstTransportCycleActive))
!= (__plugin->m_in->m_lastFlags & (kVstTransportPlaying | kVstTransportCycleActive))
|| syncData->m_playbackJumped)
{
_timeInfo.flags |= kVstTransportChanged;
}
__plugin->m_in->m_lastFlags = _timeInfo.flags;
return (intptr_t) &_timeInfo;
}
case audioMasterProcessEvents:
SHOW_CALLBACK( "amc: audioMasterProcessEvents\n" );
// VstEvents* in <ptr>
return 0;
case audioMasterIOChanged:
SHOW_CALLBACK( "amc: audioMasterIOChanged\n" );
// numInputs, numOutputs, and/or latency has changed
return __plugin->updateInOutCount();
#ifdef OLD_VST_SDK
case audioMasterWantMidi:
SHOW_CALLBACK( "amc: audioMasterWantMidi\n" );
// <value> is a filter which is currently ignored
return 1;
case audioMasterSetTime:
SHOW_CALLBACK( "amc: audioMasterSetTime\n" );
// VstTimenfo* in <ptr>, filter in <value>, not
// supported
return 0;
case audioMasterTempoAt:
SHOW_CALLBACK( "amc: audioMasterTempoAt\n" );
return __plugin->m_bpm * 10000;
case audioMasterGetNumAutomatableParameters:
SHOW_CALLBACK( "amc: audioMasterGetNumAutomatable"
"Parameters\n" );
return 5000;
case audioMasterGetParameterQuantization:
SHOW_CALLBACK( "amc: audioMasterGetParameter\n"
"Quantization\n" );
// returns the integer value for +1.0 representation,
// or 1 if full single float precision is maintained
// in automation. parameter index in <value> (-1: all,
// any)
return 1;
case audioMasterNeedIdle:
SHOW_CALLBACK( "amc: audioMasterNeedIdle\n" );
// plug needs idle calls (outside its editor window)
return 1;
case audioMasterGetPreviousPlug:
SHOW_CALLBACK( "amc: audioMasterGetPreviousPlug\n" );
// input pin in <value> (-1: first to come), returns
// cEffect*
return 0;
case audioMasterGetNextPlug:
SHOW_CALLBACK( "amc: audioMasterGetNextPlug\n" );
// output pin in <value> (-1: first to come), returns
// cEffect*
return 0;
case audioMasterWillReplaceOrAccumulate:
SHOW_CALLBACK( "amc: audioMasterWillReplaceOr"
"Accumulate\n" );
// returns: 0: not supported, 1: replace, 2: accumulate
return 1;
case audioMasterGetSpeakerArrangement:
SHOW_CALLBACK( "amc: audioMasterGetSpeaker"
"Arrangement\n" );
// (long)input in <value>, output in <ptr>
return 0;
case audioMasterSetOutputSampleRate:
SHOW_CALLBACK( "amc: audioMasterSetOutputSample"
"Rate\n" );
// for variable i/o, sample rate in <opt>
return 0;
case audioMasterSetIcon:
SHOW_CALLBACK( "amc: audioMasterSetIcon\n" );
// TODO
// void* in <ptr>, format not defined yet
return 0;
case audioMasterOpenWindow:
SHOW_CALLBACK( "amc: audioMasterOpenWindow\n" );
// TODO
// returns platform specific ptr
return 0;
case audioMasterCloseWindow:
SHOW_CALLBACK( "amc: audioMasterCloseWindow\n" );
// TODO
// close window, platform specific handle in <ptr>
return 0;
#endif // OLD_VST_SDK
case audioMasterSizeWindow:
{
SHOW_CALLBACK( "amc: audioMasterSizeWindow\n" );
if( __plugin->m_window == 0 )
{
return 0;
}
__plugin->m_windowWidth = _index;
__plugin->m_windowHeight = _value;
#ifndef NATIVE_LINUX_VST
HWND window = __plugin->m_window;
DWORD dwStyle = GetWindowLongPtr( window, GWL_STYLE );
RECT windowSize = { 0, 0, (int) _index, (int) _value };
AdjustWindowRect( &windowSize, dwStyle, false );
SetWindowPos( window, 0, 0, 0,
windowSize.right - windowSize.left,
windowSize.bottom - windowSize.top,
SWP_NOACTIVATE | SWP_NOMOVE |
SWP_NOOWNERZORDER | SWP_NOZORDER );
#else
XResizeWindow(__plugin->m_display, __plugin->m_window, (int) _index, (int) _value);
XFlush(__plugin->m_display);
#endif
__plugin->sendMessage(
message( IdVstPluginEditorGeometry ).
addInt( __plugin->m_windowWidth ).
addInt( __plugin->m_windowHeight ) );
return 1;
}
case audioMasterGetSampleRate:
SHOW_CALLBACK( "amc: audioMasterGetSampleRate\n" );
return __plugin->sampleRate();
case audioMasterGetBlockSize:
SHOW_CALLBACK( "amc: audioMasterGetBlockSize\n" );
return __plugin->bufferSize();
case audioMasterGetInputLatency:
SHOW_CALLBACK( "amc: audioMasterGetInputLatency\n" );
return __plugin->bufferSize();
case audioMasterGetOutputLatency:
SHOW_CALLBACK( "amc: audioMasterGetOutputLatency\n" );
return __plugin->bufferSize();
case audioMasterGetCurrentProcessLevel:
SHOW_CALLBACK( "amc: audioMasterGetCurrentProcess"
"Level\n" );
// returns: 0: not supported,
// 1: currently in user thread (gui)
// 2: currently in audio thread (where process is
// called)
// 3: currently in 'sequencer' thread (midi, timer etc)
// 4: currently offline processing and thus in user
// thread
// other: not defined, but probably pre-empting user
// thread.
return 0;
case audioMasterGetAutomationState:
SHOW_CALLBACK( "amc: audioMasterGetAutomationState\n" );
// returns 0: not supported, 1: off, 2:read, 3:write,
// 4:read/write offline
return 0;
case audioMasterOfflineStart:
SHOW_CALLBACK( "amc: audioMasterOfflineStart\n" );
return 0;
case audioMasterOfflineRead:
SHOW_CALLBACK( "amc: audioMasterOfflineRead\n" );
// ptr points to offline structure, see below.
// return 0: error, 1 ok
return 0;
case audioMasterOfflineWrite:
SHOW_CALLBACK( "amc: audioMasterOfflineWrite\n" );
// same as read
return 0;
case audioMasterOfflineGetCurrentPass:
SHOW_CALLBACK( "amc: audioMasterOfflineGetCurrent"
"Pass\n" );
return 0;
case audioMasterOfflineGetCurrentMetaPass:
SHOW_CALLBACK( "amc: audioMasterOfflineGetCurrentMeta"
"Pass\n");
return 0;
case audioMasterGetVendorString:
SHOW_CALLBACK( "amc: audioMasterGetVendorString\n" );
// fills <ptr> with a string identifying the vendor
// (max 64 char)
strcpy( (char *) _ptr, "Tobias Doerffel" );
return 1;
case audioMasterGetProductString:
SHOW_CALLBACK( "amc: audioMasterGetProductString\n" );
// fills <ptr> with a string with product name
// (max 64 char)
strcpy( (char *) _ptr,
"LMMS VST Support Layer (LVSL)" );
return 1;
case audioMasterGetVendorVersion:
SHOW_CALLBACK( "amc: audioMasterGetVendorVersion\n" );
// returns vendor-specific version
return 1000;
case audioMasterVendorSpecific:
SHOW_CALLBACK( "amc: audioMasterVendorSpecific\n" );
// no definition, vendor specific handling
return 0;
case audioMasterCanDo:
SHOW_CALLBACK( "amc: audioMasterCanDo\n" );
return !strcmp( (char *) _ptr, "sendVstEvents" ) ||
!strcmp( (char *) _ptr, "sendVstMidiEvent" ) ||
!strcmp( (char *) _ptr, "sendVstTimeInfo" ) ||
!strcmp( (char *) _ptr, "sizeWindow" ) ||
!strcmp( (char *) _ptr, "supplyIdle" );
case audioMasterGetLanguage:
SHOW_CALLBACK( "amc: audioMasterGetLanguage\n" );
return static_cast<std::intptr_t>(hlang);
case audioMasterGetDirectory:
SHOW_CALLBACK( "amc: audioMasterGetDirectory\n" );
// get plug directory, FSSpec on MAC, else char*
return 0;
case audioMasterUpdateDisplay:
SHOW_CALLBACK( "amc: audioMasterUpdateDisplay\n" );
// something has changed, update 'multi-fx' display
#ifndef NATIVE_LINUX_VST
PostMessage( __MessageHwnd, WM_USER, static_cast<WPARAM>(GuiThreadMessage::GiveIdle), 0 );
#else
__plugin->sendX11Idle();
#endif
return 0;
#if kVstVersion > 2
case audioMasterBeginEdit:
SHOW_CALLBACK( "amc: audioMasterBeginEdit\n" );
// begin of automation session (when mouse down),
// parameter index in <index>
return 0;
case audioMasterEndEdit:
SHOW_CALLBACK( "amc: audioMasterEndEdit\n" );
// end of automation session (when mouse up),
// parameter index in <index>
return 0;
case audioMasterOpenFileSelector:
SHOW_CALLBACK( "amc: audioMasterOpenFileSelector\n" );
// open a fileselector window with VstFileSelect*
// in <ptr>
return 0;
#endif
default:
SHOW_CALLBACK( "amd: not handled" );
break;
}
return 0;
}
void RemoteVstPlugin::idle()
{
if( isProcessing() )
{
setShouldGiveIdle( true );
return;
}
setProcessing( true );
if (!HEADLESS && m_window)
{
pluginDispatch( effEditIdle );
}
setShouldGiveIdle( false );
setProcessing( false );
// We might have received a message whilst idling
processUIThreadMessages();
}
void RemoteVstPlugin::processUIThreadMessages()
{
setProcessing( true );
#ifdef NATIVE_LINUX_VST
pthread_mutex_lock(&message_mutex);
#endif
size_t size = m_messageList.size();
#ifdef NATIVE_LINUX_VST
pthread_mutex_unlock(&message_mutex);
#endif
while( size )
{
#ifdef NATIVE_LINUX_VST
pthread_mutex_lock(&message_mutex);
#endif
message m = m_messageList.front();
#ifdef NATIVE_LINUX_VST
pthread_mutex_unlock(&message_mutex);
#endif
processMessage( m );
#ifdef NATIVE_LINUX_VST
pthread_mutex_lock(&message_mutex);
#endif
m_messageList.pop();
#ifdef NATIVE_LINUX_VST
pthread_mutex_unlock(&message_mutex);
#endif
if( shouldGiveIdle() )
{
if (!HEADLESS && m_window)
{
pluginDispatch( effEditIdle );
}
setShouldGiveIdle( false );
}
#ifdef NATIVE_LINUX_VST
pthread_mutex_lock(&message_mutex);
#endif
size = m_messageList.size();
#ifdef NATIVE_LINUX_VST
pthread_mutex_unlock(&message_mutex);
#endif
}
setProcessing( false );
}
#ifdef NATIVE_LINUX_VST
void RemoteVstPlugin::sendX11Idle()
{
queueMessage(message( IdIdle ));
}
#endif
#ifndef NATIVE_LINUX_VST
DWORD WINAPI RemoteVstPlugin::processingThread( LPVOID _param )
#else
void * RemoteVstPlugin::processingThread(void * _param)
#endif
{
#ifndef NATIVE_LINUX_VST
__processingThreadId = GetCurrentThreadId();
#else
__processingThreadId = pthread_self();
#endif
RemoteVstPlugin * _this = static_cast<RemoteVstPlugin *>( _param );
RemotePluginClient::message m;
while( ( m = _this->receiveMessage() ).id != IdQuit )
{
if( m.id == IdStartProcessing
|| m.id == IdMidiEvent
|| m.id == IdVstSetParameter
|| m.id == IdVstSetTempo)
{
_this->processMessage( m );
}
else if( m.id == IdChangeSharedMemoryKey )
{
_this->processMessage( m );
_this->setShmIsValid( true );
}
else
{
#ifndef NATIVE_LINUX_VST
PostMessage( __MessageHwnd,
WM_USER,
static_cast<WPARAM>(GuiThreadMessage::ProcessPluginMessage),
(LPARAM) new message( m ) );
#else
_this->queueMessage( m );
#endif
}
}
// notify GUI thread about shutdown
#ifndef NATIVE_LINUX_VST
PostMessage( __MessageHwnd, WM_USER, static_cast<WPARAM>(GuiThreadMessage::ClosePlugin), 0 );
return 0;
#else
if (m.id == IdQuit)
{
_this->queueMessage( m );
}
return nullptr;
#endif
}
bool RemoteVstPlugin::setupMessageWindow()
{
#ifndef NATIVE_LINUX_VST
HMODULE hInst = GetModuleHandle( nullptr );
if( hInst == nullptr )
{
__plugin->debugMessage( "setupMessageWindow(): can't get "
"module handle\n" );
return false;
}
__MessageHwnd = CreateWindowEx( 0, "LVSL", "dummy",
0, 0, 0, 0, 0, nullptr, nullptr,
hInst, nullptr );
// install GUI update timer
SetTimer( __MessageHwnd, 1000, 50, nullptr );
#endif
return true;
}
#ifndef NATIVE_LINUX_VST
DWORD WINAPI RemoteVstPlugin::guiEventLoop()
{
MSG msg;
while( GetMessage( &msg, nullptr, 0, 0 ) > 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
return 0;
}
#else
void RemoteVstPlugin::guiEventLoop()
{
struct timespec tim, tim2;
tim.tv_sec = 0;
tim.tv_nsec = 5000000;
XEvent e;
while(true)
{
//if (XQLength(m_display) > 0)
if (m_display && XPending(m_display) > 0)
{
XNextEvent(m_display, &e);
if (e.type == ClientMessage && static_cast<Atom>(e.xclient.data.l[0]) == m_wmDeleteMessage)
{
hideEditor();
}
}
// needed by ZynAddSubFX UI
if (__plugin->isInitialized())
{
__plugin->idle();
}
if(__plugin->isInitialized() && !__plugin->isProcessing() )
{
__plugin->processUIThreadMessages();
}
nanosleep(&tim, &tim2);
if (m_shouldQuit)
{
__plugin->hideEditor();
break;
}
}
}
#endif // NATIVE_LINUX_VST
#ifndef NATIVE_LINUX_VST
LRESULT CALLBACK RemoteVstPlugin::wndProc( HWND hwnd, UINT uMsg,
WPARAM wParam, LPARAM lParam )
{
if( uMsg == WM_TIMER && __plugin->isInitialized() )
{
// give plugin some idle-time for GUI-update
__plugin->idle();
return 0;
}
else if( uMsg == WM_USER )
{
switch( static_cast<GuiThreadMessage>(wParam) )
{
case GuiThreadMessage::ProcessPluginMessage:
{
message * m = (message *) lParam;
__plugin->queueMessage( *m );
delete m;
if( !__plugin->isProcessing() )
{
__plugin->processUIThreadMessages();
}
return 0;
}
case GuiThreadMessage::GiveIdle:
__plugin->idle();
return 0;
case GuiThreadMessage::ClosePlugin:
PostQuitMessage(0);
return 0;
default:
break;
}
}
else if( uMsg == WM_SYSCOMMAND && (wParam & 0xfff0) == SC_CLOSE )
{
__plugin->hideEditor();
return 0;
}
return DefWindowProc( hwnd, uMsg, wParam, lParam );
}
#endif // NATIVE_LINUX_VST
} // namespace lmms
int main( int _argc, char * * _argv )
{
using lmms::RemoteVstPlugin;
#ifdef SYNC_WITH_SHM_FIFO
if( _argc < 4 )
#else
if( _argc < 3 )
#endif
{
fprintf( stderr, "not enough arguments\n" );
return -1;
}
#ifndef LMMS_BUILD_WIN32
const auto pollParentThread = lmms::PollParentThread{};
#endif
#ifndef NATIVE_LINUX_VST
OleInitialize(nullptr);
#else
XInitThreads();
#endif
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
// try to set realtime-priority
struct sched_param sparam;
sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
sched_get_priority_min( SCHED_FIFO ) ) / 2;
sched_setscheduler( 0, SCHED_FIFO, &sparam );
#endif
#endif // LMMS_BUILD_LINUX
#ifdef LMMS_BUILD_WIN32
if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
{
printf( "Notice: could not set high priority.\n" );
}
#endif
#ifndef NATIVE_LINUX_VST
HMODULE hInst = GetModuleHandle( nullptr );
if( hInst == nullptr )
{
return -1;
}
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = RemoteVstPlugin::wndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInst;
wc.hIcon = LoadIcon( nullptr, IDI_APPLICATION );
wc.hCursor = LoadCursor( nullptr, IDC_ARROW );
wc.hbrBackground = nullptr;
wc.lpszMenuName = nullptr;
wc.lpszClassName = "LVSL";
if( !RegisterClass( &wc ) )
{
return -1;
}
#endif
{
#ifdef SYNC_WITH_SHM_FIFO
int embedMethodIndex = 3;
#else
int embedMethodIndex = 2;
#endif
std::string embedMethod = _argv[embedMethodIndex];
if ( embedMethod == "none" )
{
std::cerr << "Starting detached." << std::endl;
EMBED = EMBED_X11 = EMBED_WIN32 = HEADLESS = false;
}
else if ( embedMethod == "win32" )
{
std::cerr << "Starting using Win32-native embedding." << std::endl;
EMBED = EMBED_WIN32 = true; EMBED_X11 = HEADLESS = false;
}
else if ( embedMethod == "qt" )
{
std::cerr << "Starting using Qt-native embedding." << std::endl;
EMBED = true; EMBED_X11 = EMBED_WIN32 = HEADLESS = false;
}
else if ( embedMethod == "xembed" )
{
std::cerr << "Starting using X11Embed protocol." << std::endl;
EMBED = EMBED_X11 = true; EMBED_WIN32 = HEADLESS = false;
}
else if ( embedMethod == "headless" )
{
std::cerr << "Starting without UI." << std::endl;
HEADLESS = true; EMBED = EMBED_X11 = EMBED_WIN32 = false;
}
else
{
std::cerr << "Unknown embed method " << embedMethod << ". Starting detached instead." << std::endl;
EMBED = EMBED_X11 = EMBED_WIN32 = HEADLESS = false;
}
}
#ifdef NATIVE_LINUX_VST
if (EMBED)
{
std::cerr << "Native linux VST works only without embedding." << std::endl;
}
#endif
// constructor automatically will process messages until it receives
// a IdVstLoadPlugin message and processes it
#ifdef SYNC_WITH_SHM_FIFO
__plugin = new RemoteVstPlugin( _argv[1], _argv[2] );
#else
__plugin = new RemoteVstPlugin( _argv[1] );
#endif
if( __plugin->isInitialized() )
{
if( RemoteVstPlugin::setupMessageWindow() == false )
{
return -1;
}
#ifndef NATIVE_LINUX_VST
if( CreateThread( nullptr, 0, RemoteVstPlugin::processingThread,
__plugin, 0, nullptr ) == nullptr )
#else
int err = 0;
err = pthread_create(&__processingThreadId, nullptr, &RemoteVstPlugin::processingThread, __plugin);
if (err != 0)
#endif
{
__plugin->debugMessage( "could not create "
"processingThread\n" );
return -1;
}
__plugin->guiEventLoop();
#ifdef NATIVE_LINUX_VST
pthread_join(__processingThreadId, nullptr);
#endif
}
delete __plugin;
#ifndef NATIVE_LINUX_VST
OleUninitialize();
#endif
return 0;
}
| 57,925
|
C++
|
.cpp
| 2,062
| 25.192047
| 122
| 0.700677
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,657
|
VstPlugin.cpp
|
LMMS_lmms/plugins/VstBase/VstPlugin.cpp
|
/*
* VstPlugin.cpp - implementation of VstPlugin class
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "VstPlugin.h"
#include "communication.h"
#include <QtEndian>
#include <QDebug>
#include <QDir>
#include <QDomElement>
#include <QFileInfo>
#include <QLocale>
#include <QTemporaryFile>
#ifdef LMMS_BUILD_LINUX
# include <QX11Info>
# include <X11EmbedContainer.h>
#endif
#include <QWindow>
#ifdef LMMS_BUILD_WIN32
# include <windows.h>
# include <QLayout>
#endif
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "GuiApplication.h"
#include "LocaleHelper.h"
#include "MainWindow.h"
#include "PathUtil.h"
#include "Song.h"
#include "FileDialog.h"
#ifdef LMMS_BUILD_LINUX
# include <X11/Xlib.h>
#endif
namespace PE
{
// Utilities for reading PE file machine type
// See specification at https://msdn.microsoft.com/library/windows/desktop/ms680547(v=vs.85).aspx
// Work around name conflict
#ifdef i386
# undef i386
#endif
enum class MachineType : uint16_t
{
unknown = 0x0,
amd64 = 0x8664,
i386 = 0x14c,
};
class FileInfo
{
public:
FileInfo(QString filePath)
: m_file(filePath)
{
m_file.open(QFile::ReadOnly);
m_map = m_file.map(0, m_file.size());
if (m_map == nullptr) {
throw std::runtime_error("Cannot map file");
}
}
~FileInfo()
{
m_file.unmap(m_map);
}
MachineType machineType()
{
int32_t peOffset = qFromLittleEndian(* reinterpret_cast<int32_t*>(m_map + 0x3C));
uchar* peSignature = m_map + peOffset;
if (memcmp(peSignature, "PE\0\0", 4)) {
throw std::runtime_error("Invalid PE file");
}
uchar * coffHeader = peSignature + 4;
uint16_t machineType = qFromLittleEndian(* reinterpret_cast<uint16_t*>(coffHeader));
return static_cast<MachineType>(machineType);
}
private:
QFile m_file;
uchar* m_map;
};
} // namespace PE
namespace lmms
{
enum class ExecutableType
{
Unknown, Win32, Win64, Linux64,
};
VstPlugin::VstPlugin( const QString & _plugin ) :
m_plugin( PathUtil::toAbsolute(_plugin) ),
m_pluginWindowID( 0 ),
m_embedMethod( (gui::getGUI() != nullptr)
? ConfigManager::inst()->vstEmbedMethod()
: "headless" ),
m_version( 0 ),
m_currentProgram()
{
setSplittedChannels( true );
auto pluginType = ExecutableType::Unknown;
#ifdef LMMS_BUILD_LINUX
QFileInfo fi(m_plugin);
if (fi.suffix() == "so")
{
pluginType = ExecutableType::Linux64;
}
else
#endif
{
try {
PE::FileInfo peInfo(m_plugin);
switch (peInfo.machineType())
{
case PE::MachineType::amd64:
pluginType = ExecutableType::Win64;
break;
case PE::MachineType::i386:
pluginType = ExecutableType::Win32;
break;
default:
qWarning() << "Unknown PE machine type"
<< QString::number(static_cast<uint16_t>(peInfo.machineType()), 16);
break;
}
} catch (std::runtime_error& e) {
qCritical() << "Error while determining PE file's machine type: " << e.what();
}
}
switch(pluginType)
{
case ExecutableType::Win64:
tryLoad( REMOTE_VST_PLUGIN_FILEPATH_64 ); // Default: RemoteVstPlugin64
break;
case ExecutableType::Win32:
tryLoad( REMOTE_VST_PLUGIN_FILEPATH_32 ); // Default: 32/RemoteVstPlugin32
break;
#ifdef LMMS_BUILD_LINUX
case ExecutableType::Linux64:
tryLoad( NATIVE_LINUX_REMOTE_VST_PLUGIN_FILEPATH_64 ); // Default: NativeLinuxRemoteVstPlugin32
break;
#endif
default:
m_failed = true;
return;
}
setTempo( Engine::getSong()->getTempo() );
connect( Engine::getSong(), SIGNAL( tempoChanged( lmms::bpm_t ) ),
this, SLOT( setTempo( lmms::bpm_t ) ), Qt::DirectConnection );
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ),
this, SLOT( updateSampleRate() ) );
// update once per second
m_idleTimer.start( 1000 );
connect( &m_idleTimer, SIGNAL( timeout() ),
this, SLOT( idleUpdate() ) );
}
VstPlugin::~VstPlugin()
{
delete m_pluginWidget;
}
void VstPlugin::tryLoad( const QString &remoteVstPluginExecutable )
{
init( remoteVstPluginExecutable, false, {m_embedMethod} );
waitForHostInfoGotten();
if( failed() )
{
return;
}
lock();
VstHostLanguage hlang = VstHostLanguage::English;
switch( QLocale::system().language() )
{
case QLocale::French: hlang = VstHostLanguage::French; break;
case QLocale::German: hlang = VstHostLanguage::German; break;
case QLocale::Italian: hlang = VstHostLanguage::Italian; break;
case QLocale::Japanese: hlang = VstHostLanguage::Japanese; break;
case QLocale::Korean: hlang = VstHostLanguage::Korean; break;
case QLocale::Spanish: hlang = VstHostLanguage::Spanish; break;
default: break;
}
sendMessage( message( IdVstSetLanguage ).addInt( static_cast<int>(hlang) ) );
sendMessage( message( IdVstLoadPlugin ).addString( QSTR_TO_STDSTR( m_plugin ) ) );
waitForInitDone();
unlock();
}
void VstPlugin::loadSettings( const QDomElement & _this )
{
if( _this.hasAttribute( "program" ) )
{
setProgram( _this.attribute( "program" ).toInt() );
}
const int num_params = _this.attribute( "numparams" ).toInt();
// if it exists try to load settings chunk
if( _this.hasAttribute( "chunk" ) )
{
loadChunk( QByteArray::fromBase64(
_this.attribute( "chunk" ).toUtf8() ) );
}
else if( num_params > 0 )
{
// no chunk, restore individual parameters
QMap<QString, QString> dump;
for( int i = 0; i < num_params; ++i )
{
const QString key = "param" +
QString::number( i );
dump[key] = _this.attribute( key );
}
setParameterDump( dump );
}
}
void VstPlugin::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
if ( m_embedMethod != "none" )
{
if( pluginWidget() != nullptr )
{
_this.setAttribute( "guivisible", pluginWidget()->isVisible() );
}
}
else
{
int visible = isUIVisible();
if ( visible != -1 )
{
_this.setAttribute( "guivisible", visible );
}
}
// try to save all settings in a chunk
QByteArray chunk = saveChunk();
if( !chunk.isEmpty() )
{
_this.setAttribute( "chunk", QString( chunk.toBase64() ) );
}
else
{
// plugin doesn't seem to support chunks, therefore save
// individual parameters
const QMap<QString, QString> & dump = parameterDump();
_this.setAttribute( "numparams", dump.size() );
for( QMap<QString, QString>::const_iterator it = dump.begin();
it != dump.end(); ++it )
{
_this.setAttribute( it.key(), it.value() );
}
}
_this.setAttribute( "program", currentProgram() );
}
void VstPlugin::toggleUI()
{
if ( m_embedMethod == "none" )
{
RemotePlugin::toggleUI();
}
else if (pluginWidget())
{
toggleEditorVisibility();
}
}
void VstPlugin::setTempo( bpm_t _bpm )
{
lock();
sendMessage( message( IdVstSetTempo ).addInt( _bpm ) );
unlock();
}
void VstPlugin::updateSampleRate()
{
lock();
sendMessage( message( IdSampleRateInformation ).
addInt( Engine::audioEngine()->outputSampleRate() ) );
waitForMessage( IdInformationUpdated, true );
unlock();
}
int VstPlugin::currentProgram()
{
lock();
sendMessage( message( IdVstCurrentProgram ) );
waitForMessage( IdVstCurrentProgram, true );
unlock();
return m_currentProgram;
}
const QMap<QString, QString> & VstPlugin::parameterDump()
{
lock();
sendMessage( IdVstGetParameterDump );
waitForMessage( IdVstParameterDump, true );
unlock();
return m_parameterDump;
}
void VstPlugin::setParameterDump( const QMap<QString, QString> & _pdump )
{
message m( IdVstSetParameterDump );
m.addInt( _pdump.size() );
for (const auto& str : _pdump)
{
const VstParameterDumpItem item =
{
str.section(':', 0, 0).toInt(), "", LocaleHelper::toFloat(str.section(':', 2, -1))
};
m.addInt( item.index );
m.addString( item.shortLabel );
m.addFloat( item.value );
}
lock();
sendMessage( m );
unlock();
}
QWidget *VstPlugin::pluginWidget()
{
return m_pluginWidget;
}
bool VstPlugin::processMessage( const message & _m )
{
switch( _m.id )
{
case IdVstPluginWindowID:
m_pluginWindowID = _m.getInt();
if( m_embedMethod == "none"
&& ConfigManager::inst()->value(
"ui", "vstalwaysontop" ).toInt() )
{
#ifdef LMMS_BUILD_WIN32
// We're changing the owner, not the parent,
// so this is legal despite MSDN's warning
SetWindowLongPtr( (HWND)(intptr_t) m_pluginWindowID,
GWLP_HWNDPARENT,
(LONG_PTR) gui::getGUI()->mainWindow()->winId() );
#endif
#ifdef LMMS_BUILD_LINUX
XSetTransientForHint( QX11Info::display(),
m_pluginWindowID,
gui::getGUI()->mainWindow()->winId() );
#endif
}
break;
case IdVstPluginEditorGeometry:
m_pluginGeometry = QSize( _m.getInt( 0 ),
_m.getInt( 1 ) );
break;
case IdVstPluginName:
m_name = _m.getQString();
break;
case IdVstPluginVersion:
m_version = _m.getInt();
break;
case IdVstPluginVendorString:
m_vendorString = _m.getQString();
break;
case IdVstPluginProductString:
m_productString = _m.getQString();
break;
case IdVstCurrentProgram:
m_currentProgram = _m.getInt();
break;
case IdVstCurrentProgramName:
m_currentProgramName = _m.getQString();
break;
case IdVstProgramNames:
m_allProgramNames = _m.getQString();
break;
case IdVstParameterLabels:
m_allParameterLabels = _m.getQString();
break;
case IdVstParameterDisplays:
m_allParameterDisplays = _m.getQString();
break;
case IdVstPluginUniqueID:
// TODO: display graphically in case of failure
printf("unique ID: %s\n", _m.getString().c_str() );
break;
case IdVstParameterDump:
{
m_parameterDump.clear();
const int num_params = _m.getInt();
int p = 0;
for( int i = 0; i < num_params; ++i )
{
VstParameterDumpItem item;
item.index = _m.getInt( ++p );
item.shortLabel = _m.getString( ++p );
item.value = _m.getFloat( ++p );
m_parameterDump["param" + QString::number( item.index )] =
QString::number( item.index ) + ":" +
/*uncomented*/ /*QString( item.shortLabel )*/ QString::fromStdString(item.shortLabel) + ":" +
QString::number( item.value );
}
break;
}
default:
return RemotePlugin::processMessage( _m );
}
return true;
}
QWidget *VstPlugin::editor()
{
return m_pluginWidget;
}
void VstPlugin::openPreset()
{
gui::FileDialog ofd(nullptr, tr("Open Preset"), "", tr("VST Plugin Preset (*.fxp *.fxb)"));
ofd.setFileMode(gui::FileDialog::ExistingFiles);
if (ofd.exec() == QDialog::Accepted && !ofd.selectedFiles().isEmpty())
{
lock();
sendMessage(message(IdLoadPresetFile).addString(QSTR_TO_STDSTR(
QDir::toNativeSeparators(ofd.selectedFiles()[0]))));
waitForMessage(IdLoadPresetFile, true);
unlock();
}
}
void VstPlugin::setProgram( int index )
{
lock();
sendMessage( message( IdVstSetProgram ).addInt( index ) );
waitForMessage( IdVstSetProgram, true );
unlock();
}
void VstPlugin::rotateProgram( int offset )
{
lock();
sendMessage( message( IdVstRotateProgram ).addInt( offset ) );
waitForMessage( IdVstRotateProgram, true );
unlock();
}
void VstPlugin::loadProgramNames()
{
lock();
sendMessage( message( IdVstProgramNames ) );
waitForMessage( IdVstProgramNames, true );
unlock();
}
void VstPlugin::loadParameterLabels()
{
lock();
sendMessage( message( IdVstParameterLabels ) );
waitForMessage( IdVstParameterLabels, true );
unlock();
}
void VstPlugin::loadParameterDisplays()
{
lock();
sendMessage( message( IdVstParameterDisplays ) );
waitForMessage( IdVstParameterDisplays, true );
unlock();
}
void VstPlugin::savePreset()
{
QString presName = currentProgramName().isEmpty() ? tr(": default") : currentProgramName();
presName.replace("\"", "'"); // QFileDialog unable to handle double quotes properly
gui::FileDialog sfd(nullptr, tr("Save Preset"), presName.section(": ", 1, 1) + tr(".fxp"),
tr("VST Plugin Preset (*.fxp *.fxb)"));
if (p_name != "") // remember last directory
{
sfd.setDirectory(QFileInfo(p_name).absolutePath());
}
sfd.setAcceptMode(gui::FileDialog::AcceptSave);
sfd.setFileMode(gui::FileDialog::AnyFile);
if (sfd.exec() == QDialog::Accepted && !sfd.selectedFiles().isEmpty() && sfd.selectedFiles()[0] != "")
{
QString fns = sfd.selectedFiles()[0];
p_name = fns;
if ((fns.toUpper().indexOf(tr(".FXP")) == -1) && (fns.toUpper().indexOf(tr(".FXB")) == -1))
{
fns = fns + tr(".fxb");
}
else
{
fns = fns.left(fns.length() - 4) + (fns.right(4)).toLower();
}
lock();
sendMessage(message(IdSavePresetFile).addString(QSTR_TO_STDSTR(QDir::toNativeSeparators(fns))));
waitForMessage(IdSavePresetFile, true);
unlock();
}
}
void VstPlugin::setParam( int i, float f )
{
lock();
sendMessage( message( IdVstSetParameter ).addInt( i ).addFloat( f ) );
//waitForMessage( IdVstSetParameter, true );
unlock();
}
void VstPlugin::idleUpdate()
{
lock();
sendMessage( message( IdVstIdleUpdate ) );
unlock();
}
void VstPlugin::showUI()
{
if ( m_embedMethod == "none" )
{
RemotePlugin::showUI();
}
else if ( m_embedMethod != "headless" )
{
if (! editor()) {
qWarning() << "VstPlugin::showUI called before VstPlugin::createUI";
}
toggleEditorVisibility( true );
}
}
void VstPlugin::hideUI()
{
if ( m_embedMethod == "none" )
{
RemotePlugin::hideUI();
}
else if ( pluginWidget() != nullptr )
{
toggleEditorVisibility( false );
}
}
// X11Embed only
void VstPlugin::handleClientEmbed()
{
lock();
sendMessage( IdShowUI );
unlock();
}
void VstPlugin::loadChunk( const QByteArray & _chunk )
{
QTemporaryFile tf;
if( tf.open() )
{
tf.write( _chunk );
tf.flush();
lock();
sendMessage( message( IdLoadSettingsFromFile ).
addString(
QSTR_TO_STDSTR(
QDir::toNativeSeparators( tf.fileName() ) ) ).
addInt( _chunk.size() ) );
waitForMessage( IdLoadSettingsFromFile, true );
unlock();
}
}
QByteArray VstPlugin::saveChunk()
{
QByteArray a;
QTemporaryFile tf;
if( tf.open() )
{
lock();
sendMessage( message( IdSaveSettingsToFile ).
addString(
QSTR_TO_STDSTR(
QDir::toNativeSeparators( tf.fileName() ) ) ) );
waitForMessage( IdSaveSettingsToFile, true );
unlock();
a = tf.readAll();
}
return a;
}
void VstPlugin::toggleEditorVisibility( int visible )
{
QWidget* w = editor();
if ( ! w ) {
return;
}
if ( visible < 0 ) {
visible = ! w->isVisible();
}
w->setVisible( visible );
}
void VstPlugin::createUI( QWidget * parent )
{
if ( m_pluginWidget ) {
qWarning() << "VstPlugin::createUI called twice";
m_pluginWidget->setParent( parent );
return;
}
if( m_pluginWindowID == 0 )
{
return;
}
QWidget* container = nullptr;
if (m_embedMethod == "qt" )
{
QWindow* vw = QWindow::fromWinId(m_pluginWindowID);
container = QWidget::createWindowContainer(vw, parent );
container->installEventFilter(this);
} else
#ifdef LMMS_BUILD_WIN32
if (m_embedMethod == "win32" )
{
QWidget * helper = new QWidget;
QHBoxLayout * l = new QHBoxLayout( helper );
QWidget * target = new QWidget( helper );
l->setSpacing( 0 );
l->setContentsMargins(0, 0, 0, 0);
l->addWidget( target );
// we've to call that for making sure, Qt created the windows
helper->winId();
HWND targetHandle = (HWND)target->winId();
HWND pluginHandle = (HWND)(intptr_t)m_pluginWindowID;
DWORD style = GetWindowLong(pluginHandle, GWL_STYLE);
style = style & ~(WS_POPUP);
style = style | WS_CHILD;
SetWindowLong(pluginHandle, GWL_STYLE, style);
SetParent(pluginHandle, targetHandle);
DWORD threadId = GetWindowThreadProcessId(pluginHandle, nullptr);
DWORD currentThreadId = GetCurrentThreadId();
AttachThreadInput(currentThreadId, threadId, true);
container = helper;
RemotePlugin::showUI();
} else
#endif
#ifdef LMMS_BUILD_LINUX
if (m_embedMethod == "xembed" )
{
if (parent)
{
parent->setAttribute(Qt::WA_NativeWindow);
}
auto embedContainer = new QX11EmbedContainer(parent);
connect(embedContainer, SIGNAL(clientIsEmbedded()), this, SLOT(handleClientEmbed()));
embedContainer->embedClient( m_pluginWindowID );
container = embedContainer;
} else
#endif
{
qCritical() << "Unknown embed method" << m_embedMethod;
return;
}
container->setFixedSize( m_pluginGeometry );
container->setWindowTitle( name() );
m_pluginWidget = container;
}
bool VstPlugin::eventFilter(QObject *obj, QEvent *event)
{
if (embedMethod() == "qt" && obj == m_pluginWidget)
{
if (event->type() == QEvent::Show) {
RemotePlugin::showUI();
}
qDebug() << obj << event;
}
return false;
}
QString VstPlugin::embedMethod() const
{
return m_embedMethod;
}
} // namespace lmms
| 17,219
|
C++
|
.cpp
| 659
| 23.531108
| 103
| 0.705689
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,658
|
Xpressive.cpp
|
LMMS_lmms/plugins/Xpressive/Xpressive.cpp
|
/*
* Xpressive.cpp - Instrument which uses a mathematical formula parser
*
* Copyright (c) 2016-2017 Orr Dvori
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Xpressive.h"
#include <QDomElement>
#include <QPlainTextEdit>
#include "AudioEngine.h"
#include "Engine.h"
#include "Graph.h"
#include "GuiApplication.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "MainWindow.h"
#include "NotePlayHandle.h"
#include "PixmapButton.h"
#include "Song.h"
#include "base64.h"
#include "lmms_constants.h"
#include "embed.h"
#include "ExprSynth.h"
#include "plugin_export.h"
namespace lmms
{
extern "C" {
Plugin::Descriptor PLUGIN_EXPORT xpressive_plugin_descriptor = { LMMS_STRINGIFY(
PLUGIN_NAME), "Xpressive", QT_TRANSLATE_NOOP("PluginBrowser",
"Mathematical expression parser"), "Orr Dvori", 0x0100,
Plugin::Type::Instrument, new PluginPixmapLoader("logo"), nullptr, nullptr };
}
/*
* nice test:
O1 -> trianglew(2t*f)*(0.5+0.5sinew(12*A1*t+0.5))+sinew(t*f)*(0.5+0.5sinew(12*A1*t))
O2 -> trianglew(2t*f)*(0.5+0.5sinew(12*A1*t))+sinew(t*f)*(0.5+0.5sinew(12*A1*t+0.5))
*/
/***********************************************************************
*
* class Xpressive
*
* lmms - plugin
*
***********************************************************************/
#define GRAPH_LENGTH 4096
Xpressive::Xpressive(InstrumentTrack* instrument_track) :
Instrument(instrument_track, &xpressive_plugin_descriptor),
m_graphO1(-1.0f, 1.0f, 360, this),
m_graphO2(-1.0f, 1.0f, 360, this),
m_graphW1(-1.0f, 1.0f, GRAPH_LENGTH, this),
m_graphW2(-1.0f, 1.0f, GRAPH_LENGTH, this),
m_graphW3(-1.0f, 1.0f, GRAPH_LENGTH, this),
m_rawgraphW1(-1.0f, 1.0f, GRAPH_LENGTH, this),
m_rawgraphW2(-1.0f, 1.0f, GRAPH_LENGTH, this),
m_rawgraphW3(-1.0f, 1.0f, GRAPH_LENGTH, this),
m_selectedGraph(0, 0, 6, this, tr("Selected graph")),
m_parameterA1(1, -1.0f, 1.0f, 0.01f, this, tr("A1")),
m_parameterA2(1, -1.0f, 1.0f, 0.01f, this, tr("A2")),
m_parameterA3(1, -1.0f, 1.0f, 0.01f, this, tr("A3")),
m_smoothW1(0, 0.0f, 70.0f, 1.0f, this, tr("W1 smoothing")),
m_smoothW2(0, 0.0f, 70.0f, 1.0f, this, tr("W2 smoothing")),
m_smoothW3(0, 0.0f, 70.0f, 1.0f, this, tr("W3 smoothing")),
m_interpolateW1(false, this),
m_interpolateW2(false, this),
m_interpolateW3(false, this),
m_panning1( 1, -1.0f, 1.0f, 0.01f, this, tr("Panning 1")),
m_panning2(-1, -1.0f, 1.0f, 0.01f, this, tr("Panning 2")),
m_relTransition(50.0f, 0.0f, 500.0f, 1.0f, this, tr("Rel trans")),
m_W1(GRAPH_LENGTH),
m_W2(GRAPH_LENGTH),
m_W3(GRAPH_LENGTH),
m_exprValid(false, this)
{
m_outputExpression[0]="sinew(integrate(f*(1+0.05sinew(12t))))*(2^(-(1.1+A2)*t)*(0.4+0.1(1+A3)+0.4sinew((2.5+2A1)t))^2)";
m_outputExpression[1]="expw(integrate(f*atan(500t)*2/pi))*0.5+0.12";
}
void Xpressive::saveSettings(QDomDocument & _doc, QDomElement & _this) {
// Save plugin version
_this.setAttribute("version", "0.1");
_this.setAttribute("O1", QString(m_outputExpression[0]));
_this.setAttribute("O2", QString(m_outputExpression[1]));
_this.setAttribute("W1", QString(m_wavesExpression[0]));
// Save sample shape base64-encoded
QString sampleString;
base64::encode( (const char*)m_rawgraphW1.samples(),
m_rawgraphW1.length() * sizeof(float), sampleString );
_this.setAttribute( "W1sample", sampleString );
_this.setAttribute("W2", QString(m_wavesExpression[1]));
base64::encode( (const char*)m_rawgraphW2.samples(),
m_rawgraphW2.length() * sizeof(float), sampleString );
_this.setAttribute( "W2sample", sampleString );
_this.setAttribute("W3", QString(m_wavesExpression[2]));
base64::encode( (const char*)m_rawgraphW3.samples(),
m_rawgraphW3.length() * sizeof(float), sampleString );
_this.setAttribute( "W3sample", sampleString );
m_smoothW1.saveSettings(_doc,_this,"smoothW1");
m_smoothW2.saveSettings(_doc,_this,"smoothW2");
m_smoothW3.saveSettings(_doc,_this,"smoothW3");
m_interpolateW1.saveSettings(_doc,_this,"interpolateW1");
m_interpolateW2.saveSettings(_doc,_this,"interpolateW2");
m_interpolateW3.saveSettings(_doc,_this,"interpolateW3");
m_parameterA1.saveSettings(_doc,_this,"A1");
m_parameterA2.saveSettings(_doc,_this,"A2");
m_parameterA3.saveSettings(_doc,_this,"A3");
m_panning1.saveSettings(_doc,_this,"PAN1");
m_panning2.saveSettings(_doc,_this,"PAN2");
m_relTransition.saveSettings(_doc,_this,"RELTRANS");
}
void Xpressive::loadSettings(const QDomElement & _this) {
m_outputExpression[0]=_this.attribute( "O1").toLatin1();
m_outputExpression[1]=_this.attribute( "O2").toLatin1();
m_wavesExpression[0]=_this.attribute( "W1").toLatin1();
m_wavesExpression[1]=_this.attribute( "W2").toLatin1();
m_wavesExpression[2]=_this.attribute( "W3").toLatin1();
m_smoothW1.loadSettings(_this,"smoothW1");
m_smoothW2.loadSettings(_this,"smoothW2");
m_smoothW3.loadSettings(_this,"smoothW3");
m_interpolateW1.loadSettings(_this,"interpolateW1");
m_interpolateW2.loadSettings(_this,"interpolateW2");
m_interpolateW3.loadSettings(_this,"interpolateW3");
m_parameterA1.loadSettings(_this,"A1");
m_parameterA2.loadSettings(_this,"A2");
m_parameterA3.loadSettings(_this,"A3");
m_panning1.loadSettings(_this,"PAN1");
m_panning2.loadSettings(_this,"PAN2");
m_relTransition.loadSettings(_this,"RELTRANS");
int size = 0;
char * dst = 0;
base64::decode( _this.attribute( "W1sample"), &dst, &size );
m_rawgraphW1.setSamples( (float*) dst );
delete[] dst;
base64::decode( _this.attribute( "W2sample"), &dst, &size );
m_rawgraphW2.setSamples( (float*) dst );
delete[] dst;
base64::decode( _this.attribute( "W3sample"), &dst, &size );
m_rawgraphW3.setSamples( (float*) dst );
delete[] dst;
smooth(m_smoothW1.value(),&m_rawgraphW1,&m_graphW1);
smooth(m_smoothW2.value(),&m_rawgraphW2,&m_graphW2);
smooth(m_smoothW3.value(),&m_rawgraphW3,&m_graphW3);
m_W1.copyFrom(&m_graphW1);
m_W2.copyFrom(&m_graphW2);
m_W3.copyFrom(&m_graphW3);
}
QString Xpressive::nodeName() const {
return (xpressive_plugin_descriptor.name);
}
void Xpressive::playNote(NotePlayHandle* nph, SampleFrame* working_buffer) {
m_A1=m_parameterA1.value();
m_A2=m_parameterA2.value();
m_A3=m_parameterA3.value();
if (!nph->m_pluginData) {
auto exprO1 = new ExprFront(m_outputExpression[0].constData(),
Engine::audioEngine()->outputSampleRate()); // give the "last" function a whole second
auto exprO2 = new ExprFront(m_outputExpression[1].constData(), Engine::audioEngine()->outputSampleRate());
auto init_expression_step1 = [this, nph](ExprFront* e) { //lambda function to init exprO1 and exprO2
//add the constants and the variables to the expression.
e->add_constant("key", nph->key());//the key that was pressed.
e->add_constant("bnote", nph->instrumentTrack()->baseNote()); // the base note
e->add_constant("srate", Engine::audioEngine()->outputSampleRate());// sample rate of the audio engine
e->add_constant("v", nph->getVolume() / 255.0); //volume of the note.
e->add_constant("tempo", Engine::getSong()->getTempo());//tempo of the song.
e->add_variable("A1", m_A1);//A1,A2,A3: general purpose input controls.
e->add_variable("A2", m_A2);
e->add_variable("A3", m_A3);
};
init_expression_step1(exprO1);
init_expression_step1(exprO2);
m_W1.setInterpolate(m_interpolateW1.value());//set interpolation according to the user selection.
m_W2.setInterpolate(m_interpolateW2.value());
m_W3.setInterpolate(m_interpolateW3.value());
nph->m_pluginData = new ExprSynth(&m_W1, &m_W2, &m_W3, exprO1, exprO2, nph,
Engine::audioEngine()->outputSampleRate(), &m_panning1, &m_panning2, m_relTransition.value());
}
auto ps = static_cast<ExprSynth*>(nph->m_pluginData);
const fpp_t frames = nph->framesLeftForCurrentPeriod();
const f_cnt_t offset = nph->noteOffset();
ps->renderOutput(frames, working_buffer + offset);
}
void Xpressive::deleteNotePluginData(NotePlayHandle* nph) {
delete static_cast<ExprSynth *>(nph->m_pluginData);
}
gui::PluginView* Xpressive::instantiateView(QWidget* parent) {
return (new gui::XpressiveView(this, parent));
}
void Xpressive::smooth(float smoothness,const graphModel * in,graphModel * out)
{
out->setSamples(in->samples());
if (smoothness>0)
{
const int guass_size = (int)(smoothness * 5) | 1;
const int guass_center = guass_size/2;
const float delta = smoothness;
const float a= 1.0f / (sqrtf(2.0f * F_PI) * delta);
auto const guassian = new float[guass_size];
float sum = 0.0f;
float temp = 0.0f;
for (int i = 0; i < guass_size; i++)
{
temp = (i - guass_center) / delta;
sum += guassian[i] = a * powf(F_E, -0.5f * temp * temp);
}
for (int i = 0; i < guass_size; i++)
{
guassian[i] = guassian[i] / sum;
}
out->convolve(guassian, guass_size, guass_center);
delete [] guassian;
}
}
namespace gui
{
class XpressiveKnob: public Knob {
public:
void setStyle()
{
setFixedSize(29, 29);
setCenterPointX(14.5);
setCenterPointY(14.5);
setInnerRadius(4);
setOuterRadius(9);
setTotalAngle(300.0);
setLineWidth(3);
}
XpressiveKnob(QWidget * _parent, const QString & _name) :
Knob(KnobType::Styled, _parent,_name) {
setStyle();
}
XpressiveKnob(QWidget * _parent) :
Knob(KnobType::Styled, _parent) {
setStyle();
}
};
XpressiveView::XpressiveView(Instrument * _instrument, QWidget * _parent) :
InstrumentViewFixedSize(_instrument, _parent)
{
const int COL_KNOBS = 191;
const int BASE_START = 2;
const int ROW_KNOBSA1 = BASE_START;
const int ROW_KNOBSA2 = BASE_START + 32;
const int ROW_KNOBSA3 = BASE_START + 64;
const int ROW_KNOBSP1 = BASE_START + 100;
const int ROW_KNOBSP2 = BASE_START + 100 + 32;
const int ROW_KNOBREL = BASE_START + 100 + 64;
const int ROW_BTN = BASE_START + 85;
const int ROW_WAVEBTN = BASE_START + 233 - 26;
const int EXPR_TEXT_Y = BASE_START + 102;
const int EXPR_TEXT_H = 90;
setAutoFillBackground(true);
QPalette pal;
pal.setBrush(backgroundRole(), PLUGIN_NAME::getIconPixmap("artwork"));
setPalette(pal);
m_graph = new Graph(this, Graph::Style::Linear, 180, 81);
m_graph->move(3, BASE_START + 1);
m_graph->setAutoFillBackground(true);
m_graph->setGraphColor(QColor(255, 255, 255));
m_graph->setEnabled(false);
m_graph->setToolTip(tr("Draw your own waveform here "
"by dragging your mouse on this graph."));
pal = QPalette();
pal.setBrush(backgroundRole(), PLUGIN_NAME::getIconPixmap("wavegraph"));
m_graph->setPalette(pal);
m_w1Btn = new PixmapButton(this, nullptr);
m_w1Btn->move(3, ROW_BTN);
m_w1Btn->setActiveGraphic(PLUGIN_NAME::getIconPixmap("w1_active"));
m_w1Btn->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("w1_inactive"));
m_w1Btn->setToolTip(tr("Select oscillator W1"));
m_w2Btn = new PixmapButton(this, nullptr);
m_w2Btn->move(26, ROW_BTN);
m_w2Btn->setActiveGraphic(PLUGIN_NAME::getIconPixmap("w2_active"));
m_w2Btn->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("w2_inactive"));
m_w2Btn->setToolTip(tr("Select oscillator W2"));
m_w3Btn = new PixmapButton(this, nullptr);
m_w3Btn->move(49, ROW_BTN);
m_w3Btn->setActiveGraphic(PLUGIN_NAME::getIconPixmap("w3_active"));
m_w3Btn->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("w3_inactive"));
m_w3Btn->setToolTip(tr("Select oscillator W3"));
m_o1Btn = new PixmapButton(this, nullptr);
m_o1Btn->move(79, ROW_BTN);
m_o1Btn->setActiveGraphic(PLUGIN_NAME::getIconPixmap("o1_active"));
m_o1Btn->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("o1_inactive"));
m_o1Btn->setToolTip(tr("Select output O1"));
m_o2Btn = new PixmapButton(this, nullptr);
m_o2Btn->move(101, ROW_BTN);
m_o2Btn->setActiveGraphic(PLUGIN_NAME::getIconPixmap("o2_active"));
m_o2Btn->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("o2_inactive"));
m_o2Btn->setToolTip(tr("Select output O2"));
m_helpBtn = new PixmapButton(this, nullptr);
m_helpBtn->move(133, ROW_BTN);
m_helpBtn->setActiveGraphic(PLUGIN_NAME::getIconPixmap("help_active"));
m_helpBtn->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("help_inactive"));
m_helpBtn->setToolTip(tr("Open help window"));
m_selectedGraphGroup = new automatableButtonGroup(this);
m_selectedGraphGroup->addButton(m_w1Btn);
m_selectedGraphGroup->addButton(m_w2Btn);
m_selectedGraphGroup->addButton(m_w3Btn);
m_selectedGraphGroup->addButton(m_o1Btn);
m_selectedGraphGroup->addButton(m_o2Btn);
auto e = castModel<Xpressive>();
m_selectedGraphGroup->setModel(&e->selectedGraph());
m_sinWaveBtn = new PixmapButton(this, tr("Sine wave"));
m_sinWaveBtn->move(4, ROW_WAVEBTN);
m_sinWaveBtn->setActiveGraphic(embed::getIconPixmap("sin_wave_active"));
m_sinWaveBtn->setInactiveGraphic(embed::getIconPixmap("sin_wave_inactive"));
m_sinWaveBtn->setToolTip(tr("Sine wave"));
m_moogWaveBtn = new PixmapButton(this, tr("Moog-saw wave"));
m_moogWaveBtn->move(4, ROW_WAVEBTN-14);
m_moogWaveBtn->setActiveGraphic(
embed::getIconPixmap( "moog_saw_wave_active" ) );
m_moogWaveBtn->setInactiveGraphic(embed::getIconPixmap("moog_saw_wave_inactive"));
m_moogWaveBtn->setToolTip(tr("Moog-saw wave"));
m_expWaveBtn = new PixmapButton(this, tr("Exponential wave"));
m_expWaveBtn->move(4 +14, ROW_WAVEBTN-14);
m_expWaveBtn->setActiveGraphic(embed::getIconPixmap( "exp_wave_active" ) );
m_expWaveBtn->setInactiveGraphic(embed::getIconPixmap( "exp_wave_inactive" ) );
m_expWaveBtn->setToolTip(tr("Exponential wave"));
m_sawWaveBtn = new PixmapButton(this, tr("Saw wave"));
m_sawWaveBtn->move(4 + 14 * 2, ROW_WAVEBTN-14);
m_sawWaveBtn->setActiveGraphic(embed::getIconPixmap("saw_wave_active"));
m_sawWaveBtn->setInactiveGraphic(embed::getIconPixmap("saw_wave_inactive"));
m_sawWaveBtn->setToolTip(tr("Saw wave"));
m_usrWaveBtn = new PixmapButton(this, tr("User-defined wave"));
m_usrWaveBtn->move(4 + 14 * 3, ROW_WAVEBTN-14);
m_usrWaveBtn->setActiveGraphic(embed::getIconPixmap("usr_wave_active"));
m_usrWaveBtn->setInactiveGraphic(embed::getIconPixmap("usr_wave_inactive"));
m_usrWaveBtn->setToolTip(tr("User-defined wave"));
m_triangleWaveBtn = new PixmapButton(this, tr("Triangle wave"));
m_triangleWaveBtn->move(4 + 14, ROW_WAVEBTN);
m_triangleWaveBtn->setActiveGraphic(
embed::getIconPixmap("triangle_wave_active"));
m_triangleWaveBtn->setInactiveGraphic(
embed::getIconPixmap("triangle_wave_inactive"));
m_triangleWaveBtn->setToolTip(tr("Triangle wave"));
m_sqrWaveBtn = new PixmapButton(this, tr("Square wave"));
m_sqrWaveBtn->move(4 + 14 * 2, ROW_WAVEBTN);
m_sqrWaveBtn->setActiveGraphic(embed::getIconPixmap("square_wave_active"));
m_sqrWaveBtn->setInactiveGraphic(
embed::getIconPixmap("square_wave_inactive"));
m_sqrWaveBtn->setToolTip(tr("Square wave"));
m_whiteNoiseWaveBtn = new PixmapButton(this, tr("White noise"));
m_whiteNoiseWaveBtn->move(4 + 14 * 3, ROW_WAVEBTN);
m_whiteNoiseWaveBtn->setActiveGraphic(
embed::getIconPixmap("white_noise_wave_active"));
m_whiteNoiseWaveBtn->setInactiveGraphic(
embed::getIconPixmap("white_noise_wave_inactive"));
m_whiteNoiseWaveBtn->setToolTip(tr("White noise"));
m_waveInterpolate = new LedCheckBox("Interpolate", this, tr("WaveInterpolate"),
LedCheckBox::LedColor::Green);
m_waveInterpolate->move(2, 230);
m_expressionValidToggle = new LedCheckBox("", this, tr("ExpressionValid"),
LedCheckBox::LedColor::Red);
m_expressionValidToggle->move(168, EXPR_TEXT_Y+EXPR_TEXT_H-2);
m_expressionValidToggle->setEnabled( false );
m_expressionEditor = new QPlainTextEdit(this);
m_expressionEditor->move(3, EXPR_TEXT_Y);
m_expressionEditor->resize(180, EXPR_TEXT_H);
m_generalPurposeKnob[0] = new XpressiveKnob(this,"A1");
m_generalPurposeKnob[0]->setHintText(tr("General purpose 1:"), "");
m_generalPurposeKnob[0]->move(COL_KNOBS, ROW_KNOBSA1);
m_generalPurposeKnob[1] = new XpressiveKnob(this,"A2");
m_generalPurposeKnob[1]->setHintText(tr("General purpose 2:"), "");
m_generalPurposeKnob[1]->move(COL_KNOBS, ROW_KNOBSA2);
m_generalPurposeKnob[2] = new XpressiveKnob(this,"A3");
m_generalPurposeKnob[2]->setHintText(tr("General purpose 3:"), "");
m_generalPurposeKnob[2]->move(COL_KNOBS, ROW_KNOBSA3);
m_panningKnob[0] = new XpressiveKnob(this,"O1 panning");
m_panningKnob[0]->setHintText(tr("O1 panning:"), "");
m_panningKnob[0]->move(COL_KNOBS, ROW_KNOBSP1);
m_panningKnob[1] = new XpressiveKnob(this,"O2 panning");
m_panningKnob[1]->setHintText(tr("O2 panning:"), "");
m_panningKnob[1]->move(COL_KNOBS, ROW_KNOBSP2);
m_relKnob = new XpressiveKnob(this,"Release transition");
m_relKnob->setHintText(tr("Release transition:"), "ms");
m_relKnob->move(COL_KNOBS, ROW_KNOBREL);
m_smoothKnob=new Knob(KnobType::Styled, this, "Smoothness");
m_smoothKnob->setFixedSize(25, 25);
m_smoothKnob->setCenterPointX(12.5);
m_smoothKnob->setCenterPointY(12.5);
m_smoothKnob->setInnerRadius(4);
m_smoothKnob->setOuterRadius(9);
m_smoothKnob->setTotalAngle(280.0);
m_smoothKnob->setLineWidth(3);
m_smoothKnob->setHintText(tr("Smoothness"), "");
m_smoothKnob->move(66, EXPR_TEXT_Y + EXPR_TEXT_H + 4);
connect(m_generalPurposeKnob[0], SIGNAL(sliderMoved(float)), this,
SLOT(expressionChanged()));
connect(m_generalPurposeKnob[1], SIGNAL(sliderMoved(float)), this,
SLOT(expressionChanged()));
connect(m_generalPurposeKnob[2], SIGNAL(sliderMoved(float)), this,
SLOT(expressionChanged()));
connect(m_expressionEditor, SIGNAL(textChanged()), this,
SLOT(expressionChanged()));
connect(m_smoothKnob, SIGNAL(sliderMoved(float)), this,
SLOT(smoothChanged()));
connect(m_graph, SIGNAL(drawn()), this,
SLOT(graphDrawn()));
connect(m_sinWaveBtn, SIGNAL(clicked()), this, SLOT(sinWaveClicked()));
connect(m_triangleWaveBtn, SIGNAL(clicked()), this,
SLOT(triangleWaveClicked()));
connect(m_expWaveBtn, SIGNAL(clicked()), this, SLOT(expWaveClicked()));
connect(m_moogWaveBtn, SIGNAL(clicked()), this,
SLOT(moogSawWaveClicked()));
connect(m_sawWaveBtn, SIGNAL(clicked()), this, SLOT(sawWaveClicked()));
connect(m_sqrWaveBtn, SIGNAL(clicked()), this, SLOT(sqrWaveClicked()));
connect(m_whiteNoiseWaveBtn, SIGNAL(clicked()), this,
SLOT(noiseWaveClicked()));
connect(m_usrWaveBtn, SIGNAL(clicked()), this, SLOT(usrWaveClicked()));
connect(m_helpBtn, SIGNAL(clicked()), this, SLOT(helpClicked()));
connect(m_w1Btn, SIGNAL(clicked()), this, SLOT(updateLayout()));
connect(m_w2Btn, SIGNAL(clicked()), this, SLOT(updateLayout()));
connect(m_w3Btn, SIGNAL(clicked()), this, SLOT(updateLayout()));
connect(m_o1Btn, SIGNAL(clicked()), this, SLOT(updateLayout()));
connect(m_o2Btn, SIGNAL(clicked()), this, SLOT(updateLayout()));
updateLayout();
}
void XpressiveView::expressionChanged() {
auto e = castModel<Xpressive>();
QByteArray text = m_expressionEditor->toPlainText().toLatin1();
switch (m_selectedGraphGroup->model()->value()) {
case W1_EXPR:
e->wavesExpression(0) = text;
break;
case W2_EXPR:
e->wavesExpression(1) = text;
break;
case W3_EXPR:
e->wavesExpression(2) = text;
break;
case O1_EXPR:
e->outputExpression(0) = text;
break;
case O2_EXPR:
e->outputExpression(1) = text;
break;
}
if (m_wave_expr)
m_graph->setEnabled(m_smoothKnob->model()->value() == 0 && text.size() == 0);
if (text.size()>0)
{
const unsigned int sample_rate=m_raw_graph->length();
ExprFront expr(text.constData(),sample_rate);
float t=0;
const float f=10,key=5,v=0.5;
unsigned int frame_counter = 0;
expr.add_variable("t", t);
if (m_output_expr)
{
expr.add_constant("f", f);
expr.add_constant("key", key);
expr.add_constant("rel", 0);
expr.add_constant("trel", 0);
expr.add_constant("bnote",e->instrumentTrack()->baseNote());
expr.add_constant("v", v);
expr.add_constant("tempo", Engine::getSong()->getTempo());
expr.add_constant("A1", e->parameterA1().value());
expr.add_constant("A2", e->parameterA2().value());
expr.add_constant("A3", e->parameterA3().value());
expr.add_cyclic_vector("W1",e->graphW1().samples(),e->graphW1().length());
expr.add_cyclic_vector("W2",e->graphW2().samples(),e->graphW2().length());
expr.add_cyclic_vector("W3",e->graphW3().samples(),e->graphW3().length());
}
expr.setIntegrate(&frame_counter,sample_rate);
expr.add_constant("srate",sample_rate);
const bool parse_ok=expr.compile();
if (parse_ok) {
e->exprValid().setValue(0);
const unsigned int length = static_cast<unsigned int>(m_raw_graph->length());
auto const samples = new float[length];
// frame_counter's reference is used in the integrate function.
for (frame_counter = 0; frame_counter < length; ++frame_counter)
{
t = frame_counter / (float) length;
samples[frame_counter] = expr.evaluate();
if (std::isinf(samples[frame_counter]) != 0 || std::isnan(samples[frame_counter]) != 0)
{
samples[frame_counter] = 0;
}
}
m_raw_graph->setSamples(samples);
delete[] samples;
if (m_wave_expr)
{
smoothChanged();
}
else
{
Engine::getSong()->setModified();
}
}
else
{
e->exprValid().setValue(1);
if (m_output_expr)
m_raw_graph->clear();
}
}
else
{
e->exprValid().setValue(0);
if (m_output_expr)
m_raw_graph->clear();
}
}
void XpressiveView::smoothChanged()
{
auto e = castModel<Xpressive>();
float smoothness=0;
switch (m_selectedGraphGroup->model()->value()) {
case W1_EXPR:
smoothness=e->smoothW1().value();
break;
case W2_EXPR:
smoothness=e->smoothW2().value();
break;
case W3_EXPR:
smoothness=e->smoothW3().value();
break;
}
Xpressive::smooth(smoothness,m_raw_graph,m_graph->model());
switch (m_selectedGraphGroup->model()->value()) {
case W1_EXPR:
e->W1().copyFrom(m_graph->model());
break;
case W2_EXPR:
e->W2().copyFrom(m_graph->model());
break;
case W3_EXPR:
e->W3().copyFrom(m_graph->model());
break;
}
Engine::getSong()->setModified();
m_graph->setEnabled(m_smoothKnob->model()->value() == 0 && m_expressionEditor->toPlainText().size() == 0);
}
void XpressiveView::graphDrawn()
{
m_raw_graph->setSamples(m_graph->model()->samples());
auto e = castModel<Xpressive>();
switch (m_selectedGraphGroup->model()->value()) {
case W1_EXPR:
e->W1().copyFrom(m_graph->model());
break;
case W2_EXPR:
e->W2().copyFrom(m_graph->model());
break;
case W3_EXPR:
e->W3().copyFrom(m_graph->model());
break;
}
Engine::getSong()->setModified();
}
void XpressiveView::modelChanged() {
auto b = castModel<Xpressive>();
m_expressionValidToggle->setModel( &b->exprValid() );
m_generalPurposeKnob[0]->setModel( &b->parameterA1() );
m_generalPurposeKnob[1]->setModel( &b->parameterA2() );
m_generalPurposeKnob[2]->setModel( &b->parameterA3() );
m_panningKnob[0]->setModel( &b->panning1() );
m_panningKnob[1]->setModel( &b->panning2() );
m_relKnob->setModel( &b->relTransition() );
m_selectedGraphGroup->setModel( &b->selectedGraph() );
updateLayout();
}
void XpressiveView::updateLayout() {
auto e = castModel<Xpressive>();
m_output_expr=false;
m_wave_expr=false;
switch (m_selectedGraphGroup->model()->value()) {
case W1_EXPR:
m_wave_expr=true;
m_graph->setModel(&e->graphW1(), true);
m_raw_graph=&(e->rawgraphW1());
m_expressionEditor->setPlainText(e->wavesExpression(0));
m_smoothKnob->setModel(&e->smoothW1());
m_graph->setEnabled((e->smoothW1().value() == 0 && e->wavesExpression(0).size() == 0));
m_waveInterpolate->setModel(&e->interpolateW1());
m_smoothKnob->show();
m_usrWaveBtn->show();
m_waveInterpolate->show();
break;
case W2_EXPR:
m_wave_expr=true;
m_graph->setModel(&e->graphW2(), true);
m_raw_graph=&(e->rawgraphW2());
m_expressionEditor->setPlainText(e->wavesExpression(1));
m_smoothKnob->setModel(&e->smoothW2());
m_graph->setEnabled((e->smoothW2().value() == 0 && e->wavesExpression(1).size() == 0));
m_waveInterpolate->setModel(&e->interpolateW2());
m_smoothKnob->show();
m_usrWaveBtn->show();
m_waveInterpolate->show();
break;
case W3_EXPR:
m_wave_expr=true;
m_graph->setModel(&e->graphW3(), true);
m_raw_graph=&(e->rawgraphW3());
m_expressionEditor->setPlainText(e->wavesExpression(2));
m_smoothKnob->setModel(&e->smoothW3());
m_graph->setEnabled((e->smoothW3().value() == 0 && e->wavesExpression(2).size() == 0));
m_waveInterpolate->setModel(&e->interpolateW3());
m_smoothKnob->show();
m_usrWaveBtn->show();
m_waveInterpolate->show();
break;
case O1_EXPR:
m_output_expr=true;
m_graph->setModel(&e->graphO1(), true);
m_raw_graph=&(e->graphO1());
m_expressionEditor->setPlainText(e->outputExpression(0));
m_smoothKnob->hide();
m_graph->setEnabled(false);
m_usrWaveBtn->hide();
m_waveInterpolate->hide();
break;
case O2_EXPR:
m_output_expr=true;
m_graph->setModel(&e->graphO2(), true);
m_raw_graph=&(e->graphO2());
m_expressionEditor->setPlainText(e->outputExpression(1));
m_smoothKnob->hide();
m_graph->setEnabled(false);
m_usrWaveBtn->hide();
m_waveInterpolate->hide();
break;
}
}
void XpressiveView::sinWaveClicked() {
if (m_output_expr)
m_expressionEditor->appendPlainText("sinew(integrate(f))");
else
m_expressionEditor->appendPlainText("sinew(t)");
Engine::getSong()->setModified();
}
void XpressiveView::triangleWaveClicked() {
if (m_output_expr)
m_expressionEditor->appendPlainText("trianglew(integrate(f))");
else
m_expressionEditor->appendPlainText("trianglew(t)");
Engine::getSong()->setModified();
}
void XpressiveView::sawWaveClicked() {
if (m_output_expr)
m_expressionEditor->appendPlainText("saww(integrate(f))");
else
m_expressionEditor->appendPlainText("saww(t)");
Engine::getSong()->setModified();
}
void XpressiveView::sqrWaveClicked() {
if (m_output_expr)
m_expressionEditor->appendPlainText("squarew(integrate(f))");
else
m_expressionEditor->appendPlainText("squarew(t)");
Engine::getSong()->setModified();
}
void XpressiveView::noiseWaveClicked() {
m_expressionEditor->appendPlainText("randsv(t*srate,0)");
Engine::getSong()->setModified();
}
void XpressiveView::moogSawWaveClicked()
{
if (m_output_expr)
m_expressionEditor->appendPlainText("moogsaww(integrate(f))");
else
m_expressionEditor->appendPlainText("moogsaww(t)");
Engine::getSong()->setModified();
}
void XpressiveView::expWaveClicked()
{
if (m_output_expr)
m_expressionEditor->appendPlainText("expw(integrate(f))");
else
m_expressionEditor->appendPlainText("expw(t)");
Engine::getSong()->setModified();
}
void XpressiveView::usrWaveClicked() {
m_expressionEditor->setPlainText("");
QString fileName = m_raw_graph->setWaveToUser();
smoothChanged();
Engine::getSong()->setModified();
}
QString XpressiveHelpView::s_helpText=
"<b>O1, O2</b> - Two output waves. Panning is controlled by PN1 and PN2.<br>"
"<b>W1, W2, W3</b> - Wave samples evaluated by expression. In these samples, t variable ranges [0,1).<br>"
"These waves can be used as functions inside the output waves (O1, O2). The wave period is 1.<br>"
"<h4>Available variables:</h4><br>"
"<b>t</b> - Time in seconds.<br>"
"<b>f</b> - Note's pitched frequency. Available only in the output expressions.<br>"
"<b>key</b> - Note's keyboard key. 0 denotes C-1, 60 denotes C4, 127 denotes G9. Available only in the output expressions.<br>"
"<b>bnote</b> - Base note. By default it is 69 which means A4, unless you change it.<br>"
"<b>srate</b> - Sample rate. In wave expression it returns the wave's number of samples.<br>"
"<b>tempo</b> - Song's Tempo. Available only in the output expressions.<br>"
"<b>v</b> - Note's volume. Note that the output is already multiplied by the volume. Available only in the output expressions.<br>"
"<b>rel</b> - Gives 0.0 while the key is held, and 1.0 after the key release. Available only in the output expressions.<br>"
"<b>trel</b> - Time after release. While the note is held, it gives 0.0. Afterwards, it starts counting seconds.<br>"
"The time it takes to shift from 0.0 to 1.0 after key release is determined by the REL knob<br>"
"<b>seed</b> - A random value that remains consistent in the lifetime of a single wave. Meant to be used with <b>randsv</b><br>"
"<b>A1, A2, A3</b> - General purpose knobs. You can reference them only in O1 and O2. In range [-1,1].<br>"
"<h4>Available functions:</h4><br>"
"<b>W1, W2, W3</b> - As mentioned before. You can reference them only in O1 and O2.<br>"
"<b>cent(x)</b> - Gives pow(2,x/1200), so you can multiply it with the f variable to pitch the frequency.<br>"
"100 cents equals one semitone<br>"
"<b>semitone(x)</b> - Gives pow(2,x/12), so you can multiply it with the f variable to pitch the frequency.<br>"
"<b>last(n)</b> - Gives you the last n'th evaluated sample. In O1 and O2 it keeps a whole second. Thus the argument n must be in the range [1,srate], or else, it will return 0.<br>"
"<b>integrate(x)</b> - Integrates x by delta t (It sums values and divides them by sample rate).<br>"
"If you use notes with automated frequency, you should use:<br>"
"sinew(integrate(f)) instead of sinew(t*f)<br>"
"<b>randv(x)</b> - A random vector. Each cell is reference by an integer index in the range [0,2^31]<br>"
"Each evaluation of an expression results in different random vector.<br>"
"Although, it remains consistent in the lifetime of a single wave.<br>"
"If you want a single random values you can use randv(0),randv(1)... <br>"
"and every reference to randv(a) will give you the same value."
"If you want a random wave you can use randv(t*srate).<br>"
"Each random value is in the range [-1,1).<br>"
"<b>randsv(x,seed)</b> - works exactly like randv(x),<br>"
"except that it lets you to select the seed manualy,<br>"
"if you want to try different random values and make it consistent in each evaluation.<br>"
"<b>sinew(x)</b> - A sine wave with period of 1 (In contrast to real sine wave which have a period of 2*pi).<br>"
"<b>trianglew(x)</b> - A triangle wave with period of 1.<br>"
"<b>squarew(x)</b> - A square wave with period of 1.<br>"
"<b>saww(x)</b> - A saw wave with period of 1.<br>"
"<b>clamp(min_val,x,max_val)</b> - If x is in range of (min_val,max_val) it returns x. Otherwise if it's greater than max_val it returns max_val, else returns min_val.<br>"
"<b>abs, sin, cos, tan, cot, asin, acos, atan, atan2, sinh, cosh, tanh, asinh, acosh, atanh, sinc, "
"hypot, exp, log, log2, log10, logn, pow, sqrt, min, max, floor, ceil, round, trunc, frac, "
"avg, sgn, mod, etc. are also available.</b><br>"
"<b>Operands + - * / % ^ > < >= <= == != & | are also available.</b><br>"
"<b>Amplitude Modulation</b> - W1(t*f)*(1+W2(t*f))<br>"
"<b>Ring Modulation</b> - W1(t * f)*W2(t * f)<br>"
"<b>Mix Modulation</b> - 0.5*( W1(t * f) + W2(t * f) )<br>"
"<b>Frequency Modulation</b> - [vol1]*W1( integrate( f + srate*[vol2]*W2( integrate(f) ) ) )<br>"
"<b>Phase Modulation</b> - [vol1]*W1( integrate(f) + [vol2]*W2( integrate(f) ) )<br>"
;
XpressiveHelpView::XpressiveHelpView():QTextEdit(s_helpText)
{
#if QT_VERSION < 0x50C00
// Workaround for a bug in Qt versions below 5.12,
// where argument-dependent-lookup fails for QFlags operators
// declared inside a namepsace.
// This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h
// See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348
using ::operator|;
#endif
setWindowTitle ( "Xpressive Help" );
setTextInteractionFlags ( Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse );
getGUI()->mainWindow()->addWindowedWidget( this );
parentWidget()->setAttribute( Qt::WA_DeleteOnClose, false );
parentWidget()->setWindowIcon( PLUGIN_NAME::getIconPixmap( "logo" ) );
parentWidget()->setFixedSize( 300, 500);
// No maximize button
Qt::WindowFlags flags = parentWidget()->windowFlags();
flags &= ~Qt::WindowMaximizeButtonHint;
parentWidget()->setWindowFlags( flags );
}
void XpressiveView::helpClicked() {
XpressiveHelpView::getInstance()->show();
}
} // namespace gui
extern "C" {
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main(Model *m, void *) {
return (new Xpressive(static_cast<InstrumentTrack *>(m)));
}
}
} // namespace lmms
| 32,660
|
C++
|
.cpp
| 780
| 39.464103
| 181
| 0.712356
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,659
|
ExprSynth.cpp
|
LMMS_lmms/plugins/Xpressive/ExprSynth.cpp
|
/*
* ExprSynth.cpp - Implementation of a Frontend to ExprTk
*
* Copyright (c) 2016-2017 Orr Dvori
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "ExprSynth.h"
#include <string>
#include <vector>
#include <cmath>
#include <random>
#include "interpolation.h"
#include "lmms_math.h"
#include "NotePlayHandle.h"
#include "SampleFrame.h"
#include <exprtk.hpp>
#define WARN_EXPRTK qWarning("ExprTk exception")
namespace lmms
{
using symbol_table_t = exprtk::symbol_table<float>;
using expression_t = exprtk::expression<float>;
using parser_t = exprtk::parser<float>;
template <typename T,typename Functor,bool optimize>
struct freefunc0 : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
freefunc0() : exprtk::ifunction<T>(0) {
if (optimize) { exprtk::disable_has_side_effects(*this); }
}
inline T operator()() override
{ return Functor::process(); }
};
template <typename T,typename Functor,bool optimize>
struct freefunc1 : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
freefunc1() : exprtk::ifunction<T>(1) {
if (optimize) { exprtk::disable_has_side_effects(*this); }
}
inline T operator()(const T& x) override
{ return Functor::process(x); }
};
template <typename T>
struct IntegrateFunction : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
~IntegrateFunction() override
{
delete [] m_counters;
}
IntegrateFunction(const unsigned int* frame, unsigned int sample_rate,unsigned int max_counters) :
exprtk::ifunction<T>(1),
m_firstValue(0),
m_frame(frame),
m_sampleRate(sample_rate),
m_maxCounters(max_counters),
m_nCounters(0),
m_nCountersCalls(0),
m_cc(0)
{
m_counters=new double[max_counters];
clearArray(m_counters,max_counters);
}
inline T operator()(const T& x) override
{
if (m_frame)
{
if (m_nCountersCalls == 0)
{
m_firstValue = *m_frame;
}
if (m_firstValue == *m_frame)
{
++m_nCountersCalls;
if (m_nCountersCalls > m_maxCounters)
{
return 0;
}
m_cc = m_nCounters;
++m_nCounters;
}
else // we moved to the next frame
{
m_frame = 0; // this will indicate that we are no longer in init phase.
}
}
T res = 0;
if (m_cc < m_nCounters)
{
res = m_counters[m_cc];
m_counters[m_cc] += x;
}
m_cc = (m_cc + 1) % m_nCountersCalls;
return res / m_sampleRate;
}
unsigned int m_firstValue;
const unsigned int* m_frame;
const unsigned int m_sampleRate;
// number of counters allocated
const unsigned int m_maxCounters;
// number of integrate instances that has counters allocated
unsigned int m_nCounters;
// real number of integrate instances
unsigned int m_nCountersCalls;
unsigned int m_cc;
double *m_counters;
};
template <typename T>
struct LastSampleFunction : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
~LastSampleFunction() override
{
delete [] m_samples;
}
LastSampleFunction(unsigned int history_size) :
exprtk::ifunction<T>(1),
m_history_size(history_size),
m_pivot_last(history_size - 1)
{
m_samples = new T[history_size];
clearArray(m_samples, history_size);
}
inline T operator()(const T& x) override
{
if (!std::isnan(x) && x >= 1 && x <= m_history_size) {
return m_samples[(static_cast<std::size_t>(x) + m_pivot_last) % m_history_size];
}
return 0;
}
void setLastSample(const T& sample)
{
if (!std::isnan(sample) && !std::isinf(sample))
{
m_samples[m_pivot_last] = sample;
}
if (m_pivot_last == 0)
{
m_pivot_last = m_history_size - 1;
}
else {
--m_pivot_last;
}
}
unsigned int m_history_size;
unsigned int m_pivot_last;
T *m_samples;
};
template <typename T>
struct WaveValueFunction : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
WaveValueFunction(const T* v, std::size_t s)
: exprtk::ifunction<T>(1),
m_vec(v),
m_size(s)
{}
inline T operator()(const T& index) override
{
return m_vec[(int) ( positiveFraction(index) * m_size )];
}
const T *m_vec;
const std::size_t m_size;
};
template <typename T>
struct WaveValueFunctionInterpolate : public exprtk::ifunction<T>
{
using exprtk::ifunction<T>::operator();
WaveValueFunctionInterpolate(const T* v, std::size_t s)
: exprtk::ifunction<T>(1),
m_vec(v),
m_size(s)
{}
inline T operator()(const T& index) override
{
const T x = positiveFraction(index) * m_size;
const int ix = (int)x;
const float xfrc = fraction(x);
return linearInterpolate(m_vec[ix], m_vec[(ix + 1) % m_size], xfrc);
}
const T *m_vec;
const std::size_t m_size;
};
static const auto random_data = std::array<unsigned int, 257>{
0xd76a33ec, 0x4a767724, 0xb34ebd08 ,0xf4024196,
0x17b426e2, 0x8dc6389a, 0x1b5dcb93 ,0xa771bd3f,
0x078d502e, 0x8980988a, 0x1f64f846 ,0xb5b48ed7,
0xf0742cfb, 0xe7c66303, 0xc9472876 ,0x6c7494a5,
0x5c2203a1, 0x23986344, 0x7d344fa0 ,0x4f39474a,
0x28ac8b2b, 0x10f779b2, 0x6e79e659 ,0x32e44c52,
0xf790aa55, 0x98b05083, 0xb5d44f1c ,0xe553da04,
0xa884c6d2, 0x43274953, 0xbcb57404 ,0x43f7d32a,
0xf1890f8b, 0x019f4dce, 0x5c4ede33 ,0x2dec1a7e,
0x0f3eab09, 0x2197c93c, 0xae933f42 ,0x80d4b111,
0x6e5bd30a, 0x17139c70, 0xe15f7eb0 ,0x1798f893,
0xe1c6be1c, 0xe21edf9b, 0x4702e081 ,0x8a2cb85a,
0xbf3c1f15, 0x147f4685, 0x9221d731 ,0x3c7580f3,
0xc1c08498, 0x8e198b35, 0xf821c15a ,0x4d3cd2d4,
0xad89a3b7, 0xd48f915f, 0xcaf893f0 ,0xa64a4b8e,
0x20715f54, 0x1ba4de0a, 0x17ac6e91 ,0xd82ea8c0,
0x638a0ba5, 0xe7a76c0f, 0x486c5476 ,0x334bbd0a,
0xffe29c55, 0x7247efaf, 0x15f98e83 ,0x7a4a79ac,
0x350cd175, 0xc7107908, 0xa85c67f7 ,0x9c5002c4,
0x3cf27d2c, 0x314d8450, 0x05552886 ,0x87a73642,
0x827832e4, 0x9412cc67, 0x261979e6 ,0xb31da27f,
0x3e6bbafb, 0x663f1968, 0xd84274e2, 0xdd91d982,
0xd25c4805, 0x9567f860, 0xab99675c, 0x2254733b,
0x18799dd7, 0xee328916, 0xb9419a1b, 0x01b7a66f,
0xbcdc05e1, 0x788de4ae, 0x366e77cf, 0x81a1ebd2,
0x97be859a, 0x17d4b533, 0x22dab3a9, 0xc99871ea,
0xc7502c91, 0x4474b65f, 0x655d059d, 0x0ddc1348,
0x8325909b, 0x4873c155, 0x9fa30438, 0x7250b7a8,
0x90db2715, 0xf65e1cef, 0x41b74cf4, 0x38fba01c,
0xe9eefb40, 0x9e5524ea, 0x1d3fc077, 0x04ec39db,
0x1c0d501c, 0xb93f26d9, 0xf9f910b9, 0x806fce99,
0x5691ffdf, 0x1e63b27a, 0xf2035d42, 0xd3218a0b,
0x12eae6db, 0xeba372a9, 0x6f975260, 0xc514ae91,
0xebddb8ad, 0xc53207c0, 0xdbda57dc, 0x8fb38ef4,
0xfaa4f1bc, 0x40caf49f, 0xcb394b41, 0x424fc698,
0xb79a9ece, 0x331202d6, 0xc604ed4d, 0x5e85819f,
0x67222eda, 0xd976ba71, 0x7d083ec6, 0x040c819e,
0xc762c934, 0xa6684333, 0x2eaccc54, 0x69dc04b9,
0x0499cf36, 0x6351f438, 0x6db2dc34, 0x787ae036,
0x11b5c6ac, 0x552b7227, 0x32a4c993, 0xf7f4c49d,
0x7ac9e2d9, 0xf3d32020, 0x4ff01f89, 0x6f0e60bb,
0x3c6ed445, 0x7ca01986, 0x96901ecf, 0xe10df188,
0x62a6da6d, 0x8deee09f, 0x5347cb66, 0x5249f452,
0x22704d4d, 0x6221555f, 0x6aa0ea90, 0xe1f7bae3,
0xd106626f, 0x6365a9db, 0x1989bb81, 0xfc2daa73,
0x303c60b3, 0xcd867baa, 0x7c5787c2, 0x60082b30,
0xa68d3a81, 0x15a10f5d, 0x81b21c8a, 0x4bfb82e2,
0xff01c176, 0xff3c8b65, 0x8cc6bd29, 0xc678d6ff,
0x99b86508, 0x3c47e314, 0x766ecc05, 0xba186cb0,
0x42f57199, 0x5ef524f4, 0xb8419750, 0x6ae2a9d0,
0x291eaa18, 0x4e64b189, 0x506eb1d3, 0x78361d46,
0x6a2fcb7e, 0xbc0a46de, 0xb557badf, 0xad3de958,
0xa2901279, 0x491decbf, 0x257383df, 0x94dd19d1,
0xd0cfbbe2, 0x9063d36d, 0x81e44c3b, 0x973e9cc9,
0xfbe34690, 0x4eee3034, 0x1c413676, 0xf6735b8f,
0xf2991aca, 0x0ec85159, 0x6ce00ade, 0xad49de57,
0x025edf30, 0x42722b67, 0x30cfa6b2, 0x32df8676,
0x387d4500, 0x97fa67fd, 0x027c994a, 0x77c71d0c,
0x478eb75a, 0x898370a6, 0x73e7cca3, 0x34ace0ad,
0xc8ecb388, 0x5375c3aa, 0x9c194d87, 0x1b65246d,
0xca000bcf, 0x8a0fb13d, 0x81b957b0, 0xac627bfb,
0xc0fe47e5, 0xf3db0ad8, 0x1c605c7d, 0x5f579884,
0x63e079b5, 0x3d96f7cf, 0x3edd46e9, 0xc347c61e,
0x7b2b2a0e, 0x63dfcf51, 0x596781dd, 0x80304c4d,
0xa66f8b47
};
inline unsigned int rotateLeft(unsigned int x, const int b)
{
if (b > -32 && b < 32 && b != 0)
{
if (b < 0)
{
x= ( x >> (-b) ) | ( x << (32 + b) );
}
else
{
x= ( x << b ) | ( x >> (32 - b) );
}
}
return x;
}
struct RandomVectorSeedFunction : public exprtk::ifunction<float>
{
using exprtk::ifunction<float>::operator();
RandomVectorSeedFunction() :
exprtk::ifunction<float>(2)
{ exprtk::disable_has_side_effects(*this); }
static inline float randv(const float& index,int irseed)
{
if (index < 0 || std::isnan(index) || std::isinf(index))
{
return 0;
}
const auto xi = (unsigned int)index;
const unsigned int si = irseed % data_size;
const unsigned int sa = irseed / data_size;
unsigned int res=rotateLeft(random_data[(xi + 23 * si + 1) % data_size] ^ random_data[(xi / data_size + sa) % data_size],sa % 31 + 1);
res ^= rotateLeft(random_data[(3 * xi + si + 13) % data_size],(xi+2*si) % 32) ^rotateLeft( random_data[(xi / data_size + 2 * sa) % data_size],xi % 31 + 1);
return static_cast<int>(res) / (float)(1 << 31);
}
inline float operator()(const float& index,const float& seed) override
{
const int irseed = seed < 0 || std::isnan(seed) || std::isinf(seed) ? 0 : static_cast<int>(seed);
return randv(index, irseed);
}
static const int data_size=sizeof(random_data)/sizeof(int);
};
static RandomVectorSeedFunction randsv_func;
struct RandomVectorFunction : public exprtk::ifunction<float>
{
using exprtk::ifunction<float>::operator();
RandomVectorFunction(const unsigned int seed) :
exprtk::ifunction<float>(1),
m_rseed(seed)
{ exprtk::disable_has_side_effects(*this); }
inline float operator()(const float& index) override
{
return RandomVectorSeedFunction::randv(index,m_rseed);
}
const unsigned int m_rseed;
};
namespace SimpleRandom {
std::mt19937 generator (17); // mt19937 is a standard mersenne_twister_engine
std::uniform_real_distribution<float> dist(-1.0f, 1.0f);
struct float_random_with_engine
{
static inline float process()
{
return dist(generator);
}
};
} // namespace SimpleRandom
static freefunc0<float,SimpleRandom::float_random_with_engine,false> simple_rand;
class ExprFrontData
{
public:
ExprFrontData(int last_func_samples):
m_rand_vec(SimpleRandom::generator()),
m_integ_func(nullptr),
m_last_func(last_func_samples)
{}
~ExprFrontData()
{
for (const auto& cyclic : m_cyclics)
{
delete cyclic;
}
for (const auto& cyclic : m_cyclics_interp)
{
delete cyclic;
}
if (m_integ_func)
{
delete m_integ_func;
}
}
symbol_table_t m_symbol_table;
expression_t m_expression;
std::string m_expression_string;
std::vector<WaveValueFunction<float>* > m_cyclics;
std::vector<WaveValueFunctionInterpolate<float>* > m_cyclics_interp;
RandomVectorFunction m_rand_vec;
IntegrateFunction<float> *m_integ_func;
LastSampleFunction<float> m_last_func;
};
struct sin_wave
{
static inline float process(float x)
{
x = positiveFraction(x);
return sinf(x * F_2PI);
}
};
static freefunc1<float,sin_wave,true> sin_wave_func;
struct square_wave
{
static inline float process(float x)
{
x = positiveFraction(x);
if (x >= 0.5f) { return -1.0f; }
else { return 1.0f; }
}
};
static freefunc1<float,square_wave,true> square_wave_func;
struct triangle_wave
{
static inline float process(float x)
{
x=positiveFraction(x);
if (x < 0.25f)
{
return x * 4.0f;
}
else
{
if (x < 0.75f) { return 2.0f - x * 4.0f; }
else { return x * 4.0f - 4.0f; }
}
}
};
static freefunc1<float,triangle_wave,true> triangle_wave_func;
struct saw_wave
{
static inline float process(float x)
{
x=positiveFraction(x);
return 2.0f * x - 1.0f;
}
};
static freefunc1<float,saw_wave,true> saw_wave_func;
struct moogsaw_wave
{
static inline float process(float x)
{
x = positiveFraction(x);
if( x < 0.5f )
{
return -1.0f + x * 4.0f;
}
return 1.0f - 2.0f * x;
}
};
static freefunc1<float,moogsaw_wave,true> moogsaw_wave_func;
struct moog_wave
{
static inline float process(float x)
{
x = positiveFraction(x);
if( x > 0.5f )
{
x = 1.0f - x;
return -1.0f + 4.0f * x * x;
}
return -1.0f + 8.0f * x * x;
}
};
static freefunc1<float,moog_wave,true> moog_wave_func;
struct exp_wave
{
static inline float process(float x)
{
x = positiveFraction(x);
if( x > 0.5f )
{
x = 1.0f - x;
}
return -1.0f + 8.0f * x * x;
}
};
static freefunc1<float,exp_wave,true> exp_wave_func;
struct exp2_wave
{
static inline float process(float x)
{
x = positiveFraction(x);
if( x > 0.5f )
{
return -1.0f + 8.0f * (1.0f-x) * x;
}
return -1.0f + 8.0f * x * x;
}
};
static freefunc1<float,exp2_wave,true> exp2_wave_func;
struct harmonic_cent
{
static inline float process(float x)
{
return powf(2, x / 1200);
}
};
static freefunc1<float,harmonic_cent,true> harmonic_cent_func;
struct harmonic_semitone
{
static inline float process(float x)
{
return powf(2, x / 12);
}
};
static freefunc1<float,harmonic_semitone,true> harmonic_semitone_func;
ExprFront::ExprFront(const char * expr, int last_func_samples)
{
m_valid = false;
try
{
m_data = new ExprFrontData(last_func_samples);
m_data->m_expression_string = expr;
m_data->m_symbol_table.add_pi();
m_data->m_symbol_table.add_constant("e", F_E);
m_data->m_symbol_table.add_constant("seed", SimpleRandom::generator() & max_float_integer_mask);
m_data->m_symbol_table.add_function("sinew", sin_wave_func);
m_data->m_symbol_table.add_function("squarew", square_wave_func);
m_data->m_symbol_table.add_function("trianglew", triangle_wave_func);
m_data->m_symbol_table.add_function("saww", saw_wave_func);
m_data->m_symbol_table.add_function("moogsaww", moogsaw_wave_func);
m_data->m_symbol_table.add_function("moogw", moog_wave_func);
m_data->m_symbol_table.add_function("expw", exp_wave_func);
m_data->m_symbol_table.add_function("expnw", exp2_wave_func);
m_data->m_symbol_table.add_function("cent", harmonic_cent_func);
m_data->m_symbol_table.add_function("semitone", harmonic_semitone_func);
m_data->m_symbol_table.add_function("rand", simple_rand);
m_data->m_symbol_table.add_function("randv", m_data->m_rand_vec);
m_data->m_symbol_table.add_function("randsv", randsv_func);
m_data->m_symbol_table.add_function("last", m_data->m_last_func);
}
catch(...)
{
WARN_EXPRTK;
}
}
ExprFront::~ExprFront()
{
try
{
delete m_data;
}
catch(...)
{
WARN_EXPRTK;
}
}
bool ExprFront::compile()
{
m_valid = false;
try
{
m_data->m_expression.register_symbol_table(m_data->m_symbol_table);
parser_t::settings_store sstore;
sstore.disable_all_logic_ops();
sstore.disable_all_assignment_ops();
sstore.disable_all_control_structures();
parser_t parser(sstore);
m_valid=parser.compile(m_data->m_expression_string, m_data->m_expression);
}
catch(...)
{
WARN_EXPRTK;
}
return m_valid;
}
float ExprFront::evaluate()
{
try
{
if (!m_valid) return 0;
float res = m_data->m_expression.value();
m_data->m_last_func.setLastSample(res);
return res;
}
catch(...)
{
WARN_EXPRTK;
}
return 0;
}
bool ExprFront::add_variable(const char* name, float& ref)
{
try
{
return m_data->m_symbol_table.add_variable(name, ref);
}
catch(...)
{
WARN_EXPRTK;
}
return false;
}
bool ExprFront::add_constant(const char* name, float ref)
{
try
{
return m_data->m_symbol_table.add_constant(name, ref);
}
catch(...)
{
WARN_EXPRTK;
}
return false;
}
bool ExprFront::add_cyclic_vector(const char* name, const float* data, size_t length, bool interp)
{
try
{
if (interp)
{
auto wvf = new WaveValueFunctionInterpolate<float>(data, length);
m_data->m_cyclics_interp.push_back(wvf);
return m_data->m_symbol_table.add_function(name, *wvf);
}
else
{
auto wvf = new WaveValueFunction<float>(data, length);
m_data->m_cyclics.push_back(wvf);
return m_data->m_symbol_table.add_function(name, *wvf);
}
}
catch(...)
{
WARN_EXPRTK;
}
return false;
}
size_t find_occurances(const std::string& haystack, const char* const needle)
{
size_t last_pos = 0;
size_t count = 0;
const size_t len = strlen(needle);
if (len > 0)
{
while (last_pos + len <= haystack.length())
{
last_pos = haystack.find(needle, last_pos);
if (last_pos == std::string::npos)
break;
++count;
last_pos += len;
}
}
return count;
}
void ExprFront::setIntegrate(const unsigned int* const frameCounter, const unsigned int sample_rate)
{
if (m_data->m_integ_func == nullptr)
{
const unsigned int ointeg = find_occurances(m_data->m_expression_string,"integrate");
if ( ointeg > 0 )
{
m_data->m_integ_func = new IntegrateFunction<float>(frameCounter,sample_rate,ointeg);
try
{
m_data->m_symbol_table.add_function("integrate",*m_data->m_integ_func);
}
catch(...)
{
WARN_EXPRTK;
}
}
}
}
ExprSynth::ExprSynth(const WaveSample *gW1, const WaveSample *gW2, const WaveSample *gW3,
ExprFront *exprO1, ExprFront *exprO2,
NotePlayHandle *nph, const sample_rate_t sample_rate,
const FloatModel* pan1, const FloatModel* pan2, float rel_trans):
m_exprO1(exprO1),
m_exprO2(exprO2),
m_W1(gW1),
m_W2(gW2),
m_W3(gW3),
m_nph(nph),
m_sample_rate(sample_rate),
m_pan1(pan1),
m_pan2(pan2),
m_rel_transition(rel_trans)
{
m_note_sample = 0;
m_note_rel_sample = 0;
m_note_rel_sec = 0;
m_note_sample_sec = 0;
m_released = 0;
m_frequency = m_nph->frequency();
m_rel_inc = 1000.0 / (m_sample_rate * m_rel_transition);//rel_transition in ms. compute how much increment in each frame
auto init_expression_step2 = [this](ExprFront * e) {
e->add_cyclic_vector("W1", m_W1->m_samples,m_W1->m_length, m_W1->m_interpolate);
e->add_cyclic_vector("W2", m_W2->m_samples,m_W2->m_length, m_W2->m_interpolate);
e->add_cyclic_vector("W3", m_W3->m_samples,m_W3->m_length, m_W3->m_interpolate);
e->add_variable("t", m_note_sample_sec);
e->add_variable("f", m_frequency);
e->add_variable("rel",m_released);
e->add_variable("trel",m_note_rel_sec);
e->setIntegrate(&m_note_sample,m_sample_rate);
e->compile();
};
init_expression_step2(m_exprO1);
init_expression_step2(m_exprO2);
}
ExprSynth::~ExprSynth()
{
if (m_exprO1)
{
delete m_exprO1;
}
if (m_exprO2)
{
delete m_exprO2;
}
}
void ExprSynth::renderOutput(fpp_t frames, SampleFrame* buf)
{
try
{
bool o1_valid = m_exprO1->isValid();
bool o2_valid = m_exprO2->isValid();
if (!o1_valid && !o2_valid)
{
return;
}
float o1 = 0, o2 = 0;
float pn1 = m_pan1->value() * 0.5;
float pn2 = m_pan2->value() * 0.5;
const float new_freq = m_nph->frequency();
const float freq_inc = (new_freq - m_frequency) / frames;
const bool is_released = m_nph->isReleased();
expression_t *o1_rawExpr = &(m_exprO1->getData()->m_expression);
expression_t *o2_rawExpr = &(m_exprO2->getData()->m_expression);
LastSampleFunction<float> * last_func1 = &m_exprO1->getData()->m_last_func;
LastSampleFunction<float> * last_func2 = &m_exprO2->getData()->m_last_func;
if (is_released && m_note_rel_sample == 0)
{
m_note_rel_sample = m_note_sample;
}
if (o1_valid && o2_valid)
{
for (fpp_t frame = 0; frame < frames ; ++frame)
{
if (is_released && m_released < 1)
{
m_released = fmin(m_released+m_rel_inc, 1);
}
o1 = o1_rawExpr->value();
o2 = o2_rawExpr->value();
last_func1->setLastSample(o1);//put result in the circular buffer for the "last" function.
last_func2->setLastSample(o2);
buf[frame][0] = (-pn1 + 0.5) * o1 + (-pn2 + 0.5) * o2;
buf[frame][1] = ( pn1 + 0.5) * o1 + ( pn2 + 0.5) * o2;
m_note_sample++;
m_note_sample_sec = m_note_sample / (float)m_sample_rate;
if (is_released)
{
m_note_rel_sec = (m_note_sample - m_note_rel_sample) / (float)m_sample_rate;
}
m_frequency += freq_inc;
}
}
else
{
if (o2_valid)
{
o1_rawExpr = o2_rawExpr;
last_func1 = last_func2;
pn1 = pn2;
}
for (fpp_t frame = 0; frame < frames ; ++frame)
{
if (is_released && m_released < 1)
{
m_released = fmin(m_released+m_rel_inc, 1);
}
o1 = o1_rawExpr->value();
last_func1->setLastSample(o1);
buf[frame][0] = (-pn1 + 0.5) * o1;
buf[frame][1] = ( pn1 + 0.5) * o1;
m_note_sample++;
m_note_sample_sec = m_note_sample / (float)m_sample_rate;
if (is_released)
{
m_note_rel_sec = (m_note_sample - m_note_rel_sample) / (float)m_sample_rate;
}
m_frequency += freq_inc;
}
}
m_frequency = new_freq;
}
catch(...)
{
WARN_EXPRTK;
}
}
} // namespace lmms
| 21,018
|
C++
|
.cpp
| 768
| 24.957031
| 157
| 0.709374
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,660
|
SidInstrument.cpp
|
LMMS_lmms/plugins/Sid/SidInstrument.cpp
|
/*
* SidInstrument.cpp - ResID based software-synthesizer
*
* Copyright (c) 2008 Csaba Hruska <csaba.hruska/at/gmail.com>
* Attila Herman <attila589/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include <cmath>
#include <cstdio>
#include <sid.h>
#include "SidInstrument.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "NotePlayHandle.h"
#include "PixmapButton.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
#define C64_PAL_CYCLES_PER_SEC 985248
#define NUMSIDREGS 0x19
#define SIDWRITEDELAY 9 // lda $xxxx,x 4 cycles, sta $d400,x 5 cycles
#define SIDWAVEDELAY 4 // and $xxxx,x 4 cycles extra
auto sidorder = std::array<unsigned char, 25>
{0x15,0x16,0x18,0x17,
0x05,0x06,0x02,0x03,0x00,0x01,0x04,
0x0c,0x0d,0x09,0x0a,0x07,0x08,0x0b,
0x13,0x14,0x10,0x11,0x0e,0x0f,0x12};
static auto attackTime = std::array<const char*, 16>{ "2 ms", "8 ms", "16 ms", "24 ms",
"38 ms", "56 ms", "68 ms", "80 ms",
"100 ms", "250 ms", "500 ms", "800 ms",
"1 s", "3 s", "5 s", "8 s" };
static auto decRelTime = std::array<const char*, 16>{ "6 ms", "24 ms", "48 ms", "72 ms",
"114 ms", "168 ms", "204 ms", "240 ms",
"300 ms", "750 ms", "1.5 s", "2.4 s",
"3 s", "9 s", "15 s", "24 s" };
// release time time in ms
static const auto relTime = std::array{ 6, 24, 48, 72, 114, 168, 204, 240, 300, 750,
1500, 2400, 3000, 9000, 15000, 24000 };
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT sid_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"SID",
QT_TRANSLATE_NOOP( "PluginBrowser", "Emulation of the MOS6581 and MOS8580 "
"SID.\nThis chip was used in the Commodore 64 computer." ),
"Csaba Hruska <csaba.hruska/at/gmail.com>"
"Attila Herman <attila589/at/gmail.com>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
VoiceObject::VoiceObject( Model * _parent, int _idx ) :
Model( _parent ),
m_pulseWidthModel( 2048.0f, 0.0f, 4095.0f, 1.0f, this,
tr( "Voice %1 pulse width" ).arg( _idx+1 ) ),
m_attackModel( 8.0f, 0.0f, 15.0f, 1.0f, this,
tr( "Voice %1 attack" ).arg( _idx+1 ) ),
m_decayModel( 8.0f, 0.0f, 15.0f, 1.0f, this,
tr( "Voice %1 decay" ).arg( _idx+1 ) ),
m_sustainModel( 15.0f, 0.0f, 15.0f, 1.0f, this,
tr( "Voice %1 sustain" ).arg( _idx+1 ) ),
m_releaseModel( 8.0f, 0.0f, 15.0f, 1.0f, this,
tr( "Voice %1 release" ).arg( _idx+1 ) ),
m_coarseModel( 0.0f, -24.0, 24.0, 1.0f, this,
tr( "Voice %1 coarse detuning" ).arg( _idx+1 ) ),
m_waveFormModel( static_cast<int>(WaveForm::Triangle), 0, NumWaveShapes-1, this,
tr( "Voice %1 wave shape" ).arg( _idx+1 ) ),
m_syncModel( false, this, tr( "Voice %1 sync" ).arg( _idx+1 ) ),
m_ringModModel( false, this, tr( "Voice %1 ring modulate" ).arg( _idx+1 ) ),
m_filteredModel( false, this, tr( "Voice %1 filtered" ).arg( _idx+1 ) ),
m_testModel( false, this, tr( "Voice %1 test" ).arg( _idx+1 ) )
{
}
SidInstrument::SidInstrument( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &sid_plugin_descriptor ),
// filter
m_filterFCModel( 1024.0f, 0.0f, 2047.0f, 1.0f, this, tr( "Cutoff frequency" ) ),
m_filterResonanceModel( 8.0f, 0.0f, 15.0f, 1.0f, this, tr( "Resonance" ) ),
m_filterModeModel( static_cast<int>(FilterType::LowPass), 0, NumFilterTypes-1, this, tr( "Filter type" )),
// misc
m_voice3OffModel( false, this, tr( "Voice 3 off" ) ),
m_volumeModel( 15.0f, 0.0f, 15.0f, 1.0f, this, tr( "Volume" ) ),
m_chipModel( static_cast<int>(ChipModel::MOS8580), 0, NumChipModels-1, this, tr( "Chip model" ) )
{
for( int i = 0; i < 3; ++i )
{
m_voice[i] = new VoiceObject( this, i );
}
}
void SidInstrument::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
// voices
for( int i = 0; i < 3; ++i )
{
const QString is = QString::number( i );
m_voice[i]->m_pulseWidthModel.saveSettings(
_doc, _this, "pulsewidth" + is );
m_voice[i]->m_attackModel.saveSettings(
_doc, _this, "attack" + is );
m_voice[i]->m_decayModel.saveSettings(
_doc, _this, "decay" + is );
m_voice[i]->m_sustainModel.saveSettings(
_doc, _this, "sustain" + is );
m_voice[i]->m_releaseModel.saveSettings(
_doc, _this, "release" + is );
m_voice[i]->m_coarseModel.saveSettings(
_doc, _this, "coarse" + is );
m_voice[i]->m_waveFormModel.saveSettings(
_doc, _this,"waveform" + is );
m_voice[i]->m_syncModel.saveSettings(
_doc, _this, "sync" + is );
m_voice[i]->m_ringModModel.saveSettings(
_doc, _this, "ringmod" + is );
m_voice[i]->m_filteredModel.saveSettings(
_doc, _this,"filtered" + is );
m_voice[i]->m_testModel.saveSettings(
_doc, _this, "test" + is );
}
// filter
m_filterFCModel.saveSettings( _doc, _this, "filterFC" );
m_filterResonanceModel.saveSettings( _doc, _this, "filterResonance" );
m_filterModeModel.saveSettings( _doc, _this, "filterMode" );
// misc
m_voice3OffModel.saveSettings( _doc, _this, "voice3Off" );
m_volumeModel.saveSettings( _doc, _this, "volume" );
m_chipModel.saveSettings( _doc, _this, "chipModel" );
}
void SidInstrument::loadSettings( const QDomElement & _this )
{
// voices
for( int i = 0; i < 3; ++i )
{
const QString is = QString::number( i );
m_voice[i]->m_pulseWidthModel.loadSettings( _this, "pulsewidth" + is );
m_voice[i]->m_attackModel.loadSettings( _this, "attack" + is );
m_voice[i]->m_decayModel.loadSettings( _this, "decay" + is );
m_voice[i]->m_sustainModel.loadSettings( _this, "sustain" + is );
m_voice[i]->m_releaseModel.loadSettings( _this, "release" + is );
m_voice[i]->m_coarseModel.loadSettings( _this, "coarse" + is );
m_voice[i]->m_waveFormModel.loadSettings( _this, "waveform" + is );
m_voice[i]->m_syncModel.loadSettings( _this, "sync" + is );
m_voice[i]->m_ringModModel.loadSettings( _this, "ringmod" + is );
m_voice[i]->m_filteredModel.loadSettings( _this, "filtered" + is );
m_voice[i]->m_testModel.loadSettings( _this, "test" + is );
}
// filter
m_filterFCModel.loadSettings( _this, "filterFC" );
m_filterResonanceModel.loadSettings( _this, "filterResonance" );
m_filterModeModel.loadSettings( _this, "filterMode" );
// misc
m_voice3OffModel.loadSettings( _this, "voice3Off" );
m_volumeModel.loadSettings( _this, "volume" );
m_chipModel.loadSettings( _this, "chipModel" );
}
QString SidInstrument::nodeName() const
{
return( sid_plugin_descriptor.name );
}
float SidInstrument::desiredReleaseTimeMs() const
{
int maxrel = 0;
for (const auto& voice : m_voice)
{
maxrel = std::max(maxrel, static_cast<int>(voice->m_releaseModel.value()));
}
return computeReleaseTimeMsByFrameCount(relTime[maxrel]);
}
static int sid_fillbuffer(unsigned char* sidreg, reSID::SID *sid, int tdelta, short *ptr, int samples)
{
int total = 0;
// customly added
int residdelay = 0;
int badline = rand() % NUMSIDREGS;
for (int c = 0; c < NUMSIDREGS; c++)
{
unsigned char o = sidorder[c];
// Extra delay for loading the waveform (and mt_chngate,x)
if ((o == 4) || (o == 11) || (o == 18))
{
int tdelta2 = SIDWAVEDELAY;
int result = sid->clock(tdelta2, ptr, samples);
total += result;
ptr += result;
samples -= result;
tdelta -= SIDWAVEDELAY;
}
// Possible random badline delay once per writing
if ((badline == c) && (residdelay))
{
int tdelta2 = residdelay;
int result = sid->clock(tdelta2, ptr, samples);
total += result;
ptr += result;
samples -= result;
tdelta -= residdelay;
}
sid->write(o, sidreg[o]);
int tdelta2 = SIDWRITEDELAY;
int result = sid->clock(tdelta2, ptr, samples);
total += result;
ptr += result;
samples -= result;
tdelta -= SIDWRITEDELAY;
}
int result = sid->clock(tdelta, ptr, samples);
total += result;
return total;
}
void SidInstrument::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
const int clockrate = C64_PAL_CYCLES_PER_SEC;
const int samplerate = Engine::audioEngine()->outputSampleRate();
if (!_n->m_pluginData)
{
auto sid = new reSID::SID();
sid->set_sampling_parameters(clockrate, reSID::SAMPLE_FAST, samplerate);
sid->set_chip_model(reSID::MOS8580);
sid->enable_filter( true );
sid->reset();
_n->m_pluginData = sid;
}
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
auto sid = static_cast<reSID::SID*>(_n->m_pluginData);
int delta_t = clockrate * frames / samplerate + 4;
#ifndef _MSC_VER
short buf[frames];
#else
const auto buf = static_cast<short*>(_alloca(frames * sizeof(short)));
#endif
auto sidreg = std::array<unsigned char, NUMSIDREGS>{};
for (auto& reg : sidreg)
{
reg = 0x00;
}
if( (ChipModel)m_chipModel.value() == ChipModel::MOS6581 )
{
sid->set_chip_model(reSID::MOS6581);
}
else
{
sid->set_chip_model(reSID::MOS8580);
}
// voices
reSID::reg8 data8 = 0;
reSID::reg16 data16 = 0;
size_t base = 0;
float freq = 0.0;
float note = 0.0;
for (size_t i = 0; i < 3; ++i)
{
base = i*7;
// freq ( Fn = Fout / Fclk * 16777216 ) + coarse detuning
freq = _n->frequency();
note = 69.0 + 12.0 * log( freq / 440.0 ) / log( 2 );
note += m_voice[i]->m_coarseModel.value();
freq = 440.0 * pow( 2.0, (note-69.0)/12.0 );
data16 = int( freq / float(clockrate) * 16777216.0 );
sidreg[base+0] = data16&0x00FF;
sidreg[base+1] = (data16>>8)&0x00FF;
// pw
data16 = (int)m_voice[i]->m_pulseWidthModel.value();
sidreg[base+2] = data16&0x00FF;
sidreg[base+3] = (data16>>8)&0x000F;
// control: wave form, (test), ringmod, sync, gate
data8 = _n->isReleased()?0:1;
data8 += m_voice[i]->m_syncModel.value()?2:0;
data8 += m_voice[i]->m_ringModModel.value()?4:0;
data8 += m_voice[i]->m_testModel.value()?8:0;
switch( static_cast<VoiceObject::WaveForm>(m_voice[i]->m_waveFormModel.value()) )
{
default: break;
case VoiceObject::WaveForm::Noise: data8 += 128; break;
case VoiceObject::WaveForm::Square: data8 += 64; break;
case VoiceObject::WaveForm::Saw: data8 += 32; break;
case VoiceObject::WaveForm::Triangle: data8 += 16; break;
}
sidreg[base+4] = data8&0x00FF;
// ad
data16 = (int)m_voice[i]->m_attackModel.value();
data8 = (data16&0x0F)<<4;
data16 = (int)m_voice[i]->m_decayModel.value();
data8 += (data16&0x0F);
sidreg[base+5] = data8&0x00FF;
// sr
data16 = (int)m_voice[i]->m_sustainModel.value();
data8 = (data16&0x0F)<<4;
data16 = (int)m_voice[i]->m_releaseModel.value();
data8 += (data16&0x0F);
sidreg[base+6] = data8&0x00FF;
}
// filtered
// FC (FilterCutoff)
data16 = (int)m_filterFCModel.value();
sidreg[21] = data16&0x0007;
sidreg[22] = (data16>>3)&0x00FF;
// res, filt ex,3,2,1
data16 = (int)m_filterResonanceModel.value();
data8 = (data16&0x000F)<<4;
data8 += m_voice[2]->m_filteredModel.value()?4:0;
data8 += m_voice[1]->m_filteredModel.value()?2:0;
data8 += m_voice[0]->m_filteredModel.value()?1:0;
sidreg[23] = data8&0x00FF;
// mode vol
data16 = (int)m_volumeModel.value();
data8 = data16&0x000F;
data8 += m_voice3OffModel.value()?128:0;
switch( static_cast<FilterType>(m_filterModeModel.value()) )
{
default: break;
case FilterType::LowPass: data8 += 16; break;
case FilterType::BandPass: data8 += 32; break;
case FilterType::HighPass: data8 += 64; break;
}
sidreg[24] = data8&0x00FF;
const auto num = static_cast<f_cnt_t>(sid_fillbuffer(sidreg.data(), sid, delta_t, buf, frames));
if (num != frames) {
printf("!!!Not enough samples\n");
}
// loop backwards to avoid overwriting data in the short-to-float conversion
for (auto frame = std::size_t{0}; frame < frames; ++frame)
{
sample_t s = float(buf[frame])/32768.0;
for( ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch )
{
_working_buffer[frame+offset][ch] = s;
}
}
}
void SidInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<reSID::SID*>(_n->m_pluginData);
}
gui::PluginView* SidInstrument::instantiateView( QWidget * _parent )
{
return( new gui::SidInstrumentView( this, _parent ) );
}
namespace gui
{
class sidKnob : public Knob
{
public:
sidKnob( QWidget * _parent ) :
Knob( KnobType::Styled, _parent )
{
setFixedSize( 16, 16 );
setCenterPointX( 7.5 );
setCenterPointY( 7.5 );
setInnerRadius( 2 );
setOuterRadius( 8 );
setTotalAngle( 270.0 );
setLineWidth( 2 );
}
};
SidInstrumentView::SidInstrumentView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
m_volKnob = new sidKnob( this );
m_volKnob->setHintText( tr( "Volume:" ), "" );
m_volKnob->move( 7, 64 );
m_resKnob = new sidKnob( this );
m_resKnob->setHintText( tr( "Resonance:" ), "" );
m_resKnob->move( 7 + 28, 64 );
m_cutKnob = new sidKnob( this );
m_cutKnob->setHintText( tr( "Cutoff frequency:" ), " Hz" );
m_cutKnob->move( 7 + 2*28, 64 );
auto hp_btn = new PixmapButton(this, nullptr);
hp_btn->move( 140, 77 );
hp_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "hpred" ) );
hp_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "hp" ) );
hp_btn->setToolTip(tr("High-pass filter "));
auto bp_btn = new PixmapButton(this, nullptr);
bp_btn->move( 164, 77 );
bp_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "bpred" ) );
bp_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "bp" ) );
bp_btn->setToolTip(tr("Band-pass filter "));
auto lp_btn = new PixmapButton(this, nullptr);
lp_btn->move( 185, 77 );
lp_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "lpred" ) );
lp_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "lp" ) );
lp_btn->setToolTip(tr("Low-pass filter "));
m_passBtnGrp = new automatableButtonGroup( this );
m_passBtnGrp->addButton( hp_btn );
m_passBtnGrp->addButton( bp_btn );
m_passBtnGrp->addButton( lp_btn );
m_offButton = new PixmapButton( this, nullptr );
m_offButton->setCheckable( true );
m_offButton->move( 207, 77 );
m_offButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "3offred" ) );
m_offButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "3off" ) );
m_offButton->setToolTip(tr("Voice 3 off "));
auto mos6581_btn = new PixmapButton(this, nullptr);
mos6581_btn->move( 170, 59 );
mos6581_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "6581red" ) );
mos6581_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "6581" ) );
mos6581_btn->setToolTip(tr("MOS6581 SID "));
auto mos8580_btn = new PixmapButton(this, nullptr);
mos8580_btn->move( 207, 59 );
mos8580_btn->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "8580red" ) );
mos8580_btn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "8580" ) );
mos8580_btn->setToolTip(tr("MOS8580 SID "));
m_sidTypeBtnGrp = new automatableButtonGroup( this );
m_sidTypeBtnGrp->addButton( mos6581_btn );
m_sidTypeBtnGrp->addButton( mos8580_btn );
for( int i = 0; i < 3; i++ )
{
Knob *ak = new sidKnob( this );
ak->setHintText( tr("Attack:"), "" );
ak->move( 7, 114 + i*50 );
Knob *dk = new sidKnob( this );
dk->setHintText( tr("Decay:") , "" );
dk->move( 7 + 28, 114 + i*50 );
Knob *sk = new sidKnob( this );
sk->setHintText( tr("Sustain:"), "" );
sk->move( 7 + 2*28, 114 + i*50 );
Knob *rk = new sidKnob( this );
rk->setHintText( tr("Release:"), "" );
rk->move( 7 + 3*28, 114 + i*50 );
Knob *pwk = new sidKnob( this );
pwk->setHintText( tr("Pulse Width:"), "" );
pwk->move( 7 + 4*28, 114 + i*50 );
Knob *crsk = new sidKnob( this );
crsk->setHintText( tr("Coarse:"), " semitones" );
crsk->move( 147, 114 + i*50 );
auto pulse_btn = new PixmapButton(this, nullptr);
pulse_btn->move( 187, 101 + i*50 );
pulse_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "pulsered" ) );
pulse_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "pulse" ) );
pulse_btn->setToolTip(tr("Pulse wave"));
auto triangle_btn = new PixmapButton(this, nullptr);
triangle_btn->move( 168, 101 + i*50 );
triangle_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "trianglered" ) );
triangle_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "triangle" ) );
triangle_btn->setToolTip(tr("Triangle wave"));
auto saw_btn = new PixmapButton(this, nullptr);
saw_btn->move( 207, 101 + i*50 );
saw_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "sawred" ) );
saw_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "saw" ) );
saw_btn->setToolTip(tr("Saw wave"));
auto noise_btn = new PixmapButton(this, nullptr);
noise_btn->move( 226, 101 + i*50 );
noise_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "noisered" ) );
noise_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "noise" ) );
noise_btn->setToolTip(tr("Noise"));
auto wfbg = new automatableButtonGroup(this);
wfbg->addButton( pulse_btn );
wfbg->addButton( triangle_btn );
wfbg->addButton( saw_btn );
wfbg->addButton( noise_btn );
auto sync_btn = new PixmapButton(this, nullptr);
sync_btn->setCheckable( true );
sync_btn->move( 207, 134 + i*50 );
sync_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "syncred" ) );
sync_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "sync" ) );
sync_btn->setToolTip(tr("Sync"));
auto ringMod_btn = new PixmapButton(this, nullptr);
ringMod_btn->setCheckable( true );
ringMod_btn->move( 170, 116 + i*50 );
ringMod_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "ringred" ) );
ringMod_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "ring" ) );
ringMod_btn->setToolTip(tr("Ring modulation"));
auto filter_btn = new PixmapButton(this, nullptr);
filter_btn->setCheckable( true );
filter_btn->move( 207, 116 + i*50 );
filter_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "filterred" ) );
filter_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "filter" ) );
filter_btn->setToolTip(tr("Filtered"));
auto test_btn = new PixmapButton(this, nullptr);
test_btn->setCheckable( true );
test_btn->move( 170, 134 + i*50 );
test_btn->setActiveGraphic(
PLUGIN_NAME::getIconPixmap( "testred" ) );
test_btn->setInactiveGraphic(
PLUGIN_NAME::getIconPixmap( "test" ) );
test_btn->setToolTip(tr("Test"));
m_voiceKnobs[i] = voiceKnobs( ak, dk, sk, rk, pwk, crsk, wfbg,
sync_btn, ringMod_btn, filter_btn, test_btn );
}
}
void SidInstrumentView::updateKnobHint()
{
auto k = castModel<SidInstrument>();
for( int i = 0; i < 3; ++i )
{
m_voiceKnobs[i].m_attKnob->setHintText( tr( "Attack:" ) + " ", " (" +
QString::fromLatin1( attackTime[(int)k->m_voice[i]->
m_attackModel.value()] ) + ")" );
m_voiceKnobs[i].m_attKnob->setToolTip(
attackTime[(int)k->m_voice[i]->m_attackModel.value()] );
m_voiceKnobs[i].m_decKnob->setHintText( tr( "Decay:" ) + " ", " (" +
QString::fromLatin1( decRelTime[(int)k->m_voice[i]->
m_decayModel.value()] ) + ")" );
m_voiceKnobs[i].m_decKnob->setToolTip(
decRelTime[(int)k->m_voice[i]->m_decayModel.value()] );
m_voiceKnobs[i].m_relKnob->setHintText( tr( "Release:" ) + " ", " (" +
QString::fromLatin1( decRelTime[(int)k->m_voice[i]->
m_releaseModel.value()] ) + ")" );
m_voiceKnobs[i].m_relKnob->setToolTip(
decRelTime[(int)k->m_voice[i]->m_releaseModel.value()]);
m_voiceKnobs[i].m_pwKnob->setHintText( tr( "Pulse width:" )+ " ", " (" +
QString::number( (double)k->m_voice[i]->
m_pulseWidthModel.value() / 40.95 ) + "%)" );
m_voiceKnobs[i].m_pwKnob->setToolTip(
QString::number( (double)k->m_voice[i]->
m_pulseWidthModel.value() / 40.95 ) + "%" );
}
m_cutKnob->setHintText( tr( "Cutoff frequency:" ) + " ", " (" +
QString::number ( (int) ( 9970.0 / 2047.0 *
(double)k->m_filterFCModel.value() + 30.0 ) ) + " Hz)" );
m_cutKnob->setToolTip(QString::number((int) (9970.0 / 2047.0 *
(double)k->m_filterFCModel.value() + 30.0 ) ) + " Hz" );
}
void SidInstrumentView::updateKnobToolTip()
{
auto k = castModel<SidInstrument>();
for( int i = 0; i < 3; ++i )
{
m_voiceKnobs[i].m_sustKnob->setToolTip(
QString::number( (int)k->m_voice[i]->m_sustainModel.value() ) );
m_voiceKnobs[i].m_crsKnob->setToolTip(
QString::number( (int)k->m_voice[i]->m_coarseModel.value() ) +
" semitones" );
}
m_volKnob->setToolTip(
QString::number( (int)k->m_volumeModel.value() ) );
m_resKnob->setToolTip(
QString::number( (int)k->m_filterResonanceModel.value() ) );
}
void SidInstrumentView::modelChanged()
{
auto k = castModel<SidInstrument>();
m_volKnob->setModel( &k->m_volumeModel );
m_resKnob->setModel( &k->m_filterResonanceModel );
m_cutKnob->setModel( &k->m_filterFCModel );
m_passBtnGrp->setModel( &k->m_filterModeModel );
m_offButton->setModel( &k->m_voice3OffModel );
m_sidTypeBtnGrp->setModel( &k->m_chipModel );
for( int i = 0; i < 3; ++i )
{
m_voiceKnobs[i].m_attKnob->setModel(
&k->m_voice[i]->m_attackModel );
m_voiceKnobs[i].m_decKnob->setModel(
&k->m_voice[i]->m_decayModel );
m_voiceKnobs[i].m_sustKnob->setModel(
&k->m_voice[i]->m_sustainModel );
m_voiceKnobs[i].m_relKnob->setModel(
&k->m_voice[i]->m_releaseModel );
m_voiceKnobs[i].m_pwKnob->setModel(
&k->m_voice[i]->m_pulseWidthModel );
m_voiceKnobs[i].m_crsKnob->setModel(
&k->m_voice[i]->m_coarseModel );
m_voiceKnobs[i].m_waveFormBtnGrp->setModel(
&k->m_voice[i]->m_waveFormModel );
m_voiceKnobs[i].m_syncButton->setModel(
&k->m_voice[i]->m_syncModel );
m_voiceKnobs[i].m_ringModButton->setModel(
&k->m_voice[i]->m_ringModModel );
m_voiceKnobs[i].m_filterButton->setModel(
&k->m_voice[i]->m_filteredModel );
m_voiceKnobs[i].m_testButton->setModel(
&k->m_voice[i]->m_testModel );
}
for (const auto& voice : k->m_voice)
{
connect(&voice->m_attackModel, SIGNAL(dataChanged()), this, SLOT(updateKnobHint()));
connect(&voice->m_decayModel, SIGNAL(dataChanged()), this, SLOT(updateKnobHint()));
connect(&voice->m_releaseModel, SIGNAL(dataChanged()), this, SLOT(updateKnobHint()));
connect(&voice->m_pulseWidthModel, SIGNAL(dataChanged()), this, SLOT(updateKnobHint()));
connect(&voice->m_sustainModel, SIGNAL(dataChanged()), this, SLOT(updateKnobToolTip()));
connect(&voice->m_coarseModel, SIGNAL(dataChanged()), this, SLOT(updateKnobToolTip()));
}
connect( &k->m_volumeModel, SIGNAL( dataChanged() ),
this, SLOT( updateKnobToolTip() ) );
connect( &k->m_filterResonanceModel, SIGNAL( dataChanged() ),
this, SLOT( updateKnobToolTip() ) );
connect( &k->m_filterFCModel, SIGNAL( dataChanged() ),
this, SLOT( updateKnobHint() ) );
updateKnobHint();
updateKnobToolTip();
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return( new SidInstrument( static_cast<InstrumentTrack *>( m ) ) );
}
}
} // namespace lmms
| 23,890
|
C++
|
.cpp
| 636
| 34.418239
| 107
| 0.66632
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,661
|
ReverbSCControlDialog.cpp
|
LMMS_lmms/plugins/ReverbSC/ReverbSCControlDialog.cpp
|
/*
* ReverbSCControlDialog.cpp - control dialog for ReverbSC
*
* Copyright (c) 2017 Paul Batchelor
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "ReverbSCControlDialog.h"
#include "embed.h"
#include "Knob.h"
#include "ReverbSCControls.h"
namespace lmms::gui
{
ReverbSCControlDialog::ReverbSCControlDialog( ReverbSCControls* controls ) :
EffectControlDialog( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 185, 55 );
auto inputGainKnob = new Knob(KnobType::Bright26, this);
inputGainKnob -> move( 16, 10 );
inputGainKnob->setModel( &controls->m_inputGainModel );
inputGainKnob->setLabel( tr( "Input" ) );
inputGainKnob->setHintText( tr( "Input gain:" ) , "dB" );
auto sizeKnob = new Knob(KnobType::Bright26, this);
sizeKnob -> move( 57, 10 );
sizeKnob->setModel( &controls->m_sizeModel );
sizeKnob->setLabel( tr( "Size" ) );
sizeKnob->setHintText( tr( "Size:" ) , "" );
auto colorKnob = new Knob(KnobType::Bright26, this);
colorKnob -> move( 98, 10 );
colorKnob->setModel( &controls->m_colorModel );
colorKnob->setLabel( tr( "Color" ) );
colorKnob->setHintText( tr( "Color:" ) , "" );
auto outputGainKnob = new Knob(KnobType::Bright26, this);
outputGainKnob -> move( 139, 10 );
outputGainKnob->setModel( &controls->m_outputGainModel );
outputGainKnob->setLabel( tr( "Output" ) );
outputGainKnob->setHintText( tr( "Output gain:" ) , "dB" );
}
} // namespace lmms::gui
| 2,282
|
C++
|
.cpp
| 59
| 36.677966
| 76
| 0.732369
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,664
|
VstEffectControlDialog.cpp
|
LMMS_lmms/plugins/VstEffect/VstEffectControlDialog.cpp
|
/*
* VstEffectControlDialog.cpp - dialog for displaying VST-effect GUI
*
* Copyright (c) 2006-2011 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QLayout>
#include <QMenu>
#include <QPushButton>
#include "VstEffectControlDialog.h"
#include "VstEffect.h"
#include "VstPlugin.h"
#include "PixmapButton.h"
#include "embed.h"
#include "FontHelper.h"
#include <QToolBar>
#include <QLabel>
namespace lmms::gui
{
VstEffectControlDialog::VstEffectControlDialog( VstEffectControls * _ctl ) :
EffectControlDialog( _ctl ),
m_pluginWidget( nullptr ),
m_plugin( nullptr ),
tbLabel( nullptr )
{
#if QT_VERSION < 0x50C00
// Workaround for a bug in Qt versions below 5.12,
// where argument-dependent-lookup fails for QFlags operators
// declared inside a namepsace.
// This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h
// See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348
using ::operator|;
#endif
auto l = new QGridLayout(this);
l->setContentsMargins( 10, 10, 10, 10 );
l->setVerticalSpacing( 2 );
l->setHorizontalSpacing( 2 );
bool embed_vst = false;
if( _ctl != nullptr && _ctl->m_effect != nullptr &&
_ctl->m_effect->m_plugin != nullptr )
{
m_plugin = _ctl->m_effect->m_plugin;
embed_vst = m_plugin->embedMethod() != "none";
if (embed_vst) {
if (m_plugin->hasEditor() && ! m_plugin->pluginWidget()) {
m_plugin->createUI(this);
}
m_pluginWidget = m_plugin->pluginWidget();
}
}
if (m_plugin)
{
setWindowTitle( m_plugin->name() );
auto btn = new QPushButton(tr("Show/hide"));
if (embed_vst) {
btn->setCheckable( true );
btn->setChecked( true );
connect( btn, SIGNAL( toggled( bool ) ),
SLOT( togglePluginUI( bool ) ) );
} else {
connect( btn, SIGNAL( clicked() ),
m_plugin.data(), SLOT( toggleUI() ) );
}
btn->setMinimumWidth( 78 );
btn->setMaximumWidth( 78 );
btn->setMinimumHeight( 24 );
btn->setMaximumHeight( 24 );
m_togglePluginButton = btn;
m_managePluginButton = new PixmapButton( this, "" );
m_managePluginButton->setCheckable( false );
m_managePluginButton->setCursor( Qt::PointingHandCursor );
m_managePluginButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"controls_active" ) );
m_managePluginButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"controls" ) );
connect( m_managePluginButton, SIGNAL( clicked() ), _ctl,
SLOT( managePlugin() ) );
m_managePluginButton->setToolTip(tr("Control VST plugin from LMMS host"));
m_managePluginButton->setMinimumWidth( 26 );
m_managePluginButton->setMaximumWidth( 26 );
m_managePluginButton->setMinimumHeight( 21 );
m_managePluginButton->setMaximumHeight( 21 );
m_openPresetButton = new PixmapButton( this, "" );
m_openPresetButton->setCheckable( false );
m_openPresetButton->setCursor( Qt::PointingHandCursor );
m_openPresetButton->setActiveGraphic( embed::getIconPixmap(
"project_open" ) );
m_openPresetButton->setInactiveGraphic( embed::getIconPixmap(
"project_open" ) );
connect( m_openPresetButton, SIGNAL( clicked() ), _ctl,
SLOT( openPreset() ) );
m_openPresetButton->setToolTip(tr("Open VST plugin preset"));
m_openPresetButton->setMinimumWidth( 16 );
m_openPresetButton->setMaximumWidth( 16 );
m_openPresetButton->setMinimumHeight( 16 );
m_openPresetButton->setMaximumHeight( 16 );
m_rolLPresetButton = new PixmapButton( this, "" );
m_rolLPresetButton->setCheckable( false );
m_rolLPresetButton->setCursor( Qt::PointingHandCursor );
m_rolLPresetButton->setActiveGraphic( embed::getIconPixmap(
"stepper-left-press" ) );
m_rolLPresetButton->setInactiveGraphic( embed::getIconPixmap(
"stepper-left" ) );
connect( m_rolLPresetButton, SIGNAL( clicked() ), _ctl,
SLOT( rolrPreset() ) );
connect( m_rolLPresetButton, SIGNAL( clicked() ), this,
SLOT( update() ) );
m_rolLPresetButton->setToolTip(tr("Previous (-)"));
m_rolLPresetButton->setShortcut( Qt::Key_Minus );
m_rolLPresetButton->setMinimumWidth( 16 );
m_rolLPresetButton->setMaximumWidth( 16 );
m_rolLPresetButton->setMinimumHeight( 16 );
m_rolLPresetButton->setMaximumHeight( 16 );
m_rolRPresetButton = new PixmapButton( this, "" );
m_rolRPresetButton->setCheckable( false );
m_rolRPresetButton->setCursor( Qt::PointingHandCursor );
m_rolRPresetButton->setActiveGraphic( embed::getIconPixmap(
"stepper-right-press" ) );
m_rolRPresetButton->setInactiveGraphic( embed::getIconPixmap(
"stepper-right" ) );
connect( m_rolRPresetButton, SIGNAL( clicked() ), _ctl,
SLOT( rollPreset() ) );
connect( m_rolRPresetButton, SIGNAL( clicked() ), this,
SLOT( update() ) );
m_rolRPresetButton->setToolTip(tr("Next (+)"));
m_rolRPresetButton->setShortcut( Qt::Key_Plus );
m_rolRPresetButton->setMinimumWidth( 16 );
m_rolRPresetButton->setMaximumWidth( 16 );
m_rolRPresetButton->setMinimumHeight( 16 );
m_rolRPresetButton->setMaximumHeight( 16 );
_ctl->m_selPresetButton = new QPushButton( tr( "" ), this );
_ctl->m_selPresetButton->setCheckable( false );
_ctl->m_selPresetButton->setCursor( Qt::PointingHandCursor );
_ctl->m_selPresetButton->setIcon( embed::getIconPixmap( "stepper-down" ) );
auto menu = new QMenu;
connect( menu, SIGNAL( aboutToShow() ), _ctl, SLOT( updateMenu() ) );
_ctl->m_selPresetButton->setMenu(menu);
_ctl->m_selPresetButton->setMinimumWidth( 16 );
_ctl->m_selPresetButton->setMaximumWidth( 16 );
_ctl->m_selPresetButton->setMinimumHeight( 16 );
_ctl->m_selPresetButton->setMaximumHeight( 16 );
m_savePresetButton = new PixmapButton( this, "" );
m_savePresetButton->setCheckable( false );
m_savePresetButton->setCursor( Qt::PointingHandCursor );
m_savePresetButton->setActiveGraphic( embed::getIconPixmap(
"project_save", 21, 21 ) );
m_savePresetButton->setInactiveGraphic( embed::getIconPixmap(
"project_save", 21, 21 ) );
connect( m_savePresetButton, SIGNAL( clicked() ), _ctl,
SLOT( savePreset() ) );
m_savePresetButton->setToolTip(tr("Save preset"));
m_savePresetButton->setMinimumWidth( 21 );
m_savePresetButton->setMaximumWidth( 21 );
m_savePresetButton->setMinimumHeight( 21 );
m_savePresetButton->setMaximumHeight( 21 );
int newSize = 0;
if (m_pluginWidget) {
newSize = m_pluginWidget->width() + 20;
}
newSize = std::max(newSize, 250);
auto resize = new QWidget(this);
resize->resize( newSize, 10 );
auto space0 = new QWidget(this);
space0->resize(8, 10);
auto space1 = new QWidget(this);
space1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
QFont f( "Arial", 10 );
l->addItem( new QSpacerItem( newSize - 20, 30, QSizePolicy::Fixed,
QSizePolicy::Fixed ), 1, 0 );
l->addWidget( resize, 2, 0, 1, 1, Qt::AlignCenter );
if (m_pluginWidget) {
l->addWidget( m_pluginWidget, 3, 0, 1, 1, Qt::AlignCenter );
}
l->setRowStretch( 5, 1 );
l->setColumnStretch( 1, 1 );
auto tb = new QToolBar(this);
tb->resize( newSize , 32 );
tb->addWidget(space0);
tb->addWidget( m_rolLPresetButton );
tb->addWidget( m_rolRPresetButton );
tb->addWidget( _ctl->m_selPresetButton );
tb->addWidget( m_openPresetButton );
tb->addWidget( m_savePresetButton );
tb->addWidget( m_managePluginButton );
tb->addWidget( btn );
tb->addWidget(space1);
tbLabel = new QLabel( tr( "Effect by: " ), this );
tbLabel->setFont(adjustedToPixelSize(f, SMALL_FONT_SIZE));
tbLabel->setTextFormat(Qt::RichText);
tbLabel->setAlignment( Qt::AlignTop | Qt::AlignLeft );
tb->addWidget( tbLabel );
}
}
void VstEffectControlDialog::paintEvent( QPaintEvent * )
{
if( m_plugin != nullptr && tbLabel != nullptr )
{
tbLabel->setText( tr( "Effect by: " ) + m_plugin->vendorString() +
tr( " <br />" ) +
m_plugin->currentProgramName() );
}
}
void VstEffectControlDialog::showEvent(QShowEvent *_se)
{
EffectControlDialog::showEvent( _se );
// Workaround for a (unexplained) bug where on project-load the effect
// control window has size 0 and would only restore to the proper size upon
// moving the window or interacting with it.
if (parentWidget()) {
parentWidget()->adjustSize();
}
}
VstEffectControlDialog::~VstEffectControlDialog()
{
if (m_pluginWidget && layout()) {
layout()->removeWidget(m_pluginWidget);
m_pluginWidget->setParent(nullptr);
}
}
void VstEffectControlDialog::togglePluginUI( bool checked )
{
if( !m_plugin ) {
return;
}
if ( m_togglePluginButton->isChecked() != checked ) {
m_togglePluginButton->setChecked( checked );
}
if ( checked ) {
m_plugin->showUI();
} else {
m_plugin->hideUI();
}
}
} // namespace lmms::gui
| 9,526
|
C++
|
.cpp
| 251
| 34.780876
| 77
| 0.713511
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,665
|
VstEffectControls.cpp
|
LMMS_lmms/plugins/VstEffect/VstEffectControls.cpp
|
/*
* VstEffectControls.cpp - controls for VST effect plugins
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QAction>
#include <QDomElement>
#include <QGridLayout>
#include <QMenu>
#include <QPushButton>
#include <QScrollArea>
#include "embed.h"
#include "CustomTextKnob.h"
#include "VstEffectControls.h"
#include "VstEffectControlDialog.h"
#include "VstEffect.h"
#include "VstPlugin.h"
#include "LocaleHelper.h"
#include "MainWindow.h"
#include "GuiApplication.h"
#include "SubWindow.h"
#include <QApplication>
namespace lmms
{
VstEffectControls::VstEffectControls( VstEffect * _eff ) :
EffectControls( _eff ),
m_effect( _eff ),
m_subWindow( nullptr ),
ctrHandle( nullptr ),
lastPosInMenu (0),
m_vstGuiVisible ( true )
// m_presetLabel ( NULL )
{
}
VstEffectControls::~VstEffectControls()
{
delete ctrHandle;
ctrHandle = nullptr;
}
void VstEffectControls::loadSettings( const QDomElement & _this )
{
//m_effect->closePlugin();
//m_effect->openPlugin( _this.attribute( "plugin" ) );
m_effect->m_pluginMutex.lock();
if( m_effect->m_plugin != nullptr )
{
m_vstGuiVisible = _this.attribute( "guivisible" ).toInt();
m_effect->m_plugin->loadSettings( _this );
const QMap<QString, QString> & dump = m_effect->m_plugin->parameterDump();
paramCount = dump.size();
auto paramStr = std::array<char, 35>{};
knobFModel.resize(paramCount);
QStringList s_dumpValues;
for( int i = 0; i < paramCount; i++ )
{
std::snprintf(paramStr.data(), paramStr.size(), "param%d", i);
s_dumpValues = dump[paramStr.data()].split(":");
knobFModel[i] = new FloatModel( 0.0f, 0.0f, 1.0f, 0.01f, this, QString::number(i) );
knobFModel[i]->loadSettings(_this, paramStr.data());
if( !( knobFModel[ i ]->isAutomated() ||
knobFModel[ i ]->controllerConnection() ) )
{
knobFModel[ i ]->setValue(LocaleHelper::toFloat(s_dumpValues.at(2)));
knobFModel[ i ]->setInitValue(LocaleHelper::toFloat(s_dumpValues.at(2)));
}
connect( knobFModel[i], &FloatModel::dataChanged, this,
[this, i]() { setParameter( knobFModel[i] ); }, Qt::DirectConnection);
}
}
m_effect->m_pluginMutex.unlock();
}
void VstEffectControls::setParameter( Model * action )
{
int knobUNID = action->displayName().toInt();
if ( m_effect->m_plugin != nullptr ) {
m_effect->m_plugin->setParam( knobUNID, knobFModel[knobUNID]->value() );
}
}
void VstEffectControls::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
_this.setAttribute( "plugin", m_effect->m_key.attributes["file"] );
m_effect->m_pluginMutex.lock();
if( m_effect->m_plugin != nullptr )
{
m_effect->m_plugin->saveSettings( _doc, _this );
if (!knobFModel.empty()) {
const QMap<QString, QString> & dump = m_effect->m_plugin->parameterDump();
paramCount = dump.size();
auto paramStr = std::array<char, 35>{};
for( int i = 0; i < paramCount; i++ )
{
if (knobFModel[i]->isAutomated() || knobFModel[i]->controllerConnection()) {
std::snprintf(paramStr.data(), paramStr.size(), "param%d", i);
knobFModel[i]->saveSettings(_doc, _this, paramStr.data());
}
}
}
}
m_effect->m_pluginMutex.unlock();
}
int VstEffectControls::controlCount()
{
return m_effect->m_plugin != nullptr ? 1 : 0;
}
gui::EffectControlDialog* VstEffectControls::createView()
{
auto dialog = new gui::VstEffectControlDialog( this );
dialog->togglePluginUI( m_vstGuiVisible );
return dialog;
}
void VstEffectControls::managePlugin()
{
if ( m_effect->m_plugin != nullptr && m_subWindow == nullptr ) {
auto tt = new gui::ManageVSTEffectView(m_effect, this);
ctrHandle = (QObject *)tt;
} else if (m_subWindow != nullptr) {
if (m_subWindow->widget()->isVisible() == false ) {
m_scrollArea->show();
m_subWindow->show();
} else {
m_scrollArea->hide();
m_subWindow->hide();
}
}
}
void VstEffectControls::savePreset()
{
if ( m_effect->m_plugin != nullptr ) {
m_effect->m_plugin->savePreset();
/* bool converted;
QString str = m_vi->m_plugin->currentProgramName().section("/", 0, 0);
if (str != "")
lastPosInMenu = str.toInt(&converted, 10) - 1;
QWidget::update();*/
}
}
void VstEffectControls::updateMenu()
{
// get all presets -
if ( m_effect->m_plugin != nullptr )
{
m_effect->m_plugin->loadProgramNames();
///QWidget::update();
QString str = m_effect->m_plugin->allProgramNames();
QStringList list1 = str.split("|");
QMenu * to_menu = m_selPresetButton->menu();
to_menu->clear();
for (int i = 0; i < list1.size(); i++) {
auto presetAction = new QAction(this);
connect(presetAction, SIGNAL(triggered()), this, SLOT(selPreset()));
presetAction->setText(QString("%1. %2").arg(QString::number(i+1), list1.at(i)));
presetAction->setData(i);
if (i == lastPosInMenu) {
presetAction->setIcon(embed::getIconPixmap( "sample_file", 16, 16 ));
} else presetAction->setIcon(embed::getIconPixmap( "edit_copy", 16, 16 ));
to_menu->addAction( presetAction );
}
}
}
void VstEffectControls::openPreset()
{
if ( m_effect->m_plugin != nullptr ) {
m_effect->m_plugin->openPreset();
bool converted;
QString str = m_effect->m_plugin->currentProgramName().section("/", 0, 0);
if (str != "")
lastPosInMenu = str.toInt(&converted, 10) - 1;
//QWidget::update();
}
}
void VstEffectControls::rollPreset()
{
if ( m_effect->m_plugin != nullptr ) {
m_effect->m_plugin->rotateProgram( 1 );
bool converted;
QString str = m_effect->m_plugin->currentProgramName().section("/", 0, 0);
if (str != "")
lastPosInMenu = str.toInt(&converted, 10) - 1;
//QWidget::update();
}
}
void VstEffectControls::rolrPreset()
{
if ( m_effect->m_plugin != nullptr ) {
m_effect->m_plugin->rotateProgram( -1 );
bool converted;
QString str = m_effect->m_plugin->currentProgramName().section("/", 0, 0);
if (str != "")
lastPosInMenu = str.toInt(&converted, 10) - 1;
//QWidget::update();
}
}
void VstEffectControls::selPreset()
{
auto action = qobject_cast<QAction*>(sender());
if (action && m_effect->m_plugin != nullptr)
{
lastPosInMenu = action->data().toInt();
m_effect->m_plugin->setProgram(lastPosInMenu);
// QWidget::update();
}
}
void VstEffectControls::paintEvent( QPaintEvent * )
{
}
namespace gui
{
ManageVSTEffectView::ManageVSTEffectView( VstEffect * _eff, VstEffectControls * m_vi ) :
m_effect( _eff )
{
#if QT_VERSION < 0x50C00
// Workaround for a bug in Qt versions below 5.12,
// where argument-dependent-lookup fails for QFlags operators
// declared inside a namepsace.
// This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h
// See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348
using ::operator|;
#endif
m_vi2 = m_vi;
widget = new QWidget();
m_vi->m_scrollArea = new QScrollArea( widget );
l = new QGridLayout( widget );
m_vi->m_subWindow = getGUI()->mainWindow()->addWindowedWidget(nullptr, Qt::SubWindow |
Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint);
m_vi->m_subWindow->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
m_vi->m_subWindow->setFixedSize( 960, 300);
m_vi->m_subWindow->setWidget(m_vi->m_scrollArea);
m_vi->m_subWindow->setWindowTitle( _eff->m_plugin->name() + tr( " - VST parameter control" ) );
m_vi->m_subWindow->setWindowIcon( PLUGIN_NAME::getIconPixmap( "logo" ) );
m_vi->m_subWindow->setAttribute(Qt::WA_DeleteOnClose, false);
l->setContentsMargins( 20, 10, 10, 10 );
l->setVerticalSpacing( 10 );
l->setHorizontalSpacing( 23 );
m_syncButton = new QPushButton( tr( "VST sync" ), widget );
connect( m_syncButton, SIGNAL( clicked() ), this,
SLOT( syncPlugin() ) );
l->addWidget( m_syncButton, 0, 0, 1, 2, Qt::AlignLeft );
m_displayAutomatedOnly = new QPushButton( tr( "Automated" ), widget );
connect( m_displayAutomatedOnly, SIGNAL( clicked() ), this,
SLOT( displayAutomatedOnly() ) );
l->addWidget( m_displayAutomatedOnly, 0, 1, 1, 2, Qt::AlignLeft );
m_closeButton = new QPushButton( tr( " Close " ), widget );
connect( m_closeButton, SIGNAL( clicked() ), this,
SLOT( closeWindow() ) );
l->addWidget( m_closeButton, 0, 2, 1, 7, Qt::AlignLeft );
for( int i = 0; i < 10; i++ )
{
l->addItem( new QSpacerItem( 68, 45, QSizePolicy::Fixed, QSizePolicy::Fixed ), 0, i );
}
const QMap<QString, QString> & dump = m_effect->m_plugin->parameterDump();
m_vi->paramCount = dump.size();
vstKnobs = new CustomTextKnob *[ m_vi->paramCount ];
bool hasKnobModel = true;
if (m_vi->knobFModel.empty())
{
m_vi->knobFModel.resize(m_vi->paramCount);
hasKnobModel = false;
}
auto paramStr = std::array<char, 35>{};
QStringList s_dumpValues;
for( int i = 0; i < m_vi->paramCount; i++ )
{
std::snprintf(paramStr.data(), paramStr.size(), "param%d", i);
s_dumpValues = dump[paramStr.data()].split(":");
vstKnobs[ i ] = new CustomTextKnob( KnobType::Bright26, widget, s_dumpValues.at( 1 ) );
vstKnobs[ i ]->setDescription( s_dumpValues.at( 1 ) + ":" );
vstKnobs[ i ]->setLabel( s_dumpValues.at( 1 ).left( 15 ) );
if( !hasKnobModel )
{
std::snprintf(paramStr.data(), paramStr.size(), "%d", i);
m_vi->knobFModel[i] = new FloatModel(LocaleHelper::toFloat(s_dumpValues.at(2)),
0.0f, 1.0f, 0.01f, _eff, paramStr.data());
}
FloatModel * model = m_vi->knobFModel[i];
connect( model, &FloatModel::dataChanged, this,
[this, model]() { setParameter( model ); }, Qt::DirectConnection);
vstKnobs[ i ] ->setModel( model );
}
syncParameterText();
int i = 0;
for( int lrow = 1; lrow < ( int( m_vi->paramCount / 10 ) + 1 ) + 1; lrow++ )
{
for( int lcolumn = 0; lcolumn < 10; lcolumn++ )
{
if( i < m_vi->paramCount )
{
l->addWidget( vstKnobs[i], lrow, lcolumn, Qt::AlignCenter );
}
i++;
}
}
l->setRowStretch( ( int( m_vi->paramCount / 10 ) + 1 ), 1 );
l->setColumnStretch( 10, 1 );
widget->setLayout(l);
widget->setAutoFillBackground(true);
m_vi->m_scrollArea->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
m_vi->m_scrollArea->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
m_vi->m_scrollArea->setPalette( QApplication::palette( m_vi->m_scrollArea ) );
m_vi->m_scrollArea->setMinimumHeight( 64 );
m_vi->m_scrollArea->setWidget( widget );
m_vi->m_subWindow->show();
}
void ManageVSTEffectView::closeWindow()
{
m_vi2->m_subWindow->hide();
}
void ManageVSTEffectView::syncPlugin()
{
auto paramStr = std::array<char, 35>{};
QStringList s_dumpValues;
const QMap<QString, QString> & dump = m_effect->m_plugin->parameterDump();
for( int i = 0; i < m_vi2->paramCount; i++ )
{
// only not automated knobs are synced from VST
// those auto-setted values are not jurnaled, tracked for undo / redo
if( !( m_vi2->knobFModel[ i ]->isAutomated() ||
m_vi2->knobFModel[ i ]->controllerConnection() ) )
{
std::snprintf(paramStr.data(), paramStr.size(), "param%d", i);
s_dumpValues = dump[paramStr.data()].split(":");
float f_value = LocaleHelper::toFloat(s_dumpValues.at(2));
m_vi2->knobFModel[ i ]->setAutomatedValue( f_value );
m_vi2->knobFModel[ i ]->setInitValue( f_value );
}
}
syncParameterText();
}
void ManageVSTEffectView::displayAutomatedOnly()
{
bool isAuto = QString::compare( m_displayAutomatedOnly->text(), tr( "Automated" ) ) == 0;
for( int i = 0; i< m_vi2->paramCount; i++ )
{
if( !( m_vi2->knobFModel[ i ]->isAutomated() ||
m_vi2->knobFModel[ i ]->controllerConnection() ) )
{
if( vstKnobs[ i ]->isVisible() == true && isAuto )
{
vstKnobs[ i ]->hide();
m_displayAutomatedOnly->setText( "All" );
} else {
vstKnobs[ i ]->show();
m_displayAutomatedOnly->setText( "Automated" );
}
}
}
}
void ManageVSTEffectView::setParameter( Model * action )
{
int knobUNID = action->displayName().toInt();
if ( m_effect->m_plugin != nullptr ) {
m_effect->m_plugin->setParam( knobUNID, m_vi2->knobFModel[knobUNID]->value() );
syncParameterText();
}
}
void ManageVSTEffectView::syncParameterText()
{
m_effect->m_plugin->loadParameterLabels();
m_effect->m_plugin->loadParameterDisplays();
QString paramLabelStr = m_effect->m_plugin->allParameterLabels();
QString paramDisplayStr = m_effect->m_plugin->allParameterDisplays();
QStringList paramLabelList;
QStringList paramDisplayList;
for( int i = 0; i < paramLabelStr.size(); )
{
const int length = paramLabelStr[i].digitValue();
paramLabelList.append(paramLabelStr.mid(i + 1, length));
i += length + 1;
}
for( int i = 0; i < paramDisplayStr.size(); )
{
const int length = paramDisplayStr[i].digitValue();
paramDisplayList.append(paramDisplayStr.mid(i + 1, length));
i += length + 1;
}
for( int i = 0; i < paramLabelList.size(); ++i )
{
vstKnobs[i]->setValueText(paramDisplayList[i] + ' ' + paramLabelList[i]);
}
}
ManageVSTEffectView::~ManageVSTEffectView()
{
if (!m_vi2->knobFModel.empty())
{
for( int i = 0; i < m_vi2->paramCount; i++ )
{
delete m_vi2->knobFModel[ i ];
delete vstKnobs[ i ];
}
}
if( vstKnobs != nullptr )
{
delete [] vstKnobs;
vstKnobs = nullptr;
}
m_vi2->knobFModel.clear();
if( m_vi2->m_scrollArea != nullptr )
{
delete m_vi2->m_scrollArea;
m_vi2->m_scrollArea = nullptr;
}
if( m_vi2->m_subWindow != nullptr )
{
m_vi2->m_subWindow->setAttribute( Qt::WA_DeleteOnClose );
m_vi2->m_subWindow->close();
if( m_vi2->m_subWindow != nullptr )
{
delete m_vi2->m_subWindow;
}
m_vi2->m_subWindow = nullptr;
}
//delete m_vi2->m_subWindow;
//m_vi2->m_subWindow = NULL;
}
} // namespace gui
} // namespace lmms
| 14,523
|
C++
|
.cpp
| 433
| 30.505774
| 96
| 0.679056
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,666
|
VstEffect.cpp
|
LMMS_lmms/plugins/VstEffect/VstEffect.cpp
|
/*
* VstEffect.cpp - class for handling VST effect plugins
*
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "VstEffect.h"
#include "GuiApplication.h"
#include "Song.h"
#include "TextFloat.h"
#include "VstPlugin.h"
#include "VstSubPluginFeatures.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT vsteffect_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"VST",
QT_TRANSLATE_NOOP( "PluginBrowser",
"plugin for using arbitrary VST effects inside LMMS." ),
"Tobias Doerffel <tobydox/at/users.sf.net>",
0x0200,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
new VstSubPluginFeatures( Plugin::Type::Effect )
} ;
}
VstEffect::VstEffect( Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Effect( &vsteffect_plugin_descriptor, _parent, _key ),
m_pluginMutex(),
m_key( *_key ),
m_vstControls( this )
{
bool loaded = false;
if( !m_key.attributes["file"].isEmpty() )
{
loaded = openPlugin(m_key.attributes["file"]);
}
setDisplayName( m_key.attributes["file"].section( ".dll", 0, 0 ).isEmpty()
? m_key.name : m_key.attributes["file"].section( ".dll", 0, 0 ) );
setDontRun(!loaded);
}
Effect::ProcessStatus VstEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
assert(m_plugin != nullptr);
static thread_local auto tempBuf = std::array<SampleFrame, MAXIMUM_BUFFER_SIZE>();
std::memcpy(tempBuf.data(), buf, sizeof(SampleFrame) * frames);
if (m_pluginMutex.tryLock(Engine::getSong()->isExporting() ? -1 : 0))
{
m_plugin->process(tempBuf.data(), tempBuf.data());
m_pluginMutex.unlock();
}
const float w = wetLevel();
const float d = dryLevel();
for (fpp_t f = 0; f < frames; ++f)
{
buf[f][0] = w * tempBuf[f][0] + d * buf[f][0];
buf[f][1] = w * tempBuf[f][1] + d * buf[f][1];
}
return ProcessStatus::ContinueIfNotQuiet;
}
bool VstEffect::openPlugin(const QString& plugin)
{
gui::TextFloat* tf = nullptr;
if( gui::getGUI() != nullptr )
{
tf = gui::TextFloat::displayMessage(
VstPlugin::tr( "Loading plugin" ),
VstPlugin::tr( "Please wait while loading VST plugin..." ),
PLUGIN_NAME::getIconPixmap( "logo", 24, 24 ), 0 );
}
QMutexLocker ml( &m_pluginMutex ); Q_UNUSED( ml );
m_plugin = QSharedPointer<VstPlugin>(new VstPlugin(plugin));
if( m_plugin->failed() )
{
m_plugin.clear();
delete tf;
collectErrorForUI(VstPlugin::tr("The VST plugin %1 could not be loaded.").arg(plugin));
return false;
}
delete tf;
m_key.attributes["file"] = plugin;
return true;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * _parent, void * _data )
{
return new VstEffect( _parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(
_data ) );
}
}
} // namespace lmms
| 3,683
|
C++
|
.cpp
| 118
| 28.949153
| 89
| 0.713679
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,667
|
VstSubPluginFeatures.cpp
|
LMMS_lmms/plugins/VstEffect/VstSubPluginFeatures.cpp
|
/*
* VstSubPluginFeatures.cpp - derivation from
* Plugin::Descriptor::SubPluginFeatures for
* hosting VST-plugins
*
* Copyright (c) 2006-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDir>
#include <QLabel>
#include "VstSubPluginFeatures.h"
#include "ConfigManager.h"
namespace lmms
{
VstSubPluginFeatures::VstSubPluginFeatures( Plugin::Type _type ) :
SubPluginFeatures( _type )
{
}
void VstSubPluginFeatures::fillDescriptionWidget( QWidget * _parent,
const Key * _key ) const
{
new QLabel( QWidget::tr( "Name: " ) + _key->name, _parent );
new QLabel( QWidget::tr( "File: " ) + _key->attributes["file"], _parent );
}
void VstSubPluginFeatures::listSubPluginKeys( const Plugin::Descriptor * _desc,
KeyList & _kl ) const
{
auto dlls = new QStringList();
const QString path = QString("");
addPluginsFromDir(dlls, path );
// TODO: eval m_type
for( QStringList::ConstIterator it = dlls->begin();
it != dlls->end(); ++it )
{
EffectKey::AttributeMap am;
am["file"] = *it;
_kl.push_back( Key( _desc, QFileInfo( *it ).baseName(), am ) );
}
delete dlls;
}
void VstSubPluginFeatures::addPluginsFromDir( QStringList* filenames, QString path ) const
{
QStringList dirs = QDir ( ConfigManager::inst()->vstDir() + path ).
entryList( QStringList() << "*" ,
QDir::Dirs, QDir::Name );
for( int i = 0; i < dirs.size(); i++ )
{
if( dirs.at( i )[0] != '.' )
{
addPluginsFromDir( filenames, path+QDir::separator() + dirs.at( i ) );
}
}
QStringList dlls = QDir( ConfigManager::inst()->vstDir() + path ).
entryList( QStringList() << "*.dll"
#ifdef LMMS_BUILD_LINUX
<< "*.so"
#endif
,
QDir::Files, QDir::Name );
for( int i = 0; i < dlls.size(); i++ )
{
QString fName = path + QDir::separator() + dlls.at( i );
fName.remove( 0, 1 );
filenames->append( fName );
}
}
} // namespace lmms
| 2,763
|
C++
|
.cpp
| 84
| 30.059524
| 90
| 0.671799
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,668
|
LocalZynAddSubFx.cpp
|
LMMS_lmms/plugins/ZynAddSubFx/LocalZynAddSubFx.cpp
|
/*
* LocalZynAddSubFx.cpp - local implementation of ZynAddSubFx plugin
*
* Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LocalZynAddSubFx.h"
#include <ctime>
#include "lmmsconfig.h"
#ifdef LMMS_BUILD_WIN32
# include <wchar.h>
# include "IoHelper.h"
#else
# include <unistd.h>
#endif
#include "MidiEvent.h"
#include "SampleFrame.h"
#include <Nio/NulEngine.h>
#include <Misc/Master.h>
#include <Misc/Part.h>
#include <Misc/Util.h>
// Global variable in zynaddsubfx/src/globals.h
SYNTH_T* synth = nullptr;
namespace lmms
{
int LocalZynAddSubFx::s_instanceCount = 0;
LocalZynAddSubFx::LocalZynAddSubFx() :
m_master( nullptr ),
m_ioEngine( nullptr )
{
if( s_instanceCount == 0 )
{
initConfig();
synth = new SYNTH_T;
synth->oscilsize = config.cfg.OscilSize;
synth->alias();
srand( time( nullptr ) );
denormalkillbuf = new float[synth->buffersize];
for( int i = 0; i < synth->buffersize; ++i )
{
denormalkillbuf[i] = (RND-0.5)*1e-16;
}
}
++s_instanceCount;
m_ioEngine = new NulEngine;
m_master = new Master();
m_master->swaplr = false;
}
LocalZynAddSubFx::~LocalZynAddSubFx()
{
delete m_master;
delete m_ioEngine;
if( --s_instanceCount == 0 )
{
delete[] denormalkillbuf;
}
}
void LocalZynAddSubFx::initConfig()
{
config.init();
config.cfg.GzipCompression = 0;
}
void LocalZynAddSubFx::setSampleRate( int sampleRate )
{
synth->samplerate = sampleRate;
synth->alias();
}
void LocalZynAddSubFx::setBufferSize( int bufferSize )
{
synth->buffersize = bufferSize;
synth->alias();
}
void LocalZynAddSubFx::saveXML( const std::string & _filename )
{
char * name = strdup( _filename.c_str() );
m_master->saveXML( name );
free( name );
}
void LocalZynAddSubFx::loadXML( const std::string & _filename )
{
char * f = strdup( _filename.c_str() );
{
const auto lock = std::lock_guard{m_master->mutex};
m_master->defaults();
m_master->loadXML( f );
}
m_master->applyparameters();
#ifdef LMMS_BUILD_WIN32
_wunlink(toWString(_filename).c_str());
#else
unlink( f );
#endif
free( f );
}
void LocalZynAddSubFx::loadPreset( const std::string & _filename, int _part )
{
char * f = strdup( _filename.c_str() );
{
const auto lock = std::lock_guard{m_master->mutex};
m_master->part[_part]->defaultsinstrument();
m_master->part[_part]->loadXMLinstrument( f );
}
m_master->applyparameters();
free( f );
}
void LocalZynAddSubFx::setPresetDir( const std::string & _dir )
{
m_presetsDir = _dir;
for (auto& bankRootDir : config.cfg.bankRootDirList)
{
if (bankRootDir.empty())
{
bankRootDir = m_presetsDir;
break;
}
else if (bankRootDir == m_presetsDir)
{
break;
}
}
}
void LocalZynAddSubFx::setLmmsWorkingDir( const std::string & _dir )
{
if( config.workingDir != nullptr )
{
free( config.workingDir );
}
config.workingDir = strdup( _dir.c_str() );
initConfig();
}
void LocalZynAddSubFx::setPitchWheelBendRange( int semitones )
{
for (const auto& part : m_master->part)
{
part->ctl.setpitchwheelbendrange(semitones * 100);
}
}
void LocalZynAddSubFx::processMidiEvent( const MidiEvent& event )
{
switch( event.type() )
{
case MidiNoteOn:
if( event.velocity() > 0 )
{
if( event.key() < 0 || event.key() > MidiMaxKey )
{
break;
}
if( m_runningNotes[event.key()] > 0 )
{
m_master->noteOff( event.channel(), event.key() );
}
++m_runningNotes[event.key()];
m_master->noteOn( event.channel(), event.key(), event.velocity() );
break;
}
case MidiNoteOff:
if( event.key() < 0 || event.key() > MidiMaxKey )
{
break;
}
if( --m_runningNotes[event.key()] <= 0 )
{
m_master->noteOff( event.channel(), event.key() );
}
break;
case MidiPitchBend:
m_master->setController( event.channel(), C_pitchwheel, event.pitchBend()-8192 );
break;
case MidiControlChange:
m_master->setController( event.channel(), event.controllerNumber(), event.controllerValue() );
break;
default:
break;
}
}
void LocalZynAddSubFx::processAudio( SampleFrame* _out )
{
#ifdef _MSC_VER
const auto outputl = static_cast<float*>(_alloca(synth->buffersize * sizeof(float)));
const auto outputr = static_cast<float*>(_alloca(synth->buffersize * sizeof(float)));
#else
float outputl[synth->buffersize];
float outputr[synth->buffersize];
#endif
m_master->GetAudioOutSamples( synth->buffersize, synth->samplerate, outputl, outputr );
// TODO: move to MixHelpers
for( int f = 0; f < synth->buffersize; ++f )
{
_out[f][0] = outputl[f];
_out[f][1] = outputr[f];
}
}
} // namespace lmms
| 5,439
|
C++
|
.cpp
| 211
| 23.199052
| 97
| 0.70538
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,669
|
ZynAddSubFx.cpp
|
LMMS_lmms/plugins/ZynAddSubFx/ZynAddSubFx.cpp
|
/*
* ZynAddSubFx.cpp - ZynAddSubxFX-embedding plugin
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "lmmsconfig.h"
#include <QDir>
#include <QDomDocument>
#include <QTemporaryFile>
#include <QtGlobal>
#include <QDropEvent>
#include <QGridLayout>
#include <QPushButton>
#include "ZynAddSubFx.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "DataFile.h"
#include "InstrumentPlayHandle.h"
#include "InstrumentTrack.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "RemoteZynAddSubFx.h"
#include "LocalZynAddSubFx.h"
#include "AudioEngine.h"
#include "Clipboard.h"
#include "embed.h"
#include "FontHelper.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT zynaddsubfx_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"ZynAddSubFX",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Embedded ZynAddSubFX" ),
"Tobias Doerffel <tobydox/at/users.sf.net>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
"xiz",
nullptr,
} ;
}
ZynAddSubFxRemotePlugin::ZynAddSubFxRemotePlugin() :
RemotePlugin()
{
init( "RemoteZynAddSubFx", false );
}
bool ZynAddSubFxRemotePlugin::processMessage( const message & _m )
{
switch( _m.id )
{
case IdHideUI:
emit clickedCloseButton();
return true;
default:
break;
}
return RemotePlugin::processMessage( _m );
}
ZynAddSubFxInstrument::ZynAddSubFxInstrument(
InstrumentTrack * _instrumentTrack ) :
Instrument(_instrumentTrack, &zynaddsubfx_plugin_descriptor, nullptr, Flag::IsSingleStreamed | Flag::IsMidiBased),
m_hasGUI( false ),
m_plugin( nullptr ),
m_remotePlugin( nullptr ),
m_portamentoModel( 0, 0, 127, 1, this, tr( "Portamento" ) ),
m_filterFreqModel( 127, 0, 127, 1, this, tr( "Filter frequency" ) ),
m_filterQModel( 64, 0, 127, 1, this, tr( "Filter resonance" ) ),
m_bandwidthModel( 64, 0, 127, 1, this, tr( "Bandwidth" ) ),
m_fmGainModel( 127, 0, 127, 1, this, tr( "FM gain" ) ),
m_resCenterFreqModel( 64, 0, 127, 1, this, tr( "Resonance center frequency" ) ),
m_resBandwidthModel( 64, 0, 127, 1, this, tr( "Resonance bandwidth" ) ),
m_forwardMidiCcModel( true, this, tr( "Forward MIDI control change events" ) )
{
initPlugin();
connect( &m_portamentoModel, SIGNAL( dataChanged() ),
this, SLOT( updatePortamento() ), Qt::DirectConnection );
connect( &m_filterFreqModel, SIGNAL( dataChanged() ),
this, SLOT( updateFilterFreq() ), Qt::DirectConnection );
connect( &m_filterQModel, SIGNAL( dataChanged() ),
this, SLOT( updateFilterQ() ), Qt::DirectConnection );
connect( &m_bandwidthModel, SIGNAL( dataChanged() ),
this, SLOT( updateBandwidth() ), Qt::DirectConnection );
connect( &m_fmGainModel, SIGNAL( dataChanged() ),
this, SLOT( updateFmGain() ), Qt::DirectConnection );
connect( &m_resCenterFreqModel, SIGNAL( dataChanged() ),
this, SLOT( updateResCenterFreq() ), Qt::DirectConnection );
connect( &m_resBandwidthModel, SIGNAL( dataChanged() ),
this, SLOT( updateResBandwidth() ), Qt::DirectConnection );
// now we need a play-handle which cares for calling play()
auto iph = new InstrumentPlayHandle(this, _instrumentTrack);
Engine::audioEngine()->addPlayHandle( iph );
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ),
this, SLOT( reloadPlugin() ) );
connect( instrumentTrack()->pitchRangeModel(), SIGNAL( dataChanged() ),
this, SLOT( updatePitchRange() ), Qt::DirectConnection );
// ZynAddSubFX's internal value that LMMS's FREQ knob controls
// isn't set properly when the instrument is first loaded in,
// and doesn't update until the FREQ knob is moved
updateFilterFreq();
}
ZynAddSubFxInstrument::~ZynAddSubFxInstrument()
{
Engine::audioEngine()->removePlayHandlesOfTypes( instrumentTrack(),
PlayHandle::Type::NotePlayHandle
| PlayHandle::Type::InstrumentPlayHandle );
m_pluginMutex.lock();
delete m_plugin;
delete m_remotePlugin;
m_plugin = nullptr;
m_remotePlugin = nullptr;
m_pluginMutex.unlock();
}
void ZynAddSubFxInstrument::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
m_portamentoModel.saveSettings( _doc, _this, "portamento" );
m_filterFreqModel.saveSettings( _doc, _this, "filterfreq" );
m_filterQModel.saveSettings( _doc, _this, "filterq" );
m_bandwidthModel.saveSettings( _doc, _this, "bandwidth" );
m_fmGainModel.saveSettings( _doc, _this, "fmgain" );
m_resCenterFreqModel.saveSettings( _doc, _this, "rescenterfreq" );
m_resBandwidthModel.saveSettings( _doc, _this, "resbandwidth" );
QString modifiedControllers;
for( QMap<int, bool>::ConstIterator it = m_modifiedControllers.begin();
it != m_modifiedControllers.end(); ++it )
{
if( it.value() )
{
modifiedControllers += QString( "%1," ).arg( it.key() );
}
}
_this.setAttribute( "modifiedcontrollers", modifiedControllers );
m_forwardMidiCcModel.saveSettings( _doc, _this, "forwardmidicc" );
QTemporaryFile tf;
if( tf.open() )
{
const std::string fn = QSTR_TO_STDSTR(
QDir::toNativeSeparators( tf.fileName() ) );
m_pluginMutex.lock();
if( m_remotePlugin )
{
m_remotePlugin->lock();
m_remotePlugin->sendMessage( RemotePlugin::message( IdSaveSettingsToFile ).addString( fn ) );
m_remotePlugin->waitForMessage( IdSaveSettingsToFile );
m_remotePlugin->unlock();
}
else
{
m_plugin->saveXML( fn );
}
m_pluginMutex.unlock();
QByteArray a = tf.readAll();
QDomDocument doc( "mydoc" );
if( doc.setContent( a ) )
{
QDomNode n = _doc.importNode( doc.documentElement(), true );
_this.appendChild( n );
}
}
}
void ZynAddSubFxInstrument::loadSettings( const QDomElement & _this )
{
if( !_this.hasChildNodes() )
{
return;
}
m_portamentoModel.loadSettings( _this, "portamento" );
m_filterFreqModel.loadSettings( _this, "filterfreq" );
m_filterQModel.loadSettings( _this, "filterq" );
m_bandwidthModel.loadSettings( _this, "bandwidth" );
m_fmGainModel.loadSettings( _this, "fmgain" );
m_resCenterFreqModel.loadSettings( _this, "rescenterfreq" );
m_resBandwidthModel.loadSettings( _this, "resbandwidth" );
m_forwardMidiCcModel.loadSettings( _this, "forwardmidicc" );
QDomDocument doc;
QDomElement data = _this.firstChildElement( "ZynAddSubFX-data" );
if( data.isNull() )
{
data = _this.firstChildElement();
}
doc.appendChild( doc.importNode( data, true ) );
QTemporaryFile tf;
if( tf.open() )
{
QByteArray a = doc.toString( 0 ).toUtf8();
tf.write( a );
tf.flush();
const std::string fn = QSTR_TO_STDSTR( QDir::toNativeSeparators( tf.fileName() ) );
m_pluginMutex.lock();
if( m_remotePlugin )
{
m_remotePlugin->lock();
m_remotePlugin->sendMessage( RemotePlugin::message( IdLoadSettingsFromFile ).addString( fn ) );
m_remotePlugin->waitForMessage( IdLoadSettingsFromFile );
m_remotePlugin->unlock();
}
else
{
m_plugin->loadXML( fn );
}
m_pluginMutex.unlock();
m_modifiedControllers.clear();
for( const QString & c : _this.attribute( "modifiedcontrollers" ).split( ',' ) )
{
if( !c.isEmpty() )
{
switch( c.toInt() )
{
case C_portamento: updatePortamento(); break;
case C_filtercutoff: updateFilterFreq(); break;
case C_filterq: updateFilterQ(); break;
case C_bandwidth: updateBandwidth(); break;
case C_fmamp: updateFmGain(); break;
case C_resonance_center: updateResCenterFreq(); break;
case C_resonance_bandwidth: updateResBandwidth(); break;
default:
break;
}
}
}
emit settingsChanged();
}
emit instrumentTrack()->pitchModel()->dataChanged();
}
void ZynAddSubFxInstrument::loadFile( const QString & _file )
{
const std::string fn = QSTR_TO_STDSTR( _file );
if( m_remotePlugin )
{
m_remotePlugin->lock();
m_remotePlugin->sendMessage( RemotePlugin::message( IdLoadPresetFile ).addString( fn ) );
m_remotePlugin->waitForMessage( IdLoadPresetFile );
m_remotePlugin->unlock();
}
else
{
m_pluginMutex.lock();
m_plugin->loadPreset( fn );
m_pluginMutex.unlock();
}
instrumentTrack()->setName(QFileInfo(_file).baseName().replace(QRegularExpression("^[0-9]{4}-"), QString()));
m_modifiedControllers.clear();
emit settingsChanged();
}
QString ZynAddSubFxInstrument::nodeName() const
{
return zynaddsubfx_plugin_descriptor.name;
}
void ZynAddSubFxInstrument::play( SampleFrame* _buf )
{
if (!m_pluginMutex.tryLock(Engine::getSong()->isExporting() ? -1 : 0)) {return;}
if( m_remotePlugin )
{
m_remotePlugin->process( nullptr, _buf );
}
else
{
m_plugin->processAudio( _buf );
}
m_pluginMutex.unlock();
}
bool ZynAddSubFxInstrument::handleMidiEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset )
{
// do not forward external MIDI Control Change events if the according
// LED is not checked
if( event.type() == MidiControlChange &&
event.sourcePort() != this &&
m_forwardMidiCcModel.value() == false )
{
return true;
}
MidiEvent localEvent = event;
localEvent.setChannel( 0 );
m_pluginMutex.lock();
if( m_remotePlugin )
{
m_remotePlugin->processMidiEvent( localEvent, 0 );
}
else
{
m_plugin->processMidiEvent( localEvent );
}
m_pluginMutex.unlock();
return true;
}
void ZynAddSubFxInstrument::reloadPlugin()
{
// save state of current plugin instance
DataFile m( DataFile::Type::InstrumentTrackSettings );
saveSettings( m, m.content() );
// init plugin (will delete current one and create a new instance)
initPlugin();
// and load the settings again
loadSettings( m.content() );
}
void ZynAddSubFxInstrument::updatePitchRange()
{
m_pluginMutex.lock();
if( m_remotePlugin )
{
m_remotePlugin->sendMessage( RemotePlugin::message( IdZasfSetPitchWheelBendRange ).
addInt( instrumentTrack()->midiPitchRange() ) );
}
else
{
m_plugin->setPitchWheelBendRange( instrumentTrack()->midiPitchRange() );
}
m_pluginMutex.unlock();
}
#define GEN_CC_SLOT(slotname,midictl,modelname) \
void ZynAddSubFxInstrument::slotname() \
{ \
sendControlChange( midictl, modelname.value() ); \
m_modifiedControllers[midictl] = true; \
}
GEN_CC_SLOT(updatePortamento,C_portamento,m_portamentoModel);
GEN_CC_SLOT(updateFilterFreq,C_filtercutoff,m_filterFreqModel);
GEN_CC_SLOT(updateFilterQ,C_filterq,m_filterQModel);
GEN_CC_SLOT(updateBandwidth,C_bandwidth,m_bandwidthModel);
GEN_CC_SLOT(updateFmGain,C_fmamp,m_fmGainModel);
GEN_CC_SLOT(updateResCenterFreq,C_resonance_center,m_resCenterFreqModel);
GEN_CC_SLOT(updateResBandwidth,C_resonance_bandwidth,m_resBandwidthModel);
void ZynAddSubFxInstrument::initPlugin()
{
m_pluginMutex.lock();
delete m_plugin;
delete m_remotePlugin;
m_plugin = nullptr;
m_remotePlugin = nullptr;
if( m_hasGUI )
{
m_remotePlugin = new ZynAddSubFxRemotePlugin();
m_remotePlugin->lock();
m_remotePlugin->waitForInitDone( false );
m_remotePlugin->sendMessage(
RemotePlugin::message( IdZasfLmmsWorkingDirectory ).
addString(
QSTR_TO_STDSTR(
QString( ConfigManager::inst()->workingDir() ) ) ) );
m_remotePlugin->sendMessage(
RemotePlugin::message( IdZasfPresetDirectory ).
addString(
QSTR_TO_STDSTR(
QDir( ConfigManager::inst()->factoryPresetsDir() +
"/ZynAddSubFX" ).absolutePath() ) ) );
m_remotePlugin->updateSampleRate( Engine::audioEngine()->outputSampleRate() );
// temporary workaround until the VST synchronization feature gets stripped out of the RemotePluginClient class
// causing not to send buffer size information requests
m_remotePlugin->sendMessage( RemotePlugin::message( IdBufferSizeInformation ).addInt( Engine::audioEngine()->framesPerPeriod() ) );
m_remotePlugin->showUI();
m_remotePlugin->unlock();
}
else
{
m_plugin = new LocalZynAddSubFx;
m_plugin->setSampleRate( Engine::audioEngine()->outputSampleRate() );
m_plugin->setBufferSize( Engine::audioEngine()->framesPerPeriod() );
}
m_pluginMutex.unlock();
}
void ZynAddSubFxInstrument::sendControlChange( MidiControllers midiCtl, float value )
{
handleMidiEvent( MidiEvent( MidiControlChange, instrumentTrack()->midiPort()->realOutputChannel(), midiCtl, (int) value, this ) );
}
gui::PluginView* ZynAddSubFxInstrument::instantiateView( QWidget * _parent )
{
return new gui::ZynAddSubFxView( this, _parent );
}
namespace gui
{
ZynAddSubFxView::ZynAddSubFxView( Instrument * _instrument, QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap(
"artwork" ) );
setPalette( pal );
auto l = new QGridLayout(this);
l->setContentsMargins( 20, 80, 10, 10 );
l->setVerticalSpacing( 16 );
l->setHorizontalSpacing( 10 );
m_portamento = new Knob( KnobType::Bright26, this );
m_portamento->setHintText( tr( "Portamento:" ), "" );
m_portamento->setLabel( tr( "PORT" ) );
m_filterFreq = new Knob( KnobType::Bright26, this );
m_filterFreq->setHintText( tr( "Filter frequency:" ), "" );
m_filterFreq->setLabel( tr( "FREQ" ) );
m_filterQ = new Knob( KnobType::Bright26, this );
m_filterQ->setHintText( tr( "Filter resonance:" ), "" );
m_filterQ->setLabel( tr( "RES" ) );
m_bandwidth = new Knob( KnobType::Bright26, this );
m_bandwidth->setHintText( tr( "Bandwidth:" ), "" );
m_bandwidth->setLabel( tr( "BW" ) );
m_fmGain = new Knob( KnobType::Bright26, this );
m_fmGain->setHintText( tr( "FM gain:" ), "" );
m_fmGain->setLabel( tr( "FM GAIN" ) );
m_resCenterFreq = new Knob( KnobType::Bright26, this );
m_resCenterFreq->setHintText( tr( "Resonance center frequency:" ), "" );
m_resCenterFreq->setLabel( tr( "RES CF" ) );
m_resBandwidth = new Knob( KnobType::Bright26, this );
m_resBandwidth->setHintText( tr( "Resonance bandwidth:" ), "" );
m_resBandwidth->setLabel( tr( "RES BW" ) );
m_forwardMidiCC = new LedCheckBox( tr( "Forward MIDI control changes" ), this );
m_toggleUIButton = new QPushButton( tr( "Show GUI" ), this );
m_toggleUIButton->setCheckable( true );
m_toggleUIButton->setChecked( false );
m_toggleUIButton->setIcon( embed::getIconPixmap( "zoom" ) );
QFont f = m_toggleUIButton->font();
m_toggleUIButton->setFont(adjustedToPixelSize(f, DEFAULT_FONT_SIZE));
connect( m_toggleUIButton, SIGNAL( toggled( bool ) ), this,
SLOT( toggleUI() ) );
l->addWidget( m_toggleUIButton, 0, 0, 1, 4 );
l->setRowStretch( 1, 5 );
l->addWidget( m_portamento, 2, 0 );
l->addWidget( m_filterFreq, 2, 1 );
l->addWidget( m_filterQ, 2, 2 );
l->addWidget( m_bandwidth, 2, 3 );
l->addWidget( m_fmGain, 3, 0 );
l->addWidget( m_resCenterFreq, 3, 1 );
l->addWidget( m_resBandwidth, 3, 2 );
l->addWidget( m_forwardMidiCC, 4, 0, 1, 4 );
l->setRowStretch( 5, 10 );
l->setColumnStretch( 4, 10 );
setAcceptDrops( true );
}
void ZynAddSubFxView::dragEnterEvent( QDragEnterEvent * _dee )
{
// For mimeType() and MimeType enum class
using namespace Clipboard;
if( _dee->mimeData()->hasFormat( mimeType( MimeType::StringPair ) ) )
{
QString txt = _dee->mimeData()->data(
mimeType( MimeType::StringPair ) );
if( txt.section( ':', 0, 0 ) == "pluginpresetfile" )
{
_dee->acceptProposedAction();
}
else
{
_dee->ignore();
}
}
else
{
_dee->ignore();
}
}
void ZynAddSubFxView::dropEvent( QDropEvent * _de )
{
const QString type = StringPairDrag::decodeKey( _de );
const QString value = StringPairDrag::decodeValue( _de );
if( type == "pluginpresetfile" )
{
castModel<ZynAddSubFxInstrument>()->loadFile( value );
_de->accept();
return;
}
_de->ignore();
}
void ZynAddSubFxView::modelChanged()
{
auto m = castModel<ZynAddSubFxInstrument>();
// set models for controller knobs
m_portamento->setModel( &m->m_portamentoModel );
m_filterFreq->setModel( &m->m_filterFreqModel );
m_filterQ->setModel( &m->m_filterQModel );
m_bandwidth->setModel( &m->m_bandwidthModel );
m_fmGain->setModel( &m->m_fmGainModel );
m_resCenterFreq->setModel( &m->m_resCenterFreqModel );
m_resBandwidth->setModel( &m->m_resBandwidthModel );
m_forwardMidiCC->setModel( &m->m_forwardMidiCcModel );
m_toggleUIButton->setChecked( m->m_hasGUI );
}
void ZynAddSubFxView::toggleUI()
{
auto model = castModel<ZynAddSubFxInstrument>();
if( model->m_hasGUI != m_toggleUIButton->isChecked() )
{
model->m_hasGUI = m_toggleUIButton->isChecked();
model->reloadPlugin();
if( model->m_remotePlugin )
{
connect( model->m_remotePlugin, SIGNAL( clickedCloseButton() ),
m_toggleUIButton, SLOT( toggle() ) );
}
}
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main(Model * m, void *)
{
return new ZynAddSubFxInstrument(static_cast<InstrumentTrack *>(m));
}
}
} // namespace lmms
| 17,586
|
C++
|
.cpp
| 523
| 30.940727
| 133
| 0.722107
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,670
|
RemoteZynAddSubFx.cpp
|
LMMS_lmms/plugins/ZynAddSubFx/RemoteZynAddSubFx.cpp
|
/*
* RemoteZynAddSubFx.cpp - ZynAddSubFx-embedding plugin
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "RemoteZynAddSubFx.h"
#include <lmmsconfig.h>
#ifdef LMMS_BUILD_WIN32
#include <winsock2.h>
#endif
#include <queue>
#include "ThreadShims.h"
#undef CursorShape // is, by mistake, not undefed in FL
#include "RemotePluginClient.h"
#include "LocalZynAddSubFx.h"
#include <Nio/Nio.h>
#include <UI/MasterUI.h>
using namespace lmms;
class RemoteZynAddSubFx : public RemotePluginClient, public LocalZynAddSubFx
{
public:
#ifdef SYNC_WITH_SHM_FIFO
RemoteZynAddSubFx( const std::string& _shm_in, const std::string& _shm_out ) :
RemotePluginClient( _shm_in, _shm_out ),
#else
RemoteZynAddSubFx( const char * socketPath ) :
RemotePluginClient( socketPath ),
#endif
LocalZynAddSubFx(),
m_guiSleepTime( 100 ),
m_guiExit( false )
{
Nio::start();
setInputCount( 0 );
sendMessage( IdInitDone );
waitForMessage( IdInitDone );
m_messageThread = std::thread{&RemoteZynAddSubFx::messageLoop, this};
}
~RemoteZynAddSubFx() override
{
m_messageThread.join();
Nio::stop();
}
void updateSampleRate() override
{
LocalZynAddSubFx::setSampleRate( sampleRate() );
}
void updateBufferSize() override
{
LocalZynAddSubFx::setBufferSize( bufferSize() );
}
void messageLoop()
{
message m;
while( ( m = receiveMessage() ).id != IdQuit )
{
const auto lock = std::lock_guard{m_master->mutex};
processMessage( m );
}
m_guiExit = true;
}
bool processMessage( const message & _m ) override
{
switch( _m.id )
{
case IdQuit:
break;
case IdShowUI:
case IdHideUI:
case IdLoadSettingsFromFile:
case IdLoadPresetFile:
{
const auto lock = std::lock_guard{m_guiMutex};
m_guiMessages.push( _m );
}
break;
case IdSaveSettingsToFile:
{
LocalZynAddSubFx::saveXML( _m.getString() );
sendMessage( IdSaveSettingsToFile );
break;
}
case IdZasfPresetDirectory:
LocalZynAddSubFx::setPresetDir( _m.getString() );
break;
case IdZasfLmmsWorkingDirectory:
LocalZynAddSubFx::setLmmsWorkingDir( _m.getString() );
break;
case IdZasfSetPitchWheelBendRange:
LocalZynAddSubFx::setPitchWheelBendRange( _m.getInt() );
break;
default:
return RemotePluginClient::processMessage( _m );
}
return true;
}
// all functions are called while m_master->mutex is held
void processMidiEvent( const MidiEvent& event, const f_cnt_t /* _offset */ ) override
{
LocalZynAddSubFx::processMidiEvent( event );
}
void process( const SampleFrame* _in, SampleFrame* _out ) override
{
LocalZynAddSubFx::processAudio( _out );
}
void guiLoop();
private:
const int m_guiSleepTime;
std::thread m_messageThread;
std::mutex m_guiMutex;
std::queue<RemotePluginClient::message> m_guiMessages;
bool m_guiExit;
} ;
void RemoteZynAddSubFx::guiLoop()
{
int exitProgram = 0;
MasterUI * ui = nullptr;
while( !m_guiExit )
{
if( ui )
{
Fl::wait( m_guiSleepTime / 1000.0 );
}
else
{
#ifdef LMMS_BUILD_WIN32
Sleep( m_guiSleepTime );
#else
usleep( m_guiSleepTime*1000 );
#endif
}
if( exitProgram == 1 )
{
const auto lock = std::lock_guard{m_master->mutex};
sendMessage( IdHideUI );
exitProgram = 0;
}
const auto lock = std::lock_guard{m_guiMutex};
while( m_guiMessages.size() )
{
RemotePluginClient::message m = m_guiMessages.front();
m_guiMessages.pop();
switch( m.id )
{
case IdShowUI:
// we only create GUI
if( !ui )
{
Fl::scheme( "plastic" );
ui = new MasterUI( m_master, &exitProgram );
}
ui->showUI();
ui->refresh_master_ui();
break;
case IdLoadSettingsFromFile:
{
LocalZynAddSubFx::loadXML( m.getString() );
if( ui )
{
ui->refresh_master_ui();
}
const auto lock = std::lock_guard{m_master->mutex};
sendMessage( IdLoadSettingsFromFile );
break;
}
case IdLoadPresetFile:
{
LocalZynAddSubFx::loadPreset( m.getString(), ui ?
ui->npartcounter->value()-1 : 0 );
if( ui )
{
ui->npartcounter->do_callback();
ui->updatepanel();
ui->refresh_master_ui();
}
const auto lock = std::lock_guard{m_master->mutex};
sendMessage( IdLoadPresetFile );
break;
}
default:
break;
}
}
}
Fl::flush();
delete ui;
}
int main( int _argc, char * * _argv )
{
#ifdef SYNC_WITH_SHM_FIFO
if( _argc < 3 )
#else
if( _argc < 2 )
#endif
{
fprintf( stderr, "not enough arguments\n" );
return -1;
}
#ifndef LMMS_BUILD_WIN32
const auto pollParentThread = PollParentThread{};
#endif
#ifdef SYNC_WITH_SHM_FIFO
RemoteZynAddSubFx * remoteZASF =
new RemoteZynAddSubFx( _argv[1], _argv[2] );
#else
auto remoteZASF = new RemoteZynAddSubFx(_argv[1]);
#endif
remoteZASF->guiLoop();
delete remoteZASF;
return 0;
}
#ifdef NTK_GUI
static Fl_Tiled_Image *module_backdrop;
#endif
void set_module_parameters ( Fl_Widget *o )
{
#ifdef NTK_GUI
o->box( FL_DOWN_FRAME );
o->align( o->align() | FL_ALIGN_IMAGE_BACKDROP );
o->color( FL_BLACK );
o->image( module_backdrop );
o->labeltype( FL_SHADOW_LABEL );
#else
o->box( FL_PLASTIC_UP_BOX );
o->color( FL_CYAN );
o->labeltype( FL_EMBOSSED_LABEL );
#endif
}
| 6,103
|
C++
|
.cpp
| 246
| 21.609756
| 86
| 0.69864
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,671
|
Nes.cpp
|
LMMS_lmms/plugins/Nes/Nes.cpp
|
/* Nes.cpp - A NES instrument plugin for LMMS
*
* Copyright (c) 2014 Vesa Kivimäki
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "Nes.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "interpolation.h"
#include "Knob.h"
#include "Oscillator.h"
#include "embed.h"
#include "lmms_math.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT nes_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Nescaline",
QT_TRANSLATE_NOOP( "PluginBrowser",
"A NES-like synthesizer" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
NesObject::NesObject( NesInstrument * nes, const sample_rate_t samplerate, NotePlayHandle * nph ) :
m_parent( nes ),
m_samplerate( samplerate ),
m_nph( nph )
{
m_pitchUpdateCounter = 0;
m_pitchUpdateFreq = wavelength( 60.0f );
m_LFSR = LFSR_INIT;
m_ch1Counter = 0;
m_ch2Counter = 0;
m_ch3Counter = 0;
m_ch4Counter = 0;
m_ch1EnvCounter = 0;
m_ch2EnvCounter = 0;
m_ch4EnvCounter = 0;
m_ch1EnvValue = 15;
m_ch2EnvValue = 15;
m_ch4EnvValue = 15;
m_ch1SweepCounter = 0;
m_ch2SweepCounter = 0;
m_ch4SweepCounter = 0;
m_12Last = 0.0f;
m_34Last = 0.0f;
m_maxWlen = wavelength( MIN_FREQ );
m_nsf = NES_SIMPLE_FILTER * ( m_samplerate / 44100.0 );
m_lastNoteFreq = 0;
m_lastNoiseFreq = -1.0f; // value that is always different than noisefreq so it gets updated at start
m_vibratoPhase = 0;
updatePitch();
}
void NesObject::renderOutput( SampleFrame* buf, fpp_t frames )
{
////////////////////////////////
// //
// variables for processing //
// //
////////////////////////////////
bool ch1Enabled = m_parent->m_ch1Enabled.value();
bool ch2Enabled = m_parent->m_ch2Enabled.value();
bool ch3Enabled = m_parent->m_ch3Enabled.value();
bool ch4Enabled = m_parent->m_ch4Enabled.value();
float ch1DutyCycle = DUTY_CYCLE[ m_parent->m_ch1DutyCycle.value() ];
int ch1EnvLen = wavelength( floorf( 240.0 / ( m_parent->m_ch1EnvLen.value() + 1 ) ) );
bool ch1EnvLoop = m_parent->m_ch1EnvLooped.value();
float ch2DutyCycle = DUTY_CYCLE[ m_parent->m_ch2DutyCycle.value() ];
int ch2EnvLen = wavelength( floorf( 240.0 / ( m_parent->m_ch2EnvLen.value() + 1 ) ) );
bool ch2EnvLoop = m_parent->m_ch2EnvLooped.value();
int ch4EnvLen = wavelength( floorf( 240.0 / ( m_parent->m_ch4EnvLen.value() + 1 ) ) );
bool ch4EnvLoop = m_parent->m_ch4EnvLooped.value();
// processing variables for operators
int ch1;
int ch2;
int ch3;
int ch4;
// levels for generators (used for dc offset compensation)
int ch1Level;
int ch2Level;
int ch3Level;
int ch4Level;
int ch1SweepRate = wavelength( floorf( 120.0 / ( m_parent->m_ch1SweepRate.value() + 1 ) ) );
int ch2SweepRate = wavelength( floorf( 120.0 / ( m_parent->m_ch2SweepRate.value() + 1 ) ) );
int ch4SweepRate = wavelength( floorf( 60.0f / ( 8.0f - qAbs( m_parent->m_ch4Sweep.value() ) ) ) );
int ch1Sweep = static_cast<int>( m_parent->m_ch1SweepAmt.value() * -1.0 );
int ch2Sweep = static_cast<int>( m_parent->m_ch2SweepAmt.value() * -1.0 );
int ch4Sweep = 0;
if( m_parent->m_ch4Sweep.value() != 0.0f )
{
ch4Sweep = m_parent->m_ch4Sweep.value() > 0.0f
? -1
: 1;
}
// the amounts are inverted so we correct them here
if( ch1Sweep > 0 )
{
ch1Sweep = 8 - ch1Sweep;
}
if( ch1Sweep < 0 )
{
ch1Sweep = -8 - ch1Sweep;
}
if( ch2Sweep > 0 )
{
ch2Sweep = 8 - ch2Sweep;
}
if( ch2Sweep < 0 )
{
ch2Sweep = -8 - ch2Sweep;
}
// start framebuffer loop
for( f_cnt_t f = 0; f < frames; f++ )
{
////////////////////////////////
// //
// pitch update //
// //
////////////////////////////////
m_pitchUpdateCounter++;
if( m_pitchUpdateCounter >= m_pitchUpdateFreq )
{
updatePitch();
m_pitchUpdateCounter = 0;
}
////////////////////////////////
// //
// channel 1 //
// //
////////////////////////////////
// render pulse wave
if( m_wlen1 <= m_maxWlen && m_wlen1 >= MIN_WLEN && ch1Enabled )
{
ch1Level = m_parent->m_ch1EnvEnabled.value()
? static_cast<int>( ( m_parent->m_ch1Volume.value() * m_ch1EnvValue ) / 15.0 )
: static_cast<int>( m_parent->m_ch1Volume.value() );
ch1 = m_ch1Counter > m_wlen1 * ch1DutyCycle
? 0
: ch1Level;
}
else ch1 = ch1Level = 0;
// update sweep
m_ch1SweepCounter++;
if( m_ch1SweepCounter >= ch1SweepRate )
{
m_ch1SweepCounter = 0;
if( m_parent->m_ch1SweepEnabled.value() && m_wlen1 <= m_maxWlen && m_wlen1 >= MIN_WLEN )
{
// check if the sweep goes up or down
if( ch1Sweep > 0 )
{
m_wlen1 += m_wlen1 >> qAbs( ch1Sweep );
}
if( ch1Sweep < 0 )
{
m_wlen1 -= m_wlen1 >> qAbs( ch1Sweep );
m_wlen1--; // additional minus 1 for ch1 only
}
}
}
// update framecounters
m_ch1Counter++;
m_ch1Counter = m_wlen1 ? m_ch1Counter % m_wlen1 : 0;
m_ch1EnvCounter++;
if( m_ch1EnvCounter >= ch1EnvLen )
{
m_ch1EnvCounter = 0;
m_ch1EnvValue--;
if( m_ch1EnvValue < 0 )
{
m_ch1EnvValue = ch1EnvLoop ? 15 : 0;
}
}
////////////////////////////////
// //
// channel 2 //
// //
////////////////////////////////
// render pulse wave
if( m_wlen2 <= m_maxWlen && m_wlen2 >= MIN_WLEN && ch2Enabled )
{
ch2Level = m_parent->m_ch2EnvEnabled.value()
? static_cast<int>( ( m_parent->m_ch2Volume.value() * m_ch2EnvValue ) / 15.0 )
: static_cast<int>( m_parent->m_ch2Volume.value() );
ch2 = m_ch2Counter > m_wlen2 * ch2DutyCycle
? 0
: ch2Level;
}
else ch2 = ch2Level = 0;
// update sweep
m_ch2SweepCounter++;
if( m_ch2SweepCounter >= ch2SweepRate )
{
m_ch2SweepCounter = 0;
if( m_parent->m_ch2SweepEnabled.value() && m_wlen2 <= m_maxWlen && m_wlen2 >= MIN_WLEN )
{
// check if the sweep goes up or down
if( ch2Sweep > 0 )
{
m_wlen2 += m_wlen2 >> qAbs( ch2Sweep );
}
if( ch2Sweep < 0 )
{
m_wlen2 -= m_wlen2 >> qAbs( ch2Sweep );
}
}
}
// update framecounters
m_ch2Counter++;
m_ch2Counter = m_wlen2 ? m_ch2Counter % m_wlen2 : 0;
m_ch2EnvCounter++;
if( m_ch2EnvCounter >= ch2EnvLen )
{
m_ch2EnvCounter = 0;
m_ch2EnvValue--;
if( m_ch2EnvValue < 0 )
{
m_ch2EnvValue = ch2EnvLoop
? 15
: 0;
}
}
////////////////////////////////
// //
// channel 3 //
// //
////////////////////////////////
// make sure we don't overflow
m_ch3Counter = m_wlen3 ? m_ch3Counter % m_wlen3 : 0;
// render triangle wave
if( m_wlen3 <= m_maxWlen && ch3Enabled )
{
ch3Level = static_cast<int>( m_parent->m_ch3Volume.value() );
ch3 = m_wlen3 ? TRIANGLE_WAVETABLE[ ( m_ch3Counter * 32 ) / m_wlen3 ] : 0;
ch3 = ( ch3 * ch3Level ) / 15;
}
else ch3 = ch3Level = 0;
m_ch3Counter++;
////////////////////////////////
// //
// channel 4 //
// //
////////////////////////////////
// render pseudo noise
if( ch4Enabled )
{
ch4Level = m_parent->m_ch4EnvEnabled.value()
? ( static_cast<int>( m_parent->m_ch4Volume.value() ) * m_ch4EnvValue ) / 15
: static_cast<int>( m_parent->m_ch4Volume.value() );
ch4 = LFSR()
? ch4Level
: 0;
}
else ch4 = ch4Level = 0;
// update framecounters
m_ch4Counter++;
if( m_ch4Counter >= m_wlen4 )
{
m_ch4Counter = 0;
updateLFSR( m_parent->m_ch4NoiseMode.value() );
}
m_ch4EnvCounter++;
if( m_ch4EnvCounter >= ch4EnvLen )
{
m_ch4EnvCounter = 0;
m_ch4EnvValue--;
if( m_ch4EnvValue < 0 )
{
m_ch4EnvValue = ch4EnvLoop
? 15
: 0;
}
}
m_ch4SweepCounter++;
if( m_ch4SweepCounter >= ch4SweepRate )
{
m_ch4SweepCounter = 0;
if( ch4Sweep != 0 )
{
int freqN = nearestNoiseFreq( static_cast<float>( m_samplerate ) / m_wlen4 );
freqN = qBound( 0, freqN + ch4Sweep, 15 );
m_wlen4 = wavelength( NOISE_FREQS[ freqN ] );
if( m_wlen4 == 0 && ch4Sweep == 1 ) // a workaround for sweep getting stuck on 0 wavelength
{
while( m_wlen4 == 0 )
{
m_wlen4 = wavelength( NOISE_FREQS[ ++freqN ] );
}
}
}
}
////////////////////////////////
// //
// final stage - mixing //
// //
////////////////////////////////
auto pin1 = static_cast<float>(ch1 + ch2);
// add dithering noise
pin1 *= 1.0 + ( Oscillator::noiseSample( 0.0f ) * DITHER_AMP );
pin1 = pin1 / 30.0f;
pin1 = signedPowf(pin1, NES_DIST);
pin1 = pin1 * 2.0f - 1.0f;
// simple first order iir filter, to simulate the frequency response falloff in nes analog audio output
pin1 = linearInterpolate( pin1, m_12Last, m_nsf );
m_12Last = pin1;
// compensate DC offset
pin1 += 1.0f - signedPowf(static_cast<float>(ch1Level + ch2Level) / 30.0f, NES_DIST);
pin1 *= NES_MIXING_12;
auto pin2 = static_cast<float>(ch3 + ch4);
// add dithering noise
pin2 *= 1.0 + ( Oscillator::noiseSample( 0.0f ) * DITHER_AMP );
pin2 = pin2 / 30.0f;
pin2 = signedPowf(pin2, NES_DIST);
pin2 = pin2 * 2.0f - 1.0f;
// simple first order iir filter, to simulate the frequency response falloff in nes analog audio output
pin2 = linearInterpolate( pin2, m_34Last, m_nsf );
m_34Last = pin2;
// compensate DC offset
pin2 += 1.0f - signedPowf(static_cast<float>(ch3Level + ch4Level) / 30.0f, NES_DIST);
pin2 *= NES_MIXING_34;
const float mixdown = ( pin1 + pin2 ) * NES_MIXING_ALL * m_parent->m_masterVol.value();
buf[f][0] = mixdown;
buf[f][1] = mixdown;
} // end framebuffer loop
}
void NesObject::updateVibrato( float * freq )
{
float vibratoAmt = floorf( m_parent->m_vibrato.value() ) / 15.0f;
m_vibratoPhase++;
m_vibratoPhase %= 32;
float vibratoRatio = 1.0f + ( static_cast<float>( TRIANGLE_WAVETABLE[ m_vibratoPhase ] ) * 0.02f * vibratoAmt );
*freq *= vibratoRatio;
}
void NesObject::updatePitch()
{
float freq = m_nph->frequency();
// if vibrato is active, update vibrato
if( m_parent->m_vibrato.value() > 0 )
{
updateVibrato( &freq );
}
// check if frequency has changed, if so, update wavelengths of ch1-3
if( freq != m_lastNoteFreq )
{
m_wlen1 = wavelength( freq * m_parent->m_freq1 );
m_wlen2 = wavelength( freq * m_parent->m_freq2 );
m_wlen3 = wavelength( freq * m_parent->m_freq3 );
}
// noise channel can use either note freq or preset freqs
if( m_parent->m_ch4NoiseFreqMode.value() && freq != m_lastNoteFreq )
{
float f = freq * 2.0f;
if( m_parent->m_ch4NoiseQuantize.value() ) // note freq can be quantized to the preset freqs
{
f = NOISE_FREQS[ nearestNoiseFreq( f ) ];
}
m_wlen4 = wavelength( f );
}
if( ! m_parent->m_ch4NoiseFreqMode.value() && m_lastNoiseFreq != m_parent->m_ch4NoiseFreq.value() )
{
m_wlen4 = wavelength( NOISE_FREQS[ 15 - static_cast<int>( m_parent->m_ch4NoiseFreq.value() ) ] );
m_lastNoiseFreq = m_parent->m_ch4NoiseFreq.value();
}
m_lastNoteFreq = freq;
}
NesInstrument::NesInstrument( InstrumentTrack * instrumentTrack ) :
Instrument( instrumentTrack, &nes_plugin_descriptor ),
m_ch1Enabled(true, this, tr("Channel 1 enable")),
m_ch1Crs( 0.f, -24.f, 24.f, 1.f, this, tr( "Channel 1 coarse detune" ) ),
m_ch1Volume( 15.f, 0.f, 15.f, 1.f, this, tr( "Channel 1 volume" ) ),
m_ch1EnvEnabled(false, this, tr("Channel 1 envelope enable")),
m_ch1EnvLooped(false, this, tr("Channel 1 envelope loop")),
m_ch1EnvLen( 0.f, 0.f, 15.f, 1.f, this, tr( "Channel 1 envelope length" ) ),
m_ch1DutyCycle( 0, 0, 3, this, tr( "Channel 1 duty cycle" ) ),
m_ch1SweepEnabled(false, this, tr("Channel 1 sweep enable")),
m_ch1SweepAmt( 0.f, -7.f, 7.f, 1.f, this, tr( "Channel 1 sweep amount" ) ),
m_ch1SweepRate( 0.f, 0.f, 7.f, 1.f, this, tr( "Channel 1 sweep rate" ) ),
m_ch2Enabled(true, this, tr("Channel 2 enable")),
m_ch2Crs( 0.f, -24.f, 24.f, 1.f, this, tr( "Channel 2 coarse detune" ) ),
m_ch2Volume( 15.f, 0.f, 15.f, 1.f, this, tr( "Channel 2 volume" ) ),
m_ch2EnvEnabled(false, this, tr("Channel 2 envelope enable")),
m_ch2EnvLooped(false, this, tr("Channel 2 envelope loop")),
m_ch2EnvLen( 0.f, 0.f, 15.f, 1.f, this, tr( "Channel 2 envelope length" ) ),
m_ch2DutyCycle( 2, 0, 3, this, tr( "Channel 2 duty cycle" ) ),
m_ch2SweepEnabled(false, this, tr("Channel 2 sweep enable")),
m_ch2SweepAmt( 0.f, -7.f, 7.f, 1.f, this, tr( "Channel 2 sweep amount" ) ),
m_ch2SweepRate( 0.f, 0.f, 7.f, 1.f, this, tr( "Channel 2 sweep rate" ) ),
//channel 3
m_ch3Enabled(true, this, tr("Channel 3 enable")),
m_ch3Crs( 0.f, -24.f, 24.f, 1.f, this, tr( "Channel 3 coarse detune" ) ),
m_ch3Volume( 15.f, 0.f, 15.f, 1.f, this, tr( "Channel 3 volume" ) ),
//channel 4
m_ch4Enabled(false, this, tr("Channel 4 enable")),
m_ch4Volume( 15.f, 0.f, 15.f, 1.f, this, tr( "Channel 4 volume" ) ),
m_ch4EnvEnabled(false, this, tr("Channel 4 envelope enable")),
m_ch4EnvLooped(false, this, tr("Channel 4 envelope loop")),
m_ch4EnvLen( 0.f, 0.f, 15.f, 1.f, this, tr( "Channel 4 envelope length" ) ),
m_ch4NoiseMode(false, this, tr("Channel 4 noise mode")),
m_ch4NoiseFreqMode(false, this, tr("Channel 4 frequency mode")),
m_ch4NoiseFreq( 0.f, 0.f, 15.f, 1.f, this, tr( "Channel 4 noise frequency" ) ),
m_ch4Sweep( 0.f, -7.f, 7.f, 1.f, this, tr( "Channel 4 noise frequency sweep" ) ),
m_ch4NoiseQuantize(true, this, tr("Channel 4 quantize")),
//master
m_masterVol( 1.0f, 0.0f, 2.0f, 0.01f, this, tr( "Master volume" ) ),
m_vibrato( 0.0f, 0.0f, 15.0f, 1.0f, this, tr( "Vibrato" ) )
{
connect( &m_ch1Crs, SIGNAL( dataChanged() ), this, SLOT( updateFreq1() ), Qt::DirectConnection );
connect( &m_ch2Crs, SIGNAL( dataChanged() ), this, SLOT( updateFreq2() ), Qt::DirectConnection );
connect( &m_ch3Crs, SIGNAL( dataChanged() ), this, SLOT( updateFreq3() ), Qt::DirectConnection );
updateFreq1();
updateFreq2();
updateFreq3();
}
void NesInstrument::playNote( NotePlayHandle * n, SampleFrame* workingBuffer )
{
const fpp_t frames = n->framesLeftForCurrentPeriod();
const f_cnt_t offset = n->noteOffset();
if (!n->m_pluginData)
{
auto nes = new NesObject(this, Engine::audioEngine()->outputSampleRate(), n);
n->m_pluginData = nes;
}
auto nes = static_cast<NesObject*>(n->m_pluginData);
nes->renderOutput( workingBuffer + offset, frames );
applyRelease( workingBuffer, n );
}
void NesInstrument::deleteNotePluginData( NotePlayHandle * n )
{
delete static_cast<NesObject *>( n->m_pluginData );
}
void NesInstrument::saveSettings( QDomDocument & doc, QDomElement & element )
{
m_ch1Enabled.saveSettings( doc, element, "on1" );
m_ch1Crs.saveSettings( doc, element, "crs1" );
m_ch1Volume.saveSettings( doc, element, "vol1" );
m_ch1EnvEnabled.saveSettings( doc, element, "envon1" );
m_ch1EnvLooped.saveSettings( doc, element, "envloop1" );
m_ch1EnvLen.saveSettings( doc, element, "envlen1" );
m_ch1DutyCycle.saveSettings( doc, element, "dc1" );
m_ch1SweepEnabled.saveSettings( doc, element, "sweep1" );
m_ch1SweepAmt.saveSettings( doc, element, "swamt1" );
m_ch1SweepRate.saveSettings( doc, element, "swrate1" );
// channel 2
m_ch2Enabled.saveSettings( doc, element, "on2" );
m_ch2Crs.saveSettings( doc, element, "crs2" );
m_ch2Volume.saveSettings( doc, element, "vol2" );
m_ch2EnvEnabled.saveSettings( doc, element, "envon2" );
m_ch2EnvLooped.saveSettings( doc, element, "envloop2" );
m_ch2EnvLen.saveSettings( doc, element, "envlen2" );
m_ch2DutyCycle.saveSettings( doc, element, "dc2" );
m_ch2SweepEnabled.saveSettings( doc, element, "sweep2" );
m_ch2SweepAmt.saveSettings( doc, element, "swamt2" );
m_ch2SweepRate.saveSettings( doc, element, "swrate2" );
//channel 3
m_ch3Enabled.saveSettings( doc, element, "on3" );
m_ch3Crs.saveSettings( doc, element, "crs3" );
m_ch3Volume.saveSettings( doc, element, "vol3" );
//channel 4
m_ch4Enabled.saveSettings( doc, element, "on4" );
m_ch4Volume.saveSettings( doc, element, "vol4" );
m_ch4EnvEnabled.saveSettings( doc, element, "envon4" );
m_ch4EnvLooped.saveSettings( doc, element, "envloop4" );
m_ch4EnvLen.saveSettings( doc, element, "envlen4" );
m_ch4NoiseMode.saveSettings( doc, element, "nmode4" );
m_ch4NoiseFreqMode.saveSettings( doc, element, "nfrqmode4" );
m_ch4NoiseFreq.saveSettings( doc, element, "nfreq4" );
m_ch4NoiseQuantize.saveSettings( doc, element, "nq4" );
m_ch4Sweep.saveSettings( doc, element, "nswp4" );
//master
m_masterVol.saveSettings( doc, element, "vol" );
m_vibrato.saveSettings( doc, element, "vibr" );
}
void NesInstrument::loadSettings( const QDomElement & element )
{
m_ch1Enabled.loadSettings( element, "on1" );
m_ch1Crs.loadSettings( element, "crs1" );
m_ch1Volume.loadSettings( element, "vol1" );
m_ch1EnvEnabled.loadSettings( element, "envon1" );
m_ch1EnvLooped.loadSettings( element, "envloop1" );
m_ch1EnvLen.loadSettings( element, "envlen1" );
m_ch1DutyCycle.loadSettings( element, "dc1" );
m_ch1SweepEnabled.loadSettings( element, "sweep1" );
m_ch1SweepAmt.loadSettings( element, "swamt1" );
m_ch1SweepRate.loadSettings( element, "swrate1" );
// channel 2
m_ch2Enabled.loadSettings( element, "on2" );
m_ch2Crs.loadSettings( element, "crs2" );
m_ch2Volume.loadSettings( element, "vol2" );
m_ch2EnvEnabled.loadSettings( element, "envon2" );
m_ch2EnvLooped.loadSettings( element, "envloop2" );
m_ch2EnvLen.loadSettings( element, "envlen2" );
m_ch2DutyCycle.loadSettings( element, "dc2" );
m_ch2SweepEnabled.loadSettings( element, "sweep2" );
m_ch2SweepAmt.loadSettings( element, "swamt2" );
m_ch2SweepRate.loadSettings( element, "swrate2" );
//channel 3
m_ch3Enabled.loadSettings( element, "on3" );
m_ch3Crs.loadSettings( element, "crs3" );
m_ch3Volume.loadSettings( element, "vol3" );
//channel 4
m_ch4Enabled.loadSettings( element, "on4" );
m_ch4Volume.loadSettings( element, "vol4" );
m_ch4EnvEnabled.loadSettings( element, "envon4" );
m_ch4EnvLooped.loadSettings( element, "envloop4" );
m_ch4EnvLen.loadSettings( element, "envlen4" );
m_ch4NoiseMode.loadSettings( element, "nmode4" );
m_ch4NoiseFreqMode.loadSettings( element, "nfrqmode4" );
m_ch4NoiseFreq.loadSettings( element, "nfreq4" );
m_ch4NoiseQuantize.loadSettings( element, "nq4" );
m_ch4Sweep.loadSettings( element, "nswp4" );
//master
m_masterVol.loadSettings( element, "vol" );
m_vibrato.loadSettings( element, "vibr" );
}
QString NesInstrument::nodeName() const
{
return( nes_plugin_descriptor.name );
}
gui::PluginView* NesInstrument::instantiateView( QWidget * parent )
{
return( new gui::NesInstrumentView( this, parent ) );
}
void NesInstrument::updateFreq1()
{
m_freq1 = powf( 2, m_ch1Crs.value() / 12.0f );
}
void NesInstrument::updateFreq2()
{
m_freq2 = powf( 2, m_ch2Crs.value() / 12.0f );
}
void NesInstrument::updateFreq3()
{
m_freq3 = powf( 2, m_ch3Crs.value() / 12.0f );
}
namespace gui
{
NesInstrumentView::NesInstrumentView( Instrument * instrument, QWidget * parent ) :
InstrumentViewFixedSize( instrument, parent )
{
setAutoFillBackground( true );
QPalette pal;
static auto s_artwork = PLUGIN_NAME::getIconPixmap("artwork");
pal.setBrush(backgroundRole(), s_artwork);
setPalette( pal );
const int KNOB_Y1 = 24;
const int KNOB_Y2 = 81;
const int KNOB_Y3 = 138;
const int KNOB_Y4 = 195;
const int KNOB_X1 = 12;
const int KNOB_X2 = 46;
const int KNOB_X3 = 84;
const int KNOB_X4 = 117;
const int KNOB_X5 = 151;
const int KNOB_X6 = 172;
const int KNOB_X7 = 206;
// channel 1
makeknob( m_ch1VolumeKnob, KNOB_X1, KNOB_Y1, tr( "Volume" ), "", "" )
makeknob( m_ch1CrsKnob, KNOB_X2, KNOB_Y1, tr( "Coarse detune" ), "", "" )
makeknob( m_ch1EnvLenKnob, KNOB_X3, KNOB_Y1, tr( "Envelope length" ), "", "" )
makenesled( m_ch1EnabledBtn, KNOB_X1, KNOB_Y1 - 12, tr( "Enable channel 1" ) )
makenesled( m_ch1EnvEnabledBtn, KNOB_X3, KNOB_Y1 - 12, tr( "Enable envelope 1" ) )
makenesled( m_ch1EnvLoopedBtn, 129, KNOB_Y1 - 12, tr( "Enable envelope 1 loop" ) )
makenesled( m_ch1SweepEnabledBtn, KNOB_X6, KNOB_Y1 - 12, tr( "Enable sweep 1" ) )
makeknob( m_ch1SweepAmtKnob, KNOB_X6, KNOB_Y1, tr( "Sweep amount" ), "", "" )
makeknob( m_ch1SweepRateKnob, KNOB_X7, KNOB_Y1, tr( "Sweep rate" ), "", "" )
int dcx = 117;
makedcled( ch1_dc1, dcx, 42, tr( "12.5% Duty cycle" ), "nesdc1_on" )
dcx += 13;
makedcled( ch1_dc2, dcx, 42, tr( "25% Duty cycle" ), "nesdc2_on" )
dcx += 13;
makedcled( ch1_dc3, dcx, 42, tr( "50% Duty cycle" ), "nesdc3_on" )
dcx += 13;
makedcled( ch1_dc4, dcx, 42, tr( "75% Duty cycle" ), "nesdc4_on" )
m_ch1DutyCycleGrp = new automatableButtonGroup( this );
m_ch1DutyCycleGrp -> addButton( ch1_dc1 );
m_ch1DutyCycleGrp -> addButton( ch1_dc2 );
m_ch1DutyCycleGrp -> addButton( ch1_dc3 );
m_ch1DutyCycleGrp -> addButton( ch1_dc4 );
// channel 2
makeknob( m_ch2VolumeKnob, KNOB_X1, KNOB_Y2, tr( "Volume" ), "", "" )
makeknob( m_ch2CrsKnob, KNOB_X2, KNOB_Y2, tr( "Coarse detune" ), "", "" )
makeknob( m_ch2EnvLenKnob, KNOB_X3, KNOB_Y2, tr( "Envelope length" ), "", "" )
makenesled( m_ch2EnabledBtn, KNOB_X1, KNOB_Y2 - 12, tr( "Enable channel 2" ) )
makenesled( m_ch2EnvEnabledBtn, KNOB_X3, KNOB_Y2 - 12, tr( "Enable envelope 2" ) )
makenesled( m_ch2EnvLoopedBtn, 129, KNOB_Y2 - 12, tr( "Enable envelope 2 loop" ) )
makenesled( m_ch2SweepEnabledBtn, KNOB_X6, KNOB_Y2 - 12, tr( "Enable sweep 2" ) )
makeknob( m_ch2SweepAmtKnob, KNOB_X6, KNOB_Y2, tr( "Sweep amount" ), "", "" )
makeknob( m_ch2SweepRateKnob, KNOB_X7, KNOB_Y2, tr( "Sweep rate" ), "", "" )
dcx = 117;
makedcled( ch2_dc1, dcx, 99, tr( "12.5% Duty cycle" ), "nesdc1_on" )
dcx += 13;
makedcled( ch2_dc2, dcx, 99, tr( "25% Duty cycle" ), "nesdc2_on" )
dcx += 13;
makedcled( ch2_dc3, dcx, 99, tr( "50% Duty cycle" ), "nesdc3_on" )
dcx += 13;
makedcled( ch2_dc4, dcx, 99, tr( "75% Duty cycle" ), "nesdc4_on" )
m_ch2DutyCycleGrp = new automatableButtonGroup( this );
m_ch2DutyCycleGrp -> addButton( ch2_dc1 );
m_ch2DutyCycleGrp -> addButton( ch2_dc2 );
m_ch2DutyCycleGrp -> addButton( ch2_dc3 );
m_ch2DutyCycleGrp -> addButton( ch2_dc4 );
//channel 3
makenesled( m_ch3EnabledBtn, KNOB_X1, KNOB_Y3 - 12, tr( "Enable channel 3" ) )
makeknob( m_ch3VolumeKnob, KNOB_X1, KNOB_Y3, tr( "Volume" ), "", "" )
makeknob( m_ch3CrsKnob, KNOB_X2, KNOB_Y3, tr( "Coarse detune" ), "", "" )
//channel 4
makeknob( m_ch4VolumeKnob, KNOB_X1, KNOB_Y4, tr( "Volume" ), "", "" )
makeknob( m_ch4NoiseFreqKnob, KNOB_X2, KNOB_Y4, tr( "Noise Frequency" ), "", "" )
makeknob( m_ch4EnvLenKnob, KNOB_X3, KNOB_Y4, tr( "Envelope length" ), "", "" )
makeknob( m_ch4SweepKnob, KNOB_X4, KNOB_Y4, tr( "Frequency sweep" ), "", "" )
makenesled( m_ch4EnabledBtn, KNOB_X1, KNOB_Y4 - 12, tr( "Enable channel 4" ) )
makenesled( m_ch4EnvEnabledBtn, KNOB_X3, KNOB_Y4 - 12, tr( "Enable envelope 4" ) )
makenesled( m_ch4EnvLoopedBtn, 129, KNOB_Y4 - 12, tr( "Enable envelope 4 loop" ) )
makenesled( m_ch4NoiseQuantizeBtn, 162, KNOB_Y4 - 12, tr( "Quantize noise frequency when using note frequency" ) )
makenesled( m_ch4NoiseFreqModeBtn, 148, 203, tr( "Use note frequency for noise" ) )
makenesled( m_ch4NoiseModeBtn, 148, 224, tr( "Noise mode" ) )
//master
makeknob( m_masterVolKnob, KNOB_X4, KNOB_Y3, tr( "Master volume" ), "", "" )
makeknob( m_vibratoKnob, KNOB_X5, KNOB_Y3, tr( "Vibrato" ), "", "" )
}
void NesInstrumentView::modelChanged()
{
auto nes = castModel<NesInstrument>();
m_ch1EnabledBtn->setModel( &nes->m_ch1Enabled );
m_ch1CrsKnob->setModel( &nes->m_ch1Crs );
m_ch1VolumeKnob->setModel( &nes->m_ch1Volume );
m_ch1EnvEnabledBtn->setModel( &nes->m_ch1EnvEnabled );
m_ch1EnvLoopedBtn->setModel( &nes->m_ch1EnvLooped );
m_ch1EnvLenKnob->setModel( &nes->m_ch1EnvLen );
m_ch1DutyCycleGrp->setModel( &nes->m_ch1DutyCycle );
m_ch1SweepEnabledBtn->setModel( &nes->m_ch1SweepEnabled );
m_ch1SweepAmtKnob->setModel( &nes->m_ch1SweepAmt );
m_ch1SweepRateKnob->setModel( &nes->m_ch1SweepRate );
// channel 2
m_ch2EnabledBtn->setModel( &nes->m_ch2Enabled );
m_ch2CrsKnob->setModel( &nes->m_ch2Crs );
m_ch2VolumeKnob->setModel( &nes->m_ch2Volume );
m_ch2EnvEnabledBtn->setModel( &nes->m_ch2EnvEnabled );
m_ch2EnvLoopedBtn->setModel( &nes->m_ch2EnvLooped );
m_ch2EnvLenKnob->setModel( &nes->m_ch2EnvLen );
m_ch2DutyCycleGrp->setModel( &nes->m_ch2DutyCycle );
m_ch2SweepEnabledBtn->setModel( &nes->m_ch2SweepEnabled );
m_ch2SweepAmtKnob->setModel( &nes->m_ch2SweepAmt );
m_ch2SweepRateKnob->setModel( &nes->m_ch2SweepRate );
//channel 3
m_ch3EnabledBtn->setModel( &nes->m_ch3Enabled );
m_ch3CrsKnob->setModel( &nes->m_ch3Crs );
m_ch3VolumeKnob->setModel( &nes->m_ch3Volume );
//channel 4
m_ch4EnabledBtn->setModel( &nes->m_ch4Enabled );
m_ch4VolumeKnob->setModel( &nes->m_ch4Volume );
m_ch4EnvEnabledBtn->setModel( &nes->m_ch4EnvEnabled );
m_ch4EnvLoopedBtn->setModel( &nes->m_ch4EnvLooped );
m_ch4EnvLenKnob->setModel( &nes->m_ch4EnvLen );
m_ch4NoiseModeBtn->setModel( &nes->m_ch4NoiseMode );
m_ch4NoiseFreqModeBtn->setModel( &nes->m_ch4NoiseFreqMode );
m_ch4NoiseFreqKnob->setModel( &nes->m_ch4NoiseFreq );
m_ch4SweepKnob->setModel( &nes->m_ch4Sweep );
m_ch4NoiseQuantizeBtn->setModel( &nes->m_ch4NoiseQuantize );
//master
m_masterVolKnob->setModel( &nes->m_masterVol );
m_vibratoKnob->setModel( &nes->m_vibrato );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * _data )
{
return( new NesInstrument( static_cast<InstrumentTrack *>( m ) ) );
}
}
} // namespace lmms
| 26,971
|
C++
|
.cpp
| 702
| 35.303419
| 115
| 0.65312
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,672
|
TapTempo.cpp
|
LMMS_lmms/plugins/TapTempo/TapTempo.cpp
|
/*
* TapTempo.cpp - Plugin to count beats per minute
*
*
* Copyright (c) 2022 saker <sakertooth@gmail.com>
*
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TapTempo.h"
#include <QFont>
#include <QKeyEvent>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <cfloat>
#include <cmath>
#include <string>
#include "AudioEngine.h"
#include "Engine.h"
#include "LedCheckBox.h"
#include "SamplePlayHandle.h"
#include "Song.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms {
extern "C" {
Plugin::Descriptor PLUGIN_EXPORT taptempo_plugin_descriptor
= {LMMS_STRINGIFY(PLUGIN_NAME), "Tap Tempo", QT_TRANSLATE_NOOP("PluginBrowser", "Tap to the beat"),
"saker <sakertooth@gmail.com>", 0x0100, Plugin::Type::Tool, new PluginPixmapLoader("logo"), nullptr, nullptr};
PLUGIN_EXPORT Plugin* lmms_plugin_main(Model*, void*)
{
return new TapTempo;
}
}
TapTempo::TapTempo()
: ToolPlugin(&taptempo_plugin_descriptor, nullptr)
{
}
void TapTempo::onBpmClick()
{
const auto currentTime = clock::now();
if (m_numTaps == 0)
{
m_startTime = currentTime;
}
else
{
using namespace std::chrono_literals;
const auto secondsElapsed = (currentTime - m_startTime) / 1.0s;
if (m_numTaps >= m_tapsNeededToDisplay) { m_bpm = m_numTaps / secondsElapsed * 60; }
}
++m_numTaps;
}
QString TapTempo::nodeName() const
{
return taptempo_plugin_descriptor.name;
}
} // namespace lmms
| 2,168
|
C++
|
.cpp
| 75
| 27.173333
| 112
| 0.746641
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,673
|
TapTempoView.cpp
|
LMMS_lmms/plugins/TapTempo/TapTempoView.cpp
|
/*
* TapTempoView.cpp - Plugin to count beats per minute
*
*
* Copyright (c) 2022 saker <sakertooth@gmail.com>
*
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "TapTempoView.h"
#include <QCheckBox>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QVariant>
#include <QWidget>
#include "Engine.h"
#include "FontHelper.h"
#include "SamplePlayHandle.h"
#include "Song.h"
#include "TapTempo.h"
namespace lmms::gui {
TapTempoView::TapTempoView(TapTempo* plugin)
: ToolPluginView(plugin)
, m_plugin(plugin)
{
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
auto font = QFont();
m_tapButton = new QPushButton();
m_tapButton->setFixedSize(200, 200);
m_tapButton->setFont(adjustedToPixelSize(font, 32));
m_tapButton->setText(tr("0"));
auto precisionCheckBox = new QCheckBox(tr("Precision"));
precisionCheckBox->setFocusPolicy(Qt::NoFocus);
precisionCheckBox->setToolTip(tr("Display in high precision"));
precisionCheckBox->setText(tr("Precision"));
auto muteCheckBox = new QCheckBox(tr("0.0 ms"));
muteCheckBox->setFocusPolicy(Qt::NoFocus);
muteCheckBox->setToolTip(tr("Mute metronome"));
muteCheckBox->setText(tr("Mute"));
m_msLabel = new QLabel();
m_msLabel->setFocusPolicy(Qt::NoFocus);
m_msLabel->setToolTip(tr("BPM in milliseconds"));
m_msLabel->setText(tr("0 ms"));
m_hzLabel = new QLabel();
m_hzLabel->setFocusPolicy(Qt::NoFocus);
m_hzLabel->setToolTip(tr("Frequency of BPM"));
m_hzLabel->setText(tr("0.0000 hz"));
auto resetButton = new QPushButton(tr("Reset"));
resetButton->setFocusPolicy(Qt::NoFocus);
resetButton->setToolTip(tr("Reset counter and sidebar information"));
auto syncButton = new QPushButton(tr("Sync"));
syncButton->setFocusPolicy(Qt::NoFocus);
syncButton->setToolTip(tr("Sync with project tempo"));
auto optionLayout = new QVBoxLayout();
optionLayout->addWidget(precisionCheckBox);
optionLayout->addWidget(muteCheckBox);
auto bpmInfoLayout = new QVBoxLayout();
bpmInfoLayout->addWidget(m_msLabel, 0, Qt::AlignHCenter);
bpmInfoLayout->addWidget(m_hzLabel, 0, Qt::AlignHCenter);
auto sidebarLayout = new QHBoxLayout();
sidebarLayout->addLayout(optionLayout);
sidebarLayout->addLayout(bpmInfoLayout);
auto buttonsLayout = new QHBoxLayout();
buttonsLayout->addWidget(resetButton, 0, Qt::AlignCenter);
buttonsLayout->addWidget(syncButton, 0, Qt::AlignCenter);
auto mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(m_tapButton, 0, Qt::AlignCenter);
mainLayout->addLayout(buttonsLayout);
mainLayout->addLayout(sidebarLayout);
connect(m_tapButton, &QPushButton::pressed, this, [this, muteCheckBox]() {
if (!muteCheckBox->isChecked())
{
const auto timeSigNumerator = Engine::getSong()->getTimeSigModel().getNumerator();
Engine::audioEngine()->addPlayHandle(new SamplePlayHandle(
m_plugin->m_numTaps % timeSigNumerator == 0 ? "misc/metronome02.ogg" : "misc/metronome01.ogg"));
}
m_plugin->onBpmClick();
updateLabels();
});
connect(resetButton, &QPushButton::pressed, this, [this]() { closeEvent(nullptr); });
connect(precisionCheckBox, &QCheckBox::toggled, [this](bool checked) {
m_plugin->m_showDecimal = checked;
updateLabels();
});
connect(syncButton, &QPushButton::clicked, this, [this]() {
const auto& tempoModel = Engine::getSong()->tempoModel();
if (m_plugin->m_bpm < tempoModel.minValue() || m_plugin->m_bpm > tempoModel.maxValue()) { return; }
Engine::getSong()->setTempo(std::round(m_plugin->m_bpm));
});
hide();
if (parentWidget())
{
parentWidget()->hide();
parentWidget()->layout()->setSizeConstraint(QLayout::SetFixedSize);
Qt::WindowFlags flags = parentWidget()->windowFlags();
flags |= Qt::MSWindowsFixedSizeDialogHint;
flags &= ~Qt::WindowMaximizeButtonHint;
parentWidget()->setWindowFlags(flags);
}
}
void TapTempoView::updateLabels()
{
const double bpm = m_plugin->m_showDecimal ? m_plugin->m_bpm : std::round(m_plugin->m_bpm);
const double hz = bpm / 60;
const double ms = bpm > 0 ? 1 / hz * 1000 : 0;
m_tapButton->setText(QString::number(bpm, 'f', m_plugin->m_showDecimal ? 1 : 0));
m_msLabel->setText(tr("%1 ms").arg(ms, 0, 'f', m_plugin->m_showDecimal ? 1 : 0));
m_hzLabel->setText(tr("%1 hz").arg(hz, 0, 'f', 4));
}
void TapTempoView::keyPressEvent(QKeyEvent* event)
{
QWidget::keyPressEvent(event);
if (!event->isAutoRepeat()) { m_plugin->onBpmClick(); }
}
void TapTempoView::closeEvent(QCloseEvent*)
{
m_plugin->m_numTaps = 0;
m_plugin->m_bpm = 0;
updateLabels();
}
} // namespace lmms::gui
| 5,308
|
C++
|
.cpp
| 140
| 35.757143
| 101
| 0.740856
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,674
|
AmplifierControls.cpp
|
LMMS_lmms/plugins/Amplifier/AmplifierControls.cpp
|
/*
* AmplifierControls.cpp - controls for amplifier effect
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "AmplifierControls.h"
#include "Amplifier.h"
namespace lmms
{
AmplifierControls::AmplifierControls(AmplifierEffect* effect) :
EffectControls(effect),
m_effect(effect),
m_volumeModel(100.0f, 0.0f, 200.0f, 0.1f, this, tr("Volume")),
m_panModel(0.0f, -100.0f, 100.0f, 0.1f, this, tr("Panning")),
m_leftModel(100.0f, 0.0f, 200.0f, 0.1f, this, tr("Left gain")),
m_rightModel(100.0f, 0.0f, 200.0f, 0.1f, this, tr("Right gain"))
{
}
void AmplifierControls::loadSettings(const QDomElement& parent)
{
m_volumeModel.loadSettings(parent, "volume");
m_panModel.loadSettings(parent, "pan");
m_leftModel.loadSettings(parent, "left");
m_rightModel.loadSettings(parent, "right");
}
void AmplifierControls::saveSettings(QDomDocument& doc, QDomElement& parent)
{
m_volumeModel.saveSettings(doc, parent, "volume");
m_panModel.saveSettings(doc, parent, "pan");
m_leftModel.saveSettings(doc, parent, "left");
m_rightModel.saveSettings(doc, parent, "right");
}
} // namespace lmms
| 2,022
|
C++
|
.cpp
| 53
| 36.245283
| 77
| 0.750383
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,675
|
Amplifier.cpp
|
LMMS_lmms/plugins/Amplifier/Amplifier.cpp
|
/*
* Amplifier.cpp - A native amplifier effect plugin with sample-exact amplification
*
* Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Amplifier.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT amplifier_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"Amplifier",
QT_TRANSLATE_NOOP("PluginBrowser", "A native amplifier plugin"),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
AmplifierEffect::AmplifierEffect(Model* parent, const Descriptor::SubPluginFeatures::Key* key) :
Effect(&lifier_plugin_descriptor, parent, key),
m_ampControls(this)
{
}
Effect::ProcessStatus AmplifierEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const float d = dryLevel();
const float w = wetLevel();
const ValueBuffer* volumeBuf = m_ampControls.m_volumeModel.valueBuffer();
const ValueBuffer* panBuf = m_ampControls.m_panModel.valueBuffer();
const ValueBuffer* leftBuf = m_ampControls.m_leftModel.valueBuffer();
const ValueBuffer* rightBuf = m_ampControls.m_rightModel.valueBuffer();
for (fpp_t f = 0; f < frames; ++f)
{
const float volume = (volumeBuf ? volumeBuf->value(f) : m_ampControls.m_volumeModel.value()) * 0.01f;
const float pan = (panBuf ? panBuf->value(f) : m_ampControls.m_panModel.value()) * 0.01f;
const float left = (leftBuf ? leftBuf->value(f) : m_ampControls.m_leftModel.value()) * 0.01f;
const float right = (rightBuf ? rightBuf->value(f) : m_ampControls.m_rightModel.value()) * 0.01f;
const float panLeft = std::min(1.0f, 1.0f - pan);
const float panRight = std::min(1.0f, 1.0f + pan);
auto& currentFrame = buf[f];
const auto s = currentFrame * SampleFrame(left * panLeft, right * panRight) * volume;
// Dry/wet mix
currentFrame = currentFrame * d + s * w;
}
return ProcessStatus::ContinueIfNotQuiet;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin* lmms_plugin_main(Model* parent, void* data)
{
return new AmplifierEffect(parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key*>(data));
}
}
} // namespace lmms
| 3,111
|
C++
|
.cpp
| 81
| 36.308642
| 106
| 0.746507
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,676
|
AmplifierControlDialog.cpp
|
LMMS_lmms/plugins/Amplifier/AmplifierControlDialog.cpp
|
/*
* AmplifierControlDialog.cpp - control dialog for amplifier effect
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "AmplifierControlDialog.h"
#include "AmplifierControls.h"
#include "embed.h"
#include "Knob.h"
namespace lmms::gui
{
AmplifierControlDialog::AmplifierControlDialog(AmplifierControls* controls) :
EffectControlDialog(controls)
{
setAutoFillBackground(true);
QPalette pal;
pal.setBrush(backgroundRole(), PLUGIN_NAME::getIconPixmap("artwork"));
setPalette(pal);
setFixedSize(100, 110);
auto makeKnob = [this](int x, int y, const QString& label, const QString& hintText, const QString& unit, FloatModel* model, bool isVolume)
{
Knob* newKnob = new Knob(KnobType::Bright26, this);
newKnob->move(x, y);
newKnob->setModel(model);
newKnob->setLabel(label);
newKnob->setHintText(hintText, unit);
newKnob->setVolumeKnob(isVolume);
return newKnob;
};
makeKnob(16, 10, tr("VOL"), tr("Volume:"), "%", &controls->m_volumeModel, true);
makeKnob(57, 10, tr("PAN"), tr("Panning:"), "%", &controls->m_panModel, false);
makeKnob(16, 65, tr("LEFT"), tr("Left gain:"), "%", &controls->m_leftModel, true);
makeKnob(57, 65, tr("RIGHT"), tr("Right gain:"), "%", &controls->m_rightModel, true);
}
} // namespace lmms::gui
| 2,201
|
C++
|
.cpp
| 54
| 37.87037
| 139
| 0.72243
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,677
|
LadspaSubPluginFeatures.cpp
|
LMMS_lmms/plugins/LadspaEffect/LadspaSubPluginFeatures.cpp
|
/*
* LadspaSubPluginFeatures.cpp - derivation from
* Plugin::Descriptor::SubPluginFeatures for
* hosting LADSPA-plugins
*
* Copyright (c) 2006-2007 Danny McRae <khjklujn/at/users.sourceforge.net>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QHBoxLayout>
#include <QLabel>
#include "LadspaSubPluginFeatures.h"
#include "AudioDevice.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "Ladspa2LMMS.h"
#include "LadspaBase.h"
namespace lmms
{
LadspaSubPluginFeatures::LadspaSubPluginFeatures( Plugin::Type _type ) :
SubPluginFeatures( _type )
{
}
QString LadspaSubPluginFeatures::displayName(const Plugin::Descriptor::SubPluginFeatures::Key &k) const
{
const ladspa_key_t & lkey = subPluginKeyToLadspaKey(&k);
Ladspa2LMMS * lm = Engine::getLADSPAManager();
return lm->getName(lkey);
}
void LadspaSubPluginFeatures::fillDescriptionWidget( QWidget * _parent,
const Key * _key ) const
{
const ladspa_key_t & lkey = subPluginKeyToLadspaKey( _key );
Ladspa2LMMS * lm = Engine::getLADSPAManager();
auto label = new QLabel(_parent);
label->setText( QWidget::tr( "Name: " ) + lm->getName( lkey ) );
auto fileInfo = new QLabel(_parent);
fileInfo->setText( QWidget::tr( "File: %1" ).arg( lkey.first ) );
auto maker = new QWidget(_parent);
auto l = new QHBoxLayout(maker);
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing( 0 );
auto maker_label = new QLabel(maker);
maker_label->setText( QWidget::tr( "Maker: " ) );
maker_label->setAlignment( Qt::AlignTop );
auto maker_content = new QLabel(maker);
maker_content->setText( lm->getMaker( lkey ) );
maker_content->setWordWrap( true );
l->addWidget( maker_label );
l->addWidget( maker_content, 1 );
auto copyright = new QWidget(_parent);
l = new QHBoxLayout( copyright );
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing( 0 );
copyright->setMinimumWidth( _parent->minimumWidth() );
auto copyright_label = new QLabel(copyright);
copyright_label->setText( QWidget::tr( "Copyright: " ) );
copyright_label->setAlignment( Qt::AlignTop );
auto copyright_content = new QLabel(copyright);
copyright_content->setText( lm->getCopyright( lkey ) );
copyright_content->setWordWrap( true );
l->addWidget( copyright_label );
l->addWidget( copyright_content, 1 );
auto requiresRealTime = new QLabel(_parent);
requiresRealTime->setText( QWidget::tr( "Requires Real Time: " ) +
( lm->hasRealTimeDependency( lkey ) ?
QWidget::tr( "Yes" ) :
QWidget::tr( "No" ) ) );
auto realTimeCapable = new QLabel(_parent);
realTimeCapable->setText( QWidget::tr( "Real Time Capable: " ) +
( lm->isRealTimeCapable( lkey ) ?
QWidget::tr( "Yes" ) :
QWidget::tr( "No" ) ) );
auto inplaceBroken = new QLabel(_parent);
inplaceBroken->setText( QWidget::tr( "In Place Broken: " ) +
( lm->isInplaceBroken( lkey ) ?
QWidget::tr( "Yes" ) :
QWidget::tr( "No" ) ) );
auto channelsIn = new QLabel(_parent);
channelsIn->setText( QWidget::tr( "Channels In: " ) +
QString::number( lm->getDescription( lkey )->inputChannels ) );
auto channelsOut = new QLabel(_parent);
channelsOut->setText( QWidget::tr( "Channels Out: " ) +
QString::number( lm->getDescription( lkey )->outputChannels ) );
}
void LadspaSubPluginFeatures::listSubPluginKeys(
const Plugin::Descriptor * _desc, KeyList & _kl ) const
{
Ladspa2LMMS * lm = Engine::getLADSPAManager();
l_sortable_plugin_t plugins;
switch( m_type )
{
case Plugin::Type::Instrument:
plugins = lm->getInstruments();
break;
case Plugin::Type::Effect:
plugins = lm->getValidEffects();
//plugins += lm->getInvalidEffects();
break;
case Plugin::Type::Tool:
plugins = lm->getAnalysisTools();
break;
case Plugin::Type::Other:
plugins = lm->getOthers();
break;
default:
break;
}
for( l_sortable_plugin_t::const_iterator it = plugins.begin();
it != plugins.end(); ++it )
{
if( lm->getDescription( ( *it ).second )->inputChannels <= Engine::audioEngine()->audioDev()->channels() )
{
_kl.push_back( ladspaKeyToSubPluginKey( _desc, ( *it ).first, ( *it ).second ) );
}
}
}
ladspa_key_t LadspaSubPluginFeatures::subPluginKeyToLadspaKey(
const Key * _key )
{
QString file = _key->attributes["file"];
return(ladspa_key_t(file.remove(QRegularExpression("\\.so$")).remove(QRegularExpression("\\.dll$")) +
#ifdef LMMS_BUILD_WIN32
".dll"
#else
".so"
#endif
, _key->attributes["plugin"] ) );
}
} // namespace lmms
| 5,377
|
C++
|
.cpp
| 147
| 33.693878
| 108
| 0.698055
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,678
|
LadspaWidgetFactory.cpp
|
LMMS_lmms/plugins/LadspaEffect/LadspaWidgetFactory.cpp
|
/*
* LadspaWidgetFactory.cpp - Factory that creates widgets for LADSPA ports
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
* Copyright (c) 2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2015-2023 Michael Gregorius
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LadspaWidgetFactory.h"
#include "LadspaControl.h"
#include "LadspaBase.h"
#include "BarModelEditor.h"
#include "LedCheckBox.h"
#include "TempoSyncBarModelEditor.h"
#include <QHBoxLayout>
#include <QLabel>
namespace lmms::gui
{
QWidget * LadspaWidgetFactory::createWidget(LadspaControl * ladspaControl, QWidget * parent)
{
auto const * port = ladspaControl->port();
QString const name = port->name;
switch (port->data_type)
{
case BufferDataType::Toggled:
{
// The actual check box is put into a widget because LedCheckBox does not play nice with layouts.
// Putting it directly into a grid layout disables the resizing behavior of all columns where it
// appears. Hence we put it into the layout of a widget that knows how to play nice with layouts.
QWidget * widgetWithLayout = new QWidget(parent);
QHBoxLayout * layout = new QHBoxLayout(widgetWithLayout);
layout->setContentsMargins(0, 0, 0, 0);
LedCheckBox * toggle = new LedCheckBox(
name, parent, QString(), LedCheckBox::LedColor::Green, false);
toggle->setModel(ladspaControl->toggledModel());
layout->addWidget(toggle, 0, Qt::AlignLeft);
return widgetWithLayout;
}
case BufferDataType::Integer:
case BufferDataType::Enum:
case BufferDataType::Floating:
return new BarModelEditor(name, ladspaControl->knobModel(), parent);
case BufferDataType::Time:
return new TempoSyncBarModelEditor(name, ladspaControl->tempoSyncKnobModel(), parent);
default:
return new QLabel(QObject::tr("%1 (unsupported)").arg(name), parent);
}
return nullptr;
}
} // namespace lmms::gui
| 2,655
|
C++
|
.cpp
| 67
| 37.373134
| 99
| 0.767107
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,679
|
LadspaMatrixControlDialog.cpp
|
LMMS_lmms/plugins/LadspaEffect/LadspaMatrixControlDialog.cpp
|
/*
* LadspaMatrixControlDialog.h - Dialog for displaying and editing control port
* values for LADSPA plugins in a matrix display
*
* Copyright (c) 2015 Michael Gregorius <michaelgregorius/at/web[dot]de>
*
* This file is part of LMMS - http://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QGroupBox>
#include <QLayout>
#include <QLabel>
#include <QScrollArea>
#include <QScrollBar>
#include <QSpacerItem>
#include <QMdiArea>
#include "LadspaBase.h"
#include "LadspaControl.h"
#include "LadspaEffect.h"
#include "LadspaMatrixControlDialog.h"
#include "LadspaWidgetFactory.h"
#include "LadspaControlView.h"
#include "LedCheckBox.h"
namespace lmms::gui
{
LadspaMatrixControlDialog::LadspaMatrixControlDialog(LadspaControls * ladspaControls) :
EffectControlDialog(ladspaControls),
m_scrollArea(nullptr),
m_stereoLink(nullptr)
{
QVBoxLayout * mainLayout = new QVBoxLayout(this);
m_scrollArea = new QScrollArea(this);
m_scrollArea->setWidgetResizable(true);
m_scrollArea->setFrameShape(QFrame::NoFrame);
// Set to always on so that the elements do not move around when the
// scroll bar is hidden or shown.
m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
// Add a scroll area that grows
mainLayout->addWidget(m_scrollArea, 1);
// Populate the parameter matrix and put it into the scroll area
updateEffectView(ladspaControls);
// Add button to link all channels if there's more than one channel
if (getChannelCount() > 1)
{
mainLayout->addSpacing(3);
m_stereoLink = new LedCheckBox(tr("Link Channels"), this, QString(), LedCheckBox::LedColor::Green, false);
m_stereoLink->setModel(&ladspaControls->m_stereoLinkModel);
mainLayout->addWidget(m_stereoLink, 0, Qt::AlignCenter);
}
}
bool LadspaMatrixControlDialog::isResizable() const
{
return true;
}
bool LadspaMatrixControlDialog::needsLinkColumn() const
{
LadspaControls * ladspaControls = getLadspaControls();
ch_cnt_t const channelCount = getChannelCount();
for (ch_cnt_t i = 0; i < channelCount; ++i)
{
// Create a const reference so that the C++11 based for loop does not detach the Qt container
auto const & currentControls = ladspaControls->m_controls[i];
for (auto ladspaControl : currentControls)
{
if (ladspaControl->m_link)
{
return true;
}
}
}
return false;
}
void LadspaMatrixControlDialog::arrangeControls(QWidget * parent, QGridLayout* gridLayout)
{
LadspaControls * ladspaControls = getLadspaControls();
int const headerRow = 0;
int const linkColumn = 0;
bool const linkColumnNeeded = needsLinkColumn();
if (linkColumnNeeded)
{
gridLayout->addWidget(new QLabel("<b>" + tr("Link") + "</b>", parent), headerRow, linkColumn, Qt::AlignHCenter);
// If there's a link column then it should not stretch
gridLayout->setColumnStretch(linkColumn, 0);
}
int const channelStartColumn = linkColumnNeeded ? 1 : 0;
// The header row should not grow vertically
gridLayout->setRowStretch(0, 0);
// Records the maximum row with parameters so that we can add a vertical spacer after that row
int maxRow = 0;
// Iterate the channels and add widgets for each control
// Note: the code assumes that all channels have the same structure, i.e. that all channels
// have the same number of parameters which are in the same order.
ch_cnt_t const numberOfChannels = getChannelCount();
for (ch_cnt_t i = 0; i < numberOfChannels; ++i)
{
int currentChannelColumn = channelStartColumn + i;
gridLayout->setColumnStretch(currentChannelColumn, 1);
// First add the channel header with the channel number
gridLayout->addWidget(new QLabel("<b>" + tr("Channel %1").arg(QString::number(i + 1)) + "</b>", parent), headerRow, currentChannelColumn, Qt::AlignHCenter);
int currentRow = 1;
if (i == 0)
{
// Configure the current parameter row to not stretch.
// Only do this once, i.e. when working with the first channel.
gridLayout->setRowStretch(currentRow, 0);
}
// Create a const reference so that the C++11 based for loop does not detach the Qt container
auto const & currentControls = ladspaControls->m_controls[i];
for (auto ladspaControl : currentControls)
{
// Only use the first channel to determine if we need to add link controls
if (i == 0 && ladspaControl->m_link)
{
LedCheckBox * linkCheckBox = new LedCheckBox("", parent, "", LedCheckBox::LedColor::Green);
linkCheckBox->setModel(&ladspaControl->m_linkEnabledModel);
linkCheckBox->setToolTip(tr("Link channels"));
gridLayout->addWidget(linkCheckBox, currentRow, linkColumn, Qt::AlignHCenter);
}
QWidget * controlWidget = LadspaWidgetFactory::createWidget(ladspaControl, this);
if (controlWidget)
{
gridLayout->addWidget(controlWidget, currentRow, currentChannelColumn);
}
// Record the maximum row so that we add a vertical spacer after that row
maxRow = std::max(maxRow, currentRow);
++currentRow;
}
}
// Add a spacer item after the maximum row
QSpacerItem * spacer = new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
gridLayout->addItem(spacer, maxRow + 1, 0);
}
QWidget * LadspaMatrixControlDialog::createMatrixWidget()
{
QWidget *widget = new QWidget(this);
QGridLayout *gridLayout = new QGridLayout(widget);
gridLayout->setMargin(0);
widget->setLayout(gridLayout);
arrangeControls(widget, gridLayout);
return widget;
}
void LadspaMatrixControlDialog::updateEffectView(LadspaControls * ladspaControls)
{
m_effectControls = ladspaControls;
// No need to delete the existing widget as it's deleted
// by the scroll view when we replace it.
QWidget * matrixWidget = createMatrixWidget();
m_scrollArea->setWidget(matrixWidget);
// Make sure that the horizontal scroll bar does not show
// From: https://forum.qt.io/topic/13374/solved-qscrollarea-vertical-scroll-only/4
m_scrollArea->setMinimumWidth(matrixWidget->minimumSizeHint().width() + m_scrollArea->verticalScrollBar()->width());
if (getChannelCount() > 1 && m_stereoLink != nullptr)
{
m_stereoLink->setModel(&ladspaControls->m_stereoLinkModel);
}
connect(ladspaControls, &LadspaControls::effectModelChanged,
this, &LadspaMatrixControlDialog::updateEffectView,
Qt::DirectConnection);
}
LadspaControls * LadspaMatrixControlDialog::getLadspaControls() const
{
return dynamic_cast<LadspaControls *>(m_effectControls);
}
ch_cnt_t LadspaMatrixControlDialog::getChannelCount() const
{
return getLadspaControls()->m_processors;
}
} // namespace lmms::gui
| 7,241
|
C++
|
.cpp
| 183
| 37.103825
| 158
| 0.760656
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,680
|
LadspaControlDialog.cpp
|
LMMS_lmms/plugins/LadspaEffect/LadspaControlDialog.cpp
|
/*
* LadspaControlDialog.cpp - dialog for displaying and editing control port
* values for LADSPA plugins
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
* Copyright (c) 2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <cmath>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QVBoxLayout>
#include "LadspaBase.h"
#include "LadspaControl.h"
#include "LadspaControls.h"
#include "LadspaControlDialog.h"
#include "LadspaControlView.h"
#include "LedCheckBox.h"
namespace lmms::gui
{
LadspaControlDialog::LadspaControlDialog( LadspaControls * _ctl ) :
EffectControlDialog( _ctl ),
m_effectLayout( nullptr ),
m_stereoLink( nullptr )
{
auto mainLay = new QVBoxLayout(this);
m_effectLayout = new QHBoxLayout();
mainLay->addLayout( m_effectLayout );
updateEffectView( _ctl );
if( _ctl->m_processors > 1 )
{
mainLay->addSpacing( 3 );
auto center = new QHBoxLayout();
mainLay->addLayout( center );
m_stereoLink = new LedCheckBox( tr( "Link Channels" ), this );
m_stereoLink->setModel( &_ctl->m_stereoLinkModel );
center->addWidget( m_stereoLink );
}
}
void LadspaControlDialog::updateEffectView( LadspaControls * _ctl )
{
QList<QGroupBox *> groupBoxes = findChildren<QGroupBox *>();
for (const auto& groupBox : groupBoxes)
{
delete groupBox;
}
m_effectControls = _ctl;
const int cols = static_cast<int>( sqrt(
static_cast<double>( _ctl->m_controlCount /
_ctl->m_processors ) ) );
for( ch_cnt_t proc = 0; proc < _ctl->m_processors; proc++ )
{
control_list_t & controls = _ctl->m_controls[proc];
int row = 0;
int col = 0;
BufferDataType last_port = BufferDataType::None;
auto grouper = _ctl->m_processors > 1
? new QGroupBox(tr("Channel ") + QString::number(proc + 1), this)
: new QGroupBox(this);
auto gl = new QGridLayout(grouper);
grouper->setLayout( gl );
grouper->setAlignment( Qt::Vertical );
for (const auto& control : controls)
{
if (control->port()->proc == proc)
{
BufferDataType this_port = control->port()->data_type;
if( last_port != BufferDataType::None &&
( this_port == BufferDataType::Toggled || this_port == BufferDataType::Enum ) &&
( last_port != BufferDataType::Toggled && last_port != BufferDataType::Enum ) )
{
++row;
col = 0;
}
gl->addWidget(new LadspaControlView(grouper, control), row, col);
if( ++col == cols )
{
++row;
col = 0;
}
last_port = control->port()->data_type;
}
}
m_effectLayout->addWidget( grouper );
}
if( _ctl->m_processors > 1 && m_stereoLink != nullptr )
{
m_stereoLink->setModel( &_ctl->m_stereoLinkModel );
}
connect( _ctl, SIGNAL( effectModelChanged( lmms::LadspaControls * ) ),
this, SLOT( updateEffectView( lmms::LadspaControls * ) ),
Qt::DirectConnection );
}
} // namespace lmms::gui
| 3,685
|
C++
|
.cpp
| 111
| 30.288288
| 85
| 0.698873
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,681
|
LadspaControls.cpp
|
LMMS_lmms/plugins/LadspaEffect/LadspaControls.cpp
|
/*
* LadspaControls.cpp - model for LADSPA plugin controls
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "LadspaBase.h"
#include "LadspaControl.h"
#include "LadspaEffect.h"
namespace lmms
{
LadspaControls::LadspaControls( LadspaEffect * _eff ) :
EffectControls( _eff ),
m_effect( _eff ),
m_processors( _eff->processorCount() ),
m_noLink( false ),
m_stereoLinkModel( true, this )
{
connect( &m_stereoLinkModel, SIGNAL( dataChanged() ),
this, SLOT( updateLinkStatesFromGlobal() ),
Qt::DirectConnection );
multi_proc_t controls = m_effect->getPortControls();
m_controlCount = controls.count();
for( ch_cnt_t proc = 0; proc < m_processors; proc++ )
{
control_list_t p;
const bool linked_control = ( m_processors > 1 && proc == 0 );
for (const auto& control : controls)
{
if (control->proc == proc)
{
control->control = new LadspaControl(this, control, linked_control);
p.append(control->control);
if (linked_control)
{
connect(control->control, SIGNAL(linkChanged(int, bool)),
this, SLOT(linkPort(int, bool)),
Qt::DirectConnection);
}
}
}
m_controls.append( p );
}
// now link all controls
if( m_processors > 1 )
{
for (const auto& control : controls)
{
if (control->proc == 0)
{
linkPort(control->control_id, true);
}
}
}
}
LadspaControls::~LadspaControls()
{
for( ch_cnt_t proc = 0; proc < m_processors; proc++ )
{
m_controls[proc].clear();
}
m_controls.clear();
}
void LadspaControls::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
if( m_processors > 1 )
{
_this.setAttribute( "link", m_stereoLinkModel.value() );
}
multi_proc_t controls = m_effect->getPortControls();
_this.setAttribute( "ports", controls.count() );
for (const auto& control : controls)
{
QString n = "port" + QString::number(control->proc) + QString::number(control->port_id);
control->control->saveSettings(_doc, _this, n);
}
}
void LadspaControls::loadSettings( const QDomElement & _this )
{
if( m_processors > 1 )
{
m_stereoLinkModel.setValue( _this.attribute( "link" ).toInt() );
}
multi_proc_t controls = m_effect->getPortControls();
for (const auto& control : controls)
{
QString n = "port" + QString::number(control->proc) + QString::number(control->port_id);
control->control->loadSettings(_this, n);
}
}
void LadspaControls::linkPort( int _port, bool _state )
{
LadspaControl * first = m_controls[0][_port];
if( _state )
{
for( ch_cnt_t proc = 1; proc < m_processors; proc++ )
{
first->linkControls( m_controls[proc][_port] );
}
}
else
{
for( ch_cnt_t proc = 1; proc < m_processors; proc++ )
{
first->unlinkControls( m_controls[proc][_port] );
}
// m_stereoLinkModel.setValue() will call updateLinkStatesFromGlobal()
// m_noLink will make sure that this will not unlink any other ports
m_noLink = true;
m_stereoLinkModel.setValue( false );
}
}
void LadspaControls::updateLinkStatesFromGlobal()
{
if( m_stereoLinkModel.value() )
{
for( int port = 0; port < m_controlCount / m_processors; port++ )
{
m_controls[0][port]->setLink( true );
}
}
else if( !m_noLink )
{
for( int port = 0; port < m_controlCount / m_processors; port++ )
{
m_controls[0][port]->setLink( false );
}
}
// if global channel link state has changed, always ignore link
// status of individual ports in the future
m_noLink = false;
}
} // namespace lmms
| 4,311
|
C++
|
.cpp
| 151
| 25.827815
| 90
| 0.6958
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,682
|
LadspaEffect.cpp
|
LMMS_lmms/plugins/LadspaEffect/LadspaEffect.cpp
|
/*
* LadspaEffect.cpp - class for processing LADSPA effects
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
* Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QVarLengthArray>
#include <QMessageBox>
#include "LadspaEffect.h"
#include "DataFile.h"
#include "AudioDevice.h"
#include "AudioEngine.h"
#include "Ladspa2LMMS.h"
#include "LadspaBase.h"
#include "LadspaControl.h"
#include "LadspaSubPluginFeatures.h"
#include "AutomationClip.h"
#include "ValueBuffer.h"
#include "Song.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT ladspaeffect_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"LADSPA",
QT_TRANSLATE_NOOP( "PluginBrowser",
"plugin for using arbitrary LADSPA-effects "
"inside LMMS." ),
"Danny McRae <khjklujn/at/users.sourceforge.net>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
new LadspaSubPluginFeatures( Plugin::Type::Effect )
} ;
}
LadspaEffect::LadspaEffect( Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Effect( &ladspaeffect_plugin_descriptor, _parent, _key ),
m_controls( nullptr ),
m_maxSampleRate( 0 ),
m_key( LadspaSubPluginFeatures::subPluginKeyToLadspaKey( _key ) )
{
Ladspa2LMMS * manager = Engine::getLADSPAManager();
if( manager->getDescription( m_key ) == nullptr )
{
Engine::getSong()->collectError(tr( "Unknown LADSPA plugin %1 requested." ).arg(
m_key.second ) );
setOkay( false );
return;
}
setDisplayName( manager->getShortName( m_key ) );
pluginInstantiation();
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ),
this, SLOT( changeSampleRate() ) );
}
LadspaEffect::~LadspaEffect()
{
pluginDestruction();
}
void LadspaEffect::changeSampleRate()
{
DataFile dataFile( DataFile::Type::EffectSettings );
m_controls->saveState( dataFile, dataFile.content() );
LadspaControls * controls = m_controls;
m_controls = nullptr;
m_pluginMutex.lock();
pluginDestruction();
pluginInstantiation();
m_pluginMutex.unlock();
controls->effectModelChanged( m_controls );
delete controls;
m_controls->restoreState( dataFile.content().firstChild().toElement() );
// the IDs of re-created controls have been saved and now need to be
// resolved again
AutomationClip::resolveAllIDs();
}
Effect::ProcessStatus LadspaEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
m_pluginMutex.lock();
if (!isOkay() || dontRun() || !isEnabled() || !isRunning())
{
m_pluginMutex.unlock();
return ProcessStatus::Sleep;
}
auto outFrames = frames;
SampleFrame* outBuf = nullptr;
QVarLengthArray<SampleFrame> sBuf(frames);
if( m_maxSampleRate < Engine::audioEngine()->outputSampleRate() )
{
outBuf = buf;
buf = sBuf.data();
sampleDown(outBuf, buf, m_maxSampleRate);
outFrames = frames * m_maxSampleRate /
Engine::audioEngine()->outputSampleRate();
}
// Copy the LMMS audio buffer to the LADSPA input buffer and initialize
// the control ports.
ch_cnt_t channel = 0;
for( ch_cnt_t proc = 0; proc < processorCount(); ++proc )
{
for( int port = 0; port < m_portCount; ++port )
{
port_desc_t * pp = m_ports.at( proc ).at( port );
switch( pp->rate )
{
case BufferRate::ChannelIn:
for (fpp_t frame = 0; frame < outFrames; ++frame)
{
pp->buffer[frame] = buf[frame][channel];
}
++channel;
break;
case BufferRate::AudioRateInput:
{
ValueBuffer * vb = pp->control->valueBuffer();
if( vb )
{
memcpy(pp->buffer, vb->values(), outFrames * sizeof(float));
}
else
{
pp->value = static_cast<LADSPA_Data>(
pp->control->value() / pp->scale );
// This only supports control rate ports, so the audio rates are
// treated as though they were control rate by setting the
// port buffer to all the same value.
for (fpp_t frame = 0; frame < outFrames; ++frame)
{
pp->buffer[frame] = pp->value;
}
}
break;
}
case BufferRate::ControlRateInput:
if( pp->control == nullptr )
{
break;
}
pp->value = static_cast<LADSPA_Data>(
pp->control->value() / pp->scale );
pp->buffer[0] =
pp->value;
break;
case BufferRate::ChannelOut:
case BufferRate::AudioRateOutput:
case BufferRate::ControlRateOutput:
break;
default:
break;
}
}
}
// Process the buffers.
for( ch_cnt_t proc = 0; proc < processorCount(); ++proc )
{
(m_descriptor->run)(m_handles[proc], outFrames);
}
// Copy the LADSPA output buffers to the LMMS buffer.
channel = 0;
const float d = dryLevel();
const float w = wetLevel();
for( ch_cnt_t proc = 0; proc < processorCount(); ++proc )
{
for( int port = 0; port < m_portCount; ++port )
{
port_desc_t * pp = m_ports.at( proc ).at( port );
switch( pp->rate )
{
case BufferRate::ChannelIn:
case BufferRate::AudioRateInput:
case BufferRate::ControlRateInput:
break;
case BufferRate::ChannelOut:
for (fpp_t frame = 0; frame < outFrames; ++frame)
{
buf[frame][channel] = d * buf[frame][channel] + w * pp->buffer[frame];
}
++channel;
break;
case BufferRate::AudioRateOutput:
case BufferRate::ControlRateOutput:
break;
default:
break;
}
}
}
if (outBuf != nullptr)
{
sampleBack(buf, outBuf, m_maxSampleRate);
}
m_pluginMutex.unlock();
return ProcessStatus::ContinueIfNotQuiet;
}
void LadspaEffect::setControl( int _control, LADSPA_Data _value )
{
if( !isOkay() )
{
return;
}
m_portControls[_control]->value = _value;
}
void LadspaEffect::pluginInstantiation()
{
m_maxSampleRate = maxSamplerate( displayName() );
Ladspa2LMMS * manager = Engine::getLADSPAManager();
// Calculate how many processing units are needed.
const ch_cnt_t lmms_chnls = Engine::audioEngine()->audioDev()->channels();
int effect_channels = manager->getDescription( m_key )->inputChannels;
setProcessorCount( lmms_chnls / effect_channels );
// get inPlaceBroken property
m_inPlaceBroken = manager->isInplaceBroken( m_key );
// Categorize the ports, and create the buffers.
m_portCount = manager->getPortCount( m_key );
int inputch = 0;
int outputch = 0;
std::array<LADSPA_Data*, 2> inbuf;
inbuf[0] = nullptr;
inbuf[1] = nullptr;
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
multi_proc_t ports;
for( int port = 0; port < m_portCount; port++ )
{
auto p = new port_desc_t;
p->name = manager->getPortName( m_key, port );
p->proc = proc;
p->port_id = port;
p->control = nullptr;
p->buffer = nullptr;
// Determine the port's category.
if( manager->isPortAudio( m_key, port ) )
{
if( p->name.toUpper().contains( "IN" ) &&
manager->isPortInput( m_key, port ) )
{
p->rate = BufferRate::ChannelIn;
p->buffer = new LADSPA_Data[Engine::audioEngine()->framesPerPeriod()];
inbuf[ inputch ] = p->buffer;
inputch++;
}
else if( p->name.toUpper().contains( "OUT" ) &&
manager->isPortOutput( m_key, port ) )
{
p->rate = BufferRate::ChannelOut;
if( ! m_inPlaceBroken && inbuf[ outputch ] )
{
p->buffer = inbuf[ outputch ];
outputch++;
}
else
{
p->buffer = new LADSPA_Data[Engine::audioEngine()->framesPerPeriod()];
m_inPlaceBroken = true;
}
}
else if( manager->isPortInput( m_key, port ) )
{
p->rate = BufferRate::AudioRateInput;
p->buffer = new LADSPA_Data[Engine::audioEngine()->framesPerPeriod()];
}
else
{
p->rate = BufferRate::AudioRateOutput;
p->buffer = new LADSPA_Data[Engine::audioEngine()->framesPerPeriod()];
}
}
else
{
p->buffer = new LADSPA_Data[1];
if( manager->isPortInput( m_key, port ) )
{
p->rate = BufferRate::ControlRateInput;
}
else
{
p->rate = BufferRate::ControlRateOutput;
}
}
p->scale = 1.0f;
if( manager->isEnum( m_key, port ) )
{
p->data_type = BufferDataType::Enum;
}
else if( manager->isPortToggled( m_key, port ) )
{
p->data_type = BufferDataType::Toggled;
}
else if( manager->isInteger( m_key, port ) )
{
p->data_type = BufferDataType::Integer;
}
else if( p->name.toUpper().contains( "(SECONDS)" ) )
{
p->data_type = BufferDataType::Time;
p->scale = 1000.0f;
int loc = p->name.toUpper().indexOf(
"(SECONDS)" );
p->name.replace( loc, 9, "(ms)" );
}
else if( p->name.toUpper().contains( "(S)" ) )
{
p->data_type = BufferDataType::Time;
p->scale = 1000.0f;
int loc = p->name.toUpper().indexOf( "(S)" );
p->name.replace( loc, 3, "(ms)" );
}
else if( p->name.toUpper().contains( "(MS)" ) )
{
p->data_type = BufferDataType::Time;
int loc = p->name.toUpper().indexOf( "(MS)" );
p->name.replace( loc, 4, "(ms)" );
}
else
{
p->data_type = BufferDataType::Floating;
}
// Get the range and default values.
p->max = manager->getUpperBound( m_key, port );
if( p->max == NOHINT )
{
p->max = p->name.toUpper() == "GAIN" ? 10.0f :
1.0f;
}
if( manager->areHintsSampleRateDependent(
m_key, port ) )
{
p->max *= m_maxSampleRate;
}
p->min = manager->getLowerBound( m_key, port );
if( p->min == NOHINT )
{
p->min = 0.0f;
}
if( manager->areHintsSampleRateDependent(
m_key, port ) )
{
p->min *= m_maxSampleRate;
}
p->def = manager->getDefaultSetting( m_key, port );
if( p->def == NOHINT )
{
if( p->data_type != BufferDataType::Toggled )
{
p->def = ( p->min + p->max ) / 2.0f;
}
else
{
p->def = 1.0f;
}
}
else if( manager->areHintsSampleRateDependent( m_key, port ) )
{
p->def *= m_maxSampleRate;
}
p->max *= p->scale;
p->min *= p->scale;
p->def *= p->scale;
p->value = p->def;
p->suggests_logscale = manager->isLogarithmic( m_key, port );
ports.append( p );
// For convenience, keep a separate list of the ports that are used
// to control the processors.
if( p->rate == BufferRate::AudioRateInput ||
p->rate == BufferRate::ControlRateInput )
{
p->control_id = m_portControls.count();
m_portControls.append( p );
}
}
m_ports.append( ports );
}
// Instantiate the processing units.
m_descriptor = manager->getDescriptor( m_key );
if( m_descriptor == nullptr )
{
QMessageBox::warning( 0, "Effect",
"Can't get LADSPA descriptor function: " + m_key.second,
QMessageBox::Ok, QMessageBox::NoButton );
setOkay( false );
return;
}
if( m_descriptor->run == nullptr )
{
QMessageBox::warning( 0, "Effect",
"Plugin has no processor: " + m_key.second,
QMessageBox::Ok, QMessageBox::NoButton );
setDontRun( true );
}
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
LADSPA_Handle effect = manager->instantiate( m_key,
m_maxSampleRate );
if( effect == nullptr )
{
QMessageBox::warning( 0, "Effect",
"Can't get LADSPA instance: " + m_key.second,
QMessageBox::Ok, QMessageBox::NoButton );
setOkay( false );
return;
}
m_handles.append( effect );
}
// Connect the ports.
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
for( int port = 0; port < m_portCount; port++ )
{
port_desc_t * pp = m_ports.at( proc ).at( port );
if( !manager->connectPort( m_key,
m_handles[proc],
port,
pp->buffer ) )
{
QMessageBox::warning( 0, "Effect",
"Failed to connect port: " + m_key.second,
QMessageBox::Ok, QMessageBox::NoButton );
setDontRun( true );
return;
}
}
}
// Activate the processing units.
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
manager->activate( m_key, m_handles[proc] );
}
m_controls = new LadspaControls( this );
}
void LadspaEffect::pluginDestruction()
{
if( !isOkay() )
{
return;
}
delete m_controls;
for( ch_cnt_t proc = 0; proc < processorCount(); proc++ )
{
Ladspa2LMMS * manager = Engine::getLADSPAManager();
manager->deactivate( m_key, m_handles[proc] );
manager->cleanup( m_key, m_handles[proc] );
for( int port = 0; port < m_portCount; port++ )
{
port_desc_t * pp = m_ports.at( proc ).at( port );
if( m_inPlaceBroken || pp->rate != BufferRate::ChannelOut )
{
if( pp->buffer) delete[] pp->buffer;
}
delete pp;
}
m_ports[proc].clear();
}
m_ports.clear();
m_handles.clear();
m_portControls.clear();
}
static QMap<QString, sample_rate_t> __buggy_plugins;
sample_rate_t LadspaEffect::maxSamplerate( const QString & _name )
{
if( __buggy_plugins.isEmpty() )
{
__buggy_plugins["C* AmpVTS"] = 88200;
__buggy_plugins["Chorus2"] = 44100;
__buggy_plugins["Notch Filter"] = 96000;
__buggy_plugins["TAP Reflector"] = 192000;
}
if( __buggy_plugins.contains( _name ) )
{
return( __buggy_plugins[_name] );
}
return( Engine::audioEngine()->outputSampleRate() );
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * _parent, void * _data )
{
return new LadspaEffect( _parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(
_data ) );
}
}
} // namespace lmms
| 14,133
|
C++
|
.cpp
| 506
| 24.217391
| 85
| 0.654721
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,683
|
Lb302.cpp
|
LMMS_lmms/plugins/Lb302/Lb302.cpp
|
/*
* Lb302.cpp - implementation of class Lb302 which is a bass synth attempting
* to emulate the Roland TB-303 bass synth
*
* Copyright (c) 2006-2008 Paul Giblock <pgib/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* Lb302FilterIIR2 is based on the gsyn filter code by Andy Sloane.
*
* Lb302Filter3Pole is based on the TB-303 instrument written by
* Josep M Comajuncosas for the CSounds library
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
// Need to include this first to ensure we get M_PI in MinGW with C++11
#define _USE_MATH_DEFINES
#include <cmath>
#include "Lb302.h"
#include "AutomatableButton.h"
#include "Engine.h"
#include "InstrumentPlayHandle.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "NotePlayHandle.h"
#include "Oscillator.h"
#include "PixmapButton.h"
#include "BandLimitedWave.h"
#include "embed.h"
#include "plugin_export.h"
// Envelope Recalculation period
#define ENVINC 64
//
// New config
//
#define LB_24_IGNORE_ENVELOPE
#define LB_FILTERED
//#define LB_DECAY
//#define LB_24_RES_TRICK
#define LB_DIST_RATIO 4.0
#define LB_24_VOL_ADJUST 3.0
//#define LB_DECAY_NOTES
#define LB_DEBUG
//
// Old config
//
namespace lmms
{
//#define engine::audioEngine()->outputSampleRate() 44100.0f
const float sampleRateCutoff = 44100.0f;
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT lb302_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"LB302",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Incomplete monophonic imitation TB-303" ),
"Paul Giblock <pgib/at/users.sf.net>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
};
}
//
// Lb302Filter
//
Lb302Filter::Lb302Filter(Lb302FilterKnobState* p_fs) :
fs(p_fs),
vcf_c0(0),
vcf_e0(0),
vcf_e1(0)
{
};
void Lb302Filter::recalc()
{
vcf_e1 = exp(6.109 + 1.5876*(fs->envmod) + 2.1553*(fs->cutoff) - 1.2*(1.0-(fs->reso)));
vcf_e0 = exp(5.613 - 0.8*(fs->envmod) + 2.1553*(fs->cutoff) - 0.7696*(1.0-(fs->reso)));
vcf_e0*=M_PI/Engine::audioEngine()->outputSampleRate();
vcf_e1*=M_PI/Engine::audioEngine()->outputSampleRate();
vcf_e1 -= vcf_e0;
vcf_rescoeff = exp(-1.20 + 3.455*(fs->reso));
};
void Lb302Filter::envRecalc()
{
vcf_c0 *= fs->envdecay; // Filter Decay. vcf_decay is adjusted for Hz and ENVINC
// vcf_rescoeff = exp(-1.20 + 3.455*(fs->reso)); moved above
};
void Lb302Filter::playNote()
{
vcf_c0 = vcf_e1;
}
//
// Lb302FilterIIR2
//
Lb302FilterIIR2::Lb302FilterIIR2(Lb302FilterKnobState* p_fs) :
Lb302Filter(p_fs),
vcf_d1(0),
vcf_d2(0),
vcf_a(0),
vcf_b(0),
vcf_c(1)
{
m_dist = new DspEffectLibrary::Distortion( 1.0, 1.0f);
};
Lb302FilterIIR2::~Lb302FilterIIR2()
{
delete m_dist;
}
void Lb302FilterIIR2::recalc()
{
Lb302Filter::recalc();
//m_dist->setThreshold(0.5+(fs->dist*2.0));
m_dist->setThreshold(fs->dist*75.0);
};
void Lb302FilterIIR2::envRecalc()
{
Lb302Filter::envRecalc();
float w = vcf_e0 + vcf_c0; // e0 is adjusted for Hz and doesn't need ENVINC
float k = exp(-w/vcf_rescoeff); // Does this mean c0 is inheritantly?
vcf_a = 2.0*cos(2.0*w) * k;
vcf_b = -k*k;
vcf_c = 1.0 - vcf_a - vcf_b;
}
float Lb302FilterIIR2::process(const float& samp)
{
float ret = vcf_a*vcf_d1 + vcf_b*vcf_d2 + vcf_c*samp;
// Delayed samples for filter
vcf_d2 = vcf_d1;
vcf_d1 = ret;
if(fs->dist > 0)
ret=m_dist->nextSample(ret);
// output = IIR2 + dry
return ret;
}
//
// Lb302Filter3Pole
//
Lb302Filter3Pole::Lb302Filter3Pole(Lb302FilterKnobState *p_fs) :
Lb302Filter(p_fs),
ay1(0),
ay2(0),
aout(0),
lastin(0)
{
};
void Lb302Filter3Pole::recalc()
{
// DO NOT CALL BASE CLASS
vcf_e0 = 0.000001f;
vcf_e1 = 1.0;
}
// TODO: Try using k instead of vcf_reso
void Lb302Filter3Pole::envRecalc()
{
Lb302Filter::envRecalc();
// e0 is adjusted for Hz and doesn't need ENVINC
float w = vcf_e0 + vcf_c0;
float k = (fs->cutoff > 0.975)?0.975:fs->cutoff;
// sampleRateCutoff should not be changed to anything dynamic that is outside the
// scope of LB302 (like e.g. the audio engine's sample rate) as this changes the filter's cutoff
// behavior without any modification to its controls.
float kfco = 50.f + (k)*((2300.f-1600.f*(fs->envmod))+(w) *
(700.f+1500.f*(k)+(1500.f+(k)*(sampleRateCutoff/2.f-6000.f)) *
(fs->envmod)) );
//+iacc*(.3+.7*kfco*kenvmod)*kaccent*kaccurve*2000
#ifdef LB_24_IGNORE_ENVELOPE
// kfcn = fs->cutoff;
kfcn = 2.0 * kfco / Engine::audioEngine()->outputSampleRate();
#else
kfcn = w;
#endif
kp = ((-2.7528*kfcn + 3.0429)*kfcn + 1.718)*kfcn - 0.9984;
kp1 = kp+1.0;
kp1h = 0.5*kp1;
#ifdef LB_24_RES_TRICK
k = exp(-w/vcf_rescoeff);
kres = (((k))) * (((-2.7079*kp1 + 10.963)*kp1 - 14.934)*kp1 + 8.4974);
#else
kres = (((fs->reso))) * (((-2.7079*kp1 + 10.963)*kp1 - 14.934)*kp1 + 8.4974);
#endif
value = 1.0+( (fs->dist) *(1.5 + 2.0*kres*(1.0-kfcn))); // ENVMOD was DIST
}
float Lb302Filter3Pole::process(const float& samp)
{
float ax1 = lastin;
float ay11 = ay1;
float ay31 = ay2;
lastin = (samp) - tanh(kres*aout);
ay1 = kp1h * (lastin+ax1) - kp*ay1;
ay2 = kp1h * (ay1 + ay11) - kp*ay2;
aout = kp1h * (ay2 + ay31) - kp*aout;
return tanh(aout*value)*LB_24_VOL_ADJUST/(1.0+fs->dist);
}
//
// LBSynth
//
static float computeDecayFactor(float decayTimeInSeconds, float targetedAttenuation)
{
// This is the number of samples that correspond to the decay time in seconds
auto samplesNeededForDecay = decayTimeInSeconds * Engine::audioEngine()->outputSampleRate();
// This computes the factor that's needed to make a signal with a value of 1 decay to the
// targeted attenuation over the time in number of samples.
return std::pow(targetedAttenuation, 1. / samplesNeededForDecay);
}
Lb302Synth::Lb302Synth( InstrumentTrack * _instrumentTrack ) :
Instrument(_instrumentTrack, &lb302_plugin_descriptor, nullptr, Flag::IsSingleStreamed),
vcf_cut_knob( 0.75f, 0.0f, 1.5f, 0.005f, this, tr( "VCF Cutoff Frequency" ) ),
vcf_res_knob( 0.75f, 0.0f, 1.25f, 0.005f, this, tr( "VCF Resonance" ) ),
vcf_mod_knob( 0.1f, 0.0f, 1.0f, 0.005f, this, tr( "VCF Envelope Mod" ) ),
vcf_dec_knob( 0.1f, 0.0f, 1.0f, 0.005f, this, tr( "VCF Envelope Decay" ) ),
dist_knob( 0.0f, 0.0f, 1.0f, 0.01f, this, tr( "Distortion" ) ),
wave_shape( 8.0f, 0.0f, 11.0f, this, tr( "Waveform" ) ),
slide_dec_knob( 0.6f, 0.0f, 1.0f, 0.005f, this, tr( "Slide Decay" ) ),
slideToggle( false, this, tr( "Slide" ) ),
accentToggle( false, this, tr( "Accent" ) ),
deadToggle( false, this, tr( "Dead" ) ),
db24Toggle( false, this, tr( "24dB/oct Filter" ) ),
vca_attack(1.f - 0.96406088f),
vca_a0(0.5),
vca_a(0.),
vca_mode(VcaMode::NeverPlayed)
{
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ),
this, SLOT ( filterChanged() ) );
connect( &vcf_cut_knob, SIGNAL( dataChanged() ),
this, SLOT ( filterChanged() ) );
connect( &vcf_res_knob, SIGNAL( dataChanged() ),
this, SLOT ( filterChanged() ) );
connect( &vcf_mod_knob, SIGNAL( dataChanged() ),
this, SLOT ( filterChanged() ) );
connect( &vcf_dec_knob, SIGNAL( dataChanged() ),
this, SLOT ( filterChanged() ) );
connect( &db24Toggle, SIGNAL( dataChanged() ),
this, SLOT ( db24Toggled() ) );
connect( &dist_knob, SIGNAL( dataChanged() ),
this, SLOT ( filterChanged()));
// SYNTH
vco_inc = 0.0;
vco_c = 0;
vco_k = 0;
vco_slide = 0; vco_slideinc = 0;
vco_slidebase = 0;
fs.cutoff = 0;
fs.envmod = 0;
fs.reso = 0;
fs.envdecay = 0;
fs.dist = 0;
vcf_envpos = ENVINC;
vco_shape = VcoShape::BLSawtooth;
vcfs[0] = new Lb302FilterIIR2(&fs);
vcfs[1] = new Lb302Filter3Pole(&fs);
db24Toggled();
sample_cnt = 0;
release_frame = 0;
catch_frame = 0;
catch_decay = 0;
last_offset = 0;
new_freq = false;
filterChanged();
auto iph = new InstrumentPlayHandle(this, _instrumentTrack);
Engine::audioEngine()->addPlayHandle( iph );
}
Lb302Synth::~Lb302Synth()
{
for (const auto& vcf : vcfs)
{
delete vcf;
}
}
void Lb302Synth::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
vcf_cut_knob.saveSettings( _doc, _this, "vcf_cut" );
vcf_res_knob.saveSettings( _doc, _this, "vcf_res" );
vcf_mod_knob.saveSettings( _doc, _this, "vcf_mod" );
vcf_dec_knob.saveSettings( _doc, _this, "vcf_dec" );
wave_shape.saveSettings( _doc, _this, "shape");
dist_knob.saveSettings( _doc, _this, "dist");
slide_dec_knob.saveSettings( _doc, _this, "slide_dec");
slideToggle.saveSettings( _doc, _this, "slide");
deadToggle.saveSettings( _doc, _this, "dead");
db24Toggle.saveSettings( _doc, _this, "db24");
}
void Lb302Synth::loadSettings( const QDomElement & _this )
{
vcf_cut_knob.loadSettings( _this, "vcf_cut" );
vcf_res_knob.loadSettings( _this, "vcf_res" );
vcf_mod_knob.loadSettings( _this, "vcf_mod" );
vcf_dec_knob.loadSettings( _this, "vcf_dec" );
dist_knob.loadSettings( _this, "dist");
slide_dec_knob.loadSettings( _this, "slide_dec");
wave_shape.loadSettings( _this, "shape");
slideToggle.loadSettings( _this, "slide");
deadToggle.loadSettings( _this, "dead");
db24Toggle.loadSettings( _this, "db24");
db24Toggled();
filterChanged();
}
// TODO: Split into one function per knob. envdecay doesn't require
// recalcFilter.
void Lb302Synth::filterChanged()
{
fs.cutoff = vcf_cut_knob.value();
fs.reso = vcf_res_knob.value();
fs.envmod = vcf_mod_knob.value();
fs.dist = LB_DIST_RATIO*dist_knob.value();
float d = 0.2 + (2.3*vcf_dec_knob.value());
d *= Engine::audioEngine()->outputSampleRate(); // d *= smpl rate
fs.envdecay = pow(0.1, 1.0/d * ENVINC); // decay is 0.1 to the 1/d * ENVINC
// vcf_envdecay is now adjusted for both
// sampling rate and ENVINC
recalcFilter();
}
void Lb302Synth::db24Toggled()
{
vcf = vcfs[db24Toggle.value()];
// These recalcFilter calls might suck
recalcFilter();
}
QString Lb302Synth::nodeName() const
{
return( lb302_plugin_descriptor.name );
}
// OBSOLETE. Break apart once we get Q_OBJECT to work. >:[
void Lb302Synth::recalcFilter()
{
#if (QT_VERSION >= QT_VERSION_CHECK(5,14,0))
vcf.loadRelaxed()->recalc();
#else
vcf.load()->recalc();
#endif
// THIS IS OLD 3pole/24dB code, I may reintegrate it. Don't need it
// right now. Should be toggled by LB_24_RES_TRICK at the moment.
/*kfcn = 2.0 * (((vcf_cutoff*3000))) / engine::audioEngine()->outputSampleRate();
kp = ((-2.7528*kfcn + 3.0429)*kfcn + 1.718)*kfcn - 0.9984;
kp1 = kp+1.0;
kp1h = 0.5*kp1;
kres = (((vcf_reso))) * (((-2.7079*kp1 + 10.963)*kp1 - 14.934)*kp1 + 8.4974);
value = 1.0+( (((0))) *(1.5 + 2.0*kres*(1.0-kfcn))); // ENVMOD was DIST*/
vcf_envpos = ENVINC; // Trigger filter update in process()
}
inline float GET_INC(float freq) {
return freq/Engine::audioEngine()->outputSampleRate(); // TODO: Use actual sampling rate.
}
int Lb302Synth::process(SampleFrame* outbuf, const std::size_t size)
{
const float sampleRatio = 44100.f / Engine::audioEngine()->outputSampleRate();
// Hold on to the current VCF, and use it throughout this period
Lb302Filter *filter = vcf.loadAcquire();
if( release_frame == 0 || ! m_playingNote )
{
vca_mode = VcaMode::Decay;
}
if( new_freq )
{
//printf(" playing new note..\n");
Lb302Note note;
note.vco_inc = GET_INC( true_freq );
note.dead = deadToggle.value();
initNote(¬e);
new_freq = false;
}
// TODO: NORMAL RELEASE
// vca_mode = 1;
// Note: this has to be computed during processing and cannot be initialized
// in the constructor because it's dependent on the sample rate and that might
// change during rendering!
//
// At 44.1 kHz this will compute something very close to the previously
// hard coded value of 0.99897516.
auto decay = computeDecayFactor(0.245260770975f, 1.f / 65536.f);
for (auto i = std::size_t{0}; i < size; i++)
{
// start decay if we're past release
if (i >= release_frame) { vca_mode = VcaMode::Decay; }
// update vcf
if(vcf_envpos >= ENVINC) {
filter->envRecalc();
vcf_envpos = 0;
if (vco_slide) {
vco_inc = vco_slidebase - vco_slide;
// Calculate coeff from dec_knob on knob change.
vco_slide -= vco_slide * ( 0.1f - slide_dec_knob.value() * 0.0999f ) * sampleRatio; // TODO: Adjust for ENVINC
}
}
sample_cnt++;
vcf_envpos++;
//int decay_frames = 128;
// update vco
vco_c += vco_inc;
if(vco_c > 0.5)
vco_c -= 1.0;
switch(int(rint(wave_shape.value()))) {
case 0: vco_shape = VcoShape::Sawtooth; break;
case 1: vco_shape = VcoShape::Triangle; break;
case 2: vco_shape = VcoShape::Square; break;
case 3: vco_shape = VcoShape::RoundSquare; break;
case 4: vco_shape = VcoShape::Moog; break;
case 5: vco_shape = VcoShape::Sine; break;
case 6: vco_shape = VcoShape::Exponential; break;
case 7: vco_shape = VcoShape::WhiteNoise; break;
case 8: vco_shape = VcoShape::BLSawtooth; break;
case 9: vco_shape = VcoShape::BLSquare; break;
case 10: vco_shape = VcoShape::BLTriangle; break;
case 11: vco_shape = VcoShape::BLMoog; break;
default: vco_shape = VcoShape::Sawtooth; break;
}
// add vco_shape_param the changes the shape of each curve.
// merge sawtooths with triangle and square with round square?
switch (vco_shape) {
case VcoShape::Sawtooth: // p0: curviness of line
vco_k = vco_c; // Is this sawtooth backwards?
break;
case VcoShape::Triangle: // p0: duty rev.saw<->triangle<->saw p1: curviness
vco_k = (vco_c*2.0)+0.5;
if (vco_k>0.5)
vco_k = 1.0- vco_k;
break;
case VcoShape::Square: // p0: slope of top
vco_k = (vco_c<0)?0.5:-0.5;
break;
case VcoShape::RoundSquare: // p0: width of round
vco_k = (vco_c<0)?(sqrtf(1-(vco_c*vco_c*4))-0.5):-0.5;
break;
case VcoShape::Moog: // Maybe the fall should be exponential/sinsoidal instead of quadric.
// [-0.5, 0]: Rise, [0,0.25]: Slope down, [0.25,0.5]: Low
vco_k = (vco_c*2.0)+0.5;
if (vco_k>1.0) {
vco_k = -0.5 ;
}
else if (vco_k>0.5) {
float w = 2.0 * (vco_k - 0.5) - 1.0;
vco_k = 0.5 - sqrtf(1.0-(w*w));
}
vco_k *= 2.0; // MOOG wave gets filtered away
break;
case VcoShape::Sine:
// [-0.5, 0.5] : [-pi, pi]
vco_k = 0.5f * Oscillator::sinSample( vco_c );
break;
case VcoShape::Exponential:
vco_k = 0.5 * Oscillator::expSample( vco_c );
break;
case VcoShape::WhiteNoise:
vco_k = 0.5 * Oscillator::noiseSample( vco_c );
break;
// The next cases all use the BandLimitedWave class which uses the oscillator increment `vco_inc` to compute samples.
// If that oscillator increment is 0 we return a 0 sample because calling BandLimitedWave::pdToLen(0) leads to a
// division by 0 which in turn leads to floating point exceptions.
case VcoShape::BLSawtooth:
vco_k = vco_inc == 0. ? 0. : BandLimitedWave::oscillate(vco_c + 0.5f, BandLimitedWave::pdToLen(vco_inc), BandLimitedWave::Waveform::BLSaw) * 0.5f;
break;
case VcoShape::BLSquare:
vco_k = vco_inc == 0. ? 0. : BandLimitedWave::oscillate(vco_c + 0.5f, BandLimitedWave::pdToLen(vco_inc), BandLimitedWave::Waveform::BLSquare) * 0.5f;
break;
case VcoShape::BLTriangle:
vco_k = vco_inc == 0. ? 0. : BandLimitedWave::oscillate(vco_c + 0.5f, BandLimitedWave::pdToLen(vco_inc), BandLimitedWave::Waveform::BLTriangle) * 0.5f;
break;
case VcoShape::BLMoog:
vco_k = vco_inc == 0. ? 0. : BandLimitedWave::oscillate(vco_c + 0.5f, BandLimitedWave::pdToLen(vco_inc), BandLimitedWave::Waveform::BLMoog);
break;
}
//vca_a = 0.5;
// Write out samples.
#ifdef LB_FILTERED
//samp = vcf->process(vco_k)*2.0*vca_a;
//samp = vcf->process(vco_k)*2.0;
float samp = filter->process(vco_k) * vca_a;
//printf("%f %d\n", vco_c, sample_cnt);
//samp = vco_k * vca_a;
if( sample_cnt <= 4 )
{
// vca_a = 0;
}
#else
//samp = vco_k*vca_a;
#endif
/*
float releaseFrames = desiredReleaseFrames();
samp *= (releaseFrames - catch_decay)/releaseFrames;
*/
//LB302 samp *= (float)(decay_frames - catch_decay)/(float)decay_frames;
for( int c = 0; c < DEFAULT_CHANNELS; c++ )
{
outbuf[i][c] = samp;
}
// Handle Envelope
if(vca_mode==VcaMode::Attack) {
vca_a+=(vca_a0-vca_a)*vca_attack;
if(sample_cnt>=0.5*Engine::audioEngine()->outputSampleRate())
vca_mode = VcaMode::Idle;
}
else if(vca_mode == VcaMode::Decay) {
vca_a *= decay;
// the following line actually speeds up processing
if(vca_a < (1/65536.0)) {
vca_a = 0;
vca_mode = VcaMode::NeverPlayed;
}
}
}
return 1;
}
/* Prepares the active LB302 note. I separated this into a function because it
* needs to be called onplayNote() when a new note is started. It also needs
* to be called from process() when a prior edge-to-edge note is done releasing.
*/
void Lb302Synth::initNote( Lb302Note *n)
{
catch_decay = 0;
vco_inc = n->vco_inc;
// Always reset vca on non-dead notes, and
// Only reset vca on decaying(decayed) and never-played
if(n->dead == 0 || (vca_mode == VcaMode::Decay || vca_mode == VcaMode::NeverPlayed)) {
//printf(" good\n");
sample_cnt = 0;
vca_mode = VcaMode::Attack;
// LB303:
//vca_a = 0;
}
else {
vca_mode = VcaMode::Idle;
}
initSlide();
// Slide-from note, save inc for next note
if (slideToggle.value()) {
vco_slideinc = vco_inc; // May need to equal vco_slidebase+vco_slide if last note slid
}
recalcFilter();
if(n->dead ==0){
// Swap next two blocks??
#if (QT_VERSION >= QT_VERSION_CHECK(5,14,0))
vcf.loadRelaxed()->playNote();
#else
vcf.load()->playNote();
#endif
// Ensure envelope is recalculated
vcf_envpos = ENVINC;
// Double Check
//vca_mode = 0;
//vca_a = 0.0;
}
}
void Lb302Synth::initSlide()
{
// Initiate Slide
if (vco_slideinc) {
//printf(" sliding\n");
vco_slide = vco_inc-vco_slideinc; // Slide amount
vco_slidebase = vco_inc; // The REAL frequency
vco_slideinc = 0; // reset from-note
}
else {
vco_slide = 0;
}
}
void Lb302Synth::playNote( NotePlayHandle * _n, SampleFrame* _working_buffer )
{
if( _n->isMasterNote() || ( _n->hasParent() && _n->isReleased() ) )
{
return;
}
// sort notes: new notes to the end
m_notesMutex.lock();
if( _n->totalFramesPlayed() == 0 )
{
m_notes.append( _n );
}
else
{
m_notes.prepend( _n );
}
m_notesMutex.unlock();
release_frame = std::max(release_frame, _n->framesLeft() + _n->offset());
}
void Lb302Synth::processNote( NotePlayHandle * _n )
{
/// Start a new note.
if (_n->m_pluginData != this)
{
m_playingNote = _n;
new_freq = true;
_n->m_pluginData = this;
}
if( ! m_playingNote && ! _n->isReleased() && release_frame > 0 )
{
m_playingNote = _n;
if ( slideToggle.value() )
{
vco_slideinc = GET_INC( _n->frequency() );
}
}
// Check for slide
if( m_playingNote == _n )
{
true_freq = _n->frequency();
if( slideToggle.value() ) {
vco_slidebase = GET_INC( true_freq ); // The REAL frequency
}
else {
vco_inc = GET_INC( true_freq );
}
}
}
void Lb302Synth::play( SampleFrame* _working_buffer )
{
m_notesMutex.lock();
while( ! m_notes.isEmpty() )
{
processNote( m_notes.takeFirst() );
};
m_notesMutex.unlock();
const fpp_t frames = Engine::audioEngine()->framesPerPeriod();
process( _working_buffer, frames );
// release_frame = 0; //removed for issue # 1432
}
void Lb302Synth::deleteNotePluginData( NotePlayHandle * _n )
{
//printf("GONE\n");
if( m_playingNote == _n )
{
m_playingNote = nullptr;
}
}
gui::PluginView * Lb302Synth::instantiateView( QWidget * _parent )
{
return( new gui::Lb302SynthView( this, _parent ) );
}
namespace gui
{
Lb302SynthView::Lb302SynthView( Instrument * _instrument, QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
// GUI
m_vcfCutKnob = new Knob( KnobType::Bright26, this );
m_vcfCutKnob->move( 75, 130 );
m_vcfCutKnob->setHintText( tr( "Cutoff Freq:" ), "" );
m_vcfCutKnob->setLabel( "" );
m_vcfResKnob = new Knob( KnobType::Bright26, this );
m_vcfResKnob->move( 120, 130 );
m_vcfResKnob->setHintText( tr( "Resonance:" ), "" );
m_vcfResKnob->setLabel( "" );
m_vcfModKnob = new Knob( KnobType::Bright26, this );
m_vcfModKnob->move( 165, 130 );
m_vcfModKnob->setHintText( tr( "Env Mod:" ), "" );
m_vcfModKnob->setLabel( "" );
m_vcfDecKnob = new Knob( KnobType::Bright26, this );
m_vcfDecKnob->move( 210, 130 );
m_vcfDecKnob->setHintText( tr( "Decay:" ), "" );
m_vcfDecKnob->setLabel( "" );
m_slideToggle = new LedCheckBox( "", this );
m_slideToggle->move( 10, 180 );
/* m_accentToggle = new LedCheckBox( "", this );
m_accentToggle->move( 10, 200 );
m_accentToggle->setDisabled(true);*/ // accent removed pending real implementation - no need for non-functional buttons
m_deadToggle = new LedCheckBox( "", this );
m_deadToggle->move( 10, 200 );
m_db24Toggle = new LedCheckBox( "", this );
m_db24Toggle->move( 10, 150);
m_db24Toggle->setToolTip(
tr( "303-es-que, 24dB/octave, 3 pole filter" ) );
m_slideDecKnob = new Knob( KnobType::Bright26, this );
m_slideDecKnob->move( 210, 75 );
m_slideDecKnob->setHintText( tr( "Slide Decay:" ), "" );
m_slideDecKnob->setLabel( "");
m_distKnob = new Knob( KnobType::Bright26, this );
m_distKnob->move( 210, 190 );
m_distKnob->setHintText( tr( "DIST:" ), "" );
m_distKnob->setLabel( tr( ""));
// Shapes
// move to 120,75
const int waveBtnX = 10;
const int waveBtnY = 96;
auto sawWaveBtn = new PixmapButton(this, tr("Saw wave"));
sawWaveBtn->move( waveBtnX, waveBtnY );
sawWaveBtn->setActiveGraphic( embed::getIconPixmap(
"saw_wave_active" ) );
sawWaveBtn->setInactiveGraphic( embed::getIconPixmap(
"saw_wave_inactive" ) );
sawWaveBtn->setToolTip(
tr( "Click here for a saw-wave." ) );
auto triangleWaveBtn = new PixmapButton(this, tr("Triangle wave"));
triangleWaveBtn->move( waveBtnX+(16*1), waveBtnY );
triangleWaveBtn->setActiveGraphic(
embed::getIconPixmap( "triangle_wave_active" ) );
triangleWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "triangle_wave_inactive" ) );
triangleWaveBtn->setToolTip(
tr( "Click here for a triangle-wave." ) );
auto sqrWaveBtn = new PixmapButton(this, tr("Square wave"));
sqrWaveBtn->move( waveBtnX+(16*2), waveBtnY );
sqrWaveBtn->setActiveGraphic( embed::getIconPixmap(
"square_wave_active" ) );
sqrWaveBtn->setInactiveGraphic( embed::getIconPixmap(
"square_wave_inactive" ) );
sqrWaveBtn->setToolTip(
tr( "Click here for a square-wave." ) );
auto roundSqrWaveBtn = new PixmapButton(this, tr("Rounded square wave"));
roundSqrWaveBtn->move( waveBtnX+(16*3), waveBtnY );
roundSqrWaveBtn->setActiveGraphic( embed::getIconPixmap(
"round_square_wave_active" ) );
roundSqrWaveBtn->setInactiveGraphic( embed::getIconPixmap(
"round_square_wave_inactive" ) );
roundSqrWaveBtn->setToolTip(
tr( "Click here for a square-wave with a rounded end." ) );
auto moogWaveBtn = new PixmapButton(this, tr("Moog wave"));
moogWaveBtn->move( waveBtnX+(16*4), waveBtnY );
moogWaveBtn->setActiveGraphic(
embed::getIconPixmap( "moog_saw_wave_active" ) );
moogWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "moog_saw_wave_inactive" ) );
moogWaveBtn->setToolTip(
tr( "Click here for a moog-like wave." ) );
auto sinWaveBtn = new PixmapButton(this, tr("Sine wave"));
sinWaveBtn->move( waveBtnX+(16*5), waveBtnY );
sinWaveBtn->setActiveGraphic( embed::getIconPixmap(
"sin_wave_active" ) );
sinWaveBtn->setInactiveGraphic( embed::getIconPixmap(
"sin_wave_inactive" ) );
sinWaveBtn->setToolTip(
tr( "Click for a sine-wave." ) );
auto exponentialWaveBtn = new PixmapButton(this, tr("White noise wave"));
exponentialWaveBtn->move( waveBtnX+(16*6), waveBtnY );
exponentialWaveBtn->setActiveGraphic(
embed::getIconPixmap( "exp_wave_active" ) );
exponentialWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "exp_wave_inactive" ) );
exponentialWaveBtn->setToolTip(
tr( "Click here for an exponential wave." ) );
auto whiteNoiseWaveBtn = new PixmapButton(this, tr("White noise wave"));
whiteNoiseWaveBtn->move( waveBtnX+(16*7), waveBtnY );
whiteNoiseWaveBtn->setActiveGraphic(
embed::getIconPixmap( "white_noise_wave_active" ) );
whiteNoiseWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "white_noise_wave_inactive" ) );
whiteNoiseWaveBtn->setToolTip(
tr( "Click here for white-noise." ) );
auto blSawWaveBtn = new PixmapButton(this, tr("Bandlimited saw wave"));
blSawWaveBtn->move( waveBtnX+(16*9)-8, waveBtnY );
blSawWaveBtn->setActiveGraphic(
embed::getIconPixmap( "saw_wave_active" ) );
blSawWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "saw_wave_inactive" ) );
blSawWaveBtn->setToolTip(
tr( "Click here for bandlimited saw wave." ) );
auto blSquareWaveBtn = new PixmapButton(this, tr("Bandlimited square wave"));
blSquareWaveBtn->move( waveBtnX+(16*10)-8, waveBtnY );
blSquareWaveBtn->setActiveGraphic(
embed::getIconPixmap( "square_wave_active" ) );
blSquareWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "square_wave_inactive" ) );
blSquareWaveBtn->setToolTip(
tr( "Click here for bandlimited square wave." ) );
auto blTriangleWaveBtn = new PixmapButton(this, tr("Bandlimited triangle wave"));
blTriangleWaveBtn->move( waveBtnX+(16*11)-8, waveBtnY );
blTriangleWaveBtn->setActiveGraphic(
embed::getIconPixmap( "triangle_wave_active" ) );
blTriangleWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "triangle_wave_inactive" ) );
blTriangleWaveBtn->setToolTip(
tr( "Click here for bandlimited triangle wave." ) );
auto blMoogWaveBtn = new PixmapButton(this, tr("Bandlimited moog saw wave"));
blMoogWaveBtn->move( waveBtnX+(16*12)-8, waveBtnY );
blMoogWaveBtn->setActiveGraphic(
embed::getIconPixmap( "moog_saw_wave_active" ) );
blMoogWaveBtn->setInactiveGraphic(
embed::getIconPixmap( "moog_saw_wave_inactive" ) );
blMoogWaveBtn->setToolTip(
tr( "Click here for bandlimited moog saw wave." ) );
m_waveBtnGrp = new automatableButtonGroup( this );
m_waveBtnGrp->addButton( sawWaveBtn );
m_waveBtnGrp->addButton( triangleWaveBtn );
m_waveBtnGrp->addButton( sqrWaveBtn );
m_waveBtnGrp->addButton( roundSqrWaveBtn );
m_waveBtnGrp->addButton( moogWaveBtn );
m_waveBtnGrp->addButton( sinWaveBtn );
m_waveBtnGrp->addButton( exponentialWaveBtn );
m_waveBtnGrp->addButton( whiteNoiseWaveBtn );
m_waveBtnGrp->addButton( blSawWaveBtn );
m_waveBtnGrp->addButton( blSquareWaveBtn );
m_waveBtnGrp->addButton( blTriangleWaveBtn );
m_waveBtnGrp->addButton( blMoogWaveBtn );
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap(
"artwork" ) );
setPalette( pal );
}
void Lb302SynthView::modelChanged()
{
auto syn = castModel<Lb302Synth>();
m_vcfCutKnob->setModel( &syn->vcf_cut_knob );
m_vcfResKnob->setModel( &syn->vcf_res_knob );
m_vcfDecKnob->setModel( &syn->vcf_dec_knob );
m_vcfModKnob->setModel( &syn->vcf_mod_knob );
m_slideDecKnob->setModel( &syn->slide_dec_knob );
m_distKnob->setModel( &syn->dist_knob );
m_waveBtnGrp->setModel( &syn->wave_shape );
m_slideToggle->setModel( &syn->slideToggle );
/*m_accentToggle->setModel( &syn->accentToggle );*/
m_deadToggle->setModel( &syn->deadToggle );
m_db24Toggle->setModel( &syn->db24Toggle );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * m, void * )
{
return( new Lb302Synth(
static_cast<InstrumentTrack *>( m ) ) );
}
}
} // namespace lmms
| 28,403
|
C++
|
.cpp
| 832
| 31.314904
| 155
| 0.683366
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,684
|
DualFilterControlDialog.cpp
|
LMMS_lmms/plugins/DualFilter/DualFilterControlDialog.cpp
|
/*
* DualFilterControlDialog.cpp - control dialog for dual filter effect
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "DualFilterControlDialog.h"
#include "DualFilterControls.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "ComboBox.h"
namespace lmms::gui
{
#define makeknob( name, x, y, model, label, hint, unit ) \
Knob * name = new Knob( KnobType::Bright26, this); \
(name) -> move( x, y ); \
(name) ->setModel( &controls-> model ); \
(name) ->setLabel( label ); \
(name) ->setHintText( hint, unit );
DualFilterControlDialog::DualFilterControlDialog( DualFilterControls* controls ) :
EffectControlDialog( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 373, 109 );
makeknob( cut1Knob, 24, 26, m_cut1Model, tr( "FREQ" ), tr( "Cutoff frequency" ), "Hz" )
makeknob( res1Knob, 74, 26, m_res1Model, tr( "RESO" ), tr( "Resonance" ), "" )
makeknob( gain1Knob, 124, 26, m_gain1Model, tr( "GAIN" ), tr( "Gain" ), "%" )
makeknob( mixKnob, 173, 37, m_mixModel, tr( "MIX" ), tr( "Mix" ), "" )
makeknob( cut2Knob, 222, 26, m_cut2Model, tr( "FREQ" ), tr( "Cutoff frequency" ), "Hz" )
makeknob( res2Knob, 272, 26, m_res2Model, tr( "RESO" ), tr( "Resonance" ), "" )
makeknob( gain2Knob, 322, 26, m_gain2Model, tr( "GAIN" ), tr( "Gain" ), "%" )
gain1Knob-> setVolumeKnob( true );
gain2Knob-> setVolumeKnob( true );
auto enabled1Toggle = new LedCheckBox("", this, tr("Filter 1 enabled"), LedCheckBox::LedColor::Green);
auto enabled2Toggle = new LedCheckBox("", this, tr("Filter 2 enabled"), LedCheckBox::LedColor::Green);
enabled1Toggle -> move( 12, 11 );
enabled1Toggle -> setModel( &controls -> m_enabled1Model );
enabled1Toggle->setToolTip(tr("Enable/disable filter 1"));
enabled2Toggle -> move( 210, 11 );
enabled2Toggle -> setModel( &controls -> m_enabled2Model );
enabled2Toggle->setToolTip(tr("Enable/disable filter 2"));
auto m_filter1ComboBox = new ComboBox(this);
m_filter1ComboBox->setGeometry( 19, 70, 137, ComboBox::DEFAULT_HEIGHT );
m_filter1ComboBox->setModel( &controls->m_filter1Model );
auto m_filter2ComboBox = new ComboBox(this);
m_filter2ComboBox->setGeometry( 217, 70, 137, ComboBox::DEFAULT_HEIGHT );
m_filter2ComboBox->setModel( &controls->m_filter2Model );
}
} // namespace lmms::gui
| 3,302
|
C++
|
.cpp
| 70
| 45.128571
| 103
| 0.712687
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,685
|
DualFilter.cpp
|
LMMS_lmms/plugins/DualFilter/DualFilter.cpp
|
/*
* DualFilter.cpp - A native dual filter effect plugin with two parallel filters
*
* Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "DualFilter.h"
#include "embed.h"
#include "BasicFilters.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT dualfilter_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Dual Filter",
QT_TRANSLATE_NOOP( "PluginBrowser", "A Dual filter plugin" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
DualFilterEffect::DualFilterEffect( Model* parent, const Descriptor::SubPluginFeatures::Key* key ) :
Effect( &dualfilter_plugin_descriptor, parent, key ),
m_dfControls( this )
{
m_filter1 = new BasicFilters<2>( Engine::audioEngine()->outputSampleRate() );
m_filter2 = new BasicFilters<2>( Engine::audioEngine()->outputSampleRate() );
// ensure filters get updated
m_filter1changed = true;
m_filter2changed = true;
}
DualFilterEffect::~DualFilterEffect()
{
delete m_filter1;
delete m_filter2;
}
Effect::ProcessStatus DualFilterEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const float d = dryLevel();
const float w = wetLevel();
if (m_dfControls.m_filter1Model.isValueChanged() || m_filter1changed)
{
m_filter1->setFilterType( static_cast<BasicFilters<2>::FilterType>(m_dfControls.m_filter1Model.value()) );
m_filter1changed = true;
}
if (m_dfControls.m_filter2Model.isValueChanged() || m_filter2changed)
{
m_filter2->setFilterType( static_cast<BasicFilters<2>::FilterType>(m_dfControls.m_filter2Model.value()) );
m_filter2changed = true;
}
float cut1 = m_dfControls.m_cut1Model.value();
float res1 = m_dfControls.m_res1Model.value();
float gain1 = m_dfControls.m_gain1Model.value();
float cut2 = m_dfControls.m_cut2Model.value();
float res2 = m_dfControls.m_res2Model.value();
float gain2 = m_dfControls.m_gain2Model.value();
float mix = m_dfControls.m_mixModel.value();
ValueBuffer *cut1Buffer = m_dfControls.m_cut1Model.valueBuffer();
ValueBuffer *res1Buffer = m_dfControls.m_res1Model.valueBuffer();
ValueBuffer *gain1Buffer = m_dfControls.m_gain1Model.valueBuffer();
ValueBuffer *cut2Buffer = m_dfControls.m_cut2Model.valueBuffer();
ValueBuffer *res2Buffer = m_dfControls.m_res2Model.valueBuffer();
ValueBuffer *gain2Buffer = m_dfControls.m_gain2Model.valueBuffer();
ValueBuffer *mixBuffer = m_dfControls.m_mixModel.valueBuffer();
int cut1Inc = cut1Buffer ? 1 : 0;
int res1Inc = res1Buffer ? 1 : 0;
int gain1Inc = gain1Buffer ? 1 : 0;
int cut2Inc = cut2Buffer ? 1 : 0;
int res2Inc = res2Buffer ? 1 : 0;
int gain2Inc = gain2Buffer ? 1 : 0;
int mixInc = mixBuffer ? 1 : 0;
float *cut1Ptr = cut1Buffer ? &( cut1Buffer->values()[ 0 ] ) : &cut1;
float *res1Ptr = res1Buffer ? &( res1Buffer->values()[ 0 ] ) : &res1;
float *gain1Ptr = gain1Buffer ? &( gain1Buffer->values()[ 0 ] ) : &gain1;
float *cut2Ptr = cut2Buffer ? &( cut2Buffer->values()[ 0 ] ) : &cut2;
float *res2Ptr = res2Buffer ? &( res2Buffer->values()[ 0 ] ) : &res2;
float *gain2Ptr = gain2Buffer ? &( gain2Buffer->values()[ 0 ] ) : &gain2;
float *mixPtr = mixBuffer ? &( mixBuffer->values()[ 0 ] ) : &mix;
const bool enabled1 = m_dfControls.m_enabled1Model.value();
const bool enabled2 = m_dfControls.m_enabled2Model.value();
// buffer processing loop
for( fpp_t f = 0; f < frames; ++f )
{
// get mix amounts for wet signals of both filters
const float mix2 = ( ( *mixPtr + 1.0f ) * 0.5f );
const float mix1 = 1.0f - mix2;
const float gain1 = *gain1Ptr * 0.01f;
const float gain2 = *gain2Ptr * 0.01f;
auto s = std::array{0.0f, 0.0f}; // mix
auto s1 = std::array{buf[f][0], buf[f][1]}; // filter 1
auto s2 = std::array{buf[f][0], buf[f][1]}; // filter 2
// update filter 1
if( enabled1 )
{
//update filter 1 params here
// recalculate only when necessary: either cut/res is changed, or the changed-flag is set (filter type or samplerate changed)
if( ( ( *cut1Ptr != m_currentCut1 ||
*res1Ptr != m_currentRes1 ) ) || m_filter1changed )
{
m_filter1->calcFilterCoeffs( *cut1Ptr, *res1Ptr );
m_filter1changed = false;
m_currentCut1 = *cut1Ptr;
m_currentRes1 = *res1Ptr;
}
s1[0] = m_filter1->update( s1[0], 0 );
s1[1] = m_filter1->update( s1[1], 1 );
// apply gain
s1[0] *= gain1;
s1[1] *= gain1;
// apply mix
s[0] += ( s1[0] * mix1 );
s[1] += ( s1[1] * mix1 );
}
// update filter 2
if( enabled2 )
{
//update filter 2 params here
if( ( ( *cut2Ptr != m_currentCut2 ||
*res2Ptr != m_currentRes2 ) ) || m_filter2changed )
{
m_filter2->calcFilterCoeffs( *cut2Ptr, *res2Ptr );
m_filter2changed = false;
m_currentCut2 = *cut2Ptr;
m_currentRes2 = *res2Ptr;
}
s2[0] = m_filter2->update( s2[0], 0 );
s2[1] = m_filter2->update( s2[1], 1 );
//apply gain
s2[0] *= gain2;
s2[1] *= gain2;
// apply mix
s[0] += ( s2[0] * mix2 );
s[1] += ( s2[1] * mix2 );
}
// do another mix with dry signal
buf[f][0] = d * buf[f][0] + w * s[0];
buf[f][1] = d * buf[f][1] + w * s[1];
//increment pointers
cut1Ptr += cut1Inc;
res1Ptr += res1Inc;
gain1Ptr += gain1Inc;
cut2Ptr += cut2Inc;
res2Ptr += res2Inc;
gain2Ptr += gain2Inc;
mixPtr += mixInc;
}
return ProcessStatus::ContinueIfNotQuiet;
}
void DualFilterEffect::onEnabledChanged()
{
m_filter1->clearHistory();
m_filter2->clearHistory();
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new DualFilterEffect( parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( data ) );
}
}
} // namespace lmms
| 6,666
|
C++
|
.cpp
| 186
| 33.134409
| 128
| 0.695848
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,686
|
DualFilterControls.cpp
|
LMMS_lmms/plugins/DualFilter/DualFilterControls.cpp
|
/*
* DualFilterControls.cpp - controls for dual filter effect
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "BasicFilters.h"
#include "DualFilterControls.h"
#include "DualFilter.h"
#include "embed.h"
#include "Engine.h"
namespace lmms
{
DualFilterControls::DualFilterControls( DualFilterEffect* effect ) :
EffectControls( effect ),
m_effect( effect ),
m_enabled1Model( true, this, tr( "Filter 1 enabled" ) ),
m_filter1Model( this, tr( "Filter 1 type" ) ),
m_cut1Model( 7000.0f, 1.0f, 20000.0f, 1.0f, this, tr( "Cutoff frequency 1" ) ),
m_res1Model(0.5f, BasicFilters<>::minQ(), 10.f, 0.01f, this, tr("Q/Resonance 1")),
m_gain1Model( 100.0f, 0.0f, 200.0f, 0.1f, this, tr( "Gain 1" ) ),
m_mixModel( 0.0f, -1.0f, 1.0f, 0.01f, this, tr( "Mix" ) ),
m_enabled2Model( true, this, tr( "Filter 2 enabled" ) ),
m_filter2Model( this, tr( "Filter 2 type" ) ),
m_cut2Model( 7000.0f, 1.0f, 20000.0f, 1.0f, this, tr( "Cutoff frequency 2" ) ),
m_res2Model(0.5f, BasicFilters<>::minQ(), 10.f, 0.01f, this, tr("Q/Resonance 2")),
m_gain2Model( 100.0f, 0.0f, 200.0f, 0.1f, this, tr( "Gain 2" ) )
{
m_filter1Model.addItem( tr( "Low-pass" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter1Model.addItem( tr( "Hi-pass" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter1Model.addItem( tr( "Band-pass csg" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter1Model.addItem( tr( "Band-pass czpg" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter1Model.addItem( tr( "Notch" ), std::make_unique<PixmapLoader>( "filter_notch" ) );
m_filter1Model.addItem( tr( "All-pass" ), std::make_unique<PixmapLoader>( "filter_ap" ) );
m_filter1Model.addItem( tr( "Moog" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter1Model.addItem( tr( "2x Low-pass" ), std::make_unique<PixmapLoader>( "filter_2lp" ) );
m_filter1Model.addItem( tr( "RC Low-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter1Model.addItem( tr( "RC Band-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter1Model.addItem( tr( "RC High-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter1Model.addItem( tr( "RC Low-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter1Model.addItem( tr( "RC Band-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter1Model.addItem( tr( "RC High-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter1Model.addItem( tr( "Vocal Formant" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter1Model.addItem( tr( "2x Moog" ), std::make_unique<PixmapLoader>( "filter_2lp" ) );
m_filter1Model.addItem( tr( "SV Low-pass" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter1Model.addItem( tr( "SV Band-pass" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter1Model.addItem( tr( "SV High-pass" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter1Model.addItem( tr( "SV Notch" ), std::make_unique<PixmapLoader>( "filter_notch" ) );
m_filter1Model.addItem( tr( "Fast Formant" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter1Model.addItem( tr( "Tripole" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter2Model.addItem( tr( "Low-pass" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter2Model.addItem( tr( "Hi-pass" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter2Model.addItem( tr( "Band-pass csg" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter2Model.addItem( tr( "Band-pass czpg" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter2Model.addItem( tr( "Notch" ), std::make_unique<PixmapLoader>( "filter_notch" ) );
m_filter2Model.addItem( tr( "All-pass" ), std::make_unique<PixmapLoader>( "filter_ap" ) );
m_filter2Model.addItem( tr( "Moog" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter2Model.addItem( tr( "2x Low-pass" ), std::make_unique<PixmapLoader>( "filter_2lp" ) );
m_filter2Model.addItem( tr( "RC Low-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter2Model.addItem( tr( "RC Band-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter2Model.addItem( tr( "RC High-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter2Model.addItem( tr( "RC Low-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter2Model.addItem( tr( "RC Band-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter2Model.addItem( tr( "RC High-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter2Model.addItem( tr( "Vocal Formant" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter2Model.addItem( tr( "2x Moog" ), std::make_unique<PixmapLoader>( "filter_2lp" ) );
m_filter2Model.addItem( tr( "SV Low-pass" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filter2Model.addItem( tr( "SV Band-pass" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filter2Model.addItem( tr( "SV High-pass" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter2Model.addItem( tr( "SV Notch" ), std::make_unique<PixmapLoader>( "filter_notch" ) );
m_filter2Model.addItem( tr( "Fast Formant" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filter2Model.addItem( tr( "Tripole" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( updateFilters() ) );
}
void DualFilterControls::updateFilters()
{
// swap filters to new ones
delete m_effect->m_filter1;
delete m_effect->m_filter2;
m_effect->m_filter1 = new BasicFilters<2>( Engine::audioEngine()->outputSampleRate() );
m_effect->m_filter2 = new BasicFilters<2>( Engine::audioEngine()->outputSampleRate() );
// flag filters as needing recalculation
m_effect->m_filter1changed = true;
m_effect->m_filter2changed = true;
}
void DualFilterControls::loadSettings( const QDomElement& _this )
{
m_enabled1Model.loadSettings( _this, "enabled1" );
m_filter1Model.loadSettings( _this, "filter1" );
m_cut1Model.loadSettings( _this, "cut1" );
m_res1Model.loadSettings( _this, "res1" );
m_gain1Model.loadSettings( _this, "gain1" );
m_mixModel.loadSettings( _this, "mix" );
m_enabled2Model.loadSettings( _this, "enabled2" );
m_filter2Model.loadSettings( _this, "filter2" );
m_cut2Model.loadSettings( _this, "cut2" );
m_res2Model.loadSettings( _this, "res2" );
m_gain2Model.loadSettings( _this, "gain2" );
}
void DualFilterControls::saveSettings( QDomDocument& _doc, QDomElement& _this )
{
m_enabled1Model.saveSettings( _doc, _this, "enabled1" );
m_filter1Model.saveSettings( _doc, _this, "filter1" );
m_cut1Model.saveSettings( _doc, _this, "cut1" );
m_res1Model.saveSettings( _doc, _this, "res1" );
m_gain1Model.saveSettings( _doc, _this, "gain1" );
m_mixModel.saveSettings( _doc, _this, "mix" );
m_enabled2Model.saveSettings( _doc, _this, "enabled2" );
m_filter2Model.saveSettings( _doc, _this, "filter2" );
m_cut2Model.saveSettings( _doc, _this, "cut2" );
m_res2Model.saveSettings( _doc, _this, "res2" );
m_gain2Model.saveSettings( _doc, _this, "gain2" );
}
} // namespace lmms
| 8,124
|
C++
|
.cpp
| 133
| 59
| 105
| 0.699925
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,687
|
Lv2FxControls.cpp
|
LMMS_lmms/plugins/Lv2Effect/Lv2FxControls.cpp
|
/*
* Lv2FxControls.cpp - Lv2FxControls implementation
*
* Copyright (c) 2018-2023 Johannes Lorenz <jlsf2013$users.sourceforge.net, $=@>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Lv2FxControls.h"
#include <QDomElement>
#include "Engine.h"
#include "Lv2Effect.h"
#include "Lv2FxControlDialog.h"
namespace lmms
{
Lv2FxControls::Lv2FxControls(class Lv2Effect *effect, const QString& uri) :
EffectControls(effect),
Lv2ControlBase(this, uri)
{
connect(Engine::audioEngine(), &AudioEngine::sampleRateChanged,
this, &Lv2FxControls::onSampleRateChanged);
}
void Lv2FxControls::reload()
{
Lv2ControlBase::reload();
emit modelChanged();
}
void Lv2FxControls::onSampleRateChanged()
{
// TODO: once lv2 options are implemented,
// plugins that support it might allow changing their samplerate
// through it instead of reloading
reload();
}
void Lv2FxControls::saveSettings(QDomDocument &doc, QDomElement &that)
{
Lv2ControlBase::saveSettings(doc, that);
}
void Lv2FxControls::loadSettings(const QDomElement &that)
{
Lv2ControlBase::loadSettings(that);
}
int Lv2FxControls::controlCount()
{
return static_cast<int>(Lv2ControlBase::controlCount());
}
gui::EffectControlDialog *Lv2FxControls::createView()
{
return new gui::Lv2FxControlDialog(this);
}
void Lv2FxControls::changeControl() // TODO: what is that?
{
// engine::getSong()->setModified();
}
} // namespace lmms
| 2,185
|
C++
|
.cpp
| 70
| 29.157143
| 80
| 0.770563
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,688
|
Lv2Effect.cpp
|
LMMS_lmms/plugins/Lv2Effect/Lv2Effect.cpp
|
/*
* Lv2Effect.cpp - implementation of LV2 effect
*
* Copyright (c) 2018-2023 Johannes Lorenz <jlsf2013$users.sourceforge.net, $=@>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Lv2Effect.h"
#include <QDebug>
#include "Lv2SubPluginFeatures.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT lv2effect_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"LV2",
QT_TRANSLATE_NOOP("PluginBrowser",
"plugin for using arbitrary LV2-effects inside LMMS."),
"Johannes Lorenz <jlsf2013$$$users.sourceforge.net, $$$=@>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
new Lv2SubPluginFeatures(Plugin::Type::Effect)
};
}
Lv2Effect::Lv2Effect(Model* parent, const Descriptor::SubPluginFeatures::Key *key) :
Effect(&lv2effect_plugin_descriptor, parent, key),
m_controls(this, key->attributes["uri"]),
m_tmpOutputSmps(Engine::audioEngine()->framesPerPeriod())
{
}
Effect::ProcessStatus Lv2Effect::processImpl(SampleFrame* buf, const fpp_t frames)
{
Q_ASSERT(frames <= static_cast<fpp_t>(m_tmpOutputSmps.size()));
m_controls.copyBuffersFromLmms(buf, frames);
m_controls.copyModelsFromLmms();
// m_pluginMutex.lock();
m_controls.run(frames);
// m_pluginMutex.unlock();
m_controls.copyModelsToLmms();
m_controls.copyBuffersToLmms(m_tmpOutputSmps.data(), frames);
bool corrupt = wetLevel() < 0; // #3261 - if w < 0, bash w := 0, d := 1
const float d = corrupt ? 1 : dryLevel();
const float w = corrupt ? 0 : wetLevel();
for(fpp_t f = 0; f < frames; ++f)
{
buf[f][0] = d * buf[f][0] + w * m_tmpOutputSmps[f][0];
buf[f][1] = d * buf[f][1] + w * m_tmpOutputSmps[f][1];
}
return ProcessStatus::ContinueIfNotQuiet;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin *lmms_plugin_main(Model *_parent, void *_data)
{
using KeyType = Plugin::Descriptor::SubPluginFeatures::Key;
try {
return new Lv2Effect(_parent, static_cast<const KeyType*>(_data));
} catch (const std::runtime_error& e) {
qCritical() << e.what();
return nullptr;
}
}
}
} // namespace lmms
| 2,887
|
C++
|
.cpp
| 87
| 31.103448
| 84
| 0.732033
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,689
|
Lv2FxControlDialog.cpp
|
LMMS_lmms/plugins/Lv2Effect/Lv2FxControlDialog.cpp
|
/*
* Lv2FxControlDialog.cpp - Lv2FxControlDialog implementation
*
* Copyright (c) 2018-2023 Johannes Lorenz <jlsf2013$users.sourceforge.net, $=@>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Lv2FxControlDialog.h"
#include <QPushButton>
#include "Lv2FxControls.h"
namespace lmms::gui
{
Lv2FxControlDialog::Lv2FxControlDialog(Lv2FxControls *controls) :
EffectControlDialog(controls),
Lv2ViewBase(this, controls)
{
if (m_reloadPluginButton) {
connect(m_reloadPluginButton, &QPushButton::clicked,
this, [this](){ lv2Controls()->reload(); });
}
if (m_toggleUIButton) {
connect(m_toggleUIButton, &QPushButton::toggled,
this, [this](){ toggleUI(); });
}
if (m_helpButton) {
connect(m_helpButton, &QPushButton::toggled,
this, [this](bool visible){ toggleHelp(visible); });
}
// for Effects, modelChanged only goes to the top EffectView
// we need to call it manually
modelChanged();
}
Lv2FxControls *Lv2FxControlDialog::lv2Controls()
{
return static_cast<Lv2FxControls *>(m_effectControls);
}
void Lv2FxControlDialog::modelChanged()
{
Lv2ViewBase::modelChanged(lv2Controls());
connect(lv2Controls(), &Lv2FxControls::modelChanged,
this, [this](){ this->modelChanged();} );
}
void Lv2FxControlDialog::hideEvent(QHideEvent *event)
{
closeHelpWindow();
QWidget::hideEvent(event);
}
} // namespace lmms::gui
| 2,111
|
C++
|
.cpp
| 64
| 30.796875
| 80
| 0.75629
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,690
|
WaveShaper.cpp
|
LMMS_lmms/plugins/WaveShaper/WaveShaper.cpp
|
/*
* WaveShaper.cpp - waveshaper effect-plugin
*
* Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "WaveShaper.h"
#include "lmms_math.h"
#include "embed.h"
#include "interpolation.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT waveshaper_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Waveshaper Effect",
QT_TRANSLATE_NOOP( "PluginBrowser",
"plugin for waveshaping" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
WaveShaperEffect::WaveShaperEffect( Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Effect( &waveshaper_plugin_descriptor, _parent, _key ),
m_wsControls( this )
{
}
Effect::ProcessStatus WaveShaperEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
// variables for effect
int i = 0;
const float d = dryLevel();
const float w = wetLevel();
float input = m_wsControls.m_inputModel.value();
float output = m_wsControls.m_outputModel.value();
const float * samples = m_wsControls.m_wavegraphModel.samples();
const bool clip = m_wsControls.m_clipModel.value();
ValueBuffer *inputBuffer = m_wsControls.m_inputModel.valueBuffer();
ValueBuffer *outputBufer = m_wsControls.m_outputModel.valueBuffer();
int inputInc = inputBuffer ? 1 : 0;
int outputInc = outputBufer ? 1 : 0;
const float *inputPtr = inputBuffer ? &( inputBuffer->values()[ 0 ] ) : &input;
const float *outputPtr = outputBufer ? &( outputBufer->values()[ 0 ] ) : &output;
for (fpp_t f = 0; f < frames; ++f)
{
auto s = std::array{buf[f][0], buf[f][1]};
// apply input gain
s[0] *= *inputPtr;
s[1] *= *inputPtr;
// clip if clip enabled
if( clip )
{
s[0] = qBound( -1.0f, s[0], 1.0f );
s[1] = qBound( -1.0f, s[1], 1.0f );
}
// start effect
for( i=0; i <= 1; ++i )
{
const int lookup = static_cast<int>( qAbs( s[i] ) * 200.0f );
const float frac = fraction( qAbs( s[i] ) * 200.0f );
const float posneg = s[i] < 0 ? -1.0f : 1.0f;
if( lookup < 1 )
{
s[i] = frac * samples[0] * posneg;
}
else if( lookup < 200 )
{
s[i] = linearInterpolate( samples[ lookup - 1 ],
samples[ lookup ], frac )
* posneg;
}
else
{
s[i] *= samples[199];
}
}
// apply output gain
s[0] *= *outputPtr;
s[1] *= *outputPtr;
// mix wet/dry signals
buf[f][0] = d * buf[f][0] + w * s[0];
buf[f][1] = d * buf[f][1] + w * s[1];
outputPtr += outputInc;
inputPtr += inputInc;
}
return ProcessStatus::ContinueIfNotQuiet;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * _parent, void * _data )
{
return( new WaveShaperEffect( _parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(
_data ) ) );
}
}
} // namespace lmms
| 3,790
|
C++
|
.cpp
| 124
| 27.91129
| 89
| 0.686983
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,691
|
WaveShaperControlDialog.cpp
|
LMMS_lmms/plugins/WaveShaper/WaveShaperControlDialog.cpp
|
/*
* WaveShaperControlDialog.cpp - control dialog for WaveShaper effect
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "WaveShaperControlDialog.h"
#include "WaveShaperControls.h"
#include "embed.h"
#include "Graph.h"
#include "Knob.h"
#include "PixmapButton.h"
#include "LedCheckBox.h"
namespace lmms::gui
{
WaveShaperControlDialog::WaveShaperControlDialog(
WaveShaperControls * _controls ) :
EffectControlDialog( _controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(),
PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 224, 274 );
auto waveGraph = new Graph(this, Graph::Style::LinearNonCyclic, 204, 205);
waveGraph -> move( 10, 6 );
waveGraph -> setModel( &_controls -> m_wavegraphModel );
waveGraph -> setAutoFillBackground( true );
pal = QPalette();
pal.setBrush( backgroundRole(),
PLUGIN_NAME::getIconPixmap("wavegraph") );
waveGraph->setPalette( pal );
waveGraph->setGraphColor( QColor( 85, 204, 145 ) );
waveGraph -> setMaximumSize( 204, 205 );
auto inputKnob = new Knob(KnobType::Bright26, this);
inputKnob -> setVolumeKnob( true );
inputKnob -> setVolumeRatio( 1.0 );
inputKnob -> move( 26, 225 );
inputKnob->setModel( &_controls->m_inputModel );
inputKnob->setLabel( tr( "INPUT" ) );
inputKnob->setHintText( tr( "Input gain:" ) , "" );
auto outputKnob = new Knob(KnobType::Bright26, this);
outputKnob -> setVolumeKnob( true );
outputKnob -> setVolumeRatio( 1.0 );
outputKnob -> move( 76, 225 );
outputKnob->setModel( &_controls->m_outputModel );
outputKnob->setLabel( tr( "OUTPUT" ) );
outputKnob->setHintText( tr( "Output gain:" ), "" );
auto resetButton = new PixmapButton(this, tr("Reset wavegraph"));
resetButton -> move( 162, 221 );
resetButton -> resize( 13, 46 );
resetButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "reset_active" ) );
resetButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "reset_inactive" ) );
resetButton->setToolTip(tr("Reset wavegraph"));
auto smoothButton = new PixmapButton(this, tr("Smooth wavegraph"));
smoothButton -> move( 162, 237 );
smoothButton -> resize( 13, 46 );
smoothButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "smooth_active" ) );
smoothButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "smooth_inactive" ) );
smoothButton->setToolTip(tr("Smooth wavegraph"));
auto addOneButton = new PixmapButton(this, tr("Increase wavegraph amplitude by 1 dB"));
addOneButton -> move( 131, 221 );
addOneButton -> resize( 13, 29 );
addOneButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "add1_active" ) );
addOneButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "add1_inactive" ) );
addOneButton->setToolTip(tr("Increase wavegraph amplitude by 1 dB"));
auto subOneButton = new PixmapButton(this, tr("Decrease wavegraph amplitude by 1 dB"));
subOneButton -> move( 131, 237 );
subOneButton -> resize( 13, 29 );
subOneButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "sub1_active" ) );
subOneButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "sub1_inactive" ) );
subOneButton->setToolTip(tr("Decrease wavegraph amplitude by 1 dB"));
auto clipInputToggle = new LedCheckBox("Clip input", this, tr("Clip input"), LedCheckBox::LedColor::Green);
clipInputToggle -> move( 131, 252 );
clipInputToggle -> setModel( &_controls -> m_clipModel );
clipInputToggle->setToolTip(tr("Clip input signal to 0 dB"));
connect( resetButton, SIGNAL (clicked () ),
_controls, SLOT ( resetClicked() ) );
connect( smoothButton, SIGNAL (clicked () ),
_controls, SLOT ( smoothClicked() ) );
connect( addOneButton, SIGNAL( clicked() ),
_controls, SLOT( addOneClicked() ) );
connect( subOneButton, SIGNAL( clicked() ),
_controls, SLOT( subOneClicked() ) );
}
} // namespace lmms::gui
| 4,729
|
C++
|
.cpp
| 105
| 42.847619
| 108
| 0.732798
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,692
|
WaveShaperControls.cpp
|
LMMS_lmms/plugins/WaveShaper/WaveShaperControls.cpp
|
/*
* WaveShaperControls.cpp - controls for WaveShaper effect
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "WaveShaperControls.h"
#include "WaveShaper.h"
#include "base64.h"
#include "Graph.h"
#include "Engine.h"
#include "Song.h"
namespace lmms
{
#define onedB 1.1220184543019633f
WaveShaperControls::WaveShaperControls( WaveShaperEffect * _eff ) :
EffectControls( _eff ),
m_effect( _eff ),
m_inputModel( 1.0f, 0.0f, 5.0f, 0.01f, this, tr( "Input gain" ) ),
m_outputModel( 1.0f, 0.0f, 5.0f, 0.01f, this, tr( "Output gain" ) ),
m_wavegraphModel( 0.0f, 1.0f, 200, this ),
m_clipModel( false, this )
{
connect( &m_wavegraphModel, SIGNAL( samplesChanged( int, int ) ),
this, SLOT( samplesChanged( int, int ) ) );
setDefaultShape();
}
void WaveShaperControls::samplesChanged( int _begin, int _end)
{
Engine::getSong()->setModified();
}
void WaveShaperControls::loadSettings( const QDomElement & _this )
{
//load input, output knobs
m_inputModel.loadSettings( _this, "inputGain" );
m_outputModel.loadSettings( _this, "outputGain" );
m_clipModel.loadSettings( _this, "clipInput" );
//load waveshape
int size = 0;
char * dst = 0;
base64::decode( _this.attribute( "waveShape"), &dst, &size );
m_wavegraphModel.setSamples( (float*) dst );
delete[] dst;
}
void WaveShaperControls::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
//save input, output knobs
m_inputModel.saveSettings( _doc, _this, "inputGain" );
m_outputModel.saveSettings( _doc, _this, "outputGain" );
m_clipModel.saveSettings( _doc, _this, "clipInput" );
//save waveshape
QString sampleString;
base64::encode( (const char *)m_wavegraphModel.samples(),
m_wavegraphModel.length() * sizeof(float), sampleString );
_this.setAttribute( "waveShape", sampleString );
}
void WaveShaperControls::setDefaultShape()
{
auto shp = std::array<float, 200>{};
for ( int i = 0; i<200; i++)
{
shp[i] = ((float)i + 1.0f) / 200.0f;
}
m_wavegraphModel.setLength( 200 );
m_wavegraphModel.setSamples( (float*)&shp );
}
void WaveShaperControls::resetClicked()
{
setDefaultShape();
Engine::getSong()->setModified();
}
void WaveShaperControls::smoothClicked()
{
m_wavegraphModel.smoothNonCyclic();
Engine::getSong()->setModified();
}
void WaveShaperControls::addOneClicked()
{
for( int i=0; i<200; i++ )
{
m_wavegraphModel.setSampleAt( i, qBound( 0.0f, m_wavegraphModel.samples()[i] * onedB, 1.0f ) );
}
Engine::getSong()->setModified();
}
void WaveShaperControls::subOneClicked()
{
for( int i=0; i<200; i++ )
{
m_wavegraphModel.setSampleAt( i, qBound( 0.0f, m_wavegraphModel.samples()[i] / onedB, 1.0f ) );
}
Engine::getSong()->setModified();
}
} // namespace lmms
| 3,630
|
C++
|
.cpp
| 113
| 30.088496
| 97
| 0.725445
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,693
|
MultitapEcho.cpp
|
LMMS_lmms/plugins/MultitapEcho/MultitapEcho.cpp
|
/*
* MultitapEcho.cpp - a multitap echo delay plugin
*
* Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "MultitapEcho.h"
#include "embed.h"
#include "lmms_basics.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT multitapecho_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Multitap Echo",
QT_TRANSLATE_NOOP( "PluginBrowser", "A multitap echo delay plugin" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
MultitapEchoEffect::MultitapEchoEffect( Model* parent, const Descriptor::SubPluginFeatures::Key* key ) :
Effect( &multitapecho_plugin_descriptor, parent, key ),
m_stages( 1 ),
m_controls( this ),
m_buffer( 16100.0f ),
m_sampleRate( Engine::audioEngine()->outputSampleRate() ),
m_sampleRatio( 1.0f / m_sampleRate )
{
m_work = new SampleFrame[Engine::audioEngine()->framesPerPeriod()];
m_buffer.reset();
m_stages = static_cast<int>( m_controls.m_stages.value() );
updateFilters( 0, 19 );
}
MultitapEchoEffect::~MultitapEchoEffect()
{
delete[] m_work;
}
void MultitapEchoEffect::updateFilters( int begin, int end )
{
for( int i = begin; i <= end; ++i )
{
for( int s = 0; s < m_stages; ++s )
{
setFilterFreq( m_lpFreq[i] * m_sampleRatio, m_filter[i][s] );
}
}
}
void MultitapEchoEffect::runFilter( SampleFrame* dst, SampleFrame* src, StereoOnePole & filter, const fpp_t frames )
{
for (auto f = std::size_t{0}; f < frames; ++f)
{
dst[f][0] = filter.update( src[f][0], 0 );
dst[f][1] = filter.update( src[f][1], 1 );
}
}
Effect::ProcessStatus MultitapEchoEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const float d = dryLevel();
const float w = wetLevel();
// get processing vars
const int steps = m_controls.m_steps.value();
const float stepLength = m_controls.m_stepLength.value();
const float dryGain = dbfsToAmp( m_controls.m_dryGain.value() );
const bool swapInputs = m_controls.m_swapInputs.value();
// check if number of stages has changed
if( m_controls.m_stages.isValueChanged() )
{
m_stages = static_cast<int>( m_controls.m_stages.value() );
updateFilters( 0, steps - 1 );
}
// add dry buffer - never swap inputs for dry
m_buffer.writeAddingMultiplied(buf, f_cnt_t{0}, frames, dryGain);
// swapped inputs?
if( swapInputs )
{
float offset = stepLength;
for( int i = 0; i < steps; ++i ) // add all steps swapped
{
for( int s = 0; s < m_stages; ++s )
{
runFilter( m_work, buf, m_filter[i][s], frames );
}
m_buffer.writeSwappedAddingMultiplied( m_work, offset, frames, m_amp[i] );
offset += stepLength;
}
}
else
{
float offset = stepLength;
for( int i = 0; i < steps; ++i ) // add all steps
{
for( int s = 0; s < m_stages; ++s )
{
runFilter( m_work, buf, m_filter[i][s], frames );
}
m_buffer.writeAddingMultiplied( m_work, offset, frames, m_amp[i] );
offset += stepLength;
}
}
// pop the buffer and mix it into output
m_buffer.pop( m_work );
for (auto f = std::size_t{0}; f < frames; ++f)
{
buf[f][0] = d * buf[f][0] + w * m_work[f][0];
buf[f][1] = d * buf[f][1] + w * m_work[f][1];
}
return ProcessStatus::ContinueIfNotQuiet;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new MultitapEchoEffect( parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( data ) );
}
}
} // namespace lmms
| 4,431
|
C++
|
.cpp
| 142
| 28.901408
| 116
| 0.699412
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,694
|
MultitapEchoControlDialog.cpp
|
LMMS_lmms/plugins/MultitapEcho/MultitapEchoControlDialog.cpp
|
/*
* MultitapEchoControlDialog.cpp - a multitap echo delay plugin
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "MultitapEchoControlDialog.h"
#include "MultitapEchoControls.h"
#include "embed.h"
#include "Graph.h"
#include "LedCheckBox.h"
#include "Knob.h"
#include "TempoSyncKnob.h"
#include "LcdSpinBox.h"
namespace lmms::gui
{
MultitapEchoControlDialog::MultitapEchoControlDialog( MultitapEchoControls * controls ) :
EffectControlDialog( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 245, 300 );
// graph widgets
auto ampGraph = new Graph(this, Graph::Style::Bar, 204, 105);
auto lpGraph = new Graph(this, Graph::Style::Bar, 204, 105);
ampGraph->move( 30, 10 );
lpGraph->move( 30, 125 );
ampGraph->setModel( & controls->m_ampGraph );
lpGraph->setModel( & controls->m_lpGraph );
pal = QPalette();
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap("graph_bg") );
ampGraph->setAutoFillBackground( true );
ampGraph->setPalette( pal );
ampGraph->setGraphColor( QColor( 11, 213, 86) );
ampGraph -> setMaximumSize( 204, 105 );
lpGraph->setAutoFillBackground( true );
lpGraph->setPalette( pal );
lpGraph->setGraphColor( QColor( 0, 200, 187) );
lpGraph -> setMaximumSize( 204, 105 );
// steps spinbox
auto steps = new LcdSpinBox(2, this, "Steps");
steps->move( 20, 245 );
steps->setModel( & controls->m_steps );
// knobs
auto stepLength = new TempoSyncKnob(KnobType::Bright26, this);
stepLength->move( 100, 245 );
stepLength->setModel( & controls->m_stepLength );
stepLength->setLabel( tr( "Length" ) );
stepLength->setHintText( tr( "Step length:" ) , " ms" );
auto dryGain = new Knob(KnobType::Bright26, this);
dryGain->move( 150, 245 );
dryGain->setModel( & controls->m_dryGain );
dryGain->setLabel( tr( "Dry" ) );
dryGain->setHintText( tr( "Dry gain:" ) , " dBFS" );
auto stages = new Knob(KnobType::Bright26, this);
stages->move( 200, 245 );
stages->setModel( & controls->m_stages );
stages->setLabel( tr( "Stages" ) );
stages->setHintText( tr( "Low-pass stages:" ) , "x" );
// switch led
auto swapInputs = new LedCheckBox("Swap inputs", this, tr("Swap inputs"), LedCheckBox::LedColor::Green);
swapInputs->move( 20, 275 );
swapInputs->setModel( & controls->m_swapInputs );
swapInputs->setToolTip(tr("Swap left and right input channels for reflections"));
}
} // namespace lmms::gui
| 3,395
|
C++
|
.cpp
| 86
| 37.325581
| 105
| 0.728132
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,695
|
MultitapEchoControls.cpp
|
LMMS_lmms/plugins/MultitapEcho/MultitapEchoControls.cpp
|
/*
* MultitapEchoControls.cpp - a multitap echo delay plugin
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include <QVarLengthArray>
#include "MultitapEchoControls.h"
#include "MultitapEcho.h"
#include "lmms_math.h"
#include "base64.h"
namespace lmms
{
MultitapEchoControls::MultitapEchoControls( MultitapEchoEffect * eff ) :
EffectControls( eff ),
m_effect( eff ),
m_steps( 16, 4, 32, this, "Steps" ),
m_stepLength( 100.0f, 1.0f, 500.0f, 0.1f, 500.0f, this, "Step length" ),
m_dryGain( 0.0f, -80.0f, 20.0f, 0.1f, this, "Dry gain" ),
m_swapInputs( false, this, "Swap inputs" ),
m_stages( 1.0f, 1.0f, 4.0f, 1.0f, this, "Lowpass stages" ),
m_ampGraph( -60.0f, 0.0f, 16, this ),
m_lpGraph( 0.0f, 3.0f, 16, this )
{
m_stages.setStrictStepSize( true );
connect( &m_ampGraph, SIGNAL( samplesChanged( int, int ) ), this, SLOT( ampSamplesChanged( int, int ) ) );
connect( &m_lpGraph, SIGNAL( samplesChanged( int, int ) ), this, SLOT( lpSamplesChanged( int, int ) ) );
connect( &m_steps, SIGNAL( dataChanged() ), this, SLOT( lengthChanged() ) );
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( sampleRateChanged() ) );
setDefaultAmpShape();
setDefaultLpShape();
}
void MultitapEchoControls::saveSettings( QDomDocument & doc, QDomElement & parent )
{
m_steps.saveSettings( doc, parent, "steps" );
m_stepLength.saveSettings( doc, parent, "steplength" );
m_dryGain.saveSettings( doc, parent, "drygain" );
m_swapInputs.saveSettings( doc, parent, "swapinputs" );
m_stages.saveSettings( doc, parent, "stages" );
QString ampString;
base64::encode( (const char *) m_ampGraph.samples(), m_ampGraph.length() * sizeof(float), ampString );
parent.setAttribute( "ampsteps", ampString );
QString lpString;
base64::encode( (const char *) m_lpGraph.samples(), m_lpGraph.length() * sizeof(float), lpString );
parent.setAttribute( "lpsteps", lpString );
}
void MultitapEchoControls::loadSettings( const QDomElement & elem )
{
m_steps.loadSettings( elem, "steps" );
m_stepLength.loadSettings( elem, "steplength" );
m_dryGain.loadSettings( elem, "drygain" );
m_swapInputs.loadSettings( elem, "swapinputs" );
m_stages.loadSettings( elem, "stages" );
int size = 0;
char * dst = 0;
base64::decode( elem.attribute( "ampsteps"), &dst, &size );
m_ampGraph.setSamples( (float*) dst );
base64::decode( elem.attribute( "lpsteps"), &dst, &size );
m_lpGraph.setSamples( (float*) dst );
delete[] dst;
}
void MultitapEchoControls::setDefaultAmpShape()
{
const int length = m_steps.value();
QVarLengthArray<float> samples(length);
for( int i = 0; i < length; ++i )
{
samples[i] = 0.0f;
}
m_ampGraph.setSamples( &samples[0] );
}
void MultitapEchoControls::setDefaultLpShape()
{
const int length = m_steps.value();
QVarLengthArray<float> samples(length);
for( int i = 0; i < length; ++i )
{
samples[i] = 3.0f;
}
m_lpGraph.setSamples( &samples[0] );
}
void MultitapEchoControls::ampSamplesChanged( int begin, int end )
{
const float * samples = m_ampGraph.samples();
for( int i = begin; i <= end; ++i )
{
m_effect->m_amp[i] = dbfsToAmp( samples[i] );
}
}
void MultitapEchoControls::ampResetClicked()
{
setDefaultAmpShape();
}
void MultitapEchoControls::lpSamplesChanged( int begin, int end )
{
//qDebug( "b/e %d - %d", begin, end );
const float * samples = m_lpGraph.samples();
for( int i = begin; i <= end; ++i )
{
m_effect->m_lpFreq[i] = 20.0f * std::pow(10.f, samples[i] );
}
m_effect->updateFilters( begin, end );
}
void MultitapEchoControls::lpResetClicked()
{
setDefaultLpShape();
}
void MultitapEchoControls::lengthChanged()
{
const int len = m_steps.value();
m_ampGraph.setLength( len );
ampSamplesChanged( 0, len - 1 );
m_lpGraph.setLength( len );
lpSamplesChanged( 0, len - 1 );
m_effect->updateFilters( 0, len - 1 );
}
void MultitapEchoControls::sampleRateChanged()
{
m_effect->m_sampleRate = Engine::audioEngine()->outputSampleRate();
m_effect->m_sampleRatio = 1.0f / m_effect->m_sampleRate;
m_effect->updateFilters( 0, 19 );
}
} // namespace lmms
| 4,994
|
C++
|
.cpp
| 142
| 33.105634
| 107
| 0.715654
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,696
|
GigPlayer.cpp
|
LMMS_lmms/plugins/GigPlayer/GigPlayer.cpp
|
/*
* GigPlayer.cpp - a GIG player using libgig (based on Sf2 player plugin)
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
* Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* A few lines of code taken from LinuxSampler (also GPLv2) where noted:
* Copyright (C) 2003,2004 by Benno Senoner and Christian Schoenebeck
* Copyright (C) 2005-2008 Christian Schoenebeck
* Copyright (C) 2009-2010 Christian Schoenebeck and Grigor Iliev
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "GigPlayer.h"
#include <cstring>
#include <QDebug>
#include <QLayout>
#include <QLabel>
#include <QDomDocument>
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "endian_handling.h"
#include "Engine.h"
#include "FileDialog.h"
#include "InstrumentTrack.h"
#include "InstrumentPlayHandle.h"
#include "Knob.h"
#include "NotePlayHandle.h"
#include "PathUtil.h"
#include "Sample.h"
#include "Song.h"
#include "PatchesDialog.h"
#include "LcdSpinBox.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT gigplayer_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"GIG Player",
QT_TRANSLATE_NOOP( "PluginBrowser", "Player for GIG files" ),
"Garrett Wilson <g/at/floft/dot/net>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
"gig",
nullptr,
} ;
}
GigInstrument::GigInstrument( InstrumentTrack * _instrument_track ) :
Instrument(_instrument_track, &gigplayer_plugin_descriptor, nullptr, Flag::IsSingleStreamed | Flag::IsNotBendable),
m_instance( nullptr ),
m_instrument( nullptr ),
m_filename( "" ),
m_bankNum( 0, 0, 999, this, tr( "Bank" ) ),
m_patchNum( 0, 0, 127, this, tr( "Patch" ) ),
m_gain( 1.0f, 0.0f, 5.0f, 0.01f, this, tr( "Gain" ) ),
m_interpolation( SRC_LINEAR ),
m_RandomSeed( 0 ),
m_currentKeyDimension( 0 )
{
auto iph = new InstrumentPlayHandle(this, _instrument_track);
Engine::audioEngine()->addPlayHandle( iph );
updateSampleRate();
connect( &m_bankNum, SIGNAL( dataChanged() ), this, SLOT( updatePatch() ) );
connect( &m_patchNum, SIGNAL( dataChanged() ), this, SLOT( updatePatch() ) );
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( updateSampleRate() ) );
}
GigInstrument::~GigInstrument()
{
Engine::audioEngine()->removePlayHandlesOfTypes( instrumentTrack(),
PlayHandle::Type::NotePlayHandle
| PlayHandle::Type::InstrumentPlayHandle );
freeInstance();
}
void GigInstrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
_this.setAttribute( "src", m_filename );
m_patchNum.saveSettings( _doc, _this, "patch" );
m_bankNum.saveSettings( _doc, _this, "bank" );
m_gain.saveSettings( _doc, _this, "gain" );
}
void GigInstrument::loadSettings( const QDomElement & _this )
{
openFile( _this.attribute( "src" ), false );
m_patchNum.loadSettings( _this, "patch" );
m_bankNum.loadSettings( _this, "bank" );
m_gain.loadSettings( _this, "gain" );
updatePatch();
}
void GigInstrument::loadFile( const QString & _file )
{
if( !_file.isEmpty() && QFileInfo( _file ).exists() )
{
openFile( _file, false );
updatePatch();
updateSampleRate();
}
}
AutomatableModel * GigInstrument::childModel( const QString & _modelName )
{
if( _modelName == "bank" )
{
return &m_bankNum;
}
else if( _modelName == "patch" )
{
return &m_patchNum;
}
qCritical() << "requested unknown model " << _modelName;
return nullptr;
}
QString GigInstrument::nodeName() const
{
return gigplayer_plugin_descriptor.name;
}
void GigInstrument::freeInstance()
{
QMutexLocker synthLock( &m_synthMutex );
QMutexLocker notesLock( &m_notesMutex );
if( m_instance != nullptr )
{
delete m_instance;
m_instance = nullptr;
// If we're changing instruments, we got to make sure that we
// remove all pointers to the old samples and don't try accessing
// that instrument again
m_instrument = nullptr;
m_notes.clear();
}
}
void GigInstrument::openFile( const QString & _gigFile, bool updateTrackName )
{
emit fileLoading();
// Remove the current instrument if one is selected
freeInstance();
{
QMutexLocker locker( &m_synthMutex );
try
{
m_instance = new GigInstance( PathUtil::toAbsolute( _gigFile ) );
m_filename = PathUtil::toShortestRelative( _gigFile );
}
catch( ... )
{
m_instance = nullptr;
m_filename = "";
}
}
emit fileChanged();
if( updateTrackName == true )
{
instrumentTrack()->setName(PathUtil::cleanName( _gigFile ) );
updatePatch();
}
}
void GigInstrument::updatePatch()
{
if( m_bankNum.value() >= 0 && m_patchNum.value() >= 0 )
{
getInstrument();
}
}
QString GigInstrument::getCurrentPatchName()
{
QMutexLocker locker( &m_synthMutex );
if( m_instance == nullptr )
{
return "";
}
int iBankSelected = m_bankNum.value();
int iProgSelected = m_patchNum.value();
gig::Instrument * pInstrument = m_instance->gig.GetFirstInstrument();
while( pInstrument != nullptr )
{
int iBank = pInstrument->MIDIBank;
int iProg = pInstrument->MIDIProgram;
if( iBank == iBankSelected && iProg == iProgSelected )
{
QString name = QString::fromStdString( pInstrument->pInfo->Name );
if( name == "" )
{
name = "<no name>";
}
return name;
}
pInstrument = m_instance->gig.GetNextInstrument();
}
return "";
}
// A key has been pressed
void GigInstrument::playNote( NotePlayHandle * _n, SampleFrame* )
{
const float LOG440 = 2.643452676f;
int midiNote = (int) floor( 12.0 * ( log2( _n->unpitchedFrequency() ) - LOG440 ) - 4.0 );
// out of range?
if( midiNote <= 0 || midiNote >= 128 )
{
return;
}
if (!_n->m_pluginData)
{
auto pluginData = new GIGPluginData;
pluginData->midiNote = midiNote;
_n->m_pluginData = pluginData;
const int baseVelocity = instrumentTrack()->midiPort()->baseVelocity();
const uint velocity = _n->midiVelocity( baseVelocity );
QMutexLocker locker( &m_notesMutex );
m_notes.push_back( GigNote( midiNote, velocity, _n->unpitchedFrequency(), pluginData ) );
}
}
// Process the notes and output a certain number of frames (e.g. 256, set in
// the preferences)
void GigInstrument::play( SampleFrame* _working_buffer )
{
const fpp_t frames = Engine::audioEngine()->framesPerPeriod();
const auto rate = Engine::audioEngine()->outputSampleRate();
// Initialize to zeros
std::memset( &_working_buffer[0][0], 0, DEFAULT_CHANNELS * frames * sizeof( float ) );
m_synthMutex.lock();
m_notesMutex.lock();
if( m_instance == nullptr || m_instrument == nullptr )
{
m_synthMutex.unlock();
m_notesMutex.unlock();
return;
}
for( QList<GigNote>::iterator it = m_notes.begin(); it != m_notes.end(); ++it )
{
// Process notes in the KeyUp state, adding release samples if desired
if( it->state == GigState::KeyUp )
{
// If there are no samples, we're done
if( it->samples.empty() )
{
it->state = GigState::Completed;
}
else
{
it->state = GigState::PlayingKeyUp;
// Notify each sample that the key has been released
for (auto& sample : it->samples)
{
sample.adsr.keyup();
}
// Add release samples if available
if( it->release == true )
{
addSamples( *it, true );
}
}
}
// Process notes in the KeyDown state, adding samples for the notes
else if( it->state == GigState::KeyDown )
{
it->state = GigState::PlayingKeyDown;
addSamples( *it, false );
}
// Delete ended samples
for( QList<GigSample>::iterator sample = it->samples.begin();
sample != it->samples.end(); ++sample )
{
// Delete if the ADSR for a sample is complete for normal
// notes, or if a release sample, then if we've reached
// the end of the sample
if( sample->sample == nullptr || sample->adsr.done() ||
( it->isRelease == true &&
sample->pos >= sample->sample->SamplesTotal - 1 ) )
{
sample = it->samples.erase( sample );
if( sample == it->samples.end() )
{
break;
}
}
}
// Delete ended notes (either in the completed state or all the samples ended)
if( it->state == GigState::Completed || it->samples.empty() )
{
it = m_notes.erase( it );
if( it == m_notes.end() )
{
break;
}
}
}
// Fill buffer with portions of the note samples
for (auto& note : m_notes)
{
// Only process the notes if we're in a playing state
if (!(note.state == GigState::PlayingKeyDown || note.state == GigState::PlayingKeyUp ))
{
continue;
}
for (auto& sample : note.samples)
{
if (sample.sample == nullptr || sample.region == nullptr) { continue; }
// Will change if resampling
bool resample = false;
f_cnt_t samples = frames; // How many to grab
f_cnt_t used = frames; // How many we used
float freq_factor = 1.0; // How to resample
// Resample to be the correct pitch when the sample provided isn't
// solely for this one note (e.g. one or two samples per octave) or
// we are processing at a different sample rate
if (sample.region->PitchTrack == true || rate != sample.sample->SamplesPerSecond)
{
resample = true;
// Factor just for resampling
freq_factor = 1.0 * rate / sample.sample->SamplesPerSecond;
// Factor for pitch shifting as well as resampling
if (sample.region->PitchTrack == true) { freq_factor *= sample.freqFactor; }
// We need a bit of margin so we don't get glitching
samples = frames / freq_factor + Sample::s_interpolationMargins[m_interpolation];
}
// Load this note's data
SampleFrame sampleData[samples];
loadSample(sample, sampleData, samples);
// Apply ADSR using a copy so if we don't use these samples when
// resampling, the ADSR doesn't get messed up
ADSR copy = sample.adsr;
for( f_cnt_t i = 0; i < samples; ++i )
{
float amplitude = copy.value();
sampleData[i][0] *= amplitude;
sampleData[i][1] *= amplitude;
}
// Output the data resampling if needed
if( resample == true )
{
SampleFrame convertBuf[frames];
// Only output if resampling is successful (note that "used" is output)
if (sample.convertSampleRate(*sampleData, *convertBuf, samples, frames, freq_factor, used))
{
for( f_cnt_t i = 0; i < frames; ++i )
{
_working_buffer[i][0] += convertBuf[i][0];
_working_buffer[i][1] += convertBuf[i][1];
}
}
}
else
{
for( f_cnt_t i = 0; i < frames; ++i )
{
_working_buffer[i][0] += sampleData[i][0];
_working_buffer[i][1] += sampleData[i][1];
}
}
// Update note position with how many samples we actually used
sample.pos += used;
sample.adsr.inc(used);
}
}
m_notesMutex.unlock();
m_synthMutex.unlock();
// Set gain properly based on volume control
for( f_cnt_t i = 0; i < frames; ++i )
{
_working_buffer[i][0] *= m_gain.value();
_working_buffer[i][1] *= m_gain.value();
}
}
void GigInstrument::loadSample( GigSample& sample, SampleFrame* sampleData, f_cnt_t samples )
{
if( sampleData == nullptr || samples < 1 )
{
return;
}
// Determine if we need to loop part of this sample
bool loop = false;
gig::loop_type_t loopType = gig::loop_type_normal;
f_cnt_t loopStart = 0;
f_cnt_t loopLength = 0;
if( sample.region->pSampleLoops != nullptr )
{
for( uint32_t i = 0; i < sample.region->SampleLoops; ++i )
{
loop = true;
loopType = static_cast<gig::loop_type_t>( sample.region->pSampleLoops[i].LoopType );
loopStart = sample.region->pSampleLoops[i].LoopStart;
loopLength = sample.region->pSampleLoops[i].LoopLength;
// Currently only support at max one loop
break;
}
}
unsigned long allocationsize = samples * sample.sample->FrameSize;
int8_t buffer[allocationsize];
// Load the sample in different ways depending on if we're looping or not
if( loop == true && ( sample.pos >= loopStart || sample.pos + samples > loopStart ) )
{
// Calculate the new position based on the type of loop
if( loopType == gig::loop_type_bidirectional )
{
sample.pos = getPingPongIndex( sample.pos, loopStart, loopStart + loopLength );
}
else
{
sample.pos = getLoopedIndex( sample.pos, loopStart, loopStart + loopLength );
// TODO: also implement loop_type_backward support
}
sample.sample->SetPos( sample.pos );
// Load the samples (based on gig::Sample::ReadAndLoop) even around the end
// of a loop boundary wrapping to the beginning of the loop region
long samplestoread = samples;
long samplestoloopend = 0;
long readsamples = 0;
long totalreadsamples = 0;
long loopEnd = loopStart + loopLength;
do
{
samplestoloopend = loopEnd - sample.sample->GetPos();
readsamples = sample.sample->Read( &buffer[totalreadsamples * sample.sample->FrameSize],
std::min( samplestoread, samplestoloopend ) );
samplestoread -= readsamples;
totalreadsamples += readsamples;
if( readsamples >= samplestoloopend )
{
sample.sample->SetPos( loopStart );
}
}
while( samplestoread > 0 && readsamples > 0 );
}
else
{
sample.sample->SetPos( sample.pos );
unsigned long size = sample.sample->Read( &buffer, samples ) * sample.sample->FrameSize;
std::memset( (int8_t*) &buffer + size, 0, allocationsize - size );
}
// Convert from 16 or 24 bit into 32-bit float
if( sample.sample->BitDepth == 24 ) // 24 bit
{
auto pInt = reinterpret_cast<uint8_t*>(&buffer);
for( f_cnt_t i = 0; i < samples; ++i )
{
// libgig gives 24-bit data as little endian, so we must
// convert if on a big endian system
int32_t valueLeft = swap32IfBE(
( pInt[ 3 * sample.sample->Channels * i ] << 8 ) |
( pInt[ 3 * sample.sample->Channels * i + 1 ] << 16 ) |
( pInt[ 3 * sample.sample->Channels * i + 2 ] << 24 ) );
// Store the notes to this buffer before saving to output
// so we can fade them out as needed
sampleData[i][0] = 1.0 / 0x100000000 * sample.attenuation * valueLeft;
if( sample.sample->Channels == 1 )
{
sampleData[i][1] = sampleData[i][0];
}
else
{
int32_t valueRight = swap32IfBE(
( pInt[ 3 * sample.sample->Channels * i + 3 ] << 8 ) |
( pInt[ 3 * sample.sample->Channels * i + 4 ] << 16 ) |
( pInt[ 3 * sample.sample->Channels * i + 5 ] << 24 ) );
sampleData[i][1] = 1.0 / 0x100000000 * sample.attenuation * valueRight;
}
}
}
else // 16 bit
{
auto pInt = reinterpret_cast<int16_t*>(&buffer);
for( f_cnt_t i = 0; i < samples; ++i )
{
sampleData[i][0] = 1.0 / 0x10000 *
pInt[ sample.sample->Channels * i ] * sample.attenuation;
if( sample.sample->Channels == 1 )
{
sampleData[i][1] = sampleData[i][0];
}
else
{
sampleData[i][1] = 1.0 / 0x10000 *
pInt[ sample.sample->Channels * i + 1 ] * sample.attenuation;
}
}
}
}
// These two loop index functions taken from SampleBuffer.cpp
f_cnt_t GigInstrument::getLoopedIndex( f_cnt_t index, f_cnt_t startf, f_cnt_t endf ) const
{
if( index < endf )
{
return index;
}
return startf + ( index - startf )
% ( endf - startf );
}
f_cnt_t GigInstrument::getPingPongIndex( f_cnt_t index, f_cnt_t startf, f_cnt_t endf ) const
{
if( index < endf )
{
return index;
}
const f_cnt_t looplen = endf - startf;
const f_cnt_t looppos = ( index - endf ) % ( looplen * 2 );
return ( looppos < looplen )
? endf - looppos
: startf + ( looppos - looplen );
}
// A key has been released
void GigInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
auto pluginData = static_cast<GIGPluginData*>(_n->m_pluginData);
QMutexLocker locker( &m_notesMutex );
// Mark the note as being released, but only if it was playing or was just
// pressed (i.e., not if the key was already released)
for (auto& note : m_notes)
{
// Find the note by matching pointers to the plugin data
if (note.handle == pluginData && (note.state == GigState::KeyDown || note.state == GigState::PlayingKeyDown))
{
note.state = GigState::KeyUp;
}
}
// TODO: not sample exact? What about in the middle of us writing out the sample?
delete pluginData;
}
gui::PluginView* GigInstrument::instantiateView( QWidget * _parent )
{
return new gui::GigInstrumentView( this, _parent );
}
// Add the desired samples (either the normal samples or the release samples)
// to the GigNote
//
// Note: not thread safe since libgig stores current region position data in
// the instrument object
void GigInstrument::addSamples( GigNote & gignote, bool wantReleaseSample )
{
// Change key dimension, e.g. change samples based on what key is pressed
// in a certain range. From LinuxSampler
if( wantReleaseSample == true &&
gignote.midiNote >= m_instrument->DimensionKeyRange.low &&
gignote.midiNote <= m_instrument->DimensionKeyRange.high )
{
m_currentKeyDimension = float( gignote.midiNote -
m_instrument->DimensionKeyRange.low ) / (
m_instrument->DimensionKeyRange.high -
m_instrument->DimensionKeyRange.low + 1 );
}
gig::Region* pRegion = m_instrument->GetFirstRegion();
while( pRegion != nullptr )
{
Dimension dim = getDimensions( pRegion, gignote.velocity, wantReleaseSample );
gig::DimensionRegion * pDimRegion = pRegion->GetDimensionRegionByValue( dim.DimValues );
gig::Sample * pSample = pDimRegion->pSample;
// If this is a release sample, the note won't ever be
// released, so we handle it differently
gignote.isRelease = wantReleaseSample;
// Does this note have release samples? Set this only on the original
// notes and not when we get the release samples.
if( wantReleaseSample != true )
{
gignote.release = dim.release;
}
if( pSample != nullptr && pSample->SamplesTotal != 0 )
{
int keyLow = pRegion->KeyRange.low;
int keyHigh = pRegion->KeyRange.high;
if( gignote.midiNote >= keyLow && gignote.midiNote <= keyHigh )
{
float attenuation = pDimRegion->GetVelocityAttenuation( gignote.velocity );
float length = (float) pSample->SamplesTotal / Engine::audioEngine()->outputSampleRate();
// TODO: sample panning? crossfade different layers?
if( wantReleaseSample == true )
{
// From LinuxSampler, not sure how it was created
attenuation *= 1 - 0.01053 * ( 256 >> pDimRegion->ReleaseTriggerDecay ) * length;
}
else
{
attenuation *= pDimRegion->SampleAttenuation;
}
gignote.samples.push_back( GigSample( pSample, pDimRegion,
attenuation, m_interpolation, gignote.frequency ) );
}
}
pRegion = m_instrument->GetNextRegion();
}
}
// Based on our input parameters, generate a "dimension" that specifies which
// note we wish to select from the GIG file with libgig. libgig will use this
// information to select the sample.
Dimension GigInstrument::getDimensions( gig::Region * pRegion, int velocity, bool release )
{
Dimension dim;
if( pRegion == nullptr )
{
return dim;
}
for( int i = pRegion->Dimensions - 1; i >= 0; --i )
{
switch( pRegion->pDimensionDefinitions[i].dimension )
{
case gig::dimension_layer:
// TODO: implement this
dim.DimValues[i] = 0;
break;
case gig::dimension_velocity:
dim.DimValues[i] = velocity;
break;
case gig::dimension_releasetrigger:
dim.release = true;
dim.DimValues[i] = (uint) release;
break;
case gig::dimension_keyboard:
dim.DimValues[i] = (uint) ( m_currentKeyDimension * pRegion->pDimensionDefinitions[i].zones );
break;
case gig::dimension_roundrobin:
case gig::dimension_roundrobinkeyboard:
// TODO: implement this
dim.DimValues[i] = 0;
break;
case gig::dimension_random:
// From LinuxSampler, untested
m_RandomSeed = m_RandomSeed * 1103515245 + 12345;
dim.DimValues[i] = uint(
m_RandomSeed / 4294967296.0f * pRegion->pDimensionDefinitions[i].bits );
break;
case gig::dimension_samplechannel:
case gig::dimension_channelaftertouch:
case gig::dimension_modwheel:
case gig::dimension_breath:
case gig::dimension_foot:
case gig::dimension_portamentotime:
case gig::dimension_effect1:
case gig::dimension_effect2:
case gig::dimension_genpurpose1:
case gig::dimension_genpurpose2:
case gig::dimension_genpurpose3:
case gig::dimension_genpurpose4:
case gig::dimension_sustainpedal:
case gig::dimension_portamento:
case gig::dimension_sostenutopedal:
case gig::dimension_softpedal:
case gig::dimension_genpurpose5:
case gig::dimension_genpurpose6:
case gig::dimension_genpurpose7:
case gig::dimension_genpurpose8:
case gig::dimension_effect1depth:
case gig::dimension_effect2depth:
case gig::dimension_effect3depth:
case gig::dimension_effect4depth:
case gig::dimension_effect5depth:
case gig::dimension_none:
default:
dim.DimValues[i] = 0;
break;
}
}
return dim;
}
// Get the selected instrument from the GIG file we opened if we haven't gotten
// it already. This is based on the bank and patch numbers.
void GigInstrument::getInstrument()
{
// Find instrument
int iBankSelected = m_bankNum.value();
int iProgSelected = m_patchNum.value();
QMutexLocker locker( &m_synthMutex );
if( m_instance != nullptr )
{
gig::Instrument * pInstrument = m_instance->gig.GetFirstInstrument();
while( pInstrument != nullptr )
{
int iBank = pInstrument->MIDIBank;
int iProg = pInstrument->MIDIProgram;
if( iBank == iBankSelected && iProg == iProgSelected )
{
break;
}
pInstrument = m_instance->gig.GetNextInstrument();
}
m_instrument = pInstrument;
}
}
// Since the sample rate changes when we start an export, clear all the
// currently-playing notes when we get this signal. Then, the export won't
// include leftover notes that were playing in the program.
void GigInstrument::updateSampleRate()
{
QMutexLocker locker( &m_notesMutex );
m_notes.clear();
}
namespace gui
{
class gigKnob : public Knob
{
public:
gigKnob( QWidget * _parent ) :
Knob( KnobType::Bright26, _parent )
{
setFixedSize( 31, 38 );
}
} ;
GigInstrumentView::GigInstrumentView( Instrument * _instrument, QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
auto k = castModel<GigInstrument>();
connect( &k->m_bankNum, SIGNAL( dataChanged() ), this, SLOT( updatePatchName() ) );
connect( &k->m_patchNum, SIGNAL( dataChanged() ), this, SLOT( updatePatchName() ) );
// File Button
m_fileDialogButton = new PixmapButton( this );
m_fileDialogButton->setCursor( QCursor( Qt::PointingHandCursor ) );
m_fileDialogButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "fileselect_on" ) );
m_fileDialogButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "fileselect_off" ) );
m_fileDialogButton->move( 223, 68 );
connect( m_fileDialogButton, SIGNAL( clicked() ), this, SLOT( showFileDialog() ) );
m_fileDialogButton->setToolTip(tr("Open GIG file"));
// Patch Button
m_patchDialogButton = new PixmapButton( this );
m_patchDialogButton->setCursor( QCursor( Qt::PointingHandCursor ) );
m_patchDialogButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "patches_on" ) );
m_patchDialogButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "patches_off" ) );
m_patchDialogButton->setEnabled( false );
m_patchDialogButton->move( 223, 94 );
connect( m_patchDialogButton, SIGNAL( clicked() ), this, SLOT( showPatchDialog() ) );
m_patchDialogButton->setToolTip(tr("Choose patch"));
// LCDs
m_bankNumLcd = new LcdSpinBox( 3, "21pink", this );
m_bankNumLcd->move( 111, 150 );
m_patchNumLcd = new LcdSpinBox( 3, "21pink", this );
m_patchNumLcd->move( 161, 150 );
// Next row
m_filenameLabel = new QLabel( this );
m_filenameLabel->setGeometry( 61, 70, 156, 14 );
m_patchLabel = new QLabel( this );
m_patchLabel->setGeometry( 61, 94, 156, 14 );
// Gain
m_gainKnob = new gigKnob( this );
m_gainKnob->setHintText( tr( "Gain:" ) + " ", "" );
m_gainKnob->move( 32, 140 );
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
updateFilename();
}
void GigInstrumentView::modelChanged()
{
auto k = castModel<GigInstrument>();
m_bankNumLcd->setModel( &k->m_bankNum );
m_patchNumLcd->setModel( &k->m_patchNum );
m_gainKnob->setModel( &k->m_gain );
connect( k, SIGNAL( fileChanged() ), this, SLOT( updateFilename() ) );
connect( k, SIGNAL( fileLoading() ), this, SLOT( invalidateFile() ) );
updateFilename();
}
void GigInstrumentView::updateFilename()
{
auto i = castModel<GigInstrument>();
QFontMetrics fm( m_filenameLabel->font() );
QString file = i->m_filename.endsWith( ".gig", Qt::CaseInsensitive ) ?
i->m_filename.left( i->m_filename.length() - 4 ) :
i->m_filename;
m_filenameLabel->setText( fm.elidedText( file, Qt::ElideLeft, m_filenameLabel->width() ) );
m_patchDialogButton->setEnabled( !i->m_filename.isEmpty() );
updatePatchName();
update();
}
void GigInstrumentView::updatePatchName()
{
auto i = castModel<GigInstrument>();
QFontMetrics fm( font() );
QString patch = i->getCurrentPatchName();
m_patchLabel->setText( fm.elidedText( patch, Qt::ElideLeft, m_patchLabel->width() ) );
update();
}
void GigInstrumentView::invalidateFile()
{
m_patchDialogButton->setEnabled( false );
}
void GigInstrumentView::showFileDialog()
{
auto k = castModel<GigInstrument>();
FileDialog ofd( nullptr, tr( "Open GIG file" ) );
ofd.setFileMode( FileDialog::ExistingFiles );
QStringList types;
types << tr( "GIG Files (*.gig)" );
ofd.setNameFilters( types );
if( k->m_filename != "" )
{
QString f = PathUtil::toAbsolute( k->m_filename );
ofd.setDirectory( QFileInfo( f ).absolutePath() );
ofd.selectFile( QFileInfo( f ).fileName() );
}
else
{
ofd.setDirectory( ConfigManager::inst()->gigDir() );
}
m_fileDialogButton->setEnabled( false );
if( ofd.exec() == QDialog::Accepted && !ofd.selectedFiles().isEmpty() )
{
QString f = ofd.selectedFiles()[0];
if( f != "" )
{
k->openFile( f );
Engine::getSong()->setModified();
}
}
m_fileDialogButton->setEnabled( true );
}
void GigInstrumentView::showPatchDialog()
{
auto k = castModel<GigInstrument>();
PatchesDialog pd( this );
pd.setup( k->m_instance, 1, k->instrumentTrack()->name(), &k->m_bankNum, &k->m_patchNum, m_patchLabel );
pd.exec();
}
} // namespace gui
// Store information related to playing a sample from the GIG file
GigSample::GigSample( gig::Sample * pSample, gig::DimensionRegion * pDimRegion,
float attenuation, int interpolation, float desiredFreq )
: sample( pSample ), region( pDimRegion ), attenuation( attenuation ),
pos( 0 ), interpolation( interpolation ), srcState( nullptr ),
sampleFreq( 0 ), freqFactor( 1 )
{
if( sample != nullptr && region != nullptr )
{
// Note: we don't create the libsamplerate object here since we always
// also call the copy constructor when appending to the end of the
// QList. We'll create it only in the copy constructor so we only have
// to create it once.
// Calculate note pitch and frequency factor only if we're actually
// going to be changing the pitch of the notes
if( region->PitchTrack == true )
{
// Calculate what frequency the provided sample is
sampleFreq = 440.0 * powf( 2, 1.0 / 12 * (
1.0 * region->UnityNote - 69 -
0.01 * region->FineTune ) );
freqFactor = sampleFreq / desiredFreq;
}
// The sample rate we pass in is affected by how we are going to be
// resampling the note so that a 1.5 second release ends up being 1.5
// seconds after resampling
adsr = ADSR( region, sample->SamplesPerSecond / freqFactor );
}
}
GigSample::~GigSample()
{
if( srcState != nullptr )
{
src_delete( srcState );
}
}
GigSample::GigSample( const GigSample& g )
: sample( g.sample ), region( g.region ), attenuation( g.attenuation ),
adsr( g.adsr ), pos( g.pos ), interpolation( g.interpolation ),
srcState( nullptr ), sampleFreq( g.sampleFreq ), freqFactor( g.freqFactor )
{
// On the copy, we want to create the object
updateSampleRate();
}
GigSample& GigSample::operator=( const GigSample& g )
{
sample = g.sample;
region= g.region;
attenuation = g.attenuation;
adsr = g.adsr;
pos = g.pos;
interpolation = g.interpolation;
srcState = nullptr;
sampleFreq = g.sampleFreq;
freqFactor = g.freqFactor;
if( g.srcState != nullptr )
{
updateSampleRate();
}
return *this;
}
void GigSample::updateSampleRate()
{
if( srcState != nullptr )
{
src_delete( srcState );
}
int error = 0;
srcState = src_new( interpolation, DEFAULT_CHANNELS, &error );
if( srcState == nullptr || error != 0 )
{
qCritical( "error while creating libsamplerate data structure in GigSample" );
}
}
bool GigSample::convertSampleRate( SampleFrame & oldBuf, SampleFrame & newBuf,
f_cnt_t oldSize, f_cnt_t newSize, float freq_factor, f_cnt_t& used )
{
if( srcState == nullptr )
{
return false;
}
SRC_DATA src_data;
src_data.data_in = &oldBuf[0];
src_data.data_out = &newBuf[0];
src_data.input_frames = oldSize;
src_data.output_frames = newSize;
src_data.src_ratio = freq_factor;
src_data.end_of_input = 0;
// We don't need to lock this assuming that we're only outputting the
// samples in one thread
int error = src_process( srcState, &src_data );
used = src_data.input_frames_used;
if( error != 0 )
{
qCritical( "GigInstrument: error while resampling: %s", src_strerror( error ) );
return false;
}
if( oldSize != 0 && src_data.output_frames_gen == 0 )
{
qCritical( "GigInstrument: could not resample, no frames generated" );
return false;
}
if (src_data.output_frames_gen > 0 && static_cast<f_cnt_t>(src_data.output_frames_gen) < newSize)
{
qCritical() << "GigInstrument: not enough frames, wanted"
<< newSize << "generated" << src_data.output_frames_gen;
return false;
}
return true;
}
ADSR::ADSR()
: preattack( 0 ), attack( 0 ), decay1( 0 ), decay2( 0 ), infiniteSustain( false ),
sustain( 0 ), release( 0 ),
amplitude( 0 ), isAttack( true ), isRelease( false ), isDone( false ),
attackPosition( 0 ), attackLength( 0 ), decayLength( 0 ),
releasePosition( 0 ), releaseLength( 0 )
{
}
// Create the ADSR envelope from the settings in the GIG file
ADSR::ADSR( gig::DimensionRegion * region, int sampleRate )
: preattack( 0 ), attack( 0 ), decay1( 0 ), decay2( 0 ), infiniteSustain( false ),
sustain( 0 ), release( 0 ),
amplitude( 0 ), isAttack( true ), isRelease( false ), isDone( false ),
attackPosition( 0 ), attackLength( 0 ), decayLength( 0 ),
releasePosition( 0 ), releaseLength( 0 )
{
if( region != nullptr )
{
// Parameters from GIG file
preattack = 1.0 * region->EG1PreAttack / 1000; // EG1PreAttack is 0-1000 permille
attack = region->EG1Attack;
decay1 = region->EG1Decay1;
decay2 = region->EG1Decay2;
infiniteSustain = region->EG1InfiniteSustain;
sustain = 1.0 * region->EG1Sustain / 1000; // EG1Sustain is 0-1000 permille
release = region->EG1Release;
// Simple ADSR using positions in sample
amplitude = preattack;
attackLength = attack * sampleRate;
decayLength = decay1 * sampleRate; // TODO: ignoring decay2 for now
releaseLength = release * sampleRate;
// If there is no attack or decay, start at the sustain amplitude
if( attackLength == 0 && decayLength == 0 )
{
amplitude = sustain;
}
// If there is no attack, start at the full amplitude
else if( attackLength == 0 )
{
amplitude = 1.0;
}
}
}
// Next time we get the amplitude, we'll be releasing the note
void ADSR::keyup()
{
isRelease = true;
}
// Can we delete the sample now?
bool ADSR::done()
{
return isDone;
}
// Return the current amplitude and increment internal positions
float ADSR::value()
{
float currentAmplitude = amplitude;
// If we're done, don't output any signal
if( isDone == true )
{
return 0;
}
// If we're still in the attack phase, release from the current volume
// instead of jumping to the sustain volume and fading out
else if( isAttack == true && isRelease == true )
{
sustain = amplitude;
isAttack = false;
}
// If we're in the attack phase, start at the preattack amplitude and
// increase to the full before decreasing to sustain
if( isAttack == true )
{
if( attackPosition < attackLength )
{
amplitude = preattack + ( 1.0 - preattack ) / attackLength * attackPosition;
}
else if( attackPosition < attackLength + decayLength )
{
amplitude = 1.0 - ( 1.0 - sustain ) / decayLength * ( attackPosition - attackLength );
}
else
{
isAttack = false;
}
++attackPosition;
}
// If we're in the sustain phase, decrease from sustain to zero
else if( isRelease == true )
{
// Maybe not the best way of doing this, but it appears to be about right
// Satisfies f(0) = sustain and f(releaseLength) = very small
amplitude = ( sustain + 1e-3 ) * expf( -5.0 / releaseLength * releasePosition ) - 1e-3;
// Don't have an infinite exponential decay
if( amplitude <= 0 || releasePosition >= releaseLength )
{
amplitude = 0;
isDone = true;
}
++releasePosition;
}
return currentAmplitude;
}
// Increment internal positions a certain number of times
void ADSR::inc( f_cnt_t num )
{
for( f_cnt_t i = 0; i < num; ++i )
{
value();
}
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return new GigInstrument( static_cast<InstrumentTrack *>( m ) );
}
}
} // namespace lmms
| 34,172
|
C++
|
.cpp
| 1,058
| 29.300567
| 116
| 0.69724
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,697
|
PatchesDialog.cpp
|
LMMS_lmms/plugins/GigPlayer/PatchesDialog.cpp
|
/*
* PatchesDialog.cpp - display GIG patches (based on Sf2 patches_dialog.cpp)
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "PatchesDialog.h"
#include <QHeaderView>
namespace lmms::gui
{
// Custom list-view item (as for numerical sort purposes...)
class PatchItem : public QTreeWidgetItem
{
public:
// Constructor.
PatchItem( QTreeWidget *pListView,
QTreeWidgetItem *pItemAfter )
: QTreeWidgetItem( pListView, pItemAfter ) {}
// Sort/compare overriden method.
bool operator< ( const QTreeWidgetItem& other ) const override
{
int iColumn = QTreeWidgetItem::treeWidget()->sortColumn();
const QString& s1 = text( iColumn );
const QString& s2 = other.text( iColumn );
if( iColumn == 0 || iColumn == 2 )
{
return s1.toInt() < s2.toInt();
}
else
{
return s1 < s2;
}
}
};
// Constructor.
PatchesDialog::PatchesDialog( QWidget * pParent, Qt::WindowFlags wflags )
: QDialog( pParent, wflags )
{
// Setup UI struct...
setupUi( this );
m_pSynth = nullptr;
m_iChan = 0;
m_iBank = 0;
m_iProg = 0;
// Soundfonts list view...
QHeaderView * pHeader = m_progListView->header();
pHeader->setDefaultAlignment( Qt::AlignLeft );
pHeader->setSectionsMovable( false );
pHeader->setStretchLastSection( true );
m_progListView->resizeColumnToContents( 0 ); // Prog.
// Initial sort order...
m_bankListView->sortItems( 0, Qt::AscendingOrder );
m_progListView->sortItems( 0, Qt::AscendingOrder );
// UI connections...
QObject::connect( m_bankListView,
SIGNAL( currentItemChanged( QTreeWidgetItem *,QTreeWidgetItem * ) ),
SLOT( bankChanged() ) );
QObject::connect( m_progListView,
SIGNAL( currentItemChanged( QTreeWidgetItem *, QTreeWidgetItem * ) ),
SLOT( progChanged( QTreeWidgetItem *, QTreeWidgetItem * ) ) );
QObject::connect( m_progListView,
SIGNAL( itemActivated( QTreeWidgetItem *, int ) ),
SLOT( accept() ) );
QObject::connect( m_okButton,
SIGNAL( clicked() ),
SLOT( accept() ) );
QObject::connect( m_cancelButton,
SIGNAL( clicked() ),
SLOT( reject() ) );
}
// Dialog setup loader.
void PatchesDialog::setup( GigInstance * pSynth, int iChan,
const QString & chanName,
LcdSpinBoxModel * bankModel,
LcdSpinBoxModel * progModel,
QLabel * patchLabel )
{
// We'll going to changes the whole thing...
m_dirty = 0;
m_bankModel = bankModel;
m_progModel = progModel;
m_patchLabel = patchLabel;
// Set the proper caption...
setWindowTitle( chanName + " - GIG patches" );
// set m_pSynth to NULL so we don't trigger any progChanged events
m_pSynth = nullptr;
// Load bank list from actual synth stack...
m_bankListView->setSortingEnabled( false );
m_bankListView->clear();
// now it should be safe to set internal stuff
m_pSynth = pSynth;
m_iChan = iChan;
//fluid_preset_t preset;
QTreeWidgetItem * pBankItem = nullptr;
// Currently just use zero as the only bank
int iBankDefault = -1;
int iProgDefault = -1;
gig::Instrument * pInstrument = m_pSynth->gig.GetFirstInstrument();
while( pInstrument )
{
int iBank = pInstrument->MIDIBank;
int iProg = pInstrument->MIDIProgram;
if ( !findBankItem( iBank ) )
{
pBankItem = new PatchItem( m_bankListView, pBankItem );
if( pBankItem )
{
pBankItem->setText( 0, QString::number( iBank ) );
if( iBankDefault == -1 )
{
iBankDefault = iBank;
iProgDefault = iProg;
}
}
}
pInstrument = m_pSynth->gig.GetNextInstrument();
}
m_bankListView->setSortingEnabled( true );
// Set the selected bank.
if( iBankDefault != -1 )
{
m_iBank = iBankDefault;
}
pBankItem = findBankItem( m_iBank );
m_bankListView->setCurrentItem( pBankItem );
m_bankListView->scrollToItem( pBankItem );
bankChanged();
// Set the selected program.
if( iProgDefault != -1 )
{
m_iProg = iProgDefault;
}
QTreeWidgetItem * pProgItem = findProgItem( m_iProg );
m_progListView->setCurrentItem( pProgItem );
m_progListView->scrollToItem( pProgItem );
}
// Stabilize current state form.
void PatchesDialog::stabilizeForm()
{
m_okButton->setEnabled( validateForm() );
}
// Validate form fields.
bool PatchesDialog::validateForm()
{
bool bValid = true;
bValid = bValid && ( m_bankListView->currentItem() != nullptr );
bValid = bValid && ( m_progListView->currentItem() != nullptr );
return bValid;
}
// Realize a bank-program selection preset.
void PatchesDialog::setBankProg( int iBank, int iProg )
{
if( m_pSynth == nullptr )
{
return;
}
}
// Validate form fields and accept it valid.
void PatchesDialog::accept()
{
if( validateForm() )
{
// Unload from current selected dialog items.
int iBank = ( m_bankListView->currentItem() )->text( 0 ).toInt();
int iProg = ( m_progListView->currentItem() )->text( 0 ).toInt();
// And set it right away...
setBankProg( iBank, iProg );
if( m_dirty > 0 )
{
m_bankModel->setValue( iBank );
m_progModel->setValue( iProg );
m_patchLabel->setText( m_progListView->
currentItem()->text( 1 ) );
}
// We got it.
QDialog::accept();
}
}
// Reject settings (Cancel button slot).
void PatchesDialog::reject()
{
// Reset selection to initial selection, if applicable...
if( m_dirty > 0 )
{
setBankProg( m_bankModel->value(), m_progModel->value() );
}
// Done (hopefully nothing).
QDialog::reject();
}
// Find the bank item of given bank number id.
QTreeWidgetItem * PatchesDialog::findBankItem( int iBank )
{
QList<QTreeWidgetItem *> banks
= m_bankListView->findItems(
QString::number( iBank ), Qt::MatchExactly, 0 );
QListIterator<QTreeWidgetItem *> iter( banks );
if( iter.hasNext() )
{
return iter.next();
}
else
{
return nullptr;
}
}
// Find the program item of given program number id.
QTreeWidgetItem *PatchesDialog::findProgItem( int iProg )
{
QList<QTreeWidgetItem *> progs
= m_progListView->findItems(
QString::number( iProg ), Qt::MatchExactly, 0 );
QListIterator<QTreeWidgetItem *> iter( progs );
if( iter.hasNext() )
{
return iter.next();
}
else
{
return nullptr;
}
}
// Bank change slot.
void PatchesDialog::bankChanged()
{
if( m_pSynth == nullptr )
{
return;
}
QTreeWidgetItem * pBankItem = m_bankListView->currentItem();
if( pBankItem == nullptr )
{
return;
}
int iBankSelected = pBankItem->text( 0 ).toInt();
// Clear up the program listview.
m_progListView->setSortingEnabled( false );
m_progListView->clear();
QTreeWidgetItem * pProgItem = nullptr;
gig::Instrument * pInstrument = m_pSynth->gig.GetFirstInstrument();
while( pInstrument )
{
QString name = QString::fromStdString( pInstrument->pInfo->Name );
if( name == "" )
{
name = "<no name>";
}
int iBank = pInstrument->MIDIBank;
int iProg = pInstrument->MIDIProgram;
if( iBank == iBankSelected && !findProgItem( iProg ) )
{
pProgItem = new PatchItem( m_progListView, pProgItem );
if( pProgItem )
{
pProgItem->setText( 0, QString::number( iProg ) );
pProgItem->setText( 1, name );
}
}
pInstrument = m_pSynth->gig.GetNextInstrument();
}
m_progListView->setSortingEnabled( true );
// Stabilize the form.
stabilizeForm();
}
// Program change slot.
void PatchesDialog::progChanged( QTreeWidgetItem * curr, QTreeWidgetItem * prev )
{
if( m_pSynth == nullptr || curr == nullptr )
{
return;
}
// Which preview state...
if( validateForm() )
{
// Set current selection.
int iBank = ( m_bankListView->currentItem() )->text( 0 ).toInt();
int iProg = curr->text( 0 ).toInt();
// And set it right away...
setBankProg( iBank, iProg );
// Now we're dirty nuff.
m_dirty++;
}
// Stabilize the form.
stabilizeForm();
}
} // namespace lmms::gui
| 8,495
|
C++
|
.cpp
| 302
| 25.463576
| 81
| 0.707061
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,698
|
Vestige.cpp
|
LMMS_lmms/plugins/Vestige/Vestige.cpp
|
/*
* Vestige.cpp - instrument-plugin for hosting VST-instruments
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QtGlobal>
#include "VstPlugin.h"
#include "Vestige.h"
#include <memory>
#include <QDropEvent>
#include <QGridLayout>
#include <QPainter>
#include <QPushButton>
#include <QScrollArea>
#include <QMdiArea>
#include <QMenu>
#include <QDomElement>
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "CustomTextKnob.h"
#include "Engine.h"
#include "FileDialog.h"
#include "GuiApplication.h"
#include "FontHelper.h"
#include "InstrumentPlayHandle.h"
#include "InstrumentTrack.h"
#include "LocaleHelper.h"
#include "MainWindow.h"
#include "PathUtil.h"
#include "PixmapButton.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "SubWindow.h"
#include "TextFloat.h"
#include "Clipboard.h"
#include "embed.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor Q_DECL_EXPORT vestige_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"VeSTige",
QT_TRANSLATE_NOOP( "PluginBrowser",
"VST-host for using VST(i)-plugins within LMMS" ),
"Tobias Doerffel <tobydox/at/users.sf.net>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
#ifdef LMMS_BUILD_LINUX
"dll,so",
#else
"dll",
#endif
nullptr,
} ;
}
namespace gui
{
class vstSubWin : public SubWindow
{
public:
vstSubWin( QWidget * _parent ) :
SubWindow( _parent )
{
setAttribute( Qt::WA_DeleteOnClose, false );
setWindowFlags( Qt::WindowCloseButtonHint );
}
~vstSubWin() override = default;
void closeEvent( QCloseEvent * e ) override
{
// ignore close-events - for some reason otherwise the VST GUI
// remains hidden when re-opening
hide();
e->ignore();
}
};
} // namespace gui
class VstInstrumentPlugin : public VstPlugin
{
public:
using VstPlugin::VstPlugin;
void createUI( QWidget *parent ) override
{
Q_UNUSED(parent);
if ( !hasEditor() ) {
return;
}
if ( embedMethod() != "none" ) {
m_pluginSubWindow.reset(new gui::vstSubWin( gui::getGUI()->mainWindow()->workspace() ));
VstPlugin::createUI( m_pluginSubWindow.get() );
m_pluginSubWindow->setWidget(pluginWidget());
} else {
VstPlugin::createUI( nullptr );
}
}
/// Overwrite editor() to return the sub window instead of the embed widget
/// itself. This makes toggleUI() and related functions toggle the
/// sub window's visibility.
QWidget* editor() override
{
return m_pluginSubWindow.get();
}
private:
std::unique_ptr<QMdiSubWindow> m_pluginSubWindow;
};
VestigeInstrument::VestigeInstrument( InstrumentTrack * _instrument_track ) :
Instrument(_instrument_track, &vestige_plugin_descriptor, nullptr, Flag::IsSingleStreamed | Flag::IsMidiBased),
m_plugin( nullptr ),
m_pluginMutex(),
m_subWindow( nullptr ),
m_scrollArea( nullptr ),
knobFModel( nullptr ),
p_subWindow( nullptr )
{
// now we need a play-handle which cares for calling play()
auto iph = new InstrumentPlayHandle(this, _instrument_track);
Engine::audioEngine()->addPlayHandle( iph );
connect( ConfigManager::inst(), SIGNAL( valueChanged(QString,QString,QString) ),
this, SLOT( handleConfigChange(QString, QString, QString) ),
Qt::QueuedConnection );
}
VestigeInstrument::~VestigeInstrument()
{
if (p_subWindow != nullptr) {
delete p_subWindow;
p_subWindow = nullptr;
}
if (knobFModel != nullptr) {
delete []knobFModel;
knobFModel = nullptr;
}
Engine::audioEngine()->removePlayHandlesOfTypes( instrumentTrack(),
PlayHandle::Type::NotePlayHandle
| PlayHandle::Type::InstrumentPlayHandle );
closePlugin();
}
void VestigeInstrument::loadSettings( const QDomElement & _this )
{
QString plugin = _this.attribute( "plugin" );
if( plugin.isEmpty() )
{
return;
}
loadFile( plugin );
m_pluginMutex.lock();
if( m_plugin != nullptr )
{
m_plugin->loadSettings( _this );
if (instrumentTrack() != nullptr && instrumentTrack()->isPreviewMode())
{
m_plugin->hideUI();
}
else if (_this.attribute( "guivisible" ).toInt())
{
m_plugin->showUI();
} else
{
m_plugin->hideUI();
}
const QMap<QString, QString> & dump = m_plugin->parameterDump();
paramCount = dump.size();
auto paramStr = std::array<char, 35>{};
knobFModel = new FloatModel *[ paramCount ];
QStringList s_dumpValues;
for( int i = 0; i < paramCount; i++ )
{
std::snprintf(paramStr.data(), paramStr.size(), "param%d", i);
s_dumpValues = dump[paramStr.data()].split(":");
knobFModel[i] = new FloatModel( 0.0f, 0.0f, 1.0f, 0.01f, this, QString::number(i) );
knobFModel[i]->loadSettings(_this, paramStr.data());
if( !( knobFModel[ i ]->isAutomated() || knobFModel[ i ]->controllerConnection() ) )
{
knobFModel[ i ]->setValue(LocaleHelper::toFloat(s_dumpValues.at(2)));
knobFModel[ i ]->setInitValue(LocaleHelper::toFloat(s_dumpValues.at(2)));
}
connect( knobFModel[i], &FloatModel::dataChanged, this,
[this, i]() { setParameter( knobFModel[i] ); }, Qt::DirectConnection);
}
}
m_pluginMutex.unlock();
}
void VestigeInstrument::setParameter( Model * action )
{
int knobUNID = action->displayName().toInt();
if ( m_plugin != nullptr ) {
m_plugin->setParam( knobUNID, knobFModel[knobUNID]->value() );
}
}
void VestigeInstrument::handleConfigChange(QString cls, QString attr, QString value)
{
Q_UNUSED(cls); Q_UNUSED(attr); Q_UNUSED(value);
// Disabled for consistency with VST effects that don't implement this. (#3786)
// if ( cls == "ui" && attr == "vstembedmethod" )
// {
// reloadPlugin();
// }
}
void VestigeInstrument::reloadPlugin()
{
closePlugin();
loadFile( m_pluginDLL );
}
void VestigeInstrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
_this.setAttribute( "plugin", PathUtil::toShortestRelative(m_pluginDLL) );
m_pluginMutex.lock();
if( m_plugin != nullptr )
{
m_plugin->saveSettings( _doc, _this );
if (knobFModel != nullptr) {
const QMap<QString, QString> & dump = m_plugin->parameterDump();
paramCount = dump.size();
auto paramStr = std::array<char, 35>{};
for( int i = 0; i < paramCount; i++ )
{
if (knobFModel[i]->isAutomated() || knobFModel[i]->controllerConnection()) {
std::snprintf(paramStr.data(), paramStr.size(), "param%d", i);
knobFModel[i]->saveSettings(_doc, _this, paramStr.data());
}
/* QDomElement me = _doc.createElement( paramStr );
me.setAttribute( "id", knobFModel[i]->id() );
me.setAttribute( "value", knobFModel[i]->value() );
_this.appendChild( me );
ControllerConnection * m_controllerConnection = knobFModel[i]->controllerConnection();
if (m_controllerConnection) {
QDomElement controller_element;
QDomNode node = _this.namedItem( "connection" );
if( node.isElement() )
{
controller_element = node.toElement();
}
else
{
controller_element = _doc.createElement( "connection" );
_this.appendChild( controller_element );
}
QDomElement element = _doc.createElement( paramStr );
m_controllerConnection->saveSettings( _doc, element );
controller_element.appendChild( element );
}*/
}
}
}
m_pluginMutex.unlock();
}
QString VestigeInstrument::nodeName( void ) const
{
return( vestige_plugin_descriptor.name );
}
void VestigeInstrument::loadFile( const QString & _file )
{
m_pluginMutex.lock();
const bool set_ch_name = ( m_plugin != nullptr &&
instrumentTrack()->name() == m_plugin->name() ) ||
instrumentTrack()->name() == InstrumentTrack::tr( "Default preset" ) ||
instrumentTrack()->name() == displayName();
m_pluginMutex.unlock();
// if the same is loaded don't load again (for preview)
if (instrumentTrack() != nullptr && instrumentTrack()->isPreviewMode() &&
m_pluginDLL == PathUtil::toShortestRelative( _file ))
return;
if ( m_plugin != nullptr )
{
closePlugin();
}
m_pluginDLL = PathUtil::toShortestRelative( _file );
gui::TextFloat * tf = nullptr;
if( gui::getGUI() != nullptr )
{
tf = gui::TextFloat::displayMessage(
tr( "Loading plugin" ),
tr( "Please wait while loading the VST plugin..." ),
PLUGIN_NAME::getIconPixmap( "logo", 24, 24 ), 0 );
}
m_pluginMutex.lock();
m_plugin = new VstInstrumentPlugin( m_pluginDLL );
if( m_plugin->failed() )
{
m_pluginMutex.unlock();
closePlugin();
delete tf;
collectErrorForUI( VstPlugin::tr( "The VST plugin %1 could not be loaded." ).arg( m_pluginDLL ) );
m_pluginDLL = "";
return;
}
if ( !(instrumentTrack() != nullptr && instrumentTrack()->isPreviewMode()))
{
m_plugin->createUI(nullptr);
m_plugin->showUI();
}
if( set_ch_name )
{
instrumentTrack()->setName( m_plugin->name() );
}
m_pluginMutex.unlock();
emit dataChanged();
delete tf;
}
void VestigeInstrument::play( SampleFrame* _buf )
{
if (!m_pluginMutex.tryLock(Engine::getSong()->isExporting() ? -1 : 0)) {return;}
if( m_plugin == nullptr )
{
m_pluginMutex.unlock();
return;
}
m_plugin->process( nullptr, _buf );
m_pluginMutex.unlock();
}
bool VestigeInstrument::handleMidiEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset )
{
m_pluginMutex.lock();
if( m_plugin != nullptr )
{
m_plugin->processMidiEvent( event, offset );
}
m_pluginMutex.unlock();
return true;
}
void VestigeInstrument::closePlugin( void )
{
// disconnect all signals
if( knobFModel != nullptr )
{
for( int i = 0; i < paramCount; i++ )
{
delete knobFModel[ i ];
}
}
if( knobFModel != nullptr )
{
delete [] knobFModel;
knobFModel = nullptr;
}
if( m_scrollArea != nullptr )
{
// delete m_scrollArea;
m_scrollArea = nullptr;
}
if( m_subWindow != nullptr )
{
m_subWindow->setAttribute( Qt::WA_DeleteOnClose );
m_subWindow->close();
if( m_subWindow != nullptr )
{
delete m_subWindow;
}
m_subWindow = nullptr;
}
if( p_subWindow != nullptr )
{
p_subWindow = nullptr;
}
m_pluginMutex.lock();
delete m_plugin;
m_plugin = nullptr;
m_pluginMutex.unlock();
}
gui::PluginView * VestigeInstrument::instantiateView( QWidget * _parent )
{
return new gui::VestigeInstrumentView( this, _parent );
}
namespace gui
{
VestigeInstrumentView::VestigeInstrumentView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent ),
lastPosInMenu (0)
{
m_openPluginButton = new PixmapButton( this, "" );
m_openPluginButton->setCheckable( false );
m_openPluginButton->setCursor( Qt::PointingHandCursor );
m_openPluginButton->move( 216, 81 );
m_openPluginButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"select_file_active" ) );
m_openPluginButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"select_file" ) );
connect( m_openPluginButton, SIGNAL( clicked() ), this,
SLOT( openPlugin() ) );
m_openPluginButton->setToolTip(tr("Open VST plugin"));
m_managePluginButton = new PixmapButton( this, "" );
m_managePluginButton->setCheckable( false );
m_managePluginButton->setCursor( Qt::PointingHandCursor );
m_managePluginButton->move( 216, 101 );
m_managePluginButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"controls_active" ) );
m_managePluginButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"controls" ) );
connect( m_managePluginButton, SIGNAL( clicked() ), this,
SLOT( managePlugin() ) );
m_managePluginButton->setToolTip(tr("Control VST plugin from LMMS host"));
m_openPresetButton = new PixmapButton( this, "" );
m_openPresetButton->setCheckable( false );
m_openPresetButton->setCursor( Qt::PointingHandCursor );
m_openPresetButton->move( 200, 224 );
m_openPresetButton->setActiveGraphic( embed::getIconPixmap(
"project_open", 20, 20 ) );
m_openPresetButton->setInactiveGraphic( embed::getIconPixmap(
"project_open", 20, 20 ) );
connect( m_openPresetButton, SIGNAL( clicked() ), this,
SLOT( openPreset() ) );
m_openPresetButton->setToolTip(tr("Open VST plugin preset"));
m_rolLPresetButton = new PixmapButton( this, "" );
m_rolLPresetButton->setCheckable( false );
m_rolLPresetButton->setCursor( Qt::PointingHandCursor );
m_rolLPresetButton->move( 190, 201 );
m_rolLPresetButton->setActiveGraphic( embed::getIconPixmap(
"stepper-left-press" ) );
m_rolLPresetButton->setInactiveGraphic( embed::getIconPixmap(
"stepper-left" ) );
connect( m_rolLPresetButton, SIGNAL( clicked() ), this,
SLOT( previousProgram() ) );
m_rolLPresetButton->setToolTip(tr("Previous (-)"));
m_rolLPresetButton->setShortcut( Qt::Key_Minus );
m_savePresetButton = new PixmapButton( this, "" );
m_savePresetButton->setCheckable( false );
m_savePresetButton->setCursor( Qt::PointingHandCursor );
m_savePresetButton->move( 224, 224 );
m_savePresetButton->setActiveGraphic( embed::getIconPixmap(
"project_save", 20, 20 ) );
m_savePresetButton->setInactiveGraphic( embed::getIconPixmap(
"project_save", 20, 20 ) );
connect( m_savePresetButton, SIGNAL( clicked() ), this,
SLOT( savePreset() ) );
m_savePresetButton->setToolTip(tr("Save preset"));
m_rolRPresetButton = new PixmapButton( this, "" );
m_rolRPresetButton->setCheckable( false );
m_rolRPresetButton->setCursor( Qt::PointingHandCursor );
m_rolRPresetButton->move( 209, 201 );
m_rolRPresetButton->setActiveGraphic( embed::getIconPixmap(
"stepper-right-press" ) );
m_rolRPresetButton->setInactiveGraphic( embed::getIconPixmap(
"stepper-right" ) );
connect( m_rolRPresetButton, SIGNAL( clicked() ), this,
SLOT( nextProgram() ) );
m_rolRPresetButton->setToolTip(tr("Next (+)"));
m_rolRPresetButton->setShortcut( Qt::Key_Plus );
m_selPresetButton = new QPushButton( tr( "" ), this );
m_selPresetButton->setGeometry( 228, 201, 16, 16 );
auto menu = new QMenu;
connect( menu, SIGNAL( aboutToShow() ), this, SLOT( updateMenu() ) );
m_selPresetButton->setIcon( embed::getIconPixmap( "stepper-down" ) );
m_selPresetButton->setMenu(menu);
m_toggleGUIButton = new QPushButton( tr( "Show/hide GUI" ), this );
m_toggleGUIButton->setGeometry( 20, 130, 200, 24 );
m_toggleGUIButton->setIcon( embed::getIconPixmap( "zoom" ) );
m_toggleGUIButton->setFont(adjustedToPixelSize(m_toggleGUIButton->font(), LARGE_FONT_SIZE));
connect( m_toggleGUIButton, SIGNAL( clicked() ), this,
SLOT( toggleGUI() ) );
auto note_off_all_btn = new QPushButton(tr("Turn off all "
"notes"),
this);
note_off_all_btn->setGeometry( 20, 160, 200, 24 );
note_off_all_btn->setIcon( embed::getIconPixmap( "stop" ) );
note_off_all_btn->setFont(adjustedToPixelSize(note_off_all_btn->font(), LARGE_FONT_SIZE));
connect( note_off_all_btn, SIGNAL( clicked() ), this,
SLOT( noteOffAll() ) );
setAcceptDrops( true );
_instrument2 = _instrument;
_parent2 = _parent;
}
void VestigeInstrumentView::managePlugin( void )
{
if ( m_vi->m_plugin != nullptr && m_vi->m_subWindow == nullptr ) {
m_vi->p_subWindow = new ManageVestigeInstrumentView( _instrument2, _parent2, m_vi);
} else if (m_vi->m_subWindow != nullptr) {
if (m_vi->m_subWindow->widget()->isVisible() == false ) {
m_vi->m_scrollArea->show();
m_vi->m_subWindow->show();
} else {
m_vi->m_scrollArea->hide();
m_vi->m_subWindow->hide();
}
}
}
void VestigeInstrumentView::updateMenu( void )
{
// get all presets -
if ( m_vi->m_plugin != nullptr )
{
m_vi->m_plugin->loadProgramNames();
QWidget::update();
QString str = m_vi->m_plugin->allProgramNames();
QStringList list1 = str.split("|");
QMenu * to_menu = m_selPresetButton->menu();
to_menu->clear();
QVector<QAction*> presetActions(list1.size());
for (int i = 0; i < list1.size(); i++) {
presetActions[i] = new QAction(this);
connect(presetActions[i], SIGNAL(triggered()), this, SLOT(selPreset()));
presetActions[i]->setText(QString("%1. %2").arg(QString::number(i+1), list1.at(i)));
presetActions[i]->setData(i);
if (i == lastPosInMenu) {
presetActions[i]->setIcon(embed::getIconPixmap( "sample_file", 16, 16 ));
} else presetActions[i]->setIcon(embed::getIconPixmap( "edit_copy", 16, 16 ));
to_menu->addAction( presetActions[i] );
}
}
}
void VestigeInstrumentView::modelChanged()
{
m_vi = castModel<VestigeInstrument>();
}
void VestigeInstrumentView::openPlugin()
{
FileDialog ofd( nullptr, tr( "Open VST plugin" ) );
// set filters
QStringList types;
types << tr( "DLL-files (*.dll)" )
<< tr( "EXE-files (*.exe)" )
#ifdef LMMS_BUILD_LINUX
<< tr( "SO-files (*.so)" )
#endif
;
ofd.setNameFilters( types );
if( m_vi->m_pluginDLL != "" )
{
QString f = PathUtil::toAbsolute( m_vi->m_pluginDLL );
ofd.setDirectory( QFileInfo( f ).absolutePath() );
ofd.selectFile( QFileInfo( f ).fileName() );
}
else
{
ofd.setDirectory( ConfigManager::inst()->vstDir() );
}
if ( ofd.exec () == QDialog::Accepted )
{
if( ofd.selectedFiles().isEmpty() )
{
return;
}
Engine::audioEngine()->requestChangeInModel();
if (m_vi->p_subWindow != nullptr) {
delete m_vi->p_subWindow;
m_vi->p_subWindow = nullptr;
}
m_vi->loadFile( ofd.selectedFiles()[0] );
Engine::audioEngine()->doneChangeInModel();
if( m_vi->m_plugin && m_vi->m_plugin->pluginWidget() )
{
m_vi->m_plugin->pluginWidget()->setWindowIcon(
PLUGIN_NAME::getIconPixmap( "logo" ) );
}
}
}
void VestigeInstrumentView::openPreset()
{
if ( m_vi->m_plugin != nullptr ) {
m_vi->m_plugin->openPreset();
bool converted;
QString str = m_vi->m_plugin->currentProgramName().section("/", 0, 0);
if (str != "")
lastPosInMenu = str.toInt(&converted, 10) - 1;
QWidget::update();
}
}
void VestigeInstrumentView::savePreset()
{
if ( m_vi->m_plugin != nullptr )
{
m_vi->m_plugin->savePreset();
/* bool converted;
QString str = m_vi->m_plugin->presetString().section("/", 0, 0);
if (str != "")
lastPosInMenu = str.toInt(&converted, 10) - 1;
QWidget::update();*/
}
}
void VestigeInstrumentView::nextProgram()
{
if ( m_vi->m_plugin != nullptr ) {
m_vi->m_plugin->rotateProgram( 1 );
bool converted;
QString str = m_vi->m_plugin->currentProgramName().section("/", 0, 0);
if (str != "")
lastPosInMenu = str.toInt(&converted, 10) - 1;
QWidget::update();
}
}
void VestigeInstrumentView::previousProgram()
{
if ( m_vi->m_plugin != nullptr ) {
m_vi->m_plugin->rotateProgram( -1 );
bool converted;
QString str = m_vi->m_plugin->currentProgramName().section("/", 0, 0);
if (str != "")
lastPosInMenu = str.toInt(&converted, 10) - 1;
QWidget::update();
}
}
void VestigeInstrumentView::selPreset( void )
{
auto action = qobject_cast<QAction*>(sender());
if (action && m_vi->m_plugin != nullptr)
{
lastPosInMenu = action->data().toInt();
m_vi->m_plugin->setProgram(action->data().toInt());
QWidget::update();
}
}
void VestigeInstrumentView::toggleGUI( void )
{
if( m_vi == nullptr || m_vi->m_plugin == nullptr )
{
return;
}
m_vi->m_plugin->toggleUI();
}
void VestigeInstrumentView::noteOffAll( void )
{
m_vi->m_pluginMutex.lock();
if( m_vi->m_plugin != nullptr )
{
for( int key = 0; key <= MidiMaxKey; ++key )
{
m_vi->m_plugin->processMidiEvent( MidiEvent( MidiNoteOff, 0, key, 0 ), 0 );
}
}
m_vi->m_pluginMutex.unlock();
}
void VestigeInstrumentView::dragEnterEvent( QDragEnterEvent * _dee )
{
// For mimeType() and MimeType enum class
using namespace Clipboard;
if( _dee->mimeData()->hasFormat( mimeType( MimeType::StringPair ) ) )
{
QString txt = _dee->mimeData()->data(
mimeType( MimeType::StringPair ) );
if( txt.section( ':', 0, 0 ) == "vstplugin" )
{
_dee->acceptProposedAction();
}
else
{
_dee->ignore();
}
}
else
{
_dee->ignore();
}
}
void VestigeInstrumentView::dropEvent( QDropEvent * _de )
{
QString type = StringPairDrag::decodeKey( _de );
QString value = StringPairDrag::decodeValue( _de );
if( type == "vstplugin" )
{
m_vi->loadFile( value );
_de->accept();
return;
}
_de->ignore();
}
void VestigeInstrumentView::paintEvent( QPaintEvent * )
{
QPainter p( this );
static auto s_artwork = PLUGIN_NAME::getIconPixmap("artwork");
p.drawPixmap(0, 0, s_artwork);
QString plugin_name = ( m_vi->m_plugin != nullptr ) ?
m_vi->m_plugin->name()/* + QString::number(
m_plugin->version() )*/
:
tr( "No VST plugin loaded" );
QFont f = p.font();
f.setBold( true );
p.setFont(adjustedToPixelSize(f, DEFAULT_FONT_SIZE));
p.setPen( QColor( 255, 255, 255 ) );
p.drawText( 10, 100, plugin_name );
p.setPen( QColor( 50, 50, 50 ) );
p.drawText( 10, 211, tr( "Preset" ) );
// m_pluginMutex.lock();
if( m_vi->m_plugin != nullptr )
{
p.setPen( QColor( 0, 0, 0 ) );
f.setBold( false );
p.setFont(adjustedToPixelSize(f, SMALL_FONT_SIZE));
p.drawText( 10, 114, tr( "by " ) +
m_vi->m_plugin->vendorString() );
p.setPen( QColor( 255, 255, 255 ) );
p.drawText( 10, 225, m_vi->m_plugin->currentProgramName() );
}
if( m_vi->m_subWindow != nullptr )
{
m_vi->m_subWindow->setWindowTitle( m_vi->instrumentTrack()->name()
+ tr( " - VST plugin control" ) );
}
// m_pluginMutex.unlock();
}
ManageVestigeInstrumentView::ManageVestigeInstrumentView( Instrument * _instrument,
QWidget * _parent, VestigeInstrument * m_vi2 ) :
InstrumentViewFixedSize( _instrument, _parent )
{
#if QT_VERSION < 0x50C00
// Workaround for a bug in Qt versions below 5.12,
// where argument-dependent-lookup fails for QFlags operators
// declared inside a namepsace.
// This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h
// See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348
using ::operator|;
#endif
m_vi = m_vi2;
m_vi->m_scrollArea = new QScrollArea( this );
widget = new QWidget(this);
l = new QGridLayout( this );
m_vi->m_subWindow = getGUI()->mainWindow()->addWindowedWidget(nullptr, Qt::SubWindow |
Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint);
m_vi->m_subWindow->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::MinimumExpanding );
m_vi->m_subWindow->setFixedWidth( 960 );
m_vi->m_subWindow->setMinimumHeight( 300 );
m_vi->m_subWindow->setWidget(m_vi->m_scrollArea);
m_vi->m_subWindow->setWindowTitle( m_vi->instrumentTrack()->name()
+ tr( " - VST plugin control" ) );
m_vi->m_subWindow->setWindowIcon( PLUGIN_NAME::getIconPixmap( "logo" ) );
m_vi->m_subWindow->setAttribute( Qt::WA_DeleteOnClose, false );
l->setContentsMargins( 20, 10, 10, 10 );
l->setVerticalSpacing( 10 );
l->setHorizontalSpacing( 23 );
m_syncButton = new QPushButton( tr( "VST Sync" ), this );
connect( m_syncButton, SIGNAL( clicked() ), this,
SLOT( syncPlugin() ) );
l->addWidget( m_syncButton, 0, 0, 1, 2, Qt::AlignLeft );
m_displayAutomatedOnly = new QPushButton( tr( "Automated" ), this );
connect( m_displayAutomatedOnly, SIGNAL( clicked() ), this,
SLOT( displayAutomatedOnly() ) );
l->addWidget( m_displayAutomatedOnly, 0, 1, 1, 2, Qt::AlignLeft );
m_closeButton = new QPushButton( tr( " Close " ), widget );
connect( m_closeButton, SIGNAL( clicked() ), this,
SLOT( closeWindow() ) );
l->addWidget( m_closeButton, 0, 2, 1, 7, Qt::AlignLeft );
for( int i = 0; i < 10; i++ )
{
l->addItem( new QSpacerItem( 68, 45, QSizePolicy::Fixed, QSizePolicy::Fixed ), 0, i );
}
const QMap<QString, QString> & dump = m_vi->m_plugin->parameterDump();
m_vi->paramCount = dump.size();
vstKnobs = new CustomTextKnob *[ m_vi->paramCount ];
bool hasKnobModel = true;
if (m_vi->knobFModel == nullptr) {
m_vi->knobFModel = new FloatModel *[ m_vi->paramCount ];
hasKnobModel = false;
}
auto paramStr = std::array<char, 35>{};
QStringList s_dumpValues;
for( int i = 0; i < m_vi->paramCount; i++ )
{
std::snprintf(paramStr.data(), paramStr.size(), "param%d", i);
s_dumpValues = dump[paramStr.data()].split(":");
vstKnobs[ i ] = new CustomTextKnob( KnobType::Bright26, this, s_dumpValues.at( 1 ) );
vstKnobs[ i ]->setDescription( s_dumpValues.at( 1 ) + ":" );
vstKnobs[ i ]->setLabel( s_dumpValues.at( 1 ).left( 15 ) );
if( !hasKnobModel )
{
std::snprintf(paramStr.data(), paramStr.size(), "%d", i);
m_vi->knobFModel[i] = new FloatModel(LocaleHelper::toFloat(s_dumpValues.at(2)),
0.0f, 1.0f, 0.01f, castModel<VestigeInstrument>(), paramStr.data());
}
FloatModel * model = m_vi->knobFModel[i];
connect( model, &FloatModel::dataChanged, this,
[this, model]() { setParameter( model ); }, Qt::DirectConnection);
vstKnobs[i] ->setModel( model );
}
syncParameterText();
int i = 0;
for( int lrow = 1; lrow < ( int( m_vi->paramCount / 10 ) + 1 ) + 1; lrow++ )
{
for( int lcolumn = 0; lcolumn < 10; lcolumn++ )
{
if( i < m_vi->paramCount )
{
l->addWidget( vstKnobs[i], lrow, lcolumn, Qt::AlignCenter );
}
i++;
}
}
l->setRowStretch( ( int( m_vi->paramCount / 10) + 1), 1 );
l->setColumnStretch( 10, 1 );
widget->setLayout(l);
widget->setAutoFillBackground(true);
m_vi->m_scrollArea->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
m_vi->m_scrollArea->setPalette( QApplication::palette( m_vi->m_scrollArea ) );
m_vi->m_scrollArea->setMinimumHeight( 64 );
m_vi->m_scrollArea->setWidget( widget );
m_vi->m_subWindow->show();
}
void ManageVestigeInstrumentView::closeWindow()
{
m_vi->m_subWindow->hide();
}
void ManageVestigeInstrumentView::syncPlugin( void )
{
auto paramStr = std::array<char, 35>{};
QStringList s_dumpValues;
const QMap<QString, QString> & dump = m_vi->m_plugin->parameterDump();
for( int i = 0; i < m_vi->paramCount; i++ )
{
// only not automated knobs are synced from VST
// those auto-setted values are not jurnaled, tracked for undo / redo
if( !( m_vi->knobFModel[ i ]->isAutomated() || m_vi->knobFModel[ i ]->controllerConnection() ) )
{
std::snprintf(paramStr.data(), paramStr.size(), "param%d", i);
s_dumpValues = dump[paramStr.data()].split(":");
float f_value = LocaleHelper::toFloat(s_dumpValues.at(2));
m_vi->knobFModel[ i ]->setAutomatedValue( f_value );
m_vi->knobFModel[ i ]->setInitValue( f_value );
}
}
syncParameterText();
}
void ManageVestigeInstrumentView::displayAutomatedOnly( void )
{
bool isAuto = QString::compare( m_displayAutomatedOnly->text(), tr( "Automated" ) ) == 0;
for( int i = 0; i< m_vi->paramCount; i++ )
{
if( !( m_vi->knobFModel[ i ]->isAutomated() || m_vi->knobFModel[ i ]->controllerConnection() ) )
{
if( vstKnobs[ i ]->isVisible() == true && isAuto )
{
vstKnobs[ i ]->hide();
m_displayAutomatedOnly->setText( "All" );
} else {
vstKnobs[ i ]->show();
m_displayAutomatedOnly->setText( "Automated" );
}
}
}
}
ManageVestigeInstrumentView::~ManageVestigeInstrumentView()
{
if( m_vi->knobFModel != nullptr )
{
for( int i = 0; i < m_vi->paramCount; i++ )
{
delete m_vi->knobFModel[ i ];
delete vstKnobs[ i ];
}
}
if (vstKnobs != nullptr) {
delete []vstKnobs;
vstKnobs = nullptr;
}
if( m_vi->knobFModel != nullptr )
{
delete [] m_vi->knobFModel;
m_vi->knobFModel = nullptr;
}
if (m_vi->m_scrollArea != nullptr) {
delete m_vi->m_scrollArea;
m_vi->m_scrollArea = nullptr;
}
if ( m_vi->m_subWindow != nullptr ) {
m_vi->m_subWindow->setAttribute(Qt::WA_DeleteOnClose);
m_vi->m_subWindow->close();
if ( m_vi->m_subWindow != nullptr )
delete m_vi->m_subWindow;
m_vi->m_subWindow = nullptr;
}
m_vi->p_subWindow = nullptr;
}
void ManageVestigeInstrumentView::setParameter( Model * action )
{
int knobUNID = action->displayName().toInt();
if ( m_vi->m_plugin != nullptr ) {
m_vi->m_plugin->setParam( knobUNID, m_vi->knobFModel[knobUNID]->value() );
syncParameterText();
}
}
void ManageVestigeInstrumentView::syncParameterText()
{
m_vi->m_plugin->loadParameterLabels();
m_vi->m_plugin->loadParameterDisplays();
QString paramLabelStr = m_vi->m_plugin->allParameterLabels();
QString paramDisplayStr = m_vi->m_plugin->allParameterDisplays();
QStringList paramLabelList;
QStringList paramDisplayList;
for( int i = 0; i < paramLabelStr.size(); )
{
const int length = paramLabelStr[i].digitValue();
paramLabelList.append(paramLabelStr.mid(i + 1, length));
i += length + 1;
}
for( int i = 0; i < paramDisplayStr.size(); )
{
const int length = paramDisplayStr[i].digitValue();
paramDisplayList.append(paramDisplayStr.mid(i + 1, length));
i += length + 1;
}
for( int i = 0; i < paramLabelList.size(); ++i )
{
vstKnobs[i]->setValueText(paramDisplayList[i] + ' ' + paramLabelList[i]);
}
}
void ManageVestigeInstrumentView::dragEnterEvent( QDragEnterEvent * _dee )
{
// For mimeType() and MimeType enum class
using namespace Clipboard;
if( _dee->mimeData()->hasFormat( mimeType( MimeType::StringPair ) ) )
{
QString txt = _dee->mimeData()->data(
mimeType( MimeType::StringPair ) );
if( txt.section( ':', 0, 0 ) == "vstplugin" )
{
_dee->acceptProposedAction();
}
else
{
_dee->ignore();
}
}
else
{
_dee->ignore();
}
}
void ManageVestigeInstrumentView::dropEvent( QDropEvent * _de )
{
QString type = StringPairDrag::decodeKey( _de );
QString value = StringPairDrag::decodeValue( _de );
if( type == "vstplugin" )
{
m_vi->loadFile( value );
_de->accept();
return;
}
_de->ignore();
}
void ManageVestigeInstrumentView::paintEvent( QPaintEvent * )
{
m_vi->m_subWindow->setWindowTitle( m_vi->instrumentTrack()->name()
+ tr( " - VST plugin control" ) );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
Q_DECL_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return new VestigeInstrument( static_cast<InstrumentTrack *>( m ) );
}
}
} // namespace lmms
| 30,588
|
C++
|
.cpp
| 961
| 28.863684
| 112
| 0.686196
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,699
|
Monstro.cpp
|
LMMS_lmms/plugins/Monstro/Monstro.cpp
|
/*
* Monstro.cpp - a monstrous semi-modular 3-osc synth with modulation matrix
*
* Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "Monstro.h"
#include "ComboBox.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "lmms_math.h"
#include "interpolation.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT monstro_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Monstro",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Monstrous 3-oscillator synth with modulation matrix" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
MonstroSynth::MonstroSynth( MonstroInstrument * _i, NotePlayHandle * _nph ) :
m_parent( _i ),
m_nph( _nph )
{
m_osc1l_phase = 0.0f;
m_osc1r_phase = 0.0f;
m_osc2l_phase = 0.0f;
m_osc2r_phase = 0.0f;
m_osc3l_phase = 0.0f;
m_osc3r_phase = 0.0f;
m_ph2l_last = 0.0f;
m_ph2r_last = 0.0f;
m_ph3l_last = 0.0f;
m_ph3r_last = 0.0f;
m_env_phase[0] = 0.0f;
m_env_phase[1] = 0.0f;
m_lfo_phase[0] = 0.0f;
m_lfo_phase[1] = 0.0f;
m_lfo_next[0] = Oscillator::noiseSample( 0.0f );
m_lfo_next[1] = Oscillator::noiseSample( 0.0f );
m_osc1l_last = 0.0f;
m_osc1r_last = 0.0f;
m_l_last = 0.0f;
m_r_last = 0.0f;
m_invert2l = false;
m_invert2r = false;
m_invert3l = false;
m_invert3r = false;
m_counter2l = 0;
m_counter2r = 0;
m_counter3l = 0;
m_counter3r = 0;
m_lfo[0].resize( m_parent->m_fpp );
m_lfo[1].resize( m_parent->m_fpp );
m_env[0].resize( m_parent->m_fpp );
m_env[1].resize( m_parent->m_fpp );
}
void MonstroSynth::renderOutput( fpp_t _frames, SampleFrame* _buf )
{
float modtmp; // temp variable for freq modulation
// macros for modulating with env/lfos
#define modulatefreq( car, mod ) \
modtmp = 0.0f; \
if( mod##_e1 != 0.0f ) modtmp += m_env[0][f] * mod##_e1; \
if( mod##_e2 != 0.0f ) modtmp += m_env[1][f] * mod##_e2; \
if( mod##_l1 != 0.0f ) modtmp += m_lfo[0][f] * mod##_l1; \
if( mod##_l2 != 0.0f ) modtmp += m_lfo[1][f] * mod##_l2; \
car = qBound( MIN_FREQ, car * powf( 2.0f, modtmp ), MAX_FREQ );
#define modulateabs( car, mod ) \
if( mod##_e1 != 0.0f ) car += m_env[0][f] * mod##_e1; \
if( mod##_e2 != 0.0f ) car += m_env[1][f] * mod##_e2; \
if( mod##_l1 != 0.0f ) car += m_lfo[0][f] * mod##_l1; \
if( mod##_l2 != 0.0f ) car += m_lfo[1][f] * mod##_l2;
#define modulatephs( car, mod ) \
if( mod##_e1 != 0.0f ) car += m_env[0][f] * mod##_e1; \
if( mod##_e2 != 0.0f ) car += m_env[1][f] * mod##_e2; \
if( mod##_l1 != 0.0f ) car += m_lfo[0][f] * mod##_l1; \
if( mod##_l2 != 0.0f ) car += m_lfo[1][f] * mod##_l2;
#define modulatevol( car, mod ) \
if( mod##_e1 > 0.0f ) car *= ( 1.0f - mod##_e1 + mod##_e1 * m_env[0][f] ); \
if( mod##_e1 < 0.0f ) car *= ( 1.0f + mod##_e1 * m_env[0][f] ); \
if( mod##_e2 > 0.0f ) car *= ( 1.0f - mod##_e2 + mod##_e2 * m_env[1][f] ); \
if( mod##_e2 < 0.0f ) car *= ( 1.0f + mod##_e2 * m_env[1][f] ); \
if( mod##_l1 != 0.0f ) car *= ( 1.0f + mod##_l1 * m_lfo[0][f] ); \
if( mod##_l2 != 0.0f ) car *= ( 1.0f + mod##_l2 * m_lfo[1][f] ); \
car = qBound( -MODCLIP, car, MODCLIP );
////////////////////
// //
// MODULATORS //
// //
////////////////////
// LFO phase offsets
const float lfo1_po = m_parent->m_lfo1Phs.value() / 360.0f;
const float lfo2_po = m_parent->m_lfo2Phs.value() / 360.0f;
// remove cruft from phase counters to prevent overflow, add phase offset
m_lfo_phase[0] = absFraction( m_lfo_phase[0] + lfo1_po );
m_lfo_phase[1] = absFraction( m_lfo_phase[1] + lfo2_po );
// LFO rates and increment
m_lfo_rate[0] = ( m_parent->m_lfo1Rate.value() * 0.001f * m_parent->m_samplerate );
m_lfo_rate[1] = ( m_parent->m_lfo2Rate.value() * 0.001f * m_parent->m_samplerate );
m_lfo_inc[0] = 1.0f / m_lfo_rate[0];
m_lfo_inc[1] = 1.0f / m_lfo_rate[1];
m_env_sus[0] = m_parent-> m_env1Sus.value();
m_env_sus[1] = m_parent-> m_env2Sus.value();
m_lfovalue[0] = m_parent->m_lfo1Wave.value();
m_lfovalue[1] = m_parent->m_lfo2Wave.value();
m_lfoatt[0] = m_parent->m_lfo1_att;
m_lfoatt[1] = m_parent->m_lfo2_att;
m_env_pre[0] = m_parent->m_env1_pre;
m_env_att[0] = m_parent->m_env1_att;
m_env_hold[0] = m_parent->m_env1_hold;
m_env_dec[0] = m_parent->m_env1_dec;
m_env_rel[0] = m_parent->m_env1_rel;
m_env_pre[1] = m_parent->m_env2_pre;
m_env_att[1] = m_parent->m_env2_att;
m_env_hold[1] = m_parent->m_env2_hold;
m_env_dec[1] = m_parent->m_env2_dec;
m_env_rel[1] = m_parent->m_env2_rel;
// get updated osc1 values
// get pulse width
const float pw = ( m_parent->m_osc1Pw.value() * 0.01f );
const float o1pw_e1 = ( m_parent->m_pw1env1.value() );
const float o1pw_e2 = ( m_parent->m_pw1env2.value() );
const float o1pw_l1 = ( m_parent->m_pw1lfo1.value() * 0.5f );
const float o1pw_l2 = ( m_parent->m_pw1lfo2.value() * 0.5f );
const bool o1pw_mod = o1pw_e1 != 0.0f || o1pw_e2 != 0.0f || o1pw_l1 != 0.0f || o1pw_l2 != 0.0f;
// get phases
const float o1lpo = m_parent->m_osc1l_po;
const float o1rpo = m_parent->m_osc1r_po;
const float o1p_e1 = ( m_parent->m_phs1env1.value() );
const float o1p_e2 = ( m_parent->m_phs1env2.value() );
const float o1p_l1 = ( m_parent->m_phs1lfo1.value() * 0.5f );
const float o1p_l2 = ( m_parent->m_phs1lfo2.value() * 0.5f );
const bool o1p_mod = o1p_e1 != 0.0f || o1p_e2 != 0.0f || o1p_l1 != 0.0f || o1p_l2 != 0.0f;
// get pitch
const float o1lfb = ( m_parent->m_osc1l_freq * m_nph->frequency() );
const float o1rfb = ( m_parent->m_osc1r_freq * m_nph->frequency() );
const float o1f_e1 = ( m_parent->m_pit1env1.value() * 2.0f );
const float o1f_e2 = ( m_parent->m_pit1env2.value() * 2.0f );
const float o1f_l1 = ( m_parent->m_pit1lfo1.value() );
const float o1f_l2 = ( m_parent->m_pit1lfo2.value() );
const bool o1f_mod = o1f_e1 != 0.0f || o1f_e2 != 0.0f || o1f_l1 != 0.0f || o1f_l2 != 0.0f;
// get volumes
const float o1lv = m_parent->m_osc1l_vol;
const float o1rv = m_parent->m_osc1r_vol;
const float o1v_e1 = ( m_parent->m_vol1env1.value() );
const float o1v_e2 = ( m_parent->m_vol1env2.value() );
const float o1v_l1 = ( m_parent->m_vol1lfo1.value() );
const float o1v_l2 = ( m_parent->m_vol1lfo2.value() );
const bool o1v_mod = o1v_e1 != 0.0f || o1v_e2 != 0.0f || o1v_l1 != 0.0f || o1v_l2 != 0.0f;
// update osc2
// get waveform
const int o2w = m_parent->m_osc2Wave.value();
// get phases
const float o2lpo = m_parent->m_osc2l_po;
const float o2rpo = m_parent->m_osc2r_po;
const float o2p_e1 = ( m_parent->m_phs2env1.value() );
const float o2p_e2 = ( m_parent->m_phs2env2.value() );
const float o2p_l1 = ( m_parent->m_phs2lfo1.value() * 0.5f );
const float o2p_l2 = ( m_parent->m_phs2lfo2.value() * 0.5f );
const bool o2p_mod = o2p_e1 != 0.0f || o2p_e2 != 0.0f || o2p_l1 != 0.0f || o2p_l2 != 0.0f;
// get pitch
const float o2lfb = ( m_parent->m_osc2l_freq * m_nph->frequency() );
const float o2rfb = ( m_parent->m_osc2r_freq * m_nph->frequency() );
const float o2f_e1 = ( m_parent->m_pit2env1.value() * 2.0f );
const float o2f_e2 = ( m_parent->m_pit2env2.value() * 2.0f );
const float o2f_l1 = ( m_parent->m_pit2lfo1.value() );
const float o2f_l2 = ( m_parent->m_pit2lfo2.value() );
const bool o2f_mod = o2f_e1 != 0.0f || o2f_e2 != 0.0f || o2f_l1 != 0.0f || o2f_l2 != 0.0f;
// get volumes
const float o2lv = m_parent->m_osc2l_vol;
const float o2rv = m_parent->m_osc2r_vol;
const float o2v_e1 = ( m_parent->m_vol2env1.value() );
const float o2v_e2 = ( m_parent->m_vol2env2.value() );
const float o2v_l1 = ( m_parent->m_vol2lfo1.value() );
const float o2v_l2 = ( m_parent->m_vol2lfo2.value() );
const bool o2v_mod = o2v_e1 != 0.0f || o2v_e2 != 0.0f || o2v_l1 != 0.0f || o2v_l2 != 0.0f;
// update osc3
// get waveforms
const int o3w1 = m_parent->m_osc3Wave1.value();
const int o3w2 = m_parent->m_osc3Wave2.value();
// get phases
const float o3lpo = m_parent->m_osc3l_po;
const float o3rpo = m_parent->m_osc3r_po;
const float o3p_e1 = ( m_parent->m_phs3env1.value() );
const float o3p_e2 = ( m_parent->m_phs3env2.value() );
const float o3p_l1 = ( m_parent->m_phs3lfo1.value() * 0.5f );
const float o3p_l2 = ( m_parent->m_phs3lfo2.value() * 0.5f );
const bool o3p_mod = o3p_e1 != 0.0f || o3p_e2 != 0.0f || o3p_l1 != 0.0f || o3p_l2 != 0.0f;
// get pitch modulators
const float o3fb = ( m_parent->m_osc3_freq * m_nph->frequency() );
const float o3f_e1 = ( m_parent->m_pit3env1.value() * 2.0f );
const float o3f_e2 = ( m_parent->m_pit3env2.value() * 2.0f );
const float o3f_l1 = ( m_parent->m_pit3lfo1.value() );
const float o3f_l2 = ( m_parent->m_pit3lfo2.value() );
const bool o3f_mod = o3f_e1 != 0.0f || o3f_e2 != 0.0f || o3f_l1 != 0.0f || o3f_l2 != 0.0f;
// get volumes
const float o3lv = m_parent->m_osc3l_vol;
const float o3rv = m_parent->m_osc3r_vol;
const float o3v_e1 = ( m_parent->m_vol3env1.value() );
const float o3v_e2 = ( m_parent->m_vol3env2.value() );
const float o3v_l1 = ( m_parent->m_vol3lfo1.value() );
const float o3v_l2 = ( m_parent->m_vol3lfo2.value() );
const bool o3v_mod = o3v_e1 != 0.0f || o3v_e2 != 0.0f || o3v_l1 != 0.0f || o3v_l2 != 0.0f;
// get sub
const float o3sub = ( m_parent->m_osc3Sub.value() + 100.0f ) / 200.0f;
const float o3s_e1 = ( m_parent->m_sub3env1.value() );
const float o3s_e2 = ( m_parent->m_sub3env2.value() );
const float o3s_l1 = ( m_parent->m_sub3lfo1.value() * 0.5f );
const float o3s_l2 = ( m_parent->m_sub3lfo2.value() * 0.5f );
const bool o3s_mod = o3s_e1 != 0.0f || o3s_e2 != 0.0f || o3s_l1 != 0.0f || o3s_l2 != 0.0f;
//o2-o3 modulation
const int omod = m_parent->m_o23Mod.value();
// sync information
const bool o1ssr = m_parent->m_osc1SSR.value();
const bool o1ssf = m_parent->m_osc1SSF.value();
const bool o2sync = m_parent->m_osc2SyncH.value();
const bool o3sync = m_parent->m_osc3SyncH.value();
const bool o2syncr = m_parent->m_osc2SyncR.value();
const bool o3syncr = m_parent->m_osc3SyncR.value();
///////////////////////////
// //
// start buffer loop //
// //
///////////////////////////
// declare working variables for for loop
// phase manipulation vars - these can be reused by all oscs
float leftph;
float rightph;
float pd_l;
float pd_r;
float len_l(0.);
float len_r(0.);
// osc1 vars
float o1l_f;
float o1r_f;
float o1l_p = m_osc1l_phase + o1lpo; // we add phase offset here so we don't have to do it every frame
float o1r_p = m_osc1r_phase + o1rpo; // then subtract it again after loop...
float o1_pw;
// osc2 vars
float o2l_f;
float o2r_f;
float o2l_p = m_osc2l_phase + o2lpo;
float o2r_p = m_osc2r_phase + o2rpo;
// osc3 vars
float o3l_f;
float o3r_f;
float o3l_p = m_osc3l_phase + o3lpo;
float o3r_p = m_osc3r_phase + o3rpo;
float sub;
// render modulators: envelopes, lfos
updateModulators( m_env[0].data(), m_env[1].data(), m_lfo[0].data(), m_lfo[1].data(), _frames );
// begin for loop
for( f_cnt_t f = 0; f < _frames; ++f )
{
/* // debug code
if( f % 10 == 0 ) {
qDebug( "env1 %f -- env1 phase %f", m_env1_buf[f], m_env1_phase );
qDebug( "env1 pre %f att %f dec %f rel %f ", m_parent->m_env1_pre, m_parent->m_env1_att,
m_parent->m_env1_dec, m_parent->m_env1_rel );
}*/
/////////////////////////////
// //
// OSC 1 //
// //
/////////////////////////////
// calc and mod frequencies
o1l_f = o1lfb;
o1r_f = o1rfb;
if( o1f_mod )
{
modulatefreq( o1l_f, o1f )
modulatefreq( o1r_f, o1f )
}
// calc and modulate pulse
o1_pw = pw;
if( o1pw_mod )
{
modulateabs( o1_pw, o1pw )
o1_pw = qBound( PW_MIN, o1_pw, PW_MAX );
}
// calc and modulate phase
leftph = o1l_p;
rightph = o1r_p;
if( o1p_mod )
{
modulatephs( leftph, o1p )
modulatephs( rightph, o1p )
}
// pulse wave osc
sample_t O1L = ( absFraction( leftph ) < o1_pw ) ? 1.0f : -1.0f;
sample_t O1R = ( absFraction( rightph ) < o1_pw ) ? 1.0f : -1.0f;
// check for rise/fall, and sync if appropriate
// sync on rise
if( o1ssr )
{
// hard sync
if( o2sync )
{
if( O1L > m_osc1l_last ) { o2l_p = o2lpo; m_counter2l = m_parent->m_counterMax; }
if( O1R > m_osc1r_last ) { o2r_p = o2rpo; m_counter2r = m_parent->m_counterMax; }
}
if( o3sync )
{
if( O1L > m_osc1l_last ) { o3l_p = o3lpo; m_counter3l = m_parent->m_counterMax; }
if( O1R > m_osc1r_last ) { o3r_p = o3rpo; m_counter3r = m_parent->m_counterMax; }
}
// reverse sync
if( o2syncr )
{
if( O1L > m_osc1l_last ) { m_invert2l = !m_invert2l; m_counter2l = m_parent->m_counterMax; }
if( O1R > m_osc1r_last ) { m_invert2r = !m_invert2r; m_counter2r = m_parent->m_counterMax; }
}
if( o3syncr )
{
if( O1L > m_osc1l_last ) { m_invert3l = !m_invert3l; m_counter3l = m_parent->m_counterMax; }
if( O1R > m_osc1r_last ) { m_invert3r = !m_invert3r; m_counter3r = m_parent->m_counterMax; }
}
}
// sync on fall
if( o1ssf )
{
// hard sync
if( o2sync )
{
if( O1L < m_osc1l_last ) { o2l_p = o2lpo; m_counter2l = m_parent->m_counterMax; }
if( O1R < m_osc1r_last ) { o2r_p = o2rpo; m_counter2r = m_parent->m_counterMax; }
}
if( o3sync )
{
if( O1L < m_osc1l_last ) { o3l_p = o3lpo; m_counter3l = m_parent->m_counterMax; }
if( O1R < m_osc1r_last ) { o3r_p = o3rpo; m_counter3r = m_parent->m_counterMax; }
}
// reverse sync
if( o2syncr )
{
if( O1L < m_osc1l_last ) { m_invert2l = !m_invert2l; m_counter2l = m_parent->m_counterMax; }
if( O1R < m_osc1r_last ) { m_invert2r = !m_invert2r; m_counter2r = m_parent->m_counterMax; }
}
if( o3syncr )
{
if( O1L < m_osc1l_last ) { m_invert3l = !m_invert3l; m_counter3l = m_parent->m_counterMax; }
if( O1R < m_osc1r_last ) { m_invert3r = !m_invert3r; m_counter3r = m_parent->m_counterMax; }
}
}
// update last before signal is touched
// also do a very simple amp delta cap
const sample_t tmpl = m_osc1l_last;
const sample_t tmpr = m_osc1r_last;
m_osc1l_last = O1L;
m_osc1r_last = O1R;
if( tmpl != O1L ) O1L = 0.0f;
if( tmpr != O1R ) O1R = 0.0f;
// modulate volume
O1L *= o1lv;
O1R *= o1rv;
if( o1v_mod )
{
modulatevol( O1L, o1v )
modulatevol( O1R, o1v )
}
// update osc1 phase working variable
o1l_p += 1.0f / ( static_cast<float>( m_parent->m_samplerate ) / o1l_f );
o1r_p += 1.0f / ( static_cast<float>( m_parent->m_samplerate ) / o1r_f );
/////////////////////////////
// //
// OSC 2 //
// //
/////////////////////////////
// calc and mod frequencies
o2l_f = o2lfb;
o2r_f = o2rfb;
if( o2f_mod )
{
modulatefreq( o2l_f, o2f )
modulatefreq( o2r_f, o2f )
}
// calc and modulate phase
leftph = o2l_p;
rightph = o2r_p;
if( o2p_mod )
{
modulatephs( leftph, o2p )
modulatephs( rightph, o2p )
}
leftph = absFraction( leftph );
rightph = absFraction( rightph );
// phase delta
pd_l = qAbs( leftph - m_ph2l_last );
if( pd_l > 0.5 ) pd_l = 1.0 - pd_l;
pd_r = qAbs( rightph - m_ph2r_last );
if( pd_r > 0.5 ) pd_r = 1.0 - pd_r;
// multi-wave DC Oscillator
sample_t O2L = 0.;
if (pd_l != 0.)
{
len_l = BandLimitedWave::pdToLen(pd_l);
if (m_counter2l > 0)
{
len_l /= m_counter2l; m_counter2l--;
}
O2L = oscillate(o2w, leftph, len_l);
}
sample_t O2R = 0.;
if (pd_r != 0.)
{
len_r = BandLimitedWave::pdToLen(pd_r);
if (m_counter2r > 0)
{
len_r /= m_counter2r; m_counter2r--;
}
O2R = oscillate(o2w, rightph, len_r);
}
// modulate volume
O2L *= o2lv;
O2R *= o2rv;
if( o2v_mod )
{
modulatevol( O2L, o2v )
modulatevol( O2R, o2v )
}
// reverse sync - invert waveforms when needed
if( m_invert2l ) O2L *= -1.0;
if( m_invert2r ) O2R *= -1.0;
// update osc2 phases
m_ph2l_last = leftph;
m_ph2r_last = rightph;
o2l_p += 1.0f / ( static_cast<float>( m_parent->m_samplerate ) / o2l_f );
o2r_p += 1.0f / ( static_cast<float>( m_parent->m_samplerate ) / o2r_f );
/////////////////////////////
// //
// OSC 3 //
// //
/////////////////////////////
// calc and mod frequencies
o3l_f = o3fb;
o3r_f = o3fb;
if( o3f_mod )
{
modulatefreq( o3l_f, o3f )
modulatefreq( o3r_f, o3f )
}
// calc and modulate phase
leftph = o3l_p;
rightph = o3r_p;
if( o3p_mod )
{
modulatephs( leftph, o3p )
modulatephs( rightph, o3p )
}
// o2 modulation?
if( omod == MOD_PM )
{
leftph += O2L * 0.5f;
rightph += O2R * 0.5f;
}
leftph = absFraction( leftph );
rightph = absFraction( rightph );
// phase delta
pd_l = qAbs( leftph - m_ph3l_last );
if( pd_l > 0.5 ) pd_l = 1.0 - pd_l;
pd_r = qAbs( rightph - m_ph3r_last );
if( pd_r > 0.5 ) pd_r = 1.0 - pd_r;
// multi-wave DC Oscillator
sample_t O3AL = 0.;
sample_t O3AR = 0.;
// multi-wave DC Oscillator, sub-osc 2
sample_t O3BL = 0.;
sample_t O3BR = 0.;
if (pd_l != 0.)
{
len_l = BandLimitedWave::pdToLen(pd_l);
if (m_counter3l > 0)
{
len_l /= m_counter3l; m_counter3l--;
}
// sub-osc 1
O3AL = oscillate(o3w1, leftph, len_l);
// multi-wave DC Oscillator, sub-osc 2
O3BL = oscillate(o3w2, leftph, len_l);
}
if (pd_r != 0.)
{
len_r = BandLimitedWave::pdToLen(pd_r);
if (m_counter3r > 0)
{
len_r /= m_counter3r; m_counter3r--;
}
// sub-osc 1
O3AR = oscillate(o3w1, rightph, len_r);
// multi-wave DC Oscillator, sub-osc 2
O3BR = oscillate(o3w2, rightph, len_r);
}
// calc and modulate sub
sub = o3sub;
if( o3s_mod )
{
modulateabs( sub, o3s )
sub = qBound( 0.0f, sub, 1.0f );
}
sample_t O3L = linearInterpolate( O3AL, O3BL, sub );
sample_t O3R = linearInterpolate( O3AR, O3BR, sub );
// modulate volume
O3L *= o3lv;
O3R *= o3rv;
if( o3v_mod )
{
modulatevol( O3L, o3v )
modulatevol( O3R, o3v )
}
// o2 modulation?
if( omod == MOD_AM )
{
O3L = qBound( -MODCLIP, O3L * qMax( 0.0f, 1.0f + O2L ), MODCLIP );
O3R = qBound( -MODCLIP, O3R * qMax( 0.0f, 1.0f + O2R ), MODCLIP );
}
// reverse sync - invert waveforms when needed
if( m_invert3l ) O3L *= -1.0;
if( m_invert3r ) O3R *= -1.0;
// update osc3 phases
m_ph3l_last = leftph;
m_ph3r_last = rightph;
len_l = 1.0f / ( static_cast<float>( m_parent->m_samplerate ) / o3l_f );
len_r = 1.0f / ( static_cast<float>( m_parent->m_samplerate ) / o3r_f );
// handle FM as PM
if( omod == MOD_FM )
{
len_l += O2L * m_parent->m_fmCorrection;
len_r += O2R * m_parent->m_fmCorrection;
}
o3l_p += len_l;
o3r_p += len_r;
// integrator - very simple filter
sample_t L = O1L + O3L + ( omod == MOD_MIX ? O2L : 0.0f );
sample_t R = O1R + O3R + ( omod == MOD_MIX ? O2R : 0.0f );
_buf[f][0] = linearInterpolate( L, m_l_last, m_parent->m_integrator );
_buf[f][1] = linearInterpolate( R, m_r_last, m_parent->m_integrator );
m_l_last = L;
m_r_last = R;
}
// update phases
m_osc1l_phase = absFraction( o1l_p - o1lpo );
m_osc1r_phase = absFraction( o1r_p - o1rpo );
m_osc2l_phase = absFraction( o2l_p - o2lpo );
m_osc2r_phase = absFraction( o2r_p - o2rpo );
m_osc3l_phase = absFraction( o3l_p - o3lpo );
m_osc3r_phase = absFraction( o3r_p - o3rpo );
m_lfo_phase[0] = absFraction( m_lfo_phase[0] - lfo1_po );
m_lfo_phase[1] = absFraction( m_lfo_phase[1] - lfo2_po );
}
inline void MonstroSynth::updateModulators(float * env1, float * env2, float * lfo1, float * lfo2, f_cnt_t frames)
{
// frames played before
const f_cnt_t tfp = m_nph->totalFramesPlayed();
auto lfo = std::array<float*, 2>{};
auto env = std::array<float*, 2>{};
lfo[0] = lfo1;
lfo[1] = lfo2;
env[0] = env1;
env[1] = env2;
for( int i = 0; i < 2; ++i )
{
switch( m_lfovalue[i] )
{
case WAVE_SINE:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = Oscillator::sinSample( m_lfo_phase[i] );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_TRI:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = Oscillator::triangleSample( m_lfo_phase[i] );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_SAW:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = Oscillator::sawSample( m_lfo_phase[i] );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_RAMP:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = Oscillator::sawSample( m_lfo_phase[i] ) * -1.0f;
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_SQR:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = Oscillator::squareSample( m_lfo_phase[i] );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_SQRSOFT:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = oscillate( WAVE_SQRSOFT, m_lfo_phase[i], 0 );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_MOOG:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = Oscillator::moogSawSample( m_lfo_phase[i] );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_SINABS:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = oscillate( WAVE_SINABS, m_lfo_phase[i], 0 );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_EXP:
for( f_cnt_t f = 0; f < frames; ++f )
{
lfo[i][f] = Oscillator::expSample( m_lfo_phase[i] );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_RANDOM:
for( f_cnt_t f = 0; f < frames; ++f )
{
if( ( tfp + f ) % static_cast<int>( m_lfo_rate[i] ) == 0 ) m_lfo_last[i] = Oscillator::noiseSample( 0.0f );
lfo[i][f] = m_lfo_last[i];
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
case WAVE_RANDOM_SMOOTH:
for( f_cnt_t f = 0; f < frames; ++f )
{
const f_cnt_t tm = ( tfp + f ) % static_cast<int>( m_lfo_rate[i] );
if( tm == 0 )
{
m_lfo_last[i] = m_lfo_next[i];
m_lfo_next[i] = Oscillator::noiseSample( 0.0f );
}
lfo[i][f] = cosinusInterpolate( m_lfo_last[i], m_lfo_next[i], static_cast<float>( tm ) / m_lfo_rate[i] );
m_lfo_phase[i] += m_lfo_inc[i];
}
break;
}
// attack
for( f_cnt_t f = 0; f < frames; ++f )
{
if (tfp + f < static_cast<f_cnt_t>(m_lfoatt[i])) { lfo[i][f] *= static_cast<sample_t>(tfp) / m_lfoatt[i]; }
}
/////////////////////////////////////////////
// //
// //
// envelopes //
// //
// //
/////////////////////////////////////////////
for( f_cnt_t f = 0; f < frames; ++f )
{
if( m_env_phase[i] < 4.0f && m_nph->isReleased() && f >= m_nph->framesBeforeRelease() )
{
if( m_env_phase[i] < 1.0f ) m_env_phase[i] = 5.0f;
else if( m_env_phase[i] < 2.0f ) m_env_phase[i] = 5.0f - fraction( m_env_phase[i] );
else if( m_env_phase[i] < 3.0f ) m_env_phase[i] = 4.0f;
else m_env_phase[i] = 4.0f + fraction( m_env_phase[i] );
}
// process envelope
if( m_env_phase[i] < 1.0f ) // pre-delay phase
{
env[i][f] = 0.0f;
m_env_phase[i] = qMin( 1.0f, m_env_phase[i] + m_env_pre[i] );
}
else if( m_env_phase[i] < 2.0f ) // attack phase
{
env[i][f] = calcSlope( i, fraction( m_env_phase[i] ) );
m_env_phase[i] = qMin( 2.0f, m_env_phase[i] + m_env_att[i] );
}
else if( m_env_phase[i] < 3.0f ) // hold phase
{
env[i][f] = 1.0f;
m_env_phase[i] = qMin( 3.0f, m_env_phase[i] + m_env_hold[i] );
}
else if( m_env_phase[i] < 4.0f ) // decay phase
{
const sample_t s = calcSlope( i, 1.0f - fraction( m_env_phase[i] ) );
if( s <= m_env_sus[i] )
{
env[i][f] = m_env_sus[i];
}
else
{
env[i][f] = s;
m_env_phase[i] = qMin( 4.0f - m_env_sus[i], m_env_phase[i] + m_env_dec[i] );
if( m_env_phase[i] == 4.0f ) m_env_phase[i] = 5.0f; // jump over release if sustain is zero - fix for clicking
}
}
else if( m_env_phase[i] < 5.0f ) // release phase
{
env[i][f] = calcSlope( i, 1.0f - fraction( m_env_phase[i] ) );
m_env_phase[i] += m_env_rel[i];
}
else env[i][f] = 0.0f;
}
}
}
inline sample_t MonstroSynth::calcSlope( int slope, sample_t s )
{
if( m_parent->m_slope[slope] == 1.0f ) return s;
if( s == 0.0f ) return s;
return fastPow(s, m_parent->m_slope[slope]);
}
MonstroInstrument::MonstroInstrument( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &monstro_plugin_descriptor ),
m_osc1Vol(33.f, 0.f, 200.f, 0.1f, this, tr("Osc 1 volume")),
m_osc1Pan(0.f, -100.f, 100.f, 0.1f, this, tr("Osc 1 panning")),
m_osc1Crs( 0.0, -24.0, 24.0, 1.0, this, tr( "Osc 1 coarse detune" ) ),
m_osc1Ftl( 0.0, -100.0, 100.0, 1.0, this, tr( "Osc 1 fine detune left" ) ),
m_osc1Ftr( 0.0, -100.0, 100.0, 1.0, this, tr( "Osc 1 fine detune right" ) ),
m_osc1Spo(0.f, -180.f, 180.f, 0.1f, this, tr("Osc 1 stereo phase offset")),
m_osc1Pw(50.f, PW_MIN, PW_MAX, 0.01f, this, tr("Osc 1 pulse width")),
m_osc1SSR( false, this, tr( "Osc 1 sync send on rise" ) ),
m_osc1SSF( false, this, tr( "Osc 1 sync send on fall" ) ),
m_osc2Vol(33.f, 0.f, 200.f, 0.1f, this, tr("Osc 2 volume")),
m_osc2Pan(0.f, -100.f, 100.f, 0.1f, this, tr("Osc 2 panning")),
m_osc2Crs( 0.0, -24.0, 24.0, 1.0, this, tr( "Osc 2 coarse detune" ) ),
m_osc2Ftl( 0.0, -100.0, 100.0, 1.0, this, tr( "Osc 2 fine detune left" ) ),
m_osc2Ftr( 0.0, -100.0, 100.0, 1.0, this, tr( "Osc 2 fine detune right" ) ),
m_osc2Spo(0.f, -180.f, 180.f, 0.1f, this, tr("Osc 2 stereo phase offset")),
m_osc2Wave( this, tr( "Osc 2 waveform" ) ),
m_osc2SyncH( false, this, tr( "Osc 2 sync hard" ) ),
m_osc2SyncR( false, this, tr( "Osc 2 sync reverse" ) ),
m_osc3Vol(33.f, 0.f, 200.f, 0.1f, this, tr("Osc 3 volume")),
m_osc3Pan(0.f, -100.f, 100.f, 0.1f, this, tr("Osc 3 panning")),
m_osc3Crs( 0.0, -24.0, 24.0, 1.0, this, tr( "Osc 3 coarse detune" ) ),
m_osc3Spo(0.f, -180.f, 180.f, 0.1f, this, tr("Osc 3 Stereo phase offset")),
m_osc3Sub(0.f, -100.f, 100.f, 0.1f, this, tr("Osc 3 sub-oscillator mix")),
m_osc3Wave1( this, tr( "Osc 3 waveform 1" ) ),
m_osc3Wave2( this, tr( "Osc 3 waveform 2" ) ),
m_osc3SyncH( false, this, tr( "Osc 3 sync hard" ) ),
m_osc3SyncR( false, this, tr( "Osc 3 Sync reverse" ) ),
m_lfo1Wave( this, tr( "LFO 1 waveform" ) ),
m_lfo1Att( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "LFO 1 attack" ) ),
m_lfo1Rate(1.0f, 0.1f, 10000.f, 0.1f, 10000.0f, this, tr("LFO 1 rate")),
m_lfo1Phs(0.f, -180.f, 180.f, 0.1f, this, tr("LFO 1 phase")),
m_lfo2Wave( this, tr( "LFO 2 waveform" ) ),
m_lfo2Att( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "LFO 2 attack" ) ),
m_lfo2Rate(1.0f, 0.1f, 10000.f, 0.1f, 10000.0f, this, tr("LFO 2 rate")),
m_lfo2Phs(0.0, -180.f, 180.f, 0.1f, this, tr("LFO 2 phase")),
m_env1Pre( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "Env 1 pre-delay" ) ),
m_env1Att( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "Env 1 attack" ) ),
m_env1Hold( 0.0f, 0.0f, 4000.0f, 1.0f, 4000.0f, this, tr( "Env 1 hold" ) ),
m_env1Dec( 0.0f, 0.0f, 4000.0f, 1.0f, 4000.0f, this, tr( "Env 1 decay" ) ),
m_env1Sus( 1.0f, 0.0f, 1.0f, 0.001f, this, tr( "Env 1 sustain" ) ),
m_env1Rel( 0.0f, 0.0f, 4000.0f, 1.0f, 4000.0f, this, tr( "Env 1 release" ) ),
m_env1Slope( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Env 1 slope" ) ),
m_env2Pre( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "Env 2 pre-delay" ) ),
m_env2Att( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "Env 2 attack" ) ),
m_env2Hold( 0.0f, 0.0f, 4000.0f, 1.0f, 4000.0f, this, tr( "Env 2 hold" ) ),
m_env2Dec( 0.0f, 0.0f, 4000.0f, 1.0f, 4000.0f, this, tr( "Env 2 decay" ) ),
m_env2Sus( 1.0f, 0.0f, 1.0f, 0.001f, this, tr( "Env 2 sustain" ) ),
m_env2Rel( 0.0f, 0.0f, 4000.0f, 1.0f, 4000.0f, this, tr( "Env 2 release" ) ),
m_env2Slope( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Env 2 slope" ) ),
m_o23Mod( 0, 0, NUM_MODS - 1, this, tr( "Osc 2+3 modulation" ) ),
m_selectedView( 0, 0, 1, this, tr( "Selected view" ) ),
m_vol1env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Vol env 1" ) ),
m_vol1env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Vol env 2" ) ),
m_vol1lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Vol LFO 1" ) ),
m_vol1lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Vol LFO 2" ) ),
m_vol2env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Vol env 1" ) ),
m_vol2env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Vol env 2" ) ),
m_vol2lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Vol LFO 1" ) ),
m_vol2lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Vol LFO 2" ) ),
m_vol3env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Vol env 1" ) ),
m_vol3env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Vol env 2" ) ),
m_vol3lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Vol LFO 1" ) ),
m_vol3lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Vol LFO 2" ) ),
m_phs1env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Phs env 1" ) ),
m_phs1env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Phs env 2" ) ),
m_phs1lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Phs LFO 1" ) ),
m_phs1lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Phs LFO 2" ) ),
m_phs2env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Phs env 1" ) ),
m_phs2env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Phs env 2" ) ),
m_phs2lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Phs LFO 1" ) ),
m_phs2lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Phs LFO 2" ) ),
m_phs3env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Phs env 1" ) ),
m_phs3env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Phs env 2" ) ),
m_phs3lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Phs LFO 1" ) ),
m_phs3lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Phs LFO 2" ) ),
m_pit1env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Pit env 1" ) ),
m_pit1env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Pit env 2" ) ),
m_pit1lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Pit LFO 1" ) ),
m_pit1lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - Pit LFO 2" ) ),
m_pit2env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Pit env 1" ) ),
m_pit2env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Pit env 2" ) ),
m_pit2lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Pit LFO 1" ) ),
m_pit2lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 2 - Pit LFO 2" ) ),
m_pit3env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Pit env 1" ) ),
m_pit3env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Pit env 2" ) ),
m_pit3lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Pit LFO 1" ) ),
m_pit3lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Pit LFO 2" ) ),
m_pw1env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - PW env 1" ) ),
m_pw1env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - PW env 2" ) ),
m_pw1lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - PW LFO 1" ) ),
m_pw1lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 1 - PW LFO 2" ) ),
m_sub3env1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Sub env 1" ) ),
m_sub3env2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Sub env 2" ) ),
m_sub3lfo1( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Sub LFO 1" ) ),
m_sub3lfo2( 0.0f, -1.0f, 1.0f, 0.001f, this, tr( "Osc 3 - Sub LFO 2" ) )
{
// setup waveboxes
setwavemodel( m_osc2Wave )
setwavemodel( m_osc3Wave1 )
setwavemodel( m_osc3Wave2 )
setlfowavemodel( m_lfo1Wave )
setlfowavemodel( m_lfo2Wave )
// make connections:
// updateVolumes
connect( &m_osc1Vol, SIGNAL( dataChanged() ), this, SLOT( updateVolume1() ), Qt::DirectConnection );
connect( &m_osc1Pan, SIGNAL( dataChanged() ), this, SLOT( updateVolume1() ), Qt::DirectConnection );
connect( &m_osc2Vol, SIGNAL( dataChanged() ), this, SLOT( updateVolume2() ), Qt::DirectConnection );
connect( &m_osc2Pan, SIGNAL( dataChanged() ), this, SLOT( updateVolume2() ), Qt::DirectConnection );
connect( &m_osc3Vol, SIGNAL( dataChanged() ), this, SLOT( updateVolume3() ), Qt::DirectConnection );
connect( &m_osc3Pan, SIGNAL( dataChanged() ), this, SLOT( updateVolume3() ), Qt::DirectConnection );
// updateFreq
connect( &m_osc1Crs, SIGNAL( dataChanged() ), this, SLOT( updateFreq1() ), Qt::DirectConnection );
connect( &m_osc2Crs, SIGNAL( dataChanged() ), this, SLOT( updateFreq2() ), Qt::DirectConnection );
connect( &m_osc3Crs, SIGNAL( dataChanged() ), this, SLOT( updateFreq3() ), Qt::DirectConnection );
connect( &m_osc1Ftl, SIGNAL( dataChanged() ), this, SLOT( updateFreq1() ), Qt::DirectConnection );
connect( &m_osc2Ftl, SIGNAL( dataChanged() ), this, SLOT( updateFreq2() ), Qt::DirectConnection );
connect( &m_osc1Ftr, SIGNAL( dataChanged() ), this, SLOT( updateFreq1() ), Qt::DirectConnection );
connect( &m_osc2Ftr, SIGNAL( dataChanged() ), this, SLOT( updateFreq2() ), Qt::DirectConnection );
// updatePO
connect( &m_osc1Spo, SIGNAL( dataChanged() ), this, SLOT( updatePO1() ), Qt::DirectConnection );
connect( &m_osc2Spo, SIGNAL( dataChanged() ), this, SLOT( updatePO2() ), Qt::DirectConnection );
connect( &m_osc3Spo, SIGNAL( dataChanged() ), this, SLOT( updatePO3() ), Qt::DirectConnection );
// updateEnvelope1
connect( &m_env1Pre, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope1() ), Qt::DirectConnection );
connect( &m_env1Att, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope1() ), Qt::DirectConnection );
connect( &m_env1Hold, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope1() ), Qt::DirectConnection );
connect( &m_env1Dec, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope1() ), Qt::DirectConnection );
connect( &m_env1Rel, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope1() ), Qt::DirectConnection );
connect( &m_env1Slope, SIGNAL( dataChanged() ), this, SLOT( updateSlope1() ), Qt::DirectConnection );
// updateEnvelope2
connect( &m_env2Pre, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope2() ), Qt::DirectConnection );
connect( &m_env2Att, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope2() ), Qt::DirectConnection );
connect( &m_env2Hold, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope2() ), Qt::DirectConnection );
connect( &m_env2Dec, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope2() ), Qt::DirectConnection );
connect( &m_env2Rel, SIGNAL( dataChanged() ), this, SLOT( updateEnvelope2() ), Qt::DirectConnection );
connect( &m_env2Slope, SIGNAL( dataChanged() ), this, SLOT( updateSlope2() ), Qt::DirectConnection );
// updateLFOAtts
connect( &m_lfo1Att, SIGNAL( dataChanged() ), this, SLOT( updateLFOAtts() ), Qt::DirectConnection );
connect( &m_lfo2Att, SIGNAL( dataChanged() ), this, SLOT( updateLFOAtts() ), Qt::DirectConnection );
// updateSampleRate
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( updateSamplerate() ) );
m_fpp = Engine::audioEngine()->framesPerPeriod();
updateSamplerate();
updateVolume1();
updateVolume2();
updateVolume3();
updateFreq1();
updateFreq2();
updateFreq3();
updatePO1();
updatePO2();
updatePO3();
updateSlope1();
updateSlope2();
}
void MonstroInstrument::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
if (!_n->m_pluginData)
{
_n->m_pluginData = new MonstroSynth( this, _n );
}
auto ms = static_cast<MonstroSynth*>(_n->m_pluginData);
ms->renderOutput( frames, _working_buffer + offset );
//applyRelease( _working_buffer, _n ); // we have our own release
}
void MonstroInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<MonstroSynth *>( _n->m_pluginData );
}
void MonstroInstrument::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
m_osc1Vol.saveSettings( _doc, _this, "o1vol" );
m_osc1Pan.saveSettings( _doc, _this, "o1pan" );
m_osc1Crs.saveSettings( _doc, _this, "o1crs" );
m_osc1Ftl.saveSettings( _doc, _this, "o1ftl" );
m_osc1Ftr.saveSettings( _doc, _this, "o1ftr" );
m_osc1Spo.saveSettings( _doc, _this, "o1spo" );
m_osc1Pw.saveSettings( _doc, _this, "o1pw" );
m_osc1SSR.saveSettings( _doc, _this, "o1ssr" );
m_osc1SSF.saveSettings( _doc, _this, "o1ssf" );
m_osc2Vol.saveSettings( _doc, _this, "o2vol" );
m_osc2Pan.saveSettings( _doc, _this, "o2pan" );
m_osc2Crs.saveSettings( _doc, _this, "o2crs" );
m_osc2Ftl.saveSettings( _doc, _this, "o2ftl" );
m_osc2Ftr.saveSettings( _doc, _this, "o2ftr" );
m_osc2Spo.saveSettings( _doc, _this, "o2spo" );
m_osc2Wave.saveSettings( _doc, _this, "o2wav" );
m_osc2SyncH.saveSettings( _doc, _this, "o2syn" );
m_osc2SyncR.saveSettings( _doc, _this, "o2synr" );
m_osc3Vol.saveSettings( _doc, _this, "o3vol" );
m_osc3Pan.saveSettings( _doc, _this, "o3pan" );
m_osc3Crs.saveSettings( _doc, _this, "o3crs" );
m_osc3Spo.saveSettings( _doc, _this, "o3spo" );
m_osc3Sub.saveSettings( _doc, _this, "o3sub" );
m_osc3Wave1.saveSettings( _doc, _this, "o3wav1" );
m_osc3Wave2.saveSettings( _doc, _this, "o3wav2" );
m_osc3SyncH.saveSettings( _doc, _this, "o3syn" );
m_osc3SyncR.saveSettings( _doc, _this, "o3synr" );
m_lfo1Wave.saveSettings( _doc, _this, "l1wav" );
m_lfo1Att.saveSettings( _doc, _this, "l1att" );
m_lfo1Rate.saveSettings( _doc, _this, "l1rat" );
m_lfo1Phs.saveSettings( _doc, _this, "l1phs" );
m_lfo2Wave.saveSettings( _doc, _this, "l2wav" );
m_lfo2Att.saveSettings( _doc, _this, "l2att" );
m_lfo2Rate.saveSettings( _doc, _this, "l2rat" );
m_lfo2Phs.saveSettings( _doc, _this, "l2phs" );
m_env1Pre.saveSettings( _doc, _this, "e1pre" );
m_env1Att.saveSettings( _doc, _this, "e1att" );
m_env1Hold.saveSettings( _doc, _this, "e1hol" );
m_env1Dec.saveSettings( _doc, _this, "e1dec" );
m_env1Sus.saveSettings( _doc, _this, "e1sus" );
m_env1Rel.saveSettings( _doc, _this, "e1rel" );
m_env1Slope.saveSettings( _doc, _this, "e1slo" );
m_env2Pre.saveSettings( _doc, _this, "e2pre" );
m_env2Att.saveSettings( _doc, _this, "e2att" );
m_env2Hold.saveSettings( _doc, _this, "e2hol" );
m_env2Dec.saveSettings( _doc, _this, "e2dec" );
m_env2Sus.saveSettings( _doc, _this, "e2sus" );
m_env2Rel.saveSettings( _doc, _this, "e2rel" );
m_env2Slope.saveSettings( _doc, _this, "e2slo" );
m_o23Mod.saveSettings( _doc, _this, "o23mo" );
m_vol1env1.saveSettings( _doc, _this, "v1e1" );
m_vol1env2.saveSettings( _doc, _this, "v1e2" );
m_vol1lfo1.saveSettings( _doc, _this, "v1l1" );
m_vol1lfo2.saveSettings( _doc, _this, "v1l2" );
m_vol2env1.saveSettings( _doc, _this, "v2e1" );
m_vol2env2.saveSettings( _doc, _this, "v2e2" );
m_vol2lfo1.saveSettings( _doc, _this, "v2l1" );
m_vol2lfo2.saveSettings( _doc, _this, "v2l2" );
m_vol3env1.saveSettings( _doc, _this, "v3e1" );
m_vol3env2.saveSettings( _doc, _this, "v3e2" );
m_vol3lfo1.saveSettings( _doc, _this, "v3l1" );
m_vol3lfo2.saveSettings( _doc, _this, "v3l2" );
m_phs1env1.saveSettings( _doc, _this, "p1e1" );
m_phs1env2.saveSettings( _doc, _this, "p1e2" );
m_phs1lfo1.saveSettings( _doc, _this, "p1l1" );
m_phs1lfo2.saveSettings( _doc, _this, "p1l2" );
m_phs2env1.saveSettings( _doc, _this, "p2e1" );
m_phs2env2.saveSettings( _doc, _this, "p2e2" );
m_phs2lfo1.saveSettings( _doc, _this, "p2l1" );
m_phs2lfo2.saveSettings( _doc, _this, "p2l2" );
m_phs3env1.saveSettings( _doc, _this, "p3e1" );
m_phs3env2.saveSettings( _doc, _this, "p3e2" );
m_phs3lfo1.saveSettings( _doc, _this, "p3l1" );
m_phs3lfo2.saveSettings( _doc, _this, "p3l2" );
m_pit1env1.saveSettings( _doc, _this, "f1e1" );
m_pit1env2.saveSettings( _doc, _this, "f1e2" );
m_pit1lfo1.saveSettings( _doc, _this, "f1l1" );
m_pit1lfo2.saveSettings( _doc, _this, "f1l2" );
m_pit2env1.saveSettings( _doc, _this, "f2e1" );
m_pit2env2.saveSettings( _doc, _this, "f2e2" );
m_pit2lfo1.saveSettings( _doc, _this, "f2l1" );
m_pit2lfo2.saveSettings( _doc, _this, "f2l2" );
m_pit3env1.saveSettings( _doc, _this, "f3e1" );
m_pit3env2.saveSettings( _doc, _this, "f3e2" );
m_pit3lfo1.saveSettings( _doc, _this, "f3l1" );
m_pit3lfo2.saveSettings( _doc, _this, "f3l2" );
m_pw1env1.saveSettings( _doc, _this, "w1e1" );
m_pw1env2.saveSettings( _doc, _this, "w1e2" );
m_pw1lfo1.saveSettings( _doc, _this, "w1l1" );
m_pw1lfo2.saveSettings( _doc, _this, "w1l2" );
m_sub3env1.saveSettings( _doc, _this, "s3e1" );
m_sub3env2.saveSettings( _doc, _this, "s3e2" );
m_sub3lfo1.saveSettings( _doc, _this, "s3l1" );
m_sub3lfo2.saveSettings( _doc, _this, "s3l2" );
}
void MonstroInstrument::loadSettings( const QDomElement & _this )
{
m_osc1Vol.loadSettings( _this, "o1vol" );
m_osc1Pan.loadSettings( _this, "o1pan" );
m_osc1Crs.loadSettings( _this, "o1crs" );
m_osc1Ftl.loadSettings( _this, "o1ftl" );
m_osc1Ftr.loadSettings( _this, "o1ftr" );
m_osc1Spo.loadSettings( _this, "o1spo" );
m_osc1Pw.loadSettings( _this, "o1pw" );
m_osc1SSR.loadSettings( _this, "o1ssr" );
m_osc1SSF.loadSettings( _this, "o1ssf" );
m_osc2Vol.loadSettings( _this, "o2vol" );
m_osc2Pan.loadSettings( _this, "o2pan" );
m_osc2Crs.loadSettings( _this, "o2crs" );
m_osc2Ftl.loadSettings( _this, "o2ftl" );
m_osc2Ftr.loadSettings( _this, "o2ftr" );
m_osc2Spo.loadSettings( _this, "o2spo" );
m_osc2Wave.loadSettings( _this, "o2wav" );
m_osc2SyncH.loadSettings( _this, "o2syn" );
m_osc2SyncR.loadSettings( _this, "o2synr" );
m_osc3Vol.loadSettings( _this, "o3vol" );
m_osc3Pan.loadSettings( _this, "o3pan" );
m_osc3Crs.loadSettings( _this, "o3crs" );
m_osc3Spo.loadSettings( _this, "o3spo" );
m_osc3Sub.loadSettings( _this, "o3sub" );
m_osc3Wave1.loadSettings( _this, "o3wav1" );
m_osc3Wave2.loadSettings( _this, "o3wav2" );
m_osc3SyncH.loadSettings( _this, "o3syn" );
m_osc3SyncR.loadSettings( _this, "o3synr" );
m_lfo1Wave.loadSettings( _this, "l1wav" );
m_lfo1Att.loadSettings( _this, "l1att" );
m_lfo1Rate.loadSettings( _this, "l1rat" );
m_lfo1Phs.loadSettings( _this, "l1phs" );
m_lfo2Wave.loadSettings( _this, "l2wav" );
m_lfo2Att.loadSettings( _this, "l2att" );
m_lfo2Rate.loadSettings( _this, "l2rat" );
m_lfo2Phs.loadSettings( _this, "l2phs" );
m_env1Pre.loadSettings( _this, "e1pre" );
m_env1Att.loadSettings( _this, "e1att" );
m_env1Hold.loadSettings( _this, "e1hol" );
m_env1Dec.loadSettings( _this, "e1dec" );
m_env1Sus.loadSettings( _this, "e1sus" );
m_env1Rel.loadSettings( _this, "e1rel" );
m_env1Slope.loadSettings( _this, "e1slo" );
m_env2Pre.loadSettings( _this, "e2pre" );
m_env2Att.loadSettings( _this, "e2att" );
m_env2Hold.loadSettings( _this, "e2hol" );
m_env2Dec.loadSettings( _this, "e2dec" );
m_env2Sus.loadSettings( _this, "e2sus" );
m_env2Rel.loadSettings( _this, "e2rel" );
m_env2Slope.loadSettings( _this, "e2slo" );
m_o23Mod.loadSettings( _this, "o23mo" );
m_vol1env1.loadSettings( _this, "v1e1" );
m_vol1env2.loadSettings( _this, "v1e2" );
m_vol1lfo1.loadSettings( _this, "v1l1" );
m_vol1lfo2.loadSettings( _this, "v1l2" );
m_vol2env1.loadSettings( _this, "v2e1" );
m_vol2env2.loadSettings( _this, "v2e2" );
m_vol2lfo1.loadSettings( _this, "v2l1" );
m_vol2lfo2.loadSettings( _this, "v2l2" );
m_vol3env1.loadSettings( _this, "v3e1" );
m_vol3env2.loadSettings( _this, "v3e2" );
m_vol3lfo1.loadSettings( _this, "v3l1" );
m_vol3lfo2.loadSettings( _this, "v3l2" );
m_phs1env1.loadSettings( _this, "p1e1" );
m_phs1env2.loadSettings( _this, "p1e2" );
m_phs1lfo1.loadSettings( _this, "p1l1" );
m_phs1lfo2.loadSettings( _this, "p1l2" );
m_phs2env1.loadSettings( _this, "p2e1" );
m_phs2env2.loadSettings( _this, "p2e2" );
m_phs2lfo1.loadSettings( _this, "p2l1" );
m_phs2lfo2.loadSettings( _this, "p2l2" );
m_phs3env1.loadSettings( _this, "p3e1" );
m_phs3env2.loadSettings( _this, "p3e2" );
m_phs3lfo1.loadSettings( _this, "p3l1" );
m_phs3lfo2.loadSettings( _this, "p3l2" );
m_pit1env1.loadSettings( _this, "f1e1" );
m_pit1env2.loadSettings( _this, "f1e2" );
m_pit1lfo1.loadSettings( _this, "f1l1" );
m_pit1lfo2.loadSettings( _this, "f1l2" );
m_pit2env1.loadSettings( _this, "f2e1" );
m_pit2env2.loadSettings( _this, "f2e2" );
m_pit2lfo1.loadSettings( _this, "f2l1" );
m_pit2lfo2.loadSettings( _this, "f2l2" );
m_pit3env1.loadSettings( _this, "f3e1" );
m_pit3env2.loadSettings( _this, "f3e2" );
m_pit3lfo1.loadSettings( _this, "f3l1" );
m_pit3lfo2.loadSettings( _this, "f3l2" );
m_pw1env1.loadSettings( _this, "w1e1" );
m_pw1env2.loadSettings( _this, "w1e2" );
m_pw1lfo1.loadSettings( _this, "w1l1" );
m_pw1lfo2.loadSettings( _this, "w1l2" );
m_sub3env1.loadSettings( _this, "s3e1" );
m_sub3env2.loadSettings( _this, "s3e2" );
m_sub3lfo1.loadSettings( _this, "s3l1" );
m_sub3lfo2.loadSettings( _this, "s3l2" );
}
QString MonstroInstrument::nodeName() const
{
return monstro_plugin_descriptor.name;
}
float MonstroInstrument::desiredReleaseTimeMs() const
{
const auto maxEnvelope = std::max(m_env1_rel, m_env2_rel);
return std::max(1.5f, maxEnvelope);
}
gui::PluginView* MonstroInstrument::instantiateView( QWidget * _parent )
{
return( new gui::MonstroView( this, _parent ) );
}
void MonstroInstrument::updateVolume1()
{
m_osc1l_vol = leftCh( m_osc1Vol.value(), m_osc1Pan.value() );
m_osc1r_vol = rightCh( m_osc1Vol.value(), m_osc1Pan.value() );
}
void MonstroInstrument::updateVolume2()
{
m_osc2l_vol = leftCh( m_osc2Vol.value(), m_osc2Pan.value() );
m_osc2r_vol = rightCh( m_osc2Vol.value(), m_osc2Pan.value() );
}
void MonstroInstrument::updateVolume3()
{
m_osc3l_vol = leftCh( m_osc3Vol.value(), m_osc3Pan.value() );
m_osc3r_vol = rightCh( m_osc3Vol.value(), m_osc3Pan.value() );
}
void MonstroInstrument::updateFreq1()
{
m_osc1l_freq = powf( 2.0f, m_osc1Crs.value() / 12.0f ) *
powf( 2.0f, m_osc1Ftl.value() / 1200.0f );
m_osc1r_freq = powf( 2.0f, m_osc1Crs.value() / 12.0f ) *
powf( 2.0f, m_osc1Ftr.value() / 1200.0f );
}
void MonstroInstrument::updateFreq2()
{
m_osc2l_freq = powf( 2.0f, m_osc2Crs.value() / 12.0f ) *
powf( 2.0f, m_osc2Ftl.value() / 1200.0f );
m_osc2r_freq = powf( 2.0f, m_osc2Crs.value() / 12.0f ) *
powf( 2.0f, m_osc2Ftr.value() / 1200.0f );
}
void MonstroInstrument::updateFreq3()
{
m_osc3_freq = powf( 2.0f, m_osc3Crs.value() / 12.0f );
}
void MonstroInstrument::updatePO1()
{
m_osc1l_po = m_osc1Spo.value() / 720.0f;
m_osc1r_po = ( m_osc1Spo.value() * -1.0 ) / 720.0f;
}
void MonstroInstrument::updatePO2()
{
m_osc2l_po = m_osc2Spo.value() / 720.0f;
m_osc2r_po = ( m_osc2Spo.value() * -1.0 ) / 720.0f;
}
void MonstroInstrument::updatePO3()
{
m_osc3l_po = m_osc3Spo.value() / 720.0f;
m_osc3r_po = ( m_osc3Spo.value() * -1.0 ) / 720.0f;
}
void MonstroInstrument::updateEnvelope1()
{
if( m_env1Pre.value() == 0.0f ) m_env1_pre = 1.0;
else m_env1_pre = 1.0f / ( m_env1Pre.value() / 1000.0f ) / m_samplerate;
if( m_env1Att.value() == 0.0f ) m_env1_att = 1.0;
else m_env1_att = 1.0f / ( m_env1Att.value() / 1000.0f ) / m_samplerate;
if( m_env1Hold.value() == 0.0f ) m_env1_hold = 1.0;
else m_env1_hold = 1.0f / ( m_env1Hold.value() / 1000.0f ) / m_samplerate;
if( m_env1Dec.value() == 0.0f ) m_env1_dec = 1.0;
else m_env1_dec = 1.0f / ( m_env1Dec.value() / 1000.0f ) / m_samplerate;
if( m_env1Rel.value() == 0.0f ) m_env1_rel = 1.0;
else m_env1_rel = 1.0f / ( m_env1Rel.value() / 1000.0f ) / m_samplerate;
m_env1_len = ( m_env1Pre.value() + m_env1Att.value() + m_env1Hold.value() + m_env1Dec.value() ) * m_samplerate / 1000.0f;
m_env1_relF = m_env1Rel.value() * m_samplerate / 1000.0f;
}
void MonstroInstrument::updateEnvelope2()
{
if( m_env2Pre.value() == 0.0f ) m_env2_pre = 1.0;
else m_env2_pre = 1.0f / ( m_env2Pre.value() / 1000.0f ) / m_samplerate;
if( m_env2Att.value() == 0.0f ) m_env2_att = 1.0;
else m_env2_att = 1.0f / ( m_env2Att.value() / 1000.0f ) / m_samplerate;
if( m_env2Hold.value() == 0.0f ) m_env2_hold = 1.0;
else m_env2_hold = 1.0f / ( m_env2Hold.value() / 1000.0f ) / m_samplerate;
if( m_env2Dec.value() == 0.0f ) m_env2_dec = 1.0;
else m_env2_dec = 1.0f / ( m_env2Dec.value() / 1000.0f ) / m_samplerate;
if( m_env2Rel.value() == 0.0f ) m_env2_rel = 1.0;
else m_env2_rel = 1.0f / ( m_env2Rel.value() / 1000.0f ) / m_samplerate;
m_env2_len = ( m_env2Pre.value() + m_env2Att.value() + m_env2Hold.value() + m_env2Dec.value() ) * m_samplerate / 1000.0f;
m_env2_relF = m_env2Rel.value() * m_samplerate / 1000.0f;
}
void MonstroInstrument::updateLFOAtts()
{
m_lfo1_att = m_lfo1Att.value() * m_samplerate / 1000.0f;
m_lfo2_att = m_lfo2Att.value() * m_samplerate / 1000.0f;
}
void MonstroInstrument::updateSamplerate()
{
m_samplerate = Engine::audioEngine()->outputSampleRate();
m_integrator = 0.5f - ( 0.5f - INTEGRATOR ) * 44100.0f / m_samplerate;
m_fmCorrection = 44100.f / m_samplerate * FM_AMOUNT;
m_counterMax = ( m_samplerate * 5 ) / 44100;
updateEnvelope1();
updateEnvelope2();
updateLFOAtts();
}
void MonstroInstrument::updateSlope1()
{
const float slope = m_env1Slope.value();
m_slope[0] = std::pow(10.f, slope * -1.0f );
}
void MonstroInstrument::updateSlope2()
{
const float slope = m_env2Slope.value();
m_slope[1] = std::pow(10.f, slope * -1.0f );
}
namespace gui
{
MonstroView::MonstroView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
m_operatorsView = setupOperatorsView( this );
setWidgetBackground( m_operatorsView, "artwork_op" );
m_operatorsView->show();
m_operatorsView->move( 0, 0 );
m_matrixView = setupMatrixView( this );
setWidgetBackground( m_matrixView, "artwork_mat" );
m_matrixView->hide();
m_matrixView->move( 0, 0 );
// "tab buttons"
auto m_opViewButton = new PixmapButton(this, nullptr);
m_opViewButton -> move( 0,0 );
m_opViewButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "opview_active" ) );
m_opViewButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "opview_inactive" ) );
m_opViewButton->setToolTip(tr("Operators view"));
auto m_matViewButton = new PixmapButton(this, nullptr);
m_matViewButton -> move( 125,0 );
m_matViewButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "matview_active" ) );
m_matViewButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "matview_inactive" ) );
m_matViewButton->setToolTip(tr("Matrix view"));
m_selectedViewGroup = new automatableButtonGroup( this );
m_selectedViewGroup -> addButton( m_opViewButton );
m_selectedViewGroup -> addButton( m_matViewButton );
connect( m_opViewButton, SIGNAL( clicked() ), this, SLOT( updateLayout() ) );
connect( m_matViewButton, SIGNAL( clicked() ), this, SLOT( updateLayout() ) );
}
void MonstroView::updateLayout()
{
switch( m_selectedViewGroup->model()->value() )
{
case OPVIEW:
m_operatorsView->show();
m_matrixView->hide();
break;
case MATVIEW:
m_operatorsView->hide();
m_matrixView->show();
break;
}
}
void MonstroView::modelChanged()
{
auto m = castModel<MonstroInstrument>();
m_osc1VolKnob-> setModel( &m-> m_osc1Vol );
m_osc1PanKnob-> setModel( &m-> m_osc1Pan );
m_osc1CrsKnob-> setModel( &m-> m_osc1Crs );
m_osc1FtlKnob-> setModel( &m-> m_osc1Ftl );
m_osc1FtrKnob-> setModel( &m-> m_osc1Ftr );
m_osc1SpoKnob-> setModel( &m-> m_osc1Spo );
m_osc1PwKnob-> setModel( &m-> m_osc1Pw );
m_osc1SSRButton-> setModel( &m-> m_osc1SSR );
m_osc1SSFButton-> setModel( &m-> m_osc1SSF );
m_osc2VolKnob-> setModel( &m-> m_osc2Vol );
m_osc2PanKnob-> setModel( &m-> m_osc2Pan );
m_osc2CrsKnob-> setModel( &m-> m_osc2Crs );
m_osc2FtlKnob-> setModel( &m-> m_osc2Ftl );
m_osc2FtrKnob-> setModel( &m-> m_osc2Ftr );
m_osc2SpoKnob-> setModel( &m-> m_osc2Spo );
m_osc2WaveBox-> setModel( &m-> m_osc2Wave );
m_osc2SyncHButton-> setModel( &m-> m_osc2SyncH );
m_osc2SyncRButton-> setModel( &m-> m_osc2SyncR );
m_osc3VolKnob-> setModel( &m-> m_osc3Vol );
m_osc3PanKnob-> setModel( &m-> m_osc3Pan );
m_osc3CrsKnob-> setModel( &m-> m_osc3Crs );
m_osc3SpoKnob-> setModel( &m-> m_osc3Spo );
m_osc3SubKnob-> setModel( &m-> m_osc3Sub );
m_osc3Wave1Box-> setModel( &m-> m_osc3Wave1 );
m_osc3Wave2Box-> setModel( &m-> m_osc3Wave2 );
m_osc3SyncHButton-> setModel( &m-> m_osc3SyncH );
m_osc3SyncRButton-> setModel( &m-> m_osc3SyncR );
m_lfo1WaveBox-> setModel( &m-> m_lfo1Wave );
m_lfo1AttKnob-> setModel( &m-> m_lfo1Att );
m_lfo1RateKnob-> setModel( &m-> m_lfo1Rate );
m_lfo1PhsKnob-> setModel( &m-> m_lfo1Phs );
m_lfo2WaveBox-> setModel( &m-> m_lfo2Wave );
m_lfo2AttKnob-> setModel( &m-> m_lfo2Att );
m_lfo2RateKnob-> setModel( &m-> m_lfo2Rate );
m_lfo2PhsKnob-> setModel( &m-> m_lfo2Phs );
m_env1PreKnob-> setModel( &m-> m_env1Pre );
m_env1AttKnob-> setModel( &m-> m_env1Att );
m_env1HoldKnob-> setModel( &m-> m_env1Hold );
m_env1DecKnob-> setModel( &m-> m_env1Dec );
m_env1SusKnob-> setModel( &m-> m_env1Sus );
m_env1RelKnob-> setModel( &m-> m_env1Rel );
m_env1SlopeKnob-> setModel( &m-> m_env1Slope );
m_env2PreKnob-> setModel( &m-> m_env2Pre );
m_env2AttKnob-> setModel( &m-> m_env2Att );
m_env2HoldKnob-> setModel( &m-> m_env2Hold );
m_env2DecKnob-> setModel( &m-> m_env2Dec );
m_env2SusKnob-> setModel( &m-> m_env2Sus );
m_env2RelKnob-> setModel( &m-> m_env2Rel );
m_env2SlopeKnob-> setModel( &m-> m_env2Slope );
m_o23ModGroup-> setModel( &m-> m_o23Mod );
m_selectedViewGroup-> setModel( &m-> m_selectedView );
m_vol1env1Knob-> setModel( &m-> m_vol1env1 );
m_vol1env2Knob-> setModel( &m-> m_vol1env2 );
m_vol1lfo1Knob-> setModel( &m-> m_vol1lfo1 );
m_vol1lfo2Knob-> setModel( &m-> m_vol1lfo2 );
m_vol2env1Knob-> setModel( &m-> m_vol2env1 );
m_vol2env2Knob-> setModel( &m-> m_vol2env2 );
m_vol2lfo1Knob-> setModel( &m-> m_vol2lfo1 );
m_vol2lfo2Knob-> setModel( &m-> m_vol2lfo2 );
m_vol3env1Knob-> setModel( &m-> m_vol3env1 );
m_vol3env2Knob-> setModel( &m-> m_vol3env2 );
m_vol3lfo1Knob-> setModel( &m-> m_vol3lfo1 );
m_vol3lfo2Knob-> setModel( &m-> m_vol3lfo2 );
m_phs1env1Knob-> setModel( &m-> m_phs1env1 );
m_phs1env2Knob-> setModel( &m-> m_phs1env2 );
m_phs1lfo1Knob-> setModel( &m-> m_phs1lfo1 );
m_phs1lfo2Knob-> setModel( &m-> m_phs1lfo2 );
m_phs2env1Knob-> setModel( &m-> m_phs2env1 );
m_phs2env2Knob-> setModel( &m-> m_phs2env2 );
m_phs2lfo1Knob-> setModel( &m-> m_phs2lfo1 );
m_phs2lfo2Knob-> setModel( &m-> m_phs2lfo2 );
m_phs3env1Knob-> setModel( &m-> m_phs3env1 );
m_phs3env2Knob-> setModel( &m-> m_phs3env2 );
m_phs3lfo1Knob-> setModel( &m-> m_phs3lfo1 );
m_phs3lfo2Knob-> setModel( &m-> m_phs3lfo2 );
m_pit1env1Knob-> setModel( &m-> m_pit1env1 );
m_pit1env2Knob-> setModel( &m-> m_pit1env2 );
m_pit1lfo1Knob-> setModel( &m-> m_pit1lfo1 );
m_pit1lfo2Knob-> setModel( &m-> m_pit1lfo2 );
m_pit2env1Knob-> setModel( &m-> m_pit2env1 );
m_pit2env2Knob-> setModel( &m-> m_pit2env2 );
m_pit2lfo1Knob-> setModel( &m-> m_pit2lfo1 );
m_pit2lfo2Knob-> setModel( &m-> m_pit2lfo2 );
m_pit3env1Knob-> setModel( &m-> m_pit3env1 );
m_pit3env2Knob-> setModel( &m-> m_pit3env2 );
m_pit3lfo1Knob-> setModel( &m-> m_pit3lfo1 );
m_pit3lfo2Knob-> setModel( &m-> m_pit3lfo2 );
m_pw1env1Knob-> setModel( &m-> m_pw1env1 );
m_pw1env2Knob-> setModel( &m-> m_pw1env2 );
m_pw1lfo1Knob-> setModel( &m-> m_pw1lfo1 );
m_pw1lfo2Knob-> setModel( &m-> m_pw1lfo2 );
m_sub3env1Knob-> setModel( &m-> m_sub3env1 );
m_sub3env2Knob-> setModel( &m-> m_sub3env2 );
m_sub3lfo1Knob-> setModel( &m-> m_sub3lfo1 );
m_sub3lfo2Knob-> setModel( &m-> m_sub3lfo2 );
}
void MonstroView::setWidgetBackground( QWidget * _widget, const QString & _pic )
{
_widget->setAutoFillBackground( true );
QPalette pal;
pal.setBrush( _widget->backgroundRole(),
PLUGIN_NAME::getIconPixmap( _pic.toLatin1().constData() ) );
_widget->setPalette( pal );
}
QWidget * MonstroView::setupOperatorsView( QWidget * _parent )
{
// operators view
auto view = new QWidget(_parent);
view-> setFixedSize( 250, 250 );
makeknob( m_osc1VolKnob, KNOBCOL1, O1ROW, tr( "Volume" ), "%", "osc1Knob" )
makeknob( m_osc1PanKnob, KNOBCOL2, O1ROW, tr( "Panning" ), "", "osc1Knob" )
makeknob( m_osc1CrsKnob, KNOBCOL3, O1ROW, tr( "Coarse detune" ), tr( " semitones" ), "osc1Knob" )
makeknob( m_osc1FtlKnob, KNOBCOL4, O1ROW, tr( "Fine tune left" ), tr( " cents" ), "osc1Knob" )
makeknob( m_osc1FtrKnob, KNOBCOL5, O1ROW, tr( "Fine tune right" ), tr( " cents" ), "osc1Knob" )
makeknob( m_osc1SpoKnob, KNOBCOL6, O1ROW, tr( "Stereo phase offset" ), tr( " deg" ), "osc1Knob" )
makeknob( m_osc1PwKnob, KNOBCOL7, O1ROW, tr( "Pulse width" ), "%", "osc1Knob" )
m_osc1VolKnob -> setVolumeKnob( true );
maketinyled( m_osc1SSRButton, 230, 34, tr( "Send sync on pulse rise" ) )
maketinyled( m_osc1SSFButton, 230, 44, tr( "Send sync on pulse fall" ) )
makeknob( m_osc2VolKnob, KNOBCOL1, O2ROW, tr( "Volume" ), "%", "osc2Knob" )
makeknob( m_osc2PanKnob, KNOBCOL2, O2ROW, tr( "Panning" ), "", "osc2Knob" )
makeknob( m_osc2CrsKnob, KNOBCOL3, O2ROW, tr( "Coarse detune" ), tr( " semitones" ), "osc2Knob" )
makeknob( m_osc2FtlKnob, KNOBCOL4, O2ROW, tr( "Fine tune left" ), tr( " cents" ), "osc2Knob" )
makeknob( m_osc2FtrKnob, KNOBCOL5, O2ROW, tr( "Fine tune right" ), tr( " cents" ), "osc2Knob" )
makeknob( m_osc2SpoKnob, KNOBCOL6, O2ROW, tr( "Stereo phase offset" ), tr( " deg" ), "osc2Knob" )
m_osc2VolKnob -> setVolumeKnob( true );
m_osc2WaveBox = new ComboBox( view );
m_osc2WaveBox -> setGeometry( 204, O2ROW + 7, 42, ComboBox::DEFAULT_HEIGHT );
maketinyled( m_osc2SyncHButton, 212, O2ROW - 3, tr( "Hard sync oscillator 2" ) )
maketinyled( m_osc2SyncRButton, 191, O2ROW - 3, tr( "Reverse sync oscillator 2" ) )
makeknob( m_osc3VolKnob, KNOBCOL1, O3ROW, tr( "Volume" ), "%", "osc3Knob" )
makeknob( m_osc3PanKnob, KNOBCOL2, O3ROW, tr( "Panning" ), "", "osc3Knob" )
makeknob( m_osc3CrsKnob, KNOBCOL3, O3ROW, tr( "Coarse detune" ), tr( " semitones" ), "osc3Knob" )
makeknob( m_osc3SpoKnob, KNOBCOL4, O3ROW, tr( "Stereo phase offset" ), tr( " deg" ), "osc3Knob" )
makeknob( m_osc3SubKnob, KNOBCOL5, O3ROW, tr( "Sub-osc mix" ), "", "osc3Knob" )
m_osc3VolKnob -> setVolumeKnob( true );
m_osc3Wave1Box = new ComboBox( view );
m_osc3Wave1Box -> setGeometry( 160, O3ROW + 7, 42, ComboBox::DEFAULT_HEIGHT );
m_osc3Wave2Box = new ComboBox( view );
m_osc3Wave2Box -> setGeometry( 204, O3ROW + 7, 42, ComboBox::DEFAULT_HEIGHT );
maketinyled( m_osc3SyncHButton, 212, O3ROW - 3, tr( "Hard sync oscillator 3" ) )
maketinyled( m_osc3SyncRButton, 191, O3ROW - 3, tr( "Reverse sync oscillator 3" ) )
m_lfo1WaveBox = new ComboBox( view );
m_lfo1WaveBox -> setGeometry( 2, LFOROW + 7, 42, ComboBox::DEFAULT_HEIGHT );
maketsknob( m_lfo1AttKnob, LFOCOL1, LFOROW, tr( "Attack" ), " ms", "lfoKnob" )
maketsknob( m_lfo1RateKnob, LFOCOL2, LFOROW, tr( "Rate" ), " ms", "lfoKnob" )
makeknob( m_lfo1PhsKnob, LFOCOL3, LFOROW, tr( "Phase" ), tr( " deg" ), "lfoKnob" )
m_lfo2WaveBox = new ComboBox( view );
m_lfo2WaveBox -> setGeometry( 127, LFOROW + 7, 42, ComboBox::DEFAULT_HEIGHT );
maketsknob(m_lfo2AttKnob, LFOCOL4, LFOROW, tr("Attack"), " ms", "lfoKnob")
maketsknob(m_lfo2RateKnob, LFOCOL5, LFOROW, tr("Rate"), " ms", "lfoKnob")
makeknob(m_lfo2PhsKnob, LFOCOL6, LFOROW, tr("Phase"), tr(" deg"), "lfoKnob")
maketsknob(m_env1PreKnob, KNOBCOL1, E1ROW, tr("Pre-delay"), " ms", "envKnob")
maketsknob(m_env1AttKnob, KNOBCOL2, E1ROW, tr("Attack"), " ms", "envKnob")
maketsknob(m_env1HoldKnob, KNOBCOL3, E1ROW, tr("Hold"), " ms", "envKnob")
maketsknob(m_env1DecKnob, KNOBCOL4, E1ROW, tr("Decay"), " ms", "envKnob")
makeknob(m_env1SusKnob, KNOBCOL5, E1ROW, tr("Sustain"), "", "envKnob")
maketsknob(m_env1RelKnob, KNOBCOL6, E1ROW, tr("Release"), " ms", "envKnob")
makeknob(m_env1SlopeKnob, KNOBCOL7, E1ROW, tr("Slope"), "", "envKnob")
maketsknob(m_env2PreKnob, KNOBCOL1, E2ROW, tr("Pre-delay"), " ms", "envKnob")
maketsknob(m_env2AttKnob, KNOBCOL2, E2ROW, tr("Attack"), " ms", "envKnob")
maketsknob(m_env2HoldKnob, KNOBCOL3, E2ROW, tr("Hold"), " ms", "envKnob")
maketsknob(m_env2DecKnob, KNOBCOL4, E2ROW, tr("Decay"), " ms", "envKnob")
makeknob(m_env2SusKnob, KNOBCOL5, E2ROW, tr("Sustain"), "", "envKnob")
maketsknob(m_env2RelKnob, KNOBCOL6, E2ROW, tr("Release"), " ms", "envKnob")
makeknob(m_env2SlopeKnob, KNOBCOL7, E2ROW, tr("Slope"), "", "envKnob")
// mod selector
auto m_mixButton = new PixmapButton(view, nullptr);
m_mixButton -> move( 225, 185 );
m_mixButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "mix_active" ) );
m_mixButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "mix_inactive" ) );
m_mixButton->setToolTip(tr("Mix osc 2 with osc 3"));
auto m_amButton = new PixmapButton(view, nullptr);
m_amButton -> move( 225, 185 + 15 );
m_amButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "am_active" ) );
m_amButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "am_inactive" ) );
m_amButton->setToolTip(tr("Modulate amplitude of osc 3 by osc 2"));
auto m_fmButton = new PixmapButton(view, nullptr);
m_fmButton -> move( 225, 185 + 15*2 );
m_fmButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "fm_active" ) );
m_fmButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "fm_inactive" ) );
m_fmButton->setToolTip(tr("Modulate frequency of osc 3 by osc 2"));
auto m_pmButton = new PixmapButton(view, nullptr);
m_pmButton -> move( 225, 185 + 15*3 );
m_pmButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "pm_active" ) );
m_pmButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "pm_inactive" ) );
m_pmButton->setToolTip(tr("Modulate phase of osc 3 by osc 2"));
m_o23ModGroup = new automatableButtonGroup( view );
m_o23ModGroup-> addButton( m_mixButton );
m_o23ModGroup-> addButton( m_amButton );
m_o23ModGroup-> addButton( m_fmButton );
m_o23ModGroup-> addButton( m_pmButton );
return( view );
}
QWidget * MonstroView::setupMatrixView( QWidget * _parent )
{
// matrix view
auto view = new QWidget(_parent);
view-> setFixedSize( 250, 250 );
makeknob( m_vol1env1Knob, MATCOL1, MATROW1, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol1env2Knob, MATCOL2, MATROW1, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol1lfo1Knob, MATCOL3, MATROW1, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol1lfo2Knob, MATCOL4, MATROW1, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol2env1Knob, MATCOL1, MATROW3, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol2env2Knob, MATCOL2, MATROW3, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol2lfo1Knob, MATCOL3, MATROW3, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol2lfo2Knob, MATCOL4, MATROW3, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol3env1Knob, MATCOL1, MATROW5, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol3env2Knob, MATCOL2, MATROW5, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol3lfo1Knob, MATCOL3, MATROW5, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_vol3lfo2Knob, MATCOL4, MATROW5, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs1env1Knob, MATCOL1, MATROW2, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs1env2Knob, MATCOL2, MATROW2, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs1lfo1Knob, MATCOL3, MATROW2, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs1lfo2Knob, MATCOL4, MATROW2, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs2env1Knob, MATCOL1, MATROW4, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs2env2Knob, MATCOL2, MATROW4, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs2lfo1Knob, MATCOL3, MATROW4, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs2lfo2Knob, MATCOL4, MATROW4, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs3env1Knob, MATCOL1, MATROW6, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs3env2Knob, MATCOL2, MATROW6, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs3lfo1Knob, MATCOL3, MATROW6, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_phs3lfo2Knob, MATCOL4, MATROW6, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit1env1Knob, MATCOL5, MATROW1, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit1env2Knob, MATCOL6, MATROW1, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit1lfo1Knob, MATCOL7, MATROW1, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit1lfo2Knob, MATCOL8, MATROW1, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit2env1Knob, MATCOL5, MATROW3, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit2env2Knob, MATCOL6, MATROW3, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit2lfo1Knob, MATCOL7, MATROW3, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit2lfo2Knob, MATCOL8, MATROW3, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit3env1Knob, MATCOL5, MATROW5, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit3env2Knob, MATCOL6, MATROW5, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit3lfo1Knob, MATCOL7, MATROW5, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pit3lfo2Knob, MATCOL8, MATROW5, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pw1env1Knob, MATCOL5, MATROW2, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pw1env2Knob, MATCOL6, MATROW2, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pw1lfo1Knob, MATCOL7, MATROW2, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_pw1lfo2Knob, MATCOL8, MATROW2, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_sub3env1Knob, MATCOL5, MATROW6, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_sub3env2Knob, MATCOL6, MATROW6, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_sub3lfo1Knob, MATCOL7, MATROW6, tr( "Modulation amount" ), "", "matrixKnob" )
makeknob( m_sub3lfo2Knob, MATCOL8, MATROW6, tr( "Modulation amount" ), "", "matrixKnob" )
return( view );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return new MonstroInstrument( static_cast<InstrumentTrack *>( m ) );
}
}
} // namespace lmms
| 66,951
|
C++
|
.cpp
| 1,533
| 40.904762
| 122
| 0.634763
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,700
|
SlicerTWaveform.cpp
|
LMMS_lmms/plugins/SlicerT/SlicerTWaveform.cpp
|
/*
* SlicerTWaveform.cpp - slice editor for SlicerT
*
* Copyright (c) 2023 Daniel Kauss Serna <daniel.kauss.serna@gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SlicerTWaveform.h"
#include <QBitmap>
#include <qpainterpath.h>
#include "SampleWaveform.h"
#include "SlicerT.h"
#include "SlicerTView.h"
#include "embed.h"
namespace lmms {
namespace gui {
// waveform colors
static QColor s_emptyColor = QColor(0, 0, 0, 0);
static QColor s_waveformColor = QColor(123, 49, 212); // color of outer waveform
static QColor s_waveformSeekerBgColor = QColor(0, 0, 0, 255);
static QColor s_waveformEditorBgColor = QColor(15, 15, 15, 255);
static QColor s_waveformMaskColor = QColor(151, 65, 255); // update this if s_waveformColor changes
static QColor s_waveformInnerColor = QColor(183, 124, 255); // color of inner waveform
// now playing colors
static QColor s_playColor = QColor(255, 255, 255, 200); // now playing line
static QColor s_playHighlightColor = QColor(255, 255, 255, 70); // now playing note marker
// slice markers
static QColor s_sliceColor = QColor(218, 193, 255); // color of slice marker
static QColor s_sliceShadowColor = QColor(136, 120, 158); // color of dark side of slice marker
static QColor s_sliceHighlightColor = QColor(255, 255, 255); // color of highlighted slice marker
// seeker rect colors
static QColor s_seekerColor = QColor(178, 115, 255); // outline of seeker
static QColor s_seekerHighlightColor = QColor(178, 115, 255, 100); // inside of seeker
static QColor s_seekerShadowColor = QColor(0, 0, 0, 120); // color used for darkening outside seeker
// decor colors
static QColor s_editorBounding = QColor(53, 22, 90); // color of the editor bounding box
static QColor s_gradientEnd = QColor(29, 16, 47); // end color of the seeker gradient
SlicerTWaveform::SlicerTWaveform(int totalWidth, int totalHeight, SlicerT* instrument, QWidget* parent)
: QWidget(parent)
, m_width(totalWidth)
, m_height(totalHeight)
, m_seekerHeight(40)
, m_seekerWidth(totalWidth - s_seekerHorMargin * 2)
, m_editorHeight(totalHeight - m_seekerHeight - s_middleMargin - s_seekerVerMargin)
, m_editorWidth(totalWidth)
, m_sliceArrow(PLUGIN_NAME::getIconPixmap("slice_indicator_arrow"))
, m_seeker(QPixmap(m_seekerWidth, m_seekerHeight))
, m_seekerWaveform(QPixmap(m_seekerWidth, m_seekerHeight))
, m_editorWaveform(QPixmap(m_editorWidth, m_editorHeight - s_arrowHeight))
, m_sliceEditor(QPixmap(totalWidth, m_editorHeight))
, m_emptySampleIcon(embed::getIconPixmap("sample_track"))
, m_slicerTParent(instrument)
{
setMouseTracking(true);
m_seekerWaveform.fill(s_waveformSeekerBgColor);
m_editorWaveform.fill(s_waveformEditorBgColor);
connect(instrument, &SlicerT::isPlaying, this, &SlicerTWaveform::isPlaying);
connect(instrument, &SlicerT::dataChanged, this, &SlicerTWaveform::updateUI);
m_emptySampleIcon = m_emptySampleIcon.createMaskFromColor(QColor(255, 255, 255), Qt::MaskMode::MaskOutColor);
m_updateTimer.start();
updateUI();
}
void SlicerTWaveform::resizeEvent(QResizeEvent* event)
{
m_width = width();
m_height = height();
m_seekerWidth = m_width - s_seekerHorMargin * 2;
/* m_seekerHeight = m_height * 0.33f; */
m_editorWidth = m_width;
m_editorHeight = m_height - m_seekerHeight - s_middleMargin - s_seekerVerMargin;
m_seeker = QPixmap(m_seekerWidth, m_seekerHeight);
m_seekerWaveform = QPixmap(m_seekerWidth, m_seekerHeight);
m_editorWaveform = QPixmap(m_editorWidth, m_editorHeight - s_arrowHeight);
m_sliceEditor = QPixmap(m_width, m_editorHeight);
updateUI();
}
void SlicerTWaveform::drawSeekerWaveform()
{
m_seekerWaveform.fill(s_emptyColor);
if (m_slicerTParent->m_originalSample.sampleSize() <= 1) { return; }
QPainter brush(&m_seekerWaveform);
brush.setPen(s_waveformColor);
const auto& sample = m_slicerTParent->m_originalSample;
const auto waveform
= SampleWaveform::Parameters{sample.data(), sample.sampleSize(), sample.amplification(), sample.reversed()};
const auto rect = QRect(0, 0, m_seekerWaveform.width(), m_seekerWaveform.height());
SampleWaveform::visualize(waveform, brush, rect);
// increase brightness in inner color
QBitmap innerMask = m_seekerWaveform.createMaskFromColor(s_waveformMaskColor, Qt::MaskMode::MaskOutColor);
brush.setPen(s_waveformInnerColor);
brush.drawPixmap(0, 0, innerMask);
}
void SlicerTWaveform::drawSeeker()
{
m_seeker.fill(s_waveformSeekerBgColor);
if (m_slicerTParent->m_originalSample.sampleSize() <= 1) { return; }
QPainter brush(&m_seeker);
brush.drawPixmap(0, 0, m_seekerWaveform);
brush.setPen(s_sliceColor);
for (float sliceValue : m_slicerTParent->m_slicePoints)
{
float xPos = sliceValue * m_seekerWidth;
brush.drawLine(xPos, 0, xPos, m_seekerHeight);
}
float seekerStartPosX = m_seekerStart * m_seekerWidth;
float seekerEndPosX = m_seekerEnd * m_seekerWidth;
float seekerMiddleWidth = (m_seekerEnd - m_seekerStart) * m_seekerWidth;
float noteCurrentPosX = m_noteCurrent * m_seekerWidth;
float noteStartPosX = m_noteStart * m_seekerWidth;
float noteEndPosX = (m_noteEnd - m_noteStart) * m_seekerWidth;
brush.setPen(s_playColor);
brush.drawLine(noteCurrentPosX, 0, noteCurrentPosX, m_seekerHeight);
brush.fillRect(noteStartPosX, 0, noteEndPosX, m_seekerHeight, s_playHighlightColor);
brush.fillRect(seekerStartPosX, 0, seekerMiddleWidth - 1, m_seekerHeight, s_seekerHighlightColor);
brush.fillRect(0, 0, seekerStartPosX, m_seekerHeight, s_seekerShadowColor);
brush.fillRect(seekerEndPosX - 1, 0, m_seekerWidth, m_seekerHeight, s_seekerShadowColor);
brush.setPen(QPen(s_seekerColor, 1));
brush.drawRoundedRect(seekerStartPosX, 0, seekerMiddleWidth - 1, m_seekerHeight - 1, 2, 2);
}
void SlicerTWaveform::drawEditorWaveform()
{
m_editorWaveform.fill(s_emptyColor);
if (m_slicerTParent->m_originalSample.sampleSize() <= 1) { return; }
QPainter brush(&m_editorWaveform);
size_t startFrame = m_seekerStart * m_slicerTParent->m_originalSample.sampleSize();
size_t endFrame = m_seekerEnd * m_slicerTParent->m_originalSample.sampleSize();
brush.setPen(s_waveformColor);
float zoomOffset = (m_editorHeight - m_zoomLevel * m_editorHeight) / 2;
const auto& sample = m_slicerTParent->m_originalSample;
const auto waveform = SampleWaveform::Parameters{
sample.data() + startFrame, endFrame - startFrame, sample.amplification(), sample.reversed()};
const auto rect = QRect(0, zoomOffset, m_editorWidth, m_zoomLevel * m_editorHeight);
SampleWaveform::visualize(waveform, brush, rect);
// increase brightness in inner color
QBitmap innerMask = m_editorWaveform.createMaskFromColor(s_waveformMaskColor, Qt::MaskMode::MaskOutColor);
brush.setPen(s_waveformInnerColor);
brush.drawPixmap(0, 0, innerMask);
}
void SlicerTWaveform::drawEditor()
{
m_sliceEditor.fill(s_waveformEditorBgColor);
QPainter brush(&m_sliceEditor);
// No sample loaded
if (m_slicerTParent->m_originalSample.sampleSize() <= 1)
{
brush.setPen(s_playHighlightColor);
brush.setFont(QFont(brush.font().family(), 9.0f, -1, false));
brush.drawText(
m_editorWidth / 2 - 100, m_editorHeight / 2 - 110, 200, 200, Qt::AlignCenter, tr("Click to load sample"));
int iconOffsetX = m_emptySampleIcon.width() / 2.0f;
int iconOffsetY = m_emptySampleIcon.height() / 2.0f - 13;
brush.drawPixmap(m_editorWidth / 2.0f - iconOffsetX, m_editorHeight / 2.0f - iconOffsetY, m_emptySampleIcon);
return;
}
float startFrame = m_seekerStart;
float endFrame = m_seekerEnd;
float numFramesToDraw = endFrame - startFrame;
// playback state
float noteCurrentPos = (m_noteCurrent - m_seekerStart) / (m_seekerEnd - m_seekerStart) * m_editorWidth;
float noteStartPos = (m_noteStart - m_seekerStart) / (m_seekerEnd - m_seekerStart) * m_editorWidth;
float noteLength = (m_noteEnd - m_noteStart) / (m_seekerEnd - m_seekerStart) * m_editorWidth;
brush.setPen(s_playHighlightColor);
int middleY = m_editorHeight / 2 + s_arrowHeight;
brush.drawLine(0, middleY, m_editorWidth, middleY);
brush.drawPixmap(0, s_arrowHeight, m_editorWaveform);
brush.fillRect(0, 0, m_editorWidth, s_arrowHeight, s_waveformSeekerBgColor);
brush.setPen(s_playColor);
brush.drawLine(noteCurrentPos, s_arrowHeight, noteCurrentPos, m_editorHeight);
brush.fillRect(noteStartPos, s_arrowHeight, noteLength, m_editorHeight, s_playHighlightColor);
brush.setPen(QPen(s_sliceColor, 2));
for (auto i = std::size_t{0}; i < m_slicerTParent->m_slicePoints.size(); i++)
{
float xPos = (m_slicerTParent->m_slicePoints.at(i) - startFrame) / numFramesToDraw * m_editorWidth;
if (i == static_cast<std::size_t>(m_closestSlice))
{
brush.setPen(QPen(s_sliceHighlightColor, 2));
brush.drawLine(xPos, 0, xPos, m_editorHeight);
brush.drawPixmap(xPos - m_sliceArrow.width() / 2.0f, 0, m_sliceArrow);
continue;
}
else
{
brush.setPen(QPen(s_sliceShadowColor, 1));
brush.drawLine(xPos - 1, 0, xPos - 1, m_editorHeight);
brush.setPen(QPen(s_sliceColor, 1));
brush.drawLine(xPos, 0, xPos, m_editorHeight);
brush.drawPixmap(xPos - m_sliceArrow.width() / 2.0f, 0, m_sliceArrow);
}
}
// decor
brush.setPen(s_editorBounding);
brush.drawLine(0, s_arrowHeight, m_editorWidth, s_arrowHeight);
brush.drawLine(0, m_editorHeight - 1, m_editorWidth, m_editorHeight - 1);
}
void SlicerTWaveform::isPlaying(float current, float start, float end)
{
if (!m_updateTimer.hasExpired(s_minMilisPassed)) { return; }
m_noteCurrent = current;
m_noteStart = start;
m_noteEnd = end;
drawSeeker();
drawEditor();
update();
m_updateTimer.restart();
}
// this should only be called if one of the waveforms has to update
void SlicerTWaveform::updateUI()
{
drawSeekerWaveform();
drawEditorWaveform();
drawSeeker();
drawEditor();
update();
}
// updates the closest object and changes the cursor respectivly
void SlicerTWaveform::updateClosest(QMouseEvent* me)
{
float normalizedClickSeeker = static_cast<float>(me->x() - s_seekerHorMargin) / m_seekerWidth;
float normalizedClickEditor = static_cast<float>(me->x()) / m_editorWidth;
m_closestObject = UIObjects::Nothing;
m_closestSlice = -1;
if (me->y() < m_seekerHeight)
{
if (std::abs(normalizedClickSeeker - m_seekerStart) < s_distanceForClick)
{
m_closestObject = UIObjects::SeekerStart;
}
else if (std::abs(normalizedClickSeeker - m_seekerEnd) < s_distanceForClick)
{
m_closestObject = UIObjects::SeekerEnd;
}
else if (normalizedClickSeeker > m_seekerStart && normalizedClickSeeker < m_seekerEnd)
{
m_closestObject = UIObjects::SeekerMiddle;
}
}
else
{
m_closestSlice = -1;
float startFrame = m_seekerStart;
float endFrame = m_seekerEnd;
for (auto i = std::size_t{0}; i < m_slicerTParent->m_slicePoints.size(); i++)
{
float sliceIndex = m_slicerTParent->m_slicePoints.at(i);
float xPos = (sliceIndex - startFrame) / (endFrame - startFrame);
if (std::abs(xPos - normalizedClickEditor) < s_distanceForClick)
{
m_closestObject = UIObjects::SlicePoint;
m_closestSlice = i;
}
}
}
updateCursor();
drawSeeker();
drawEditor();
update();
}
void SlicerTWaveform::updateCursor()
{
if (m_closestObject == UIObjects::SlicePoint || m_closestObject == UIObjects::SeekerStart
|| m_closestObject == UIObjects::SeekerEnd)
{
setCursor(Qt::SizeHorCursor);
}
else if (m_closestObject == UIObjects::SeekerMiddle && m_seekerEnd - m_seekerStart != 1.0f)
{
setCursor(Qt::SizeAllCursor);
}
else { setCursor(Qt::ArrowCursor); }
}
// handles deletion, reset and middles seeker
void SlicerTWaveform::mousePressEvent(QMouseEvent* me)
{
switch (me->button())
{
case Qt::MouseButton::MiddleButton:
m_seekerStart = 0;
m_seekerEnd = 1;
m_zoomLevel = 1;
drawEditorWaveform();
break;
case Qt::MouseButton::LeftButton:
if (m_slicerTParent->m_originalSample.sampleSize() <= 1) { static_cast<SlicerTView*>(parent())->openFiles(); }
// update seeker middle for correct movement
m_seekerMiddle = static_cast<float>(me->x() - s_seekerHorMargin) / m_seekerWidth;
break;
case Qt::MouseButton::RightButton:
if (m_slicerTParent->m_slicePoints.size() > 2 && m_closestObject == UIObjects::SlicePoint)
{
m_slicerTParent->m_slicePoints.erase(m_slicerTParent->m_slicePoints.begin() + m_closestSlice);
}
break;
default:;
}
updateClosest(me);
}
// sort slices after moving and remove draggable object
void SlicerTWaveform::mouseReleaseEvent(QMouseEvent* me)
{
std::sort(m_slicerTParent->m_slicePoints.begin(), m_slicerTParent->m_slicePoints.end());
updateClosest(me);
}
// this handles dragging and mouse cursor changes
// what is being dragged is determined in mousePressEvent
void SlicerTWaveform::mouseMoveEvent(QMouseEvent* me)
{
// if no button pressed, update closest and cursor
if (me->buttons() == Qt::MouseButton::NoButton)
{
updateClosest(me);
return;
}
float normalizedClickSeeker = static_cast<float>(me->x() - s_seekerHorMargin) / m_seekerWidth;
float normalizedClickEditor = static_cast<float>(me->x()) / m_editorWidth;
float distStart = m_seekerStart - m_seekerMiddle;
float distEnd = m_seekerEnd - m_seekerMiddle;
float startFrame = m_seekerStart;
float endFrame = m_seekerEnd;
switch (m_closestObject)
{
case UIObjects::SeekerStart:
m_seekerStart = std::clamp(normalizedClickSeeker, 0.0f, m_seekerEnd - s_minSeekerDistance);
drawEditorWaveform();
break;
case UIObjects::SeekerEnd:
m_seekerEnd = std::clamp(normalizedClickSeeker, m_seekerStart + s_minSeekerDistance, 1.0f);
drawEditorWaveform();
break;
case UIObjects::SeekerMiddle:
m_seekerMiddle = normalizedClickSeeker;
if (m_seekerMiddle + distStart >= 0 && m_seekerMiddle + distEnd <= 1)
{
m_seekerStart = m_seekerMiddle + distStart;
m_seekerEnd = m_seekerMiddle + distEnd;
}
drawEditorWaveform();
break;
case UIObjects::SlicePoint:
if (m_closestSlice == -1) { break; }
m_slicerTParent->m_slicePoints.at(m_closestSlice)
= startFrame + normalizedClickEditor * (endFrame - startFrame);
m_slicerTParent->m_slicePoints.at(m_closestSlice)
= std::clamp(m_slicerTParent->m_slicePoints.at(m_closestSlice), 0.0f, 1.0f);
break;
case UIObjects::Nothing:
break;
}
// dont update closest, and update seeker waveform
drawSeeker();
drawEditor();
update();
}
void SlicerTWaveform::mouseDoubleClickEvent(QMouseEvent* me)
{
if (me->button() != Qt::MouseButton::LeftButton || me->y() < m_seekerHeight) { return; }
float normalizedClickEditor = static_cast<float>(me->x()) / m_editorWidth;
float startFrame = m_seekerStart;
float endFrame = m_seekerEnd;
float slicePosition = startFrame + normalizedClickEditor * (endFrame - startFrame);
m_slicerTParent->m_slicePoints.insert(m_slicerTParent->m_slicePoints.begin(), slicePosition);
std::sort(m_slicerTParent->m_slicePoints.begin(), m_slicerTParent->m_slicePoints.end());
}
void SlicerTWaveform::wheelEvent(QWheelEvent* we)
{
m_zoomLevel += we->angleDelta().y() / 360.0f * s_zoomSensitivity;
m_zoomLevel = std::max(0.0f, m_zoomLevel);
updateUI();
}
void SlicerTWaveform::paintEvent(QPaintEvent* pe)
{
QPainter p(this);
// top gradient
QLinearGradient bgGrad(QPointF(0, 0), QPointF(width(), height() - m_editorHeight));
bgGrad.setColorAt(0, s_waveformEditorBgColor);
bgGrad.setColorAt(1, s_gradientEnd);
p.setBrush(bgGrad);
p.setPen(s_emptyColor);
p.drawRect(QRect(0, 0, width(), height()));
p.setBrush(QBrush());
// seeker
QPainterPath path;
path.addRoundedRect(
QRect(s_seekerHorMargin - 2, s_seekerVerMargin - 2, m_seekerWidth + 4, m_seekerHeight + 4), 4, 4);
p.fillPath(path, s_seekerShadowColor);
p.drawPixmap(s_seekerHorMargin, s_seekerVerMargin, m_seeker);
// editor
p.setPen(QColor(s_waveformColor));
p.drawPixmap(0, m_seekerHeight + s_middleMargin + s_seekerVerMargin, m_sliceEditor);
}
} // namespace gui
} // namespace lmms
| 16,508
|
C++
|
.cpp
| 407
| 38.302211
| 112
| 0.752776
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,701
|
SlicerT.cpp
|
LMMS_lmms/plugins/SlicerT/SlicerT.cpp
|
/*
* SlicerT.cpp - simple slicer plugin
*
* Copyright (c) 2023 Daniel Kauss Serna <daniel.kauss.serna@gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SlicerT.h"
#include <QDomElement>
#include <cmath>
#include <fftw3.h>
#include "Engine.h"
#include "InstrumentTrack.h"
#include "PathUtil.h"
#include "SampleLoader.h"
#include "Song.h"
#include "embed.h"
#include "lmms_constants.h"
#include "plugin_export.h"
namespace lmms {
extern "C" {
Plugin::Descriptor PLUGIN_EXPORT slicert_plugin_descriptor = {
LMMS_STRINGIFY(PLUGIN_NAME),
"SlicerT",
QT_TRANSLATE_NOOP("PluginBrowser", "Basic Slicer"),
"Daniel Kauss Serna <daniel.kauss.serna@gmail.com>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
};
} // end extern
// ################################# SlicerT ####################################
SlicerT::SlicerT(InstrumentTrack* instrumentTrack)
: Instrument(instrumentTrack, &slicert_plugin_descriptor)
, m_noteThreshold(0.6f, 0.0f, 2.0f, 0.01f, this, tr("Note threshold"))
, m_fadeOutFrames(10.0f, 0.0f, 100.0f, 0.1f, this, tr("FadeOut"))
, m_originalBPM(1, 1, 999, this, tr("Original bpm"))
, m_sliceSnap(this, tr("Slice snap"))
, m_enableSync(false, this, tr("BPM sync"))
, m_originalSample()
, m_parentTrack(instrumentTrack)
{
m_sliceSnap.addItem("Off");
m_sliceSnap.addItem("1/1");
m_sliceSnap.addItem("1/2");
m_sliceSnap.addItem("1/4");
m_sliceSnap.addItem("1/8");
m_sliceSnap.addItem("1/16");
m_sliceSnap.addItem("1/32");
m_sliceSnap.setValue(0);
}
void SlicerT::playNote(NotePlayHandle* handle, SampleFrame* workingBuffer)
{
if (m_originalSample.sampleSize() <= 1) { return; }
int noteIndex = handle->key() - m_parentTrack->baseNote();
const fpp_t frames = handle->framesLeftForCurrentPeriod();
const f_cnt_t offset = handle->noteOffset();
const int bpm = Engine::getSong()->getTempo();
const float pitchRatio = 1 / std::exp2(m_parentTrack->pitchModel()->value() / 1200);
float speedRatio = static_cast<float>(m_originalBPM.value()) / bpm;
if (!m_enableSync.value()) { speedRatio = 1; }
speedRatio *= pitchRatio;
speedRatio *= Engine::audioEngine()->outputSampleRate() / static_cast<float>(m_originalSample.sampleRate());
float sliceStart, sliceEnd;
if (noteIndex == 0) // full sample at base note
{
sliceStart = 0;
sliceEnd = 1;
}
else if (noteIndex > 0 && static_cast<std::size_t>(noteIndex) < m_slicePoints.size())
{
noteIndex -= 1;
sliceStart = m_slicePoints[noteIndex];
sliceEnd = m_slicePoints[noteIndex + 1];
}
else
{
emit isPlaying(-1, 0, 0);
return;
}
if (!handle->m_pluginData) { handle->m_pluginData = new PlaybackState(sliceStart); }
auto playbackState = static_cast<PlaybackState*>(handle->m_pluginData);
float noteDone = playbackState->noteDone();
float noteLeft = sliceEnd - noteDone;
if (noteLeft > 0)
{
int noteFrame = noteDone * m_originalSample.sampleSize();
SRC_STATE* resampleState = playbackState->resamplingState();
SRC_DATA resampleData;
resampleData.data_in = (m_originalSample.data() + noteFrame)->data();
resampleData.data_out = (workingBuffer + offset)->data();
resampleData.input_frames = noteLeft * m_originalSample.sampleSize();
resampleData.output_frames = frames;
resampleData.src_ratio = speedRatio;
src_process(resampleState, &resampleData);
float nextNoteDone = noteDone + frames * (1.0f / speedRatio) / m_originalSample.sampleSize();
playbackState->setNoteDone(nextNoteDone);
// exponential fade out, applyRelease() not used since it extends the note length
int fadeOutFrames = m_fadeOutFrames.value() / 1000.0f * Engine::audioEngine()->outputSampleRate();
int noteFramesLeft = noteLeft * m_originalSample.sampleSize() * speedRatio;
for (auto i = std::size_t{0}; i < frames; i++)
{
float fadeValue = static_cast<float>(noteFramesLeft - static_cast<int>(i)) / fadeOutFrames;
fadeValue = std::clamp(fadeValue, 0.0f, 1.0f);
fadeValue = cosinusInterpolate(0, 1, fadeValue);
workingBuffer[i + offset][0] *= fadeValue;
workingBuffer[i + offset][1] *= fadeValue;
}
emit isPlaying(noteDone, sliceStart, sliceEnd);
}
else { emit isPlaying(-1, 0, 0); }
}
void SlicerT::deleteNotePluginData(NotePlayHandle* handle)
{
delete static_cast<PlaybackState*>(handle->m_pluginData);
emit isPlaying(-1, 0, 0);
}
// uses the spectral flux to determine the change in magnitude
// resources:
// http://www.iro.umontreal.ca/~pift6080/H09/documents/papers/bello_onset_tutorial.pdf
void SlicerT::findSlices()
{
if (m_originalSample.sampleSize() <= 1) { return; }
m_slicePoints = {};
const int windowSize = 512;
const float minBeatLength = 0.05f; // in seconds, ~ 1/4 length at 220 bpm
int sampleRate = m_originalSample.sampleRate();
int minDist = sampleRate * minBeatLength;
float maxMag = -1;
std::vector<float> singleChannel(m_originalSample.sampleSize(), 0);
for (auto i = std::size_t{0}; i < m_originalSample.sampleSize(); i++)
{
singleChannel[i] = (m_originalSample.data()[i][0] + m_originalSample.data()[i][1]) / 2;
maxMag = std::max(maxMag, singleChannel[i]);
}
// normalize and find 0 crossings
std::vector<int> zeroCrossings;
float lastValue = 1;
for (auto i = std::size_t{0}; i < singleChannel.size(); i++)
{
singleChannel[i] /= maxMag;
if (sign(lastValue) != sign(singleChannel[i]))
{
zeroCrossings.push_back(i);
lastValue = singleChannel[i];
}
}
std::vector<float> prevMags(windowSize / 2, 0);
std::vector<float> fftIn(windowSize, 0);
std::array<fftwf_complex, windowSize> fftOut;
fftwf_plan fftPlan = fftwf_plan_dft_r2c_1d(windowSize, fftIn.data(), fftOut.data(), FFTW_MEASURE);
int lastPoint = -minDist - 1; // to always store 0 first
float spectralFlux = 0;
float prevFlux = 1E-10f; // small value, no divison by zero
for (int i = 0; i < static_cast<int>(singleChannel.size()) - windowSize; i += windowSize)
{
// fft
std::copy_n(singleChannel.data() + i, windowSize, fftIn.data());
fftwf_execute(fftPlan);
// calculate spectral flux in regard to last window
for (int j = 0; j < windowSize / 2; j++) // only use niquistic frequencies
{
float real = fftOut[j][0];
float imag = fftOut[j][1];
float magnitude = std::sqrt(real * real + imag * imag);
// using L2-norm (euclidean distance)
float diff = std::sqrt(std::pow(magnitude - prevMags[j], 2));
spectralFlux += diff;
prevMags[j] = magnitude;
}
if (spectralFlux / prevFlux > 1.0f + m_noteThreshold.value() && i - lastPoint > minDist)
{
m_slicePoints.push_back(i);
lastPoint = i;
if (m_slicePoints.size() > 128) { break; } // no more keys on the keyboard
}
prevFlux = spectralFlux;
spectralFlux = 1E-10f; // again for no divison by zero
}
m_slicePoints.push_back(m_originalSample.sampleSize());
for (float& sliceValue : m_slicePoints)
{
auto closestZeroCrossing = std::lower_bound(zeroCrossings.begin(), zeroCrossings.end(), sliceValue);
if (closestZeroCrossing == zeroCrossings.end()) { continue; }
if (std::abs(sliceValue - *closestZeroCrossing) < windowSize) { sliceValue = *closestZeroCrossing; }
}
float beatsPerMin = m_originalBPM.value() / 60.0f;
float samplesPerBeat = m_originalSample.sampleRate() / beatsPerMin * 4.0f;
int noteSnap = m_sliceSnap.value();
int sliceLock = samplesPerBeat / std::exp2(noteSnap + 1);
if (noteSnap == 0) { sliceLock = 1; }
for (float& sliceValue : m_slicePoints)
{
sliceValue += sliceLock / 2.f;
sliceValue -= static_cast<int>(sliceValue) % sliceLock;
}
m_slicePoints.erase(std::unique(m_slicePoints.begin(), m_slicePoints.end()), m_slicePoints.end());
for (float& sliceIndex : m_slicePoints)
{
sliceIndex /= m_originalSample.sampleSize();
}
m_slicePoints[0] = 0;
m_slicePoints[m_slicePoints.size() - 1] = 1;
emit dataChanged();
}
// find the bpm of the sample by assuming its in 4/4 time signature ,
// and lies in the 100 - 200 bpm range
void SlicerT::findBPM()
{
if (m_originalSample.sampleSize() <= 1) { return; }
float sampleRate = m_originalSample.sampleRate();
float totalFrames = m_originalSample.sampleSize();
float sampleLength = totalFrames / sampleRate;
float bpmEstimate = 240.0f / sampleLength;
while (bpmEstimate < 100)
{
bpmEstimate *= 2;
}
while (bpmEstimate > 200)
{
bpmEstimate /= 2;
}
m_originalBPM.setValue(bpmEstimate);
m_originalBPM.setInitValue(bpmEstimate);
}
std::vector<Note> SlicerT::getMidi()
{
std::vector<Note> outputNotes;
float speedRatio = static_cast<float>(m_originalBPM.value()) / Engine::getSong()->getTempo();
float outFrames = m_originalSample.sampleSize() * speedRatio;
float framesPerTick = Engine::framesPerTick();
float totalTicks = outFrames / framesPerTick;
float lastEnd = 0;
for (auto i = std::size_t{0}; i < m_slicePoints.size() - 1; i++)
{
float sliceStart = lastEnd;
float sliceEnd = totalTicks * m_slicePoints[i + 1];
Note sliceNote = Note();
sliceNote.setKey(i + m_parentTrack->baseNote() + 1);
sliceNote.setPos(sliceStart);
sliceNote.setLength(sliceEnd - sliceStart + 1); // + 1 so that the notes allign
outputNotes.push_back(sliceNote);
lastEnd = sliceEnd;
}
return outputNotes;
}
void SlicerT::updateFile(QString file)
{
if (auto buffer = gui::SampleLoader::createBufferFromFile(file)) { m_originalSample = Sample(std::move(buffer)); }
findBPM();
findSlices();
emit dataChanged();
}
void SlicerT::updateSlices()
{
findSlices();
}
void SlicerT::saveSettings(QDomDocument& document, QDomElement& element)
{
element.setAttribute("version", "1");
element.setAttribute("src", m_originalSample.sampleFile());
if (m_originalSample.sampleFile().isEmpty())
{
element.setAttribute("sampledata", m_originalSample.toBase64());
}
element.setAttribute("totalSlices", static_cast<int>(m_slicePoints.size()));
for (auto i = std::size_t{0}; i < m_slicePoints.size(); i++)
{
element.setAttribute(tr("slice_%1").arg(i), m_slicePoints[i]);
}
m_fadeOutFrames.saveSettings(document, element, "fadeOut");
m_noteThreshold.saveSettings(document, element, "threshold");
m_originalBPM.saveSettings(document, element, "origBPM");
m_enableSync.saveSettings(document, element, "syncEnable");
}
void SlicerT::loadSettings(const QDomElement& element)
{
if (auto srcFile = element.attribute("src"); !srcFile.isEmpty())
{
if (QFileInfo(PathUtil::toAbsolute(srcFile)).exists())
{
auto buffer = gui::SampleLoader::createBufferFromFile(srcFile);
m_originalSample = Sample(std::move(buffer));
}
else
{
QString message = tr("Sample not found: %1").arg(srcFile);
Engine::getSong()->collectError(message);
}
}
else if (auto sampleData = element.attribute("sampledata"); !sampleData.isEmpty())
{
auto buffer = gui::SampleLoader::createBufferFromBase64(sampleData);
m_originalSample = Sample(std::move(buffer));
}
if (!element.attribute("totalSlices").isEmpty())
{
int totalSlices = element.attribute("totalSlices").toInt();
m_slicePoints = {};
for (int i = 0; i < totalSlices; i++)
{
m_slicePoints.push_back(element.attribute(tr("slice_%1").arg(i)).toFloat());
}
}
m_fadeOutFrames.loadSettings(element, "fadeOut");
m_noteThreshold.loadSettings(element, "threshold");
m_originalBPM.loadSettings(element, "origBPM");
m_enableSync.loadSettings(element, "syncEnable");
emit dataChanged();
}
QString SlicerT::nodeName() const
{
return slicert_plugin_descriptor.name;
}
gui::PluginView* SlicerT::instantiateView(QWidget* parent)
{
return new gui::SlicerTView(this, parent);
}
extern "C" {
PLUGIN_EXPORT Plugin* lmms_plugin_main(Model* m, void*)
{
return new SlicerT(static_cast<InstrumentTrack*>(m));
}
} // extern
} // namespace lmms
| 12,413
|
C++
|
.cpp
| 343
| 33.836735
| 115
| 0.720357
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,702
|
SlicerTView.cpp
|
LMMS_lmms/plugins/SlicerT/SlicerTView.cpp
|
/*
* SlicerTView.cpp - controls the UI for slicerT
*
* Copyright (c) 2023 Daniel Kauss Serna <daniel.kauss.serna@gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SlicerTView.h"
#include <QDropEvent>
#include <qpixmap.h>
#include <qpushbutton.h>
#include "Clipboard.h"
#include "DataFile.h"
#include "InstrumentTrack.h"
#include "InstrumentView.h"
#include "PixmapButton.h"
#include "SampleLoader.h"
#include "SlicerT.h"
#include "StringPairDrag.h"
#include "Track.h"
#include "embed.h"
namespace lmms {
namespace gui {
SlicerTView::SlicerTView(SlicerT* instrument, QWidget* parent)
: InstrumentView(instrument, parent)
, m_slicerTParent(instrument)
, m_fullLogo(PLUGIN_NAME::getIconPixmap("full_logo"))
, m_background(PLUGIN_NAME::getIconPixmap("toolbox"))
{
// window settings
setAcceptDrops(true);
setAutoFillBackground(true);
setMaximumSize(QSize(10000, 10000));
setMinimumSize(QSize(516, 400));
m_wf = new SlicerTWaveform(248, 128, instrument, this);
m_wf->move(0, s_topBarHeight);
m_snapSetting = new ComboBox(this, tr("Slice snap"));
m_snapSetting->setGeometry(185, 200, 55, ComboBox::DEFAULT_HEIGHT);
m_snapSetting->setToolTip(tr("Set slice snapping for detection"));
m_snapSetting->setModel(&m_slicerTParent->m_sliceSnap);
m_syncToggle = new PixmapButton(this, tr("Sync sample"));
m_syncToggle->setActiveGraphic(PLUGIN_NAME::getIconPixmap("sync_active"));
m_syncToggle->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("sync_inactive"));
m_syncToggle->setCheckable(true);
m_syncToggle->setToolTip(tr("Enable BPM sync"));
m_syncToggle->setModel(&m_slicerTParent->m_enableSync);
m_bpmBox = new LcdSpinBox(3, "19purple", this);
m_bpmBox->setToolTip(tr("Original sample BPM"));
m_bpmBox->setModel(&m_slicerTParent->m_originalBPM);
m_noteThresholdKnob = createStyledKnob();
m_noteThresholdKnob->setToolTip(tr("Threshold used for slicing"));
m_noteThresholdKnob->setModel(&m_slicerTParent->m_noteThreshold);
m_fadeOutKnob = createStyledKnob();
m_fadeOutKnob->setToolTip(tr("Fade Out per note in milliseconds"));
m_fadeOutKnob->setModel(&m_slicerTParent->m_fadeOutFrames);
m_midiExportButton = new QPushButton(this);
m_midiExportButton->setIcon(PLUGIN_NAME::getIconPixmap("copy_midi"));
m_midiExportButton->setToolTip(tr("Copy midi pattern to clipboard"));
connect(m_midiExportButton, &PixmapButton::clicked, this, &SlicerTView::exportMidi);
m_folderButton = new PixmapButton(this);
m_folderButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("folder_icon"));
m_folderButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("folder_icon"));
m_folderButton->setToolTip(tr("Open sample selector"));
connect(m_folderButton, &PixmapButton::clicked, this, &SlicerTView::openFiles);
m_resetButton = new QPushButton(this);
m_resetButton->setIcon(PLUGIN_NAME::getIconPixmap("reset_slices"));
m_resetButton->setToolTip(tr("Reset slices"));
connect(m_resetButton, &PixmapButton::clicked, m_slicerTParent, &SlicerT::updateSlices);
update();
}
Knob* SlicerTView::createStyledKnob()
{
Knob* newKnob = new Knob(KnobType::Styled, this);
newKnob->setFixedSize(50, 40);
newKnob->setCenterPointX(24.0);
newKnob->setCenterPointY(15.0);
return newKnob;
}
// copied from piano roll
void SlicerTView::exportMidi()
{
using namespace Clipboard;
if (m_slicerTParent->m_originalSample.sampleSize() <= 1) { return; }
DataFile dataFile(DataFile::Type::ClipboardData);
QDomElement noteList = dataFile.createElement("note-list");
dataFile.content().appendChild(noteList);
auto notes = m_slicerTParent->getMidi();
if (notes.empty()) { return; }
TimePos startPos(notes.front().pos().getBar(), 0);
for (Note& note : notes)
{
note.setPos(note.pos(startPos));
note.saveState(dataFile, noteList);
}
copyString(dataFile.toString(), MimeType::Default);
}
void SlicerTView::openFiles()
{
const auto audioFile = SampleLoader::openAudioFile();
if (audioFile.isEmpty()) { return; }
m_slicerTParent->updateFile(audioFile);
}
// all the drag stuff is copied from AudioFileProcessor
void SlicerTView::dragEnterEvent(QDragEnterEvent* dee)
{
// For mimeType() and MimeType enum class
using namespace Clipboard;
if (dee->mimeData()->hasFormat(mimeType(MimeType::StringPair)))
{
QString txt = dee->mimeData()->data(mimeType(MimeType::StringPair));
if (txt.section(':', 0, 0) == QString("clip_%1").arg(static_cast<int>(Track::Type::Sample)))
{
dee->acceptProposedAction();
}
else if (txt.section(':', 0, 0) == "samplefile") { dee->acceptProposedAction(); }
else { dee->ignore(); }
}
else { dee->ignore(); }
}
void SlicerTView::dropEvent(QDropEvent* de)
{
QString type = StringPairDrag::decodeKey(de);
QString value = StringPairDrag::decodeValue(de);
if (type == "samplefile")
{
// set m_wf wave file
m_slicerTParent->updateFile(value);
return;
}
else if (type == QString("clip_%1").arg(static_cast<int>(Track::Type::Sample)))
{
DataFile dataFile(value.toUtf8());
m_slicerTParent->updateFile(dataFile.content().firstChild().toElement().attribute("src"));
de->accept();
return;
}
de->ignore();
}
void SlicerTView::paintEvent(QPaintEvent* pe)
{
QPainter brush(this);
brush.setFont(QFont(brush.font().family(), 7, -1, false));
int boxTopY = height() - s_bottomBoxHeight;
// --- backgrounds and limiters
brush.drawPixmap(QRect(0, boxTopY, s_leftBoxWidth, s_bottomBoxHeight), m_background); // left
brush.fillRect(
QRect(s_leftBoxWidth, boxTopY, width() - s_leftBoxWidth, s_bottomBoxHeight), QColor(23, 26, 31)); // right
brush.fillRect(QRect(0, 0, width(), s_topBarHeight), QColor(20, 23, 27)); // top
// top bar dividers
brush.setPen(QColor(56, 58, 60));
brush.drawLine(0, s_topBarHeight - 1, width(), s_topBarHeight - 1);
brush.drawLine(0, 0, width(), 0);
// sample name divider
brush.setPen(QColor(56, 58, 60));
brush.drawLine(0, boxTopY, width(), boxTopY);
// boxes divider
brush.setPen(QColor(56, 24, 94));
brush.drawLine(s_leftBoxWidth, boxTopY, s_leftBoxWidth, height());
// --- top bar
brush.drawPixmap(
QRect(10, (s_topBarHeight - m_fullLogo.height()) / 2, m_fullLogo.width(), m_fullLogo.height()), m_fullLogo);
int y1_text = m_y1 + 27;
// --- left box
brush.setPen(QColor(255, 255, 255));
brush.drawText(s_x1 - 25, y1_text, s_textBoxWidth, s_textBoxHeight, Qt::AlignCenter, tr("Threshold"));
brush.drawText(s_x2 - 25, y1_text, s_textBoxWidth, s_textBoxHeight, Qt::AlignCenter, tr("Fade Out"));
brush.drawText(s_x3 - 25, y1_text, s_textBoxWidth, s_textBoxHeight, Qt::AlignCenter, tr("Reset"));
brush.drawText(s_x4 - 8, y1_text, s_textBoxWidth, s_textBoxHeight, Qt::AlignCenter, tr("Midi"));
brush.drawText(s_x5 - 16, y1_text, s_textBoxWidth, s_textBoxHeight, Qt::AlignCenter, tr("BPM"));
brush.drawText(s_x6 - 8, y1_text, s_textBoxWidth, s_textBoxHeight, Qt::AlignCenter, tr("Snap"));
int kor = 15; // knob outer radius
int kir = 9; // knob inner radius
// draw knob backgrounds
brush.setRenderHint(QPainter::Antialiasing);
// draw outer radius 2 times to make smooth
brush.setPen(QPen(QColor(159, 124, 223, 100), 4));
brush.drawArc(QRect(s_x1 - kor, m_y1, kor * 2, kor * 2), -45 * 16, 270 * 16);
brush.drawArc(QRect(s_x2 - kor, m_y1, kor * 2, kor * 2), -45 * 16, 270 * 16);
brush.setPen(QPen(QColor(159, 124, 223, 255), 2));
brush.drawArc(QRect(s_x1 - kor, m_y1, kor * 2, kor * 2), -45 * 16, 270 * 16);
brush.drawArc(QRect(s_x2 - kor, m_y1, kor * 2, kor * 2), -45 * 16, 270 * 16);
// inner knob circle
brush.setBrush(QColor(106, 90, 138));
brush.setPen(QColor(0, 0, 0, 0));
brush.drawEllipse(QPoint(s_x1, m_y1 + 15), kir, kir);
brush.drawEllipse(QPoint(s_x2, m_y1 + 15), kir, kir);
// current sample bar
brush.fillRect(QRect(0, boxTopY - s_sampleBoxHeight, width(), s_sampleBoxHeight), QColor(5, 5, 5));
brush.setPen(QColor(56, 58, 60));
brush.drawLine(width() - 24, boxTopY - s_sampleBoxHeight, width() - 24, boxTopY);
brush.setPen(QColor(255, 255, 255, 180));
brush.setFont(QFont(brush.font().family(), 8, -1, false));
QString sampleName = m_slicerTParent->getSampleName();
if (sampleName == "") { sampleName = "No sample loaded"; }
brush.drawText(5, boxTopY - s_sampleBoxHeight, width(), s_sampleBoxHeight, Qt::AlignLeft, sampleName);
}
void SlicerTView::resizeEvent(QResizeEvent* re)
{
m_y1 = height() - s_bottomBoxOffset;
// left box
m_noteThresholdKnob->move(s_x1 - 25, m_y1);
m_fadeOutKnob->move(s_x2 - 25, m_y1);
m_resetButton->move(s_x3 - 15, m_y1 + 3);
m_midiExportButton->move(s_x4 + 2, m_y1 + 3);
m_bpmBox->move(s_x5 - 13, m_y1 + 4);
m_snapSetting->move(s_x6 - 8, m_y1 + 3);
// right box
m_syncToggle->move((width() - 100), m_y1 + 5);
m_folderButton->move(width() - 20, height() - s_bottomBoxHeight - s_sampleBoxHeight + 1);
int waveFormHeight = height() - s_bottomBoxHeight - s_topBarHeight - s_sampleBoxHeight;
m_wf->resize(width(), waveFormHeight);
}
} // namespace gui
} // namespace lmms
| 9,671
|
C++
|
.cpp
| 230
| 39.921739
| 110
| 0.726934
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,703
|
CrossoverEQ.cpp
|
LMMS_lmms/plugins/CrossoverEQ/CrossoverEQ.cpp
|
/*
* CrossoverEQ.cpp - A native 4-band Crossover Equalizer
* good for simulating tonestacks or simple peakless (flat-band) equalization
*
* Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "CrossoverEQ.h"
#include "lmms_math.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT crossovereq_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Crossover Equalizer",
QT_TRANSLATE_NOOP( "PluginBrowser", "A 4-band Crossover Equalizer" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
};
}
CrossoverEQEffect::CrossoverEQEffect( Model* parent, const Descriptor::SubPluginFeatures::Key* key ) :
Effect( &crossovereq_plugin_descriptor, parent, key ),
m_controls( this ),
m_sampleRate( Engine::audioEngine()->outputSampleRate() ),
m_lp1( m_sampleRate ),
m_lp2( m_sampleRate ),
m_lp3( m_sampleRate ),
m_hp2( m_sampleRate ),
m_hp3( m_sampleRate ),
m_hp4( m_sampleRate ),
m_needsUpdate( true )
{
m_tmp2 = new SampleFrame[Engine::audioEngine()->framesPerPeriod()];
m_tmp1 = new SampleFrame[Engine::audioEngine()->framesPerPeriod()];
m_work = new SampleFrame[Engine::audioEngine()->framesPerPeriod()];
}
CrossoverEQEffect::~CrossoverEQEffect()
{
delete[] m_tmp1;
delete[] m_tmp2;
delete[] m_work;
}
void CrossoverEQEffect::sampleRateChanged()
{
m_sampleRate = Engine::audioEngine()->outputSampleRate();
m_lp1.setSampleRate( m_sampleRate );
m_lp2.setSampleRate( m_sampleRate );
m_lp3.setSampleRate( m_sampleRate );
m_hp2.setSampleRate( m_sampleRate );
m_hp3.setSampleRate( m_sampleRate );
m_hp4.setSampleRate( m_sampleRate );
m_needsUpdate = true;
}
Effect::ProcessStatus CrossoverEQEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
// filters update
if( m_needsUpdate || m_controls.m_xover12.isValueChanged() )
{
m_lp1.setLowpass( m_controls.m_xover12.value() );
m_hp2.setHighpass( m_controls.m_xover12.value() );
}
if( m_needsUpdate || m_controls.m_xover23.isValueChanged() )
{
m_lp2.setLowpass( m_controls.m_xover23.value() );
m_hp3.setHighpass( m_controls.m_xover23.value() );
}
if( m_needsUpdate || m_controls.m_xover34.isValueChanged() )
{
m_lp3.setLowpass( m_controls.m_xover34.value() );
m_hp4.setHighpass( m_controls.m_xover34.value() );
}
// gain values update
if( m_needsUpdate || m_controls.m_gain1.isValueChanged() )
{
m_gain1 = dbfsToAmp( m_controls.m_gain1.value() );
}
if( m_needsUpdate || m_controls.m_gain2.isValueChanged() )
{
m_gain2 = dbfsToAmp( m_controls.m_gain2.value() );
}
if( m_needsUpdate || m_controls.m_gain3.isValueChanged() )
{
m_gain3 = dbfsToAmp( m_controls.m_gain3.value() );
}
if( m_needsUpdate || m_controls.m_gain4.isValueChanged() )
{
m_gain4 = dbfsToAmp( m_controls.m_gain4.value() );
}
// mute values update
const bool mute1 = m_controls.m_mute1.value();
const bool mute2 = m_controls.m_mute2.value();
const bool mute3 = m_controls.m_mute3.value();
const bool mute4 = m_controls.m_mute4.value();
m_needsUpdate = false;
zeroSampleFrames(m_work, frames);
// run temp bands
for (auto f = std::size_t{0}; f < frames; ++f)
{
m_tmp1[f][0] = m_lp2.update( buf[f][0], 0 );
m_tmp1[f][1] = m_lp2.update( buf[f][1], 1 );
m_tmp2[f][0] = m_hp3.update( buf[f][0], 0 );
m_tmp2[f][1] = m_hp3.update( buf[f][1], 1 );
}
// run band 1
if( mute1 )
{
for (auto f = std::size_t{0}; f < frames; ++f)
{
m_work[f][0] += m_lp1.update( m_tmp1[f][0], 0 ) * m_gain1;
m_work[f][1] += m_lp1.update( m_tmp1[f][1], 1 ) * m_gain1;
}
}
// run band 2
if( mute2 )
{
for (auto f = std::size_t{0}; f < frames; ++f)
{
m_work[f][0] += m_hp2.update( m_tmp1[f][0], 0 ) * m_gain2;
m_work[f][1] += m_hp2.update( m_tmp1[f][1], 1 ) * m_gain2;
}
}
// run band 3
if( mute3 )
{
for (auto f = std::size_t{0}; f < frames; ++f)
{
m_work[f][0] += m_lp3.update( m_tmp2[f][0], 0 ) * m_gain3;
m_work[f][1] += m_lp3.update( m_tmp2[f][1], 1 ) * m_gain3;
}
}
// run band 4
if( mute4 )
{
for (auto f = std::size_t{0}; f < frames; ++f)
{
m_work[f][0] += m_hp4.update( m_tmp2[f][0], 0 ) * m_gain4;
m_work[f][1] += m_hp4.update( m_tmp2[f][1], 1 ) * m_gain4;
}
}
const float d = dryLevel();
const float w = wetLevel();
for (auto f = std::size_t{0}; f < frames; ++f)
{
buf[f][0] = d * buf[f][0] + w * m_work[f][0];
buf[f][1] = d * buf[f][1] + w * m_work[f][1];
}
return ProcessStatus::ContinueIfNotQuiet;
}
void CrossoverEQEffect::clearFilterHistories()
{
m_lp1.clearHistory();
m_lp2.clearHistory();
m_lp3.clearHistory();
m_hp2.clearHistory();
m_hp3.clearHistory();
m_hp4.clearHistory();
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new CrossoverEQEffect( parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( data ) );
}
}
} // namespace lmms
| 5,903
|
C++
|
.cpp
| 192
| 28.479167
| 113
| 0.685835
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,704
|
CrossoverEQControls.cpp
|
LMMS_lmms/plugins/CrossoverEQ/CrossoverEQControls.cpp
|
/*
* CrossoverEQControls.cpp - A native 4-band Crossover Equalizer
* good for simulating tonestacks or simple peakless (flat-band) equalization
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "CrossoverEQControls.h"
#include "CrossoverEQ.h"
namespace lmms
{
CrossoverEQControls::CrossoverEQControls( CrossoverEQEffect * eff ) :
EffectControls( eff ),
m_effect( eff ),
m_xover12( 125.f, 50.f, 10000.f, 1.0f, this, "Band 1/2 Crossover" ),
m_xover23( 1250.f, 50.f, 20000.f, 1.0f, this, "Band 2/3 Crossover" ),
m_xover34( 5000.f, 50.f, 20000.f, 1.0f, this, "Band 3/4 Crossover" ),
m_gain1( 0.f, -60.f, 30.f, 0.1f, this, "Band 1 Gain" ),
m_gain2( 0.f, -60.f, 30.f, 0.1f, this, "Band 2 Gain" ),
m_gain3( 0.f, -60.f, 30.f, 0.1f, this, "Band 3 Gain" ),
m_gain4( 0.f, -60.f, 30.f, 0.1f, this, "Band 4 Gain" ),
m_mute1( true, this, "Mute Band 1" ),
m_mute2( true, this, "Mute Band 2" ),
m_mute3( true, this, "Mute Band 3" ),
m_mute4( true, this, "Mute Band 4" )
{
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( sampleRateChanged() ) );
connect( &m_xover12, SIGNAL( dataChanged() ), this, SLOT( xover12Changed() ) );
connect( &m_xover23, SIGNAL( dataChanged() ), this, SLOT( xover23Changed() ) );
connect( &m_xover34, SIGNAL( dataChanged() ), this, SLOT( xover34Changed() ) );
m_xover12.setScaleLogarithmic( true );
m_xover23.setScaleLogarithmic( true );
m_xover34.setScaleLogarithmic( true );
}
void CrossoverEQControls::saveSettings( QDomDocument & doc, QDomElement & elem )
{
m_xover12.saveSettings( doc, elem, "xover12" );
m_xover23.saveSettings( doc, elem, "xover23" );
m_xover34.saveSettings( doc, elem, "xover34" );
m_gain1.saveSettings( doc, elem, "gain1" );
m_gain2.saveSettings( doc, elem, "gain2" );
m_gain3.saveSettings( doc, elem, "gain3" );
m_gain4.saveSettings( doc, elem, "gain4" );
m_mute1.saveSettings( doc, elem, "mute1" );
m_mute2.saveSettings( doc, elem, "mute2" );
m_mute3.saveSettings( doc, elem, "mute3" );
m_mute4.saveSettings( doc, elem, "mute4" );
}
void CrossoverEQControls::loadSettings( const QDomElement & elem )
{
m_xover12.loadSettings( elem, "xover12" );
m_xover23.loadSettings( elem, "xover23" );
m_xover34.loadSettings( elem, "xover34" );
m_gain1.loadSettings( elem, "gain1" );
m_gain2.loadSettings( elem, "gain2" );
m_gain3.loadSettings( elem, "gain3" );
m_gain4.loadSettings( elem, "gain4" );
m_mute1.loadSettings( elem, "mute1" );
m_mute2.loadSettings( elem, "mute2" );
m_mute3.loadSettings( elem, "mute3" );
m_mute4.loadSettings( elem, "mute4" );
m_effect->m_needsUpdate = true;
m_effect->clearFilterHistories();
}
void CrossoverEQControls::xover12Changed()
{
float v = m_xover12.value();
if( m_xover23.value() < v ) { m_xover23.setValue( v ); }
if( m_xover34.value() < v ) { m_xover34.setValue( v ); }
}
void CrossoverEQControls::xover23Changed()
{
float v = m_xover23.value();
if( m_xover12.value() > v ) { m_xover12.setValue( v ); }
if( m_xover34.value() < v ) { m_xover34.setValue( v ); }
}
void CrossoverEQControls::xover34Changed()
{
float v = m_xover34.value();
if( m_xover12.value() > v ) { m_xover12.setValue( v ); }
if( m_xover23.value() > v ) { m_xover23.setValue( v ); }
}
void CrossoverEQControls::sampleRateChanged()
{
m_effect->sampleRateChanged();
}
} // namespace lmms
| 4,232
|
C++
|
.cpp
| 105
| 38.314286
| 100
| 0.703803
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,705
|
CrossoverEQControlDialog.cpp
|
LMMS_lmms/plugins/CrossoverEQ/CrossoverEQControlDialog.cpp
|
/*
* CrossoverEQControlDialog.cpp - A native 4-band Crossover Equalizer
* good for simulating tonestacks or simple peakless (flat-band) equalization
*
* Copyright (c) 2014 Vesa Kivim√§ki <contact/dot/diizy/at/nbl/dot/fi>
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "CrossoverEQControlDialog.h"
#include "CrossoverEQControls.h"
#include "embed.h"
#include "LedCheckBox.h"
#include "Knob.h"
#include "Fader.h"
#include <QPixmap>
namespace lmms::gui
{
CrossoverEQControlDialog::CrossoverEQControlDialog( CrossoverEQControls * controls ) :
EffectControlDialog( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 167, 178 );
// knobs
auto xover12 = new Knob(KnobType::Bright26, this);
xover12->move( 29, 11 );
xover12->setModel( & controls->m_xover12 );
xover12->setLabel( "1/2" );
xover12->setHintText( tr( "Band 1/2 crossover:" ), " Hz" );
auto xover23 = new Knob(KnobType::Bright26, this);
xover23->move( 69, 11 );
xover23->setModel( & controls->m_xover23 );
xover23->setLabel( "2/3" );
xover23->setHintText( tr( "Band 2/3 crossover:" ), " Hz" );
auto xover34 = new Knob(KnobType::Bright26, this);
xover34->move( 109, 11 );
xover34->setModel( & controls->m_xover34 );
xover34->setLabel( "3/4" );
xover34->setHintText( tr( "Band 3/4 crossover:" ), " Hz" );
QPixmap const fader_knob(PLUGIN_NAME::getIconPixmap("fader_knob2"));
// faders
auto gain1 = new Fader(&controls->m_gain1, tr("Band 1 gain"), this, fader_knob);
gain1->move( 7, 56 );
gain1->setDisplayConversion( false );
gain1->setHintText( tr( "Band 1 gain:" ), " dBFS" );
gain1->setRenderUnityLine(false);
auto gain2 = new Fader(&controls->m_gain2, tr("Band 2 gain"), this, fader_knob);
gain2->move( 47, 56 );
gain2->setDisplayConversion( false );
gain2->setHintText( tr( "Band 2 gain:" ), " dBFS" );
gain2->setRenderUnityLine(false);
auto gain3 = new Fader(&controls->m_gain3, tr("Band 3 gain"), this, fader_knob);
gain3->move( 87, 56 );
gain3->setDisplayConversion( false );
gain3->setHintText( tr( "Band 3 gain:" ), " dBFS" );
gain3->setRenderUnityLine(false);
auto gain4 = new Fader(&controls->m_gain4, tr("Band 4 gain"), this, fader_knob);
gain4->move( 127, 56 );
gain4->setDisplayConversion( false );
gain4->setHintText( tr( "Band 4 gain:" ), " dBFS" );
gain4->setRenderUnityLine(false);
// leds
auto mute1 = new LedCheckBox("", this, tr("Band 1 mute"), LedCheckBox::LedColor::Green);
mute1->move( 15, 154 );
mute1->setModel( & controls->m_mute1 );
mute1->setToolTip(tr("Mute band 1"));
auto mute2 = new LedCheckBox("", this, tr("Band 2 mute"), LedCheckBox::LedColor::Green);
mute2->move( 55, 154 );
mute2->setModel( & controls->m_mute2 );
mute2->setToolTip(tr("Mute band 2"));
auto mute3 = new LedCheckBox("", this, tr("Band 3 mute"), LedCheckBox::LedColor::Green);
mute3->move( 95, 154 );
mute3->setModel( & controls->m_mute3 );
mute3->setToolTip(tr("Mute band 3"));
auto mute4 = new LedCheckBox("", this, tr("Band 4 mute"), LedCheckBox::LedColor::Green);
mute4->move( 135, 154 );
mute4->setModel( & controls->m_mute4 );
mute4->setToolTip(tr("Mute band 4"));
}
} // namespace lmms::gui
| 4,092
|
C++
|
.cpp
| 99
| 39.212121
| 89
| 0.712954
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,706
|
Patman.cpp
|
LMMS_lmms/plugins/Patman/Patman.cpp
|
/*
* Patman.cpp - a GUS-compatible patch instrument plugin
*
* Copyright (c) 2007-2008 Javier Serrano Polo <jasp00/at/users.sourceforge.net>
* Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Patman.h"
#include <QDragEnterEvent>
#include <QPainter>
#include <QDomElement>
#include "ConfigManager.h"
#include "endian_handling.h"
#include "Engine.h"
#include "FileDialog.h"
#include "FontHelper.h"
#include "InstrumentTrack.h"
#include "NotePlayHandle.h"
#include "PathUtil.h"
#include "PixmapButton.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "Clipboard.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT patman_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"PatMan",
QT_TRANSLATE_NOOP( "PluginBrowser",
"GUS-compatible patch instrument" ),
"Javier Serrano Polo <jasp00/at/users.sourceforge.net>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
"pat",
nullptr,
} ;
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return new PatmanInstrument( static_cast<InstrumentTrack *>( m ) );
}
}
PatmanInstrument::PatmanInstrument( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &patman_plugin_descriptor ),
m_loopedModel( true, this ),
m_tunedModel( true, this )
{
}
PatmanInstrument::~PatmanInstrument()
{
unloadCurrentPatch();
}
void PatmanInstrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
_this.setAttribute( "src", m_patchFile );
m_loopedModel.saveSettings( _doc, _this, "looped" );
m_tunedModel.saveSettings( _doc, _this, "tuned" );
}
void PatmanInstrument::loadSettings( const QDomElement & _this )
{
setFile( _this.attribute( "src" ), false );
m_loopedModel.loadSettings( _this, "looped" );
m_tunedModel.loadSettings( _this, "tuned" );
}
void PatmanInstrument::loadFile( const QString & _file )
{
setFile( _file );
}
QString PatmanInstrument::nodeName() const
{
return( patman_plugin_descriptor.name );
}
void PatmanInstrument::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
if( m_patchFile == "" )
{
return;
}
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
if (!_n->m_pluginData)
{
selectSample( _n );
}
auto hdata = (handle_data*)_n->m_pluginData;
float play_freq = hdata->tuned ? _n->frequency() :
hdata->sample->frequency();
if (hdata->sample->play(_working_buffer + offset, hdata->state, frames,
play_freq, m_loopedModel.value() ? Sample::Loop::On : Sample::Loop::Off))
{
applyRelease( _working_buffer, _n );
}
else
{
zeroSampleFrames(_working_buffer, frames + offset);
}
}
void PatmanInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
auto hdata = (handle_data*)_n->m_pluginData;
delete hdata->state;
delete hdata;
}
void PatmanInstrument::setFile( const QString & _patch_file, bool _rename )
{
if( _patch_file.size() <= 0 )
{
m_patchFile = QString();
return;
}
// is current instrument-track-name equal to previous-filename??
if( _rename &&
( instrumentTrack()->name() ==
QFileInfo( m_patchFile ).fileName() ||
m_patchFile == "" ) )
{
// then set it to new one
instrumentTrack()->setName( PathUtil::cleanName( _patch_file ) );
}
// else we don't touch the instrument-track-name, because the user
// named it self
m_patchFile = PathUtil::toShortestRelative( _patch_file );
LoadError error = loadPatch( PathUtil::toAbsolute( _patch_file ) );
if( error != LoadError::OK )
{
printf("Load error\n");
}
emit fileChanged();
}
PatmanInstrument::LoadError PatmanInstrument::loadPatch(
const QString & _filename )
{
unloadCurrentPatch();
FILE * fd = fopen( _filename.toUtf8().constData() , "rb" );
if( !fd )
{
perror( "fopen" );
return( LoadError::Open );
}
auto header = std::array<unsigned char, 239>{};
if (fread(header.data(), 1, 239, fd ) != 239 ||
(memcmp(header.data(), "GF1PATCH110\0ID#000002", 22)
&& memcmp(header.data(), "GF1PATCH100\0ID#000002", 22)))
{
fclose( fd );
return( LoadError::NotGUS );
}
if( header[82] != 1 && header[82] != 0 )
{
fclose( fd );
return( LoadError::Instruments );
}
if( header[151] != 1 && header[151] != 0 )
{
fclose( fd );
return( LoadError::Layers );
}
int sample_count = header[198];
for( int i = 0; i < sample_count; ++i )
{
unsigned short tmpshort;
#define SKIP_BYTES( x ) \
if ( fseek( fd, x, SEEK_CUR ) == -1 ) \
{ \
fclose( fd ); \
return( LoadError::IO ); \
}
#define READ_SHORT( x ) \
if ( fread( &tmpshort, 2, 1, fd ) != 1 ) \
{ \
fclose( fd ); \
return( LoadError::IO ); \
} \
x = (unsigned short)swap16IfBE( tmpshort );
#define READ_LONG( x ) \
if ( fread( &x, 4, 1, fd ) != 1 ) \
{ \
fclose( fd ); \
return( LoadError::IO ); \
} \
x = (unsigned)swap32IfBE( x );
// skip wave name, fractions
SKIP_BYTES( 7 + 1 );
unsigned data_length;
READ_LONG( data_length );
unsigned loop_start;
READ_LONG( loop_start );
unsigned loop_end;
READ_LONG( loop_end );
unsigned sample_rate;
READ_SHORT( sample_rate );
// skip low_freq, high_freq
SKIP_BYTES( 4 + 4 );
unsigned root_freq;
READ_LONG( root_freq );
// skip tuning, panning, envelope, tremolo, vibrato
SKIP_BYTES( 2 + 1 + 12 + 3 + 3 );
unsigned char modes;
if ( fread( &modes, 1, 1, fd ) != 1 )
{
fclose( fd );
return( LoadError::IO );
}
// skip scale frequency, scale factor, reserved space
SKIP_BYTES( 2 + 2 + 36 );
f_cnt_t frames;
std::unique_ptr<sample_t[]> wave_samples;
if( modes & MODES_16BIT )
{
frames = data_length >> 1;
wave_samples = std::make_unique<sample_t[]>(frames);
for( f_cnt_t frame = 0; frame < frames; ++frame )
{
short sample;
if ( fread( &sample, 2, 1, fd ) != 1 )
{
fclose( fd );
return( LoadError::IO );
}
sample = swap16IfBE( sample );
if( modes & MODES_UNSIGNED )
{
sample ^= 0x8000;
}
wave_samples[frame] = sample / 32767.0f;
}
loop_start >>= 1;
loop_end >>= 1;
}
else
{
frames = data_length;
wave_samples = std::make_unique<sample_t[]>(frames);
for( f_cnt_t frame = 0; frame < frames; ++frame )
{
char sample;
if ( fread( &sample, 1, 1, fd ) != 1 )
{
fclose( fd );
return( LoadError::IO );
}
if( modes & MODES_UNSIGNED )
{
sample ^= 0x80;
}
wave_samples[frame] = sample / 127.0f;
}
}
auto data = new SampleFrame[frames];
for( f_cnt_t frame = 0; frame < frames; ++frame )
{
for( ch_cnt_t chnl = 0; chnl < DEFAULT_CHANNELS;
++chnl )
{
data[frame][chnl] = wave_samples[frame];
}
}
auto psample = std::make_shared<Sample>(data, frames, sample_rate);
psample->setFrequency(root_freq / 1000.0f);
if( modes & MODES_LOOPING )
{
psample->setLoopStartFrame( loop_start );
psample->setLoopEndFrame( loop_end );
}
m_patchSamples.push_back(psample);
delete[] data;
}
fclose( fd );
return( LoadError::OK );
}
void PatmanInstrument::unloadCurrentPatch()
{
while( !m_patchSamples.empty() )
{
m_patchSamples.pop_back();
}
}
void PatmanInstrument::selectSample( NotePlayHandle * _n )
{
const float freq = _n->frequency();
float min_dist = HUGE_VALF;
std::shared_ptr<Sample> sample = nullptr;
for (const auto& patchSample : m_patchSamples)
{
float patch_freq = patchSample->frequency();
float dist = freq >= patch_freq ? freq / patch_freq :
patch_freq / freq;
if( dist < min_dist )
{
min_dist = dist;
sample = patchSample;
}
}
auto hdata = new handle_data;
hdata->tuned = m_tunedModel.value();
hdata->sample = sample ? sample : std::make_shared<Sample>();
hdata->state = new Sample::PlaybackState(_n->hasDetuningInfo());
_n->m_pluginData = hdata;
}
gui::PluginView * PatmanInstrument::instantiateView( QWidget * _parent )
{
return( new gui::PatmanView( this, _parent ) );
}
namespace gui
{
PatmanView::PatmanView( Instrument * _instrument, QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent ),
m_pi(castModel<PatmanInstrument>())
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(),
PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
m_openFileButton = new PixmapButton( this, nullptr );
m_openFileButton->setObjectName( "openFileButton" );
m_openFileButton->setCursor( QCursor( Qt::PointingHandCursor ) );
m_openFileButton->move( 227, 86 );
m_openFileButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"select_file_on" ) );
m_openFileButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"select_file" ) );
connect( m_openFileButton, SIGNAL( clicked() ),
this, SLOT( openFile() ) );
m_openFileButton->setToolTip(tr("Open patch"));
m_loopButton = new PixmapButton( this, tr( "Loop" ) );
m_loopButton->setObjectName("loopButton");
m_loopButton->setCheckable( true );
m_loopButton->move( 195, 138 );
m_loopButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"loop_on" ) );
m_loopButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"loop_off" ) );
m_loopButton->setToolTip(tr("Loop mode"));
m_tuneButton = new PixmapButton( this, tr( "Tune" ) );
m_tuneButton->setObjectName("tuneButton");
m_tuneButton->setCheckable( true );
m_tuneButton->move( 223, 138 );
m_tuneButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"tune_on" ) );
m_tuneButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"tune_off" ) );
m_tuneButton->setToolTip(tr("Tune mode"));
if (m_pi->m_patchFile.isEmpty())
{
m_displayFilename = tr("No file selected");
}
else
{
updateFilename();
}
setAcceptDrops( true );
}
void PatmanView::openFile()
{
FileDialog ofd( nullptr, tr( "Open patch file" ) );
ofd.setFileMode( FileDialog::ExistingFiles );
QStringList types;
types << tr( "Patch-Files (*.pat)" );
ofd.setNameFilters( types );
if( m_pi->m_patchFile == "" )
{
if( QDir( "/usr/share/midi/freepats" ).exists() )
{
ofd.setDirectory( "/usr/share/midi/freepats" );
}
else
{
ofd.setDirectory(
ConfigManager::inst()->userSamplesDir() );
}
}
else if( QFileInfo( m_pi->m_patchFile ).isRelative() )
{
QString f = ConfigManager::inst()->userSamplesDir()
+ m_pi->m_patchFile;
if( QFileInfo( f ).exists() == false )
{
f = ConfigManager::inst()->factorySamplesDir()
+ m_pi->m_patchFile;
}
ofd.selectFile( f );
}
else
{
ofd.selectFile( m_pi->m_patchFile );
}
if( ofd.exec() == QDialog::Accepted && !ofd.selectedFiles().isEmpty() )
{
QString f = ofd.selectedFiles()[0];
if( f != "" )
{
m_pi->setFile( f );
Engine::getSong()->setModified();
}
}
}
void PatmanView::updateFilename()
{
m_displayFilename = "";
int idx = m_pi->m_patchFile.length();
QFontMetrics fm(adjustedToPixelSize(font(), SMALL_FONT_SIZE));
// simple algorithm for creating a text from the filename that
// matches in the white rectangle
while( idx > 0 && fm.size( Qt::TextSingleLine,
m_displayFilename + "..." ).width() < 225 )
{
m_displayFilename = m_pi->m_patchFile[--idx] +
m_displayFilename;
}
if( idx > 0 )
{
m_displayFilename = "..." + m_displayFilename;
}
update();
}
void PatmanView::dragEnterEvent( QDragEnterEvent * _dee )
{
// For mimeType() and MimeType enum class
using namespace Clipboard;
if( _dee->mimeData()->hasFormat( mimeType( MimeType::StringPair ) ) )
{
QString txt = _dee->mimeData()->data(
mimeType( MimeType::StringPair ) );
if( txt.section( ':', 0, 0 ) == "samplefile" )
{
_dee->acceptProposedAction();
}
else
{
_dee->ignore();
}
}
else
{
_dee->ignore();
}
}
void PatmanView::dropEvent( QDropEvent * _de )
{
QString type = StringPairDrag::decodeKey( _de );
QString value = StringPairDrag::decodeValue( _de );
if( type == "samplefile" )
{
m_pi->setFile( value );
_de->accept();
return;
}
_de->ignore();
}
void PatmanView::paintEvent( QPaintEvent * )
{
QPainter p( this );
p.setFont(adjustedToPixelSize(font(), SMALL_FONT_SIZE));
p.drawText( 8, 116, 235, 16,
Qt::AlignLeft | Qt::TextSingleLine | Qt::AlignVCenter,
m_displayFilename );
}
void PatmanView::modelChanged()
{
m_pi = castModel<PatmanInstrument>();
m_loopButton->setModel( &m_pi->m_loopedModel );
m_tuneButton->setModel( &m_pi->m_tunedModel );
connect( m_pi, SIGNAL( fileChanged() ),
this, SLOT( updateFilename() ) );
}
} // namespace gui
} // namespace lmms
| 13,452
|
C++
|
.cpp
| 492
| 24.455285
| 80
| 0.676735
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,707
|
LadspaDescription.cpp
|
LMMS_lmms/plugins/LadspaBrowser/LadspaDescription.cpp
|
/*
* LadspaDescription.cpp - LADSPA plugin description
*
* Copyright (c) 2007 Javier Serrano Polo <jasp00/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LadspaDescription.h"
#include <QGroupBox>
#include <QLabel>
#include <QListWidget>
#include <QScrollArea>
#include <QVBoxLayout>
#include "AudioDevice.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "Ladspa2LMMS.h"
namespace lmms::gui
{
LadspaDescription::LadspaDescription( QWidget * _parent,
LadspaPluginType _type ) :
QWidget( _parent )
{
Ladspa2LMMS * manager = Engine::getLADSPAManager();
l_sortable_plugin_t plugins;
switch( _type )
{
case LadspaPluginType::Source:
plugins = manager->getInstruments();
break;
case LadspaPluginType::Transfer:
plugins = manager->getValidEffects();
break;
case LadspaPluginType::Valid:
plugins = manager->getValidEffects();
break;
case LadspaPluginType::Invalid:
plugins = manager->getInvalidEffects();
break;
case LadspaPluginType::Sink:
plugins = manager->getAnalysisTools();
break;
case LadspaPluginType::Other:
plugins = manager->getOthers();
break;
default:
break;
}
QList<QString> pluginNames;
for (const auto& plugin : plugins)
{
ch_cnt_t audioDeviceChannels = Engine::audioEngine()->audioDev()->channels();
if (_type != LadspaPluginType::Valid || manager->getDescription(plugin.second)->inputChannels <= audioDeviceChannels)
{
pluginNames.push_back(plugin.first);
m_pluginKeys.push_back(plugin.second);
}
}
auto pluginsBox = new QGroupBox(tr("Plugins"), this);
auto pluginList = new QListWidget(pluginsBox);
pluginList->addItems( pluginNames );
connect( pluginList, SIGNAL( currentRowChanged( int ) ),
SLOT( rowChanged( int ) ) );
connect( pluginList, SIGNAL( itemDoubleClicked( QListWidgetItem * ) ),
SLOT( onDoubleClicked( QListWidgetItem * ) ) );
( new QVBoxLayout( pluginsBox ) )->addWidget( pluginList );
auto descriptionBox = new QGroupBox(tr("Description"), this);
auto descriptionLayout = new QVBoxLayout(descriptionBox);
descriptionLayout->setSpacing( 0 );
descriptionLayout->setContentsMargins(0, 0, 0, 0);
m_scrollArea = new QScrollArea( descriptionBox );
descriptionLayout->addWidget( m_scrollArea );
auto layout = new QVBoxLayout(this);
layout->addWidget( pluginsBox );
layout->addWidget( descriptionBox );
if( pluginList->count() > 0 )
{
pluginList->setCurrentRow( 0 );
m_currentSelection = m_pluginKeys[0];
update( m_currentSelection );
}
}
void LadspaDescription::update( const ladspa_key_t & _key )
{
auto description = new QWidget;
m_scrollArea->setWidget( description );
auto layout = new QVBoxLayout(description);
layout->setSizeConstraint( QLayout::SetFixedSize );
Ladspa2LMMS * manager = Engine::getLADSPAManager();
auto name = new QLabel(description);
name->setText(tr("Name: ") + manager->getName(_key));
layout->addWidget( name );
auto maker = new QLabel(description);
maker->setText(tr("Maker: ") + manager->getMaker(_key));
layout->addWidget( maker );
auto copyright = new QLabel(description);
copyright->setText(tr("Copyright: ") + manager->getCopyright(_key));
layout->addWidget( copyright );
auto requiresRealTime = new QLabel(description);
requiresRealTime->setText(tr("Requires Real Time: ") +
(manager->hasRealTimeDependency(_key) ? tr("Yes") : tr("No")));
layout->addWidget( requiresRealTime );
auto realTimeCapable = new QLabel(description);
realTimeCapable->setText(tr("Real Time Capable: ") +
(manager->isRealTimeCapable(_key) ? tr("Yes") : tr("No")));
layout->addWidget( realTimeCapable );
auto inplaceBroken = new QLabel(description);
inplaceBroken->setText(tr("In Place Broken: ") +
(manager->isInplaceBroken(_key) ? tr("Yes") : tr("No")));
layout->addWidget( inplaceBroken );
auto channelsIn = new QLabel(description);
channelsIn->setText(tr("Channels In: ") + QString::number(
manager->getDescription( _key )->inputChannels ) );
layout->addWidget( channelsIn );
auto channelsOut = new QLabel(description);
channelsOut->setText(tr("Channels Out: ") + QString::number(
manager->getDescription( _key )->outputChannels ) );
layout->addWidget( channelsOut );
}
void LadspaDescription::rowChanged( int _pluginIndex )
{
m_currentSelection = m_pluginKeys[_pluginIndex];
update( m_currentSelection );
}
void LadspaDescription::onDoubleClicked( QListWidgetItem * _item )
{
emit( doubleClicked( m_currentSelection ) );
}
} // namespace lmms::gui
| 5,276
|
C++
|
.cpp
| 145
| 33.82069
| 119
| 0.743373
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,708
|
LadspaBrowser.cpp
|
LMMS_lmms/plugins/LadspaBrowser/LadspaBrowser.cpp
|
/*
* LadspaBrowser.cpp - dialog to display information about installed LADSPA
* plugins
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
* Copyright (c) 2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LadspaBrowser.h"
#include <QHBoxLayout>
#include <QLabel>
#include "LadspaDescription.h"
#include "LadspaPortDialog.h"
#include "TabBar.h"
#include "TabButton.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT ladspabrowser_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"LADSPA Plugin Browser",
QT_TRANSLATE_NOOP( "PluginBrowser",
"List installed LADSPA plugins" ),
"Danny McRae <khjklujn/at/users.sourceforge.net>",
0x0100,
Plugin::Type::Tool,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * _parent, void * _data )
{
return new LadspaBrowser;
}
}
LadspaBrowser::LadspaBrowser() :
ToolPlugin( &ladspabrowser_plugin_descriptor, nullptr )
{
}
QString LadspaBrowser::nodeName() const
{
return ladspabrowser_plugin_descriptor.name;
}
namespace gui
{
LadspaBrowserView::LadspaBrowserView( ToolPlugin * _tool ) :
ToolPluginView( _tool )
{
auto hlayout = new QHBoxLayout(this);
hlayout->setSpacing( 0 );
hlayout->setContentsMargins(0, 0, 0, 0);
m_tabBar = new TabBar( this, QBoxLayout::TopToBottom );
m_tabBar->setExclusive( true );
m_tabBar->setFixedWidth( 72 );
auto ws = new QWidget(this);
ws->setFixedSize( 500, 480 );
QWidget * available = createTab( ws, tr( "Available Effects" ), LadspaPluginType::Valid );
QWidget * unavailable = createTab( ws, tr( "Unavailable Effects" ),
LadspaPluginType::Invalid );
QWidget * instruments = createTab( ws, tr( "Instruments" ), LadspaPluginType::Source );
QWidget * analysis = createTab( ws, tr( "Analysis Tools" ), LadspaPluginType::Sink );
QWidget * other = createTab( ws, tr( "Don't know" ), LadspaPluginType::Other );
m_tabBar->addTab( available, tr( "Available Effects" ),
0, false, true
)->setIcon( embed::getIconPixmap( "setup_audio" ) );
m_tabBar->addTab( unavailable, tr( "Unavailable Effects" ),
1, false, true
)->setIcon( embed::getIconPixmap(
"unavailable_sound" ) );
m_tabBar->addTab( instruments, tr( "Instruments" ),
2, false, true
)->setIcon( embed::getIconPixmap(
"setup_midi" ) );
m_tabBar->addTab( analysis, tr( "Analysis Tools" ),
3, false, true
)->setIcon( embed::getIconPixmap( "analysis" ) );
m_tabBar->addTab( other, tr( "Don't know" ),
4, true, true
)->setIcon( embed::getIconPixmap( "uhoh" ) );
m_tabBar->setActiveTab( 0 );
hlayout->addWidget( m_tabBar );
hlayout->addSpacing( 10 );
hlayout->addWidget( ws );
hlayout->addSpacing( 10 );
hlayout->addStretch();
hide();
if( parentWidget() )
{
parentWidget()->hide();
parentWidget()->layout()->setSizeConstraint(
QLayout::SetFixedSize );
Qt::WindowFlags flags = parentWidget()->windowFlags();
flags |= Qt::MSWindowsFixedSizeDialogHint;
flags &= ~Qt::WindowMaximizeButtonHint;
parentWidget()->setWindowFlags( flags );
}
}
QWidget * LadspaBrowserView::createTab( QWidget * _parent, const QString & _txt,
LadspaPluginType _type )
{
auto tab = new QWidget(_parent);
tab->setFixedSize( 500, 400 );
auto layout = new QVBoxLayout(tab);
layout->setSpacing( 0 );
layout->setContentsMargins(0, 0, 0, 0);
const QString type = "<b>" + tr( "Type:" ) + "</b> ";
auto title = new QLabel(type + _txt, tab);
QFont f = title->font();
f.setBold( true );
layout->addSpacing( 5 );
layout->addWidget( title );
layout->addSpacing( 10 );
auto description = new LadspaDescription(tab, _type);
connect( description, SIGNAL( doubleClicked( const ::lmms::ladspa_key_t & ) ),
SLOT( showPorts( const ::lmms::ladspa_key_t & ) ) );
layout->addWidget( description, 1 );
return tab;
}
void LadspaBrowserView::showPorts( const ::lmms::ladspa_key_t & _key )
{
LadspaPortDialog ports( _key );
ports.exec();
}
} // namespace gui
} // namespace lmms
| 4,974
|
C++
|
.cpp
| 147
| 31.231293
| 91
| 0.714854
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,709
|
LadspaPortDialog.cpp
|
LMMS_lmms/plugins/LadspaBrowser/LadspaPortDialog.cpp
|
/*
* LadspaPortDialog.cpp - dialog to test a LADSPA plugin
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "LadspaPortDialog.h"
#include <QTableWidget>
#include <QVBoxLayout>
#include "AudioEngine.h"
#include "embed.h"
#include "Engine.h"
#include "Ladspa2LMMS.h"
namespace lmms::gui
{
LadspaPortDialog::LadspaPortDialog( const ladspa_key_t & _key )
{
Ladspa2LMMS * manager = Engine::getLADSPAManager();
setWindowIcon( embed::getIconPixmap( "ports" ) );
setWindowTitle( tr( "Ports" ) );
setModal( true );
auto vlayout = new QVBoxLayout(this);
vlayout->setSpacing( 0 );
vlayout->setContentsMargins(0, 0, 0, 0);
int pc = manager->getPortCount( _key );
auto settings = new QTableWidget(pc, 7, this);
QStringList ports;
ports.append( tr( "Name" ) );
ports.append( tr( "Rate" ) );
ports.append( tr( "Direction" ) );
ports.append( tr( "Type" ) );
ports.append( tr( "Min < Default < Max" ) );
ports.append( tr( "Logarithmic" ) );
ports.append( tr( "SR Dependent" ) );
settings->setHorizontalHeaderLabels( ports );
for( int row = 0; row < pc; row++ )
{
for( int col = 0; col < 7; ++col )
{
auto item = new QTableWidgetItem;
item->setFlags(QFlag(0));
settings->setItem( row, col, item );
}
int col = 0;
settings->item( row, col++ )->setText( manager->getPortName( _key, row ) );
settings->item( row, col++ )->setText( manager->isPortAudio( _key, row ) ? tr( "Audio" ) : tr( "Control" ) );
settings->item( row, col++ )->setText( manager->isPortInput( _key, row ) ? tr( "Input" ) : tr( "Output" ) );
settings->item( row, col++ )->setText( manager->isPortToggled( _key, row ) ? tr( "Toggled" ) : manager->isInteger( _key, row ) ? tr( "Integer" ) : tr( "Float" ) );
float min = manager->getLowerBound( _key, row );
float max = manager->getUpperBound( _key, row );
float def = manager->getDefaultSetting( _key, row );
QString range = "";
if( manager->areHintsSampleRateDependent( _key, row ) )
{
if( min != NOHINT )
{
min *= Engine::audioEngine()->outputSampleRate();
}
if( max != NOHINT )
{
max *= Engine::audioEngine()->outputSampleRate();
}
}
if( min == NOHINT )
{
range += "-Inf < ";
}
else if( manager->isInteger( _key, row ) )
{
range += QString::number( static_cast<int>( min ) ) +
" < ";
}
else
{
range += QString::number( min ) + " < ";
}
if( def == NOHINT )
{
range += "None < ";
}
else if( manager->isInteger( _key, row ) )
{
range += QString::number( static_cast<int>( def ) ) +
" < ";
}
else
{
range += QString::number( def ) + " < ";
}
if( max == NOHINT )
{
range += "Inf";
}
else if( manager->isInteger( _key, row ) )
{
range += QString::number( static_cast<int>( max ) );
}
else
{
range += QString::number( max );
}
if( manager->isPortOutput( _key, row ) ||
manager->isPortToggled( _key, row ) )
{
range = "";
}
settings->item( row, col++ )->setText( range );
if( manager->isLogarithmic( _key, row ) )
{
settings->item( row, col )->setText( tr( "Yes" ) );
}
col++;
if( manager->areHintsSampleRateDependent( _key, row ) )
{
settings->item( row, col )->setText( tr( "Yes" ) );
}
}
vlayout->addWidget( settings );
show();
}
} // namespace lmms::gui
| 4,141
|
C++
|
.cpp
| 138
| 26.985507
| 165
| 0.642156
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,710
|
Sf2Player.cpp
|
LMMS_lmms/plugins/Sf2Player/Sf2Player.cpp
|
/*
* Sf2Player.cpp - a soundfont2 player using fluidSynth
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
* Copyright (c) 2009-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Sf2Player.h"
#include <fluidsynth.h>
#include <QDebug>
#include <QDomElement>
#include <QLabel>
#include "ArrayVector.h"
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "FileDialog.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "InstrumentPlayHandle.h"
#include "Knob.h"
#include "NotePlayHandle.h"
#include "PathUtil.h"
#include "PixmapButton.h"
#include "Song.h"
#include "fluidsynthshims.h"
#include "PatchesDialog.h"
#include "LcdSpinBox.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT sf2player_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Sf2 Player",
QT_TRANSLATE_NOOP( "PluginBrowser", "Player for SoundFont files" ),
"Paul Giblock <drfaygo/at/gmail/dot/com>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
"sf2,sf3",
nullptr,
} ;
}
/**
* A non-owning reference to a single FluidSynth voice. Captures some initial
* properties of the referenced voice to help manage changes to it over time.
*/
class FluidVoice
{
public:
//! Create a reference to the voice currently pointed at by `voice`.
explicit FluidVoice(fluid_voice_t* voice) :
m_voice{voice},
m_id{fluid_voice_get_id(voice)},
m_coarseTune{fluid_voice_gen_get(voice, GEN_COARSETUNE)}
{ }
//! Get a pointer to the referenced voice.
fluid_voice_t* get() const noexcept { return m_voice; }
//! Get the original coarse tuning of the referenced voice.
float coarseTune() const noexcept { return m_coarseTune; }
//! Test whether this object still refers to the original voice.
bool isValid() const
{
return fluid_voice_get_id(m_voice) == m_id && fluid_voice_is_playing(m_voice);
}
private:
fluid_voice_t* m_voice;
unsigned int m_id;
float m_coarseTune;
};
struct Sf2PluginData
{
int midiNote;
int lastPanning;
float lastVelocity;
// The soundfonts I checked used at most two voices per note, so space for
// four should be safe. This may need to be increased if a soundfont with
// more voices per note is found.
ArrayVector<FluidVoice, 4> fluidVoices;
bool isNew;
f_cnt_t offset;
bool noteOffSent;
panning_t panning;
};
Sf2Instrument::Sf2Instrument( InstrumentTrack * _instrument_track ) :
Instrument(_instrument_track, &sf2player_plugin_descriptor, nullptr, Flag::IsSingleStreamed),
m_srcState( nullptr ),
m_synth(nullptr),
m_font( nullptr ),
m_fontId( 0 ),
m_filename( "" ),
m_lastMidiPitch( -1 ),
m_lastMidiPitchRange( -1 ),
m_channel( 1 ),
m_bankNum( 0, 0, 999, this, tr("Bank") ),
m_patchNum( 0, 0, 127, this, tr("Patch") ),
m_gain( 1.0f, 0.0f, 5.0f, 0.01f, this, tr( "Gain" ) ),
m_reverbOn( false, this, tr( "Reverb" ) ),
m_reverbRoomSize( FLUID_REVERB_DEFAULT_ROOMSIZE, 0, 1.0, 0.01f, this, tr( "Reverb room size" ) ),
m_reverbDamping(FLUID_REVERB_DEFAULT_DAMP, 0, 1.f, 0.01f, this, tr("Reverb damping")),
m_reverbWidth( FLUID_REVERB_DEFAULT_WIDTH, 0, 1.0, 0.01f, this, tr( "Reverb width" ) ),
m_reverbLevel( FLUID_REVERB_DEFAULT_LEVEL, 0, 1.0, 0.01f, this, tr( "Reverb level" ) ),
m_chorusOn( false, this, tr( "Chorus" ) ),
m_chorusNum( FLUID_CHORUS_DEFAULT_N, 0, 10.0, 1.0, this, tr( "Chorus voices" ) ),
m_chorusLevel(FLUID_CHORUS_DEFAULT_LEVEL, 0, 10.f, 0.01f, this, tr("Chorus level")),
m_chorusSpeed(FLUID_CHORUS_DEFAULT_SPEED, 0.29f, 5.f, 0.01f, this, tr("Chorus speed")),
m_chorusDepth(FLUID_CHORUS_DEFAULT_DEPTH, 0, 46.f, 0.05f, this, tr("Chorus depth"))
{
#if QT_VERSION_CHECK(FLUIDSYNTH_VERSION_MAJOR, FLUIDSYNTH_VERSION_MINOR, FLUIDSYNTH_VERSION_MICRO) >= QT_VERSION_CHECK(1,1,9)
// Deactivate all audio drivers in fluidsynth
const char *none[] = { nullptr };
fluid_audio_driver_register( none );
#endif
m_settings = new_fluid_settings();
//fluid_settings_setint( m_settings, (char *) "audio.period-size", engine::audioEngine()->framesPerPeriod() );
// This sets up m_synth and updates reverb/chorus/gain
reloadSynth();
#if FLUIDSYNTH_VERSION_MAJOR >= 2
// Get the default values from the setting
double settingVal;
fluid_settings_getnum_default(m_settings, "synth.reverb.room-size", &settingVal);
m_reverbRoomSize.setInitValue(settingVal);
fluid_settings_getnum_default(m_settings, "synth.reverb.damping", &settingVal);
m_reverbDamping.setInitValue(settingVal);
fluid_settings_getnum_default(m_settings, "synth.reverb.width", &settingVal);
m_reverbWidth.setInitValue(settingVal);
fluid_settings_getnum_default(m_settings, "synth.reverb.level", &settingVal);
m_reverbLevel.setInitValue(settingVal);
fluid_settings_getnum_default(m_settings, "synth.chorus.nr", &settingVal);
m_chorusNum.setInitValue(settingVal);
fluid_settings_getnum_default(m_settings, "synth.chorus.level", &settingVal);
m_chorusLevel.setInitValue(settingVal);
fluid_settings_getnum_default(m_settings, "synth.chorus.speed", &settingVal);
m_chorusSpeed.setInitValue(settingVal);
fluid_settings_getnum_default(m_settings, "synth.chorus.depth", &settingVal);
m_chorusDepth.setInitValue(settingVal);
#endif
// FIXME: there's no good way to tell if we're loading a preset or an empty instrument
// We rely on instantiate() to load the default soundfont for new instruments,
// but we don't need that when loading a project/preset/preview
if (!Engine::getSong()->isLoadingProject() && !instrumentTrack()->isPreviewMode())
{
loadFile(ConfigManager::inst()->sf2File());
}
connect( &m_bankNum, SIGNAL( dataChanged() ), this, SLOT( updatePatch() ) );
connect( &m_patchNum, SIGNAL( dataChanged() ), this, SLOT( updatePatch() ) );
connect(Engine::audioEngine(), SIGNAL(sampleRateChanged()), this, SLOT(reloadSynth()));
// Gain
connect( &m_gain, SIGNAL( dataChanged() ), this, SLOT( updateGain() ) );
// Reverb
connect( &m_reverbOn, SIGNAL( dataChanged() ), this, SLOT( updateReverbOn() ) );
connect( &m_reverbRoomSize, SIGNAL( dataChanged() ), this, SLOT( updateReverb() ) );
connect( &m_reverbDamping, SIGNAL( dataChanged() ), this, SLOT( updateReverb() ) );
connect( &m_reverbWidth, SIGNAL( dataChanged() ), this, SLOT( updateReverb() ) );
connect( &m_reverbLevel, SIGNAL( dataChanged() ), this, SLOT( updateReverb() ) );
// Chorus
connect( &m_chorusOn, SIGNAL( dataChanged() ), this, SLOT( updateChorusOn() ) );
connect( &m_chorusNum, SIGNAL( dataChanged() ), this, SLOT( updateChorus() ) );
connect( &m_chorusLevel, SIGNAL( dataChanged() ), this, SLOT( updateChorus() ) );
connect( &m_chorusSpeed, SIGNAL( dataChanged() ), this, SLOT( updateChorus() ) );
connect( &m_chorusDepth, SIGNAL( dataChanged() ), this, SLOT( updateChorus() ) );
// Microtuning
connect(Engine::getSong(), &Song::scaleListChanged, this, &Sf2Instrument::updateTuning);
connect(Engine::getSong(), &Song::keymapListChanged, this, &Sf2Instrument::updateTuning);
connect(instrumentTrack()->microtuner()->enabledModel(), &Model::dataChanged, this, &Sf2Instrument::updateTuning, Qt::DirectConnection);
connect(instrumentTrack()->microtuner()->scaleModel(), &Model::dataChanged, this, &Sf2Instrument::updateTuning, Qt::DirectConnection);
connect(instrumentTrack()->microtuner()->keymapModel(), &Model::dataChanged, this, &Sf2Instrument::updateTuning, Qt::DirectConnection);
connect(instrumentTrack()->microtuner()->keyRangeImportModel(), &Model::dataChanged, this, &Sf2Instrument::updateTuning, Qt::DirectConnection);
connect(instrumentTrack()->baseNoteModel(), &Model::dataChanged, this, &Sf2Instrument::updateTuning, Qt::DirectConnection);
auto iph = new InstrumentPlayHandle(this, _instrument_track);
Engine::audioEngine()->addPlayHandle( iph );
}
Sf2Instrument::~Sf2Instrument()
{
Engine::audioEngine()->removePlayHandlesOfTypes( instrumentTrack(),
PlayHandle::Type::NotePlayHandle
| PlayHandle::Type::InstrumentPlayHandle );
freeFont();
delete_fluid_synth( m_synth );
delete_fluid_settings( m_settings );
if( m_srcState != nullptr )
{
src_delete( m_srcState );
}
}
void Sf2Instrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
_this.setAttribute( "src", m_filename );
m_patchNum.saveSettings( _doc, _this, "patch" );
m_bankNum.saveSettings( _doc, _this, "bank" );
m_gain.saveSettings( _doc, _this, "gain" );
m_reverbOn.saveSettings( _doc, _this, "reverbOn" );
m_reverbRoomSize.saveSettings( _doc, _this, "reverbRoomSize" );
m_reverbDamping.saveSettings( _doc, _this, "reverbDamping" );
m_reverbWidth.saveSettings( _doc, _this, "reverbWidth" );
m_reverbLevel.saveSettings( _doc, _this, "reverbLevel" );
m_chorusOn.saveSettings( _doc, _this, "chorusOn" );
m_chorusNum.saveSettings( _doc, _this, "chorusNum" );
m_chorusLevel.saveSettings( _doc, _this, "chorusLevel" );
m_chorusSpeed.saveSettings( _doc, _this, "chorusSpeed" );
m_chorusDepth.saveSettings( _doc, _this, "chorusDepth" );
}
void Sf2Instrument::loadSettings( const QDomElement & _this )
{
openFile( _this.attribute( "src" ), false );
m_patchNum.loadSettings( _this, "patch" );
m_bankNum.loadSettings( _this, "bank" );
m_gain.loadSettings( _this, "gain" );
m_reverbOn.loadSettings( _this, "reverbOn" );
m_reverbRoomSize.loadSettings( _this, "reverbRoomSize" );
m_reverbDamping.loadSettings( _this, "reverbDamping" );
m_reverbWidth.loadSettings( _this, "reverbWidth" );
m_reverbLevel.loadSettings( _this, "reverbLevel" );
m_chorusOn.loadSettings( _this, "chorusOn" );
m_chorusNum.loadSettings( _this, "chorusNum" );
m_chorusLevel.loadSettings( _this, "chorusLevel" );
m_chorusSpeed.loadSettings( _this, "chorusSpeed" );
m_chorusDepth.loadSettings( _this, "chorusDepth" );
}
void Sf2Instrument::loadFile( const QString & _file )
{
if( !_file.isEmpty() && QFileInfo( _file ).exists() )
{
openFile( _file, false );
}
// setting the first bank and patch number that is found
auto sSoundCount = ::fluid_synth_sfcount( m_synth );
for ( int i = 0; i < sSoundCount; ++i ) {
int iBank = 0;
int iProg = 0;
fluid_sfont_t *pSoundFont = ::fluid_synth_get_sfont( m_synth, i );
if ( pSoundFont ) {
#ifdef CONFIG_FLUID_BANK_OFFSET
int iBankOff = ::fluid_synth_get_bank_offset( m_synth, fluid_sfont_get_id( pSoundFont ) );
#endif
fluid_sfont_iteration_start( pSoundFont );
#if FLUIDSYNTH_VERSION_MAJOR < 2
fluid_preset_t preset;
fluid_preset_t *pCurPreset = &preset;
#else
fluid_preset_t *pCurPreset = nullptr;
#endif
if ( ( pCurPreset = fluid_sfont_iteration_next_wrapper( pSoundFont, pCurPreset ) ) ) {
iBank = fluid_preset_get_banknum( pCurPreset );
iProg = fluid_preset_get_num( pCurPreset );
#ifdef CONFIG_FLUID_BANK_OFFSET
iBank += iBankOff;
#endif
::fluid_synth_bank_select( m_synth, 1, iBank );
::fluid_synth_program_change( m_synth, 1, iProg );
m_bankNum.setValue( iBank );
m_patchNum.setValue ( iProg );
break;
}
}
}
}
AutomatableModel * Sf2Instrument::childModel( const QString & _modelName )
{
if( _modelName == "bank" )
{
return &m_bankNum;
}
else if( _modelName == "patch" )
{
return &m_patchNum;
}
qCritical() << "requested unknown model " << _modelName;
return nullptr;
}
QString Sf2Instrument::nodeName() const
{
return sf2player_plugin_descriptor.name;
}
void Sf2Instrument::freeFont()
{
m_synthMutex.lock();
if (m_font != nullptr)
{
fluid_synth_sfunload(m_synth, m_fontId, true);
m_font = nullptr;
}
m_synthMutex.unlock();
}
void Sf2Instrument::openFile( const QString & _sf2File, bool updateTrackName )
{
emit fileLoading();
// Used for loading file
char * sf2Ascii = qstrdup( qPrintable( PathUtil::toAbsolute( _sf2File ) ) );
QString relativePath = PathUtil::toShortestRelative( _sf2File );
// free the soundfont if one is selected
freeFont();
m_synthMutex.lock();
bool loaded = false;
if (fluid_is_soundfont(sf2Ascii))
{
m_fontId = fluid_synth_sfload(m_synth, sf2Ascii, true);
if (fluid_synth_sfcount(m_synth) > 0)
{
// Grab this sf from the top of the stack and add to list
m_font = fluid_synth_get_sfont(m_synth, 0);
loaded = true;
}
}
if (!loaded)
{
collectErrorForUI(Sf2Instrument::tr("A soundfont %1 could not be loaded.").arg(QFileInfo(_sf2File).baseName()));
}
m_synthMutex.unlock();
if( m_fontId >= 0 )
{
// Don't reset patch/bank, so that it isn't cleared when
// someone resolves a missing file
//m_patchNum.setValue( 0 );
//m_bankNum.setValue( 0 );
m_filename = relativePath;
emit fileChanged();
}
delete[] sf2Ascii;
if( updateTrackName || instrumentTrack()->displayName() == displayName() )
{
instrumentTrack()->setName( PathUtil::cleanName( _sf2File ) );
}
updatePatch();
}
void Sf2Instrument::updatePatch()
{
if( m_bankNum.value() >= 0 && m_patchNum.value() >= 0 )
{
fluid_synth_program_select( m_synth, m_channel, m_fontId,
m_bankNum.value(), m_patchNum.value() );
}
}
QString Sf2Instrument::getCurrentPatchName()
{
int iBankSelected = m_bankNum.value();
int iProgSelected = m_patchNum.value();
// For all soundfonts (in reversed stack order) fill the available programs...
int cSoundFonts = ::fluid_synth_sfcount( m_synth );
for( int i = 0; i < cSoundFonts; i++ )
{
fluid_sfont_t *pSoundFont = fluid_synth_get_sfont( m_synth, i );
if ( pSoundFont )
{
#ifdef CONFIG_FLUID_BANK_OFFSET
int iBankOffset =
fluid_synth_get_bank_offset(
m_synth, fluid_sfont_get_id(pSoundFont) );
#endif
fluid_sfont_iteration_start( pSoundFont );
#if FLUIDSYNTH_VERSION_MAJOR < 2
fluid_preset_t preset;
fluid_preset_t *pCurPreset = &preset;
#else
fluid_preset_t *pCurPreset = nullptr;
#endif
while ((pCurPreset = fluid_sfont_iteration_next_wrapper(pSoundFont, pCurPreset)))
{
int iBank = fluid_preset_get_banknum( pCurPreset );
#ifdef CONFIG_FLUID_BANK_OFFSET
iBank += iBankOffset;
#endif
int iProg = fluid_preset_get_num( pCurPreset );
if( iBank == iBankSelected && iProg ==
iProgSelected )
{
return fluid_preset_get_name( pCurPreset );
}
}
}
}
return "";
}
void Sf2Instrument::updateGain()
{
fluid_synth_set_gain( m_synth, m_gain.value() );
}
#define FLUIDSYNTH_VERSION_HEX ((FLUIDSYNTH_VERSION_MAJOR << 16) \
| (FLUIDSYNTH_VERSION_MINOR << 8) \
| FLUIDSYNTH_VERSION_MICRO)
#define USE_NEW_EFFECT_API (FLUIDSYNTH_VERSION_HEX >= 0x020200)
void Sf2Instrument::updateReverbOn()
{
#if USE_NEW_EFFECT_API
fluid_synth_reverb_on(m_synth, -1, m_reverbOn.value() ? 1 : 0);
#else
fluid_synth_set_reverb_on(m_synth, m_reverbOn.value() ? 1 : 0);
#endif
}
void Sf2Instrument::updateReverb()
{
#if USE_NEW_EFFECT_API
fluid_synth_set_reverb_group_roomsize(m_synth, -1, m_reverbRoomSize.value());
fluid_synth_set_reverb_group_damp(m_synth, -1, m_reverbDamping.value());
fluid_synth_set_reverb_group_width(m_synth, -1, m_reverbWidth.value());
fluid_synth_set_reverb_group_level(m_synth, -1, m_reverbLevel.value());
#else
fluid_synth_set_reverb(m_synth, m_reverbRoomSize.value(),
m_reverbDamping.value(), m_reverbWidth.value(),
m_reverbLevel.value());
#endif
}
void Sf2Instrument::updateChorusOn()
{
#if USE_NEW_EFFECT_API
fluid_synth_chorus_on(m_synth, -1, m_chorusOn.value() ? 1 : 0);
#else
fluid_synth_set_chorus_on(m_synth, m_chorusOn.value() ? 1 : 0);
#endif
}
void Sf2Instrument::updateChorus()
{
#if USE_NEW_EFFECT_API
fluid_synth_set_chorus_group_nr(m_synth, -1, static_cast<int>(m_chorusNum.value()));
fluid_synth_set_chorus_group_level(m_synth, -1, m_chorusLevel.value());
fluid_synth_set_chorus_group_speed(m_synth, -1, m_chorusSpeed.value());
fluid_synth_set_chorus_group_depth(m_synth, -1, m_chorusDepth.value());
fluid_synth_set_chorus_group_type(m_synth, -1, FLUID_CHORUS_MOD_SINE);
#else
fluid_synth_set_chorus(m_synth, static_cast<int>(m_chorusNum.value()),
m_chorusLevel.value(), m_chorusSpeed.value(),
m_chorusDepth.value(), FLUID_CHORUS_MOD_SINE);
#endif
}
void Sf2Instrument::updateTuning()
{
if (instrumentTrack()->microtuner()->enabledModel()->value())
{
auto centArray = std::array<double, 128>{};
double lowestHz = pow(2., -69. / 12.) * 440.;// Frequency of MIDI note 0, which is approximately 8.175798916 Hz
for (int i = 0; i < 128; ++i)
{
// Get desired Hz of note
double noteHz = instrumentTrack()->microtuner()->keyToFreq(i, DefaultBaseKey);
// Convert Hz to cents
centArray[i] = noteHz == 0. ? 0. : 1200. * log2(noteHz / lowestHz);
}
fluid_synth_activate_key_tuning(m_synth, 0, 0, "", centArray.data(), true);
for (int chan = 0; chan < 16; chan++)
{
fluid_synth_activate_tuning(m_synth, chan, 0, 0, true);
}
}
else
{
fluid_synth_activate_key_tuning(m_synth, 0, 0, "", nullptr, true);
for (int chan = 0; chan < 16; chan++)
{
fluid_synth_activate_tuning(m_synth, chan, 0, 0, true);
}
}
}
void Sf2Instrument::reloadSynth()
{
double tempRate;
// Set & get, returns the true sample rate
fluid_settings_setnum( m_settings, (char *) "synth.sample-rate", Engine::audioEngine()->outputSampleRate() );
fluid_settings_getnum( m_settings, (char *) "synth.sample-rate", &tempRate );
m_internalSampleRate = static_cast<int>( tempRate );
if( m_font )
{
// Now, delete the old one and replace
m_synthMutex.lock();
fluid_synth_remove_sfont( m_synth, m_font );
delete_fluid_synth( m_synth );
// New synth
m_synth = new_fluid_synth( m_settings );
m_fontId = fluid_synth_add_sfont( m_synth, m_font );
m_synthMutex.unlock();
// synth program change (set bank and patch)
updatePatch();
}
else
{
// Recreate synth with no soundfonts
m_synthMutex.lock();
if (m_synth != nullptr)
{
delete_fluid_synth(m_synth);
}
m_synth = new_fluid_synth( m_settings );
m_synthMutex.unlock();
}
m_synthMutex.lock();
if( Engine::audioEngine()->currentQualitySettings().interpolation >=
AudioEngine::qualitySettings::Interpolation::SincFastest )
{
fluid_synth_set_interp_method( m_synth, -1, FLUID_INTERP_7THORDER );
}
else
{
fluid_synth_set_interp_method( m_synth, -1, FLUID_INTERP_DEFAULT );
}
m_synthMutex.unlock();
if( m_internalSampleRate < Engine::audioEngine()->outputSampleRate() )
{
m_synthMutex.lock();
if( m_srcState != nullptr )
{
src_delete( m_srcState );
}
int error;
m_srcState = src_new( Engine::audioEngine()->currentQualitySettings().libsrcInterpolation(), DEFAULT_CHANNELS, &error );
if( m_srcState == nullptr || error )
{
qCritical("error while creating libsamplerate data structure in Sf2Instrument::reloadSynth()");
}
m_synthMutex.unlock();
}
updateReverb();
updateChorus();
updateReverbOn();
updateChorusOn();
updateGain();
updateTuning();
// Reset last MIDI pitch properties, which will be set to the correct values
// upon playing the next note
m_lastMidiPitch = -1;
m_lastMidiPitchRange = -1;
}
void Sf2Instrument::playNote( NotePlayHandle * _n, SampleFrame* )
{
if( _n->isMasterNote() || ( _n->hasParent() && _n->isReleased() ) )
{
return;
}
int masterPitch = instrumentTrack()->useMasterPitchModel()->value() ? Engine::getSong()->masterPitch() : 0;
int baseNote = instrumentTrack()->baseNoteModel()->value();
int midiNote = _n->midiKey() - baseNote + DefaultBaseKey + masterPitch;
// out of range?
if (midiNote < 0 || midiNote >= 128)
{
return;
}
if (!_n->m_pluginData)
{
const int baseVelocity = instrumentTrack()->midiPort()->baseVelocity();
auto pluginData = new Sf2PluginData;
pluginData->midiNote = midiNote;
pluginData->lastPanning = 0;
pluginData->lastVelocity = _n->midiVelocity( baseVelocity );
pluginData->isNew = true;
pluginData->offset = _n->offset();
pluginData->noteOffSent = false;
pluginData->panning = _n->getPanning();
_n->m_pluginData = pluginData;
// insert the nph to the playing notes vector
m_playingNotesMutex.lock();
m_playingNotes.append( _n );
m_playingNotesMutex.unlock();
}
else if( _n->isReleased() && ! _n->instrumentTrack()->isSustainPedalPressed() ) // note is released during this period
{
auto pluginData = static_cast<Sf2PluginData*>(_n->m_pluginData);
pluginData->offset = _n->framesBeforeRelease();
pluginData->isNew = false;
m_playingNotesMutex.lock();
m_playingNotes.append( _n );
m_playingNotesMutex.unlock();
}
// Update the pitch of all the voices
if (const auto data = static_cast<Sf2PluginData*>(_n->m_pluginData)) {
const auto detuning = _n->currentDetuning();
for (const auto& voice : data->fluidVoices) {
if (voice.isValid()) {
fluid_voice_gen_set(voice.get(), GEN_COARSETUNE, voice.coarseTune() + detuning);
fluid_voice_update_param(voice.get(), GEN_COARSETUNE);
}
}
}
}
void Sf2Instrument::noteOn( Sf2PluginData * n )
{
m_synthMutex.lock();
// get list of current voice IDs so we can easily spot the new
// voice after the fluid_synth_noteon() call
const int poly = fluid_synth_get_polyphony( m_synth );
#ifndef _MSC_VER
fluid_voice_t* voices[poly];
#else
const auto voices = static_cast<fluid_voice_t**>(_alloca(poly * sizeof(fluid_voice_t*)));
#endif
fluid_synth_noteon( m_synth, m_channel, n->midiNote, n->lastVelocity );
// Get any new voices and store them in the plugin data
fluid_synth_get_voicelist(m_synth, voices, poly, -1);
for (int i = 0; i < poly && voices[i] && !n->fluidVoices.full(); ++i)
{
const auto voice = voices[i];
// FluidSynth stops voices with the same channel and pitch upon note-on,
// so voices with the current channel and pitch are playing this note.
if (fluid_voice_get_channel(voice) == m_channel
&& fluid_voice_get_key(voice) == n->midiNote
&& fluid_voice_is_on(voice)
) {
n->fluidVoices.emplace_back(voices[i]);
}
}
#if FLUIDSYNTH_VERSION_MAJOR >= 2
// Smallest balance value that results in full attenuation of one channel.
// Corresponds to internal FluidSynth macro `FLUID_CB_AMP_SIZE`.
constexpr static auto maxBalance = 1441.f;
// Convert panning from linear to exponential for FluidSynth
const auto panning = n->panning;
const auto factor = 1.f - std::abs(panning) / static_cast<float>(PanningRight);
const auto balance = std::copysign(
factor <= 0 ? maxBalance : std::min(-200.f * std::log10(factor), maxBalance),
panning
);
// Set note panning on all the voices
for (const auto& voice : n->fluidVoices) {
if (voice.isValid()) {
fluid_voice_gen_set(voice.get(), GEN_CUSTOM_BALANCE, balance);
fluid_voice_update_param(voice.get(), GEN_CUSTOM_BALANCE);
}
}
#endif
m_synthMutex.unlock();
m_notesRunningMutex.lock();
++m_notesRunning[ n->midiNote ];
m_notesRunningMutex.unlock();
}
void Sf2Instrument::noteOff( Sf2PluginData * n )
{
n->noteOffSent = true;
m_notesRunningMutex.lock();
const int notes = --m_notesRunning[n->midiNote];
m_notesRunningMutex.unlock();
if( notes <= 0 )
{
m_synthMutex.lock();
fluid_synth_noteoff( m_synth, m_channel, n->midiNote );
m_synthMutex.unlock();
}
}
void Sf2Instrument::play( SampleFrame* _working_buffer )
{
const fpp_t frames = Engine::audioEngine()->framesPerPeriod();
// set midi pitch for this period
const int currentMidiPitch = instrumentTrack()->midiPitch();
if( m_lastMidiPitch != currentMidiPitch )
{
m_lastMidiPitch = currentMidiPitch;
m_synthMutex.lock();
fluid_synth_pitch_bend( m_synth, m_channel, m_lastMidiPitch );
m_synthMutex.unlock();
}
const int currentMidiPitchRange = instrumentTrack()->midiPitchRange();
if( m_lastMidiPitchRange != currentMidiPitchRange )
{
m_lastMidiPitchRange = currentMidiPitchRange;
m_synthMutex.lock();
fluid_synth_pitch_wheel_sens( m_synth, m_channel, m_lastMidiPitchRange );
m_synthMutex.unlock();
}
// if we have no new noteons/noteoffs, just render a period and call it a day
if( m_playingNotes.isEmpty() )
{
renderFrames( frames, _working_buffer );
return;
}
// processing loop
// go through noteplayhandles in processing order
f_cnt_t currentFrame = 0;
while( ! m_playingNotes.isEmpty() )
{
// find the note with lowest offset
NotePlayHandle * currentNote = m_playingNotes[0];
for( int i = 1; i < m_playingNotes.size(); ++i )
{
auto currentData = static_cast<Sf2PluginData*>(currentNote->m_pluginData);
auto iData = static_cast<Sf2PluginData*>(m_playingNotes[i]->m_pluginData);
if( currentData->offset > iData->offset )
{
currentNote = m_playingNotes[i];
}
}
// process the current note:
// first see if we're synced in frame count
auto currentData = static_cast<Sf2PluginData*>(currentNote->m_pluginData);
if( currentData->offset > currentFrame )
{
renderFrames( currentData->offset - currentFrame, _working_buffer + currentFrame );
currentFrame = currentData->offset;
}
if( currentData->isNew )
{
noteOn( currentData );
if( currentNote->isReleased() ) // if the note is released during the same period, we have to process it again for noteoff
{
currentData->isNew = false;
currentData->offset = currentNote->framesBeforeRelease();
}
else // otherwise remove the handle
{
m_playingNotesMutex.lock();
m_playingNotes.remove( m_playingNotes.indexOf( currentNote ) );
m_playingNotesMutex.unlock();
}
}
else
{
noteOff( currentData );
m_playingNotesMutex.lock();
m_playingNotes.remove( m_playingNotes.indexOf( currentNote ) );
m_playingNotesMutex.unlock();
}
}
if( currentFrame < frames )
{
renderFrames( frames - currentFrame, _working_buffer + currentFrame );
}
}
void Sf2Instrument::renderFrames( f_cnt_t frames, SampleFrame* buf )
{
m_synthMutex.lock();
fluid_synth_get_gain(m_synth); // This flushes voice updates as a side effect
if( m_internalSampleRate < Engine::audioEngine()->outputSampleRate() &&
m_srcState != nullptr )
{
const fpp_t f = frames * m_internalSampleRate / Engine::audioEngine()->outputSampleRate();
#ifdef __GNUC__
SampleFrame tmp[f];
#else
SampleFrame* tmp = new SampleFrame[f];
#endif
fluid_synth_write_float( m_synth, f, tmp, 0, 2, tmp, 1, 2 );
SRC_DATA src_data;
src_data.data_in = (float *)tmp;
src_data.data_out = (float *)buf;
src_data.input_frames = f;
src_data.output_frames = frames;
src_data.src_ratio = (double) frames / f;
src_data.end_of_input = 0;
int error = src_process( m_srcState, &src_data );
#ifndef __GNUC__
delete[] tmp;
#endif
if( error )
{
qCritical( "Sf2Instrument: error while resampling: %s", src_strerror( error ) );
}
if (static_cast<f_cnt_t>(src_data.output_frames_gen) < frames)
{
qCritical("Sf2Instrument: not enough frames: %ld / %zu", src_data.output_frames_gen, frames);
}
}
else
{
fluid_synth_write_float( m_synth, frames, buf, 0, 2, buf, 1, 2 );
}
m_synthMutex.unlock();
}
void Sf2Instrument::deleteNotePluginData( NotePlayHandle * _n )
{
auto pluginData = static_cast<Sf2PluginData*>(_n->m_pluginData);
if( ! pluginData->noteOffSent ) // if we for some reason haven't noteoffed the note before it gets deleted,
// do it here
{
noteOff( pluginData );
m_playingNotesMutex.lock();
if( m_playingNotes.indexOf( _n ) >= 0 )
{
m_playingNotes.remove( m_playingNotes.indexOf( _n ) );
}
m_playingNotesMutex.unlock();
}
delete pluginData;
}
gui::PluginView * Sf2Instrument::instantiateView( QWidget * _parent )
{
return new gui::Sf2InstrumentView( this, _parent );
}
namespace gui
{
class Sf2Knob : public Knob
{
public:
Sf2Knob( QWidget * _parent ) :
Knob( KnobType::Styled, _parent )
{
setFixedSize( 31, 38 );
}
};
Sf2InstrumentView::Sf2InstrumentView( Instrument * _instrument, QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
// QVBoxLayout * vl = new QVBoxLayout( this );
// QHBoxLayout * hl = new QHBoxLayout();
auto k = castModel<Sf2Instrument>();
connect(&k->m_bankNum, SIGNAL(dataChanged()), this, SLOT(updatePatchName()));
connect(&k->m_patchNum, SIGNAL(dataChanged()), this, SLOT(updatePatchName()));
// File Button
m_fileDialogButton = new PixmapButton(this);
m_fileDialogButton->setCursor(QCursor(Qt::PointingHandCursor));
m_fileDialogButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("fileselect_on"));
m_fileDialogButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("fileselect_off"));
m_fileDialogButton->move(217, 107);
connect(m_fileDialogButton, SIGNAL(clicked()), this, SLOT(showFileDialog()));
m_fileDialogButton->setToolTip(tr("Open SoundFont file"));
// Patch Button
m_patchDialogButton = new PixmapButton(this);
m_patchDialogButton->setCursor(QCursor(Qt::PointingHandCursor));
m_patchDialogButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("patches_on"));
m_patchDialogButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("patches_off"));
m_patchDialogButton->setEnabled(false);
m_patchDialogButton->move(217, 125);
connect(m_patchDialogButton, SIGNAL(clicked()), this, SLOT(showPatchDialog()));
m_patchDialogButton->setToolTip(tr("Choose patch"));
// LCDs
m_bankNumLcd = new LcdSpinBox(3, "21pink", this);
m_bankNumLcd->move(131, 62);
// m_bankNumLcd->addTextForValue( -1, "---" );
// m_bankNumLcd->setEnabled( false );
m_patchNumLcd = new LcdSpinBox( 3, "21pink", this );
m_patchNumLcd->move(190, 62);
// m_patchNumLcd->addTextForValue( -1, "---" );
// m_patchNumLcd->setEnabled( false );
/*hl->addWidget( m_fileDialogButton );
hl->addWidget( m_bankNumLcd );
hl->addWidget( m_patchNumLcd );
hl->addWidget( m_patchDialogButton );
vl->addLayout( hl );*/
// Next row
//hl = new QHBoxLayout();
m_filenameLabel = new QLabel( this );
m_filenameLabel->setGeometry( 58, 109, 156, 11 );
m_patchLabel = new QLabel( this );
m_patchLabel->setGeometry( 58, 127, 156, 11 );
//hl->addWidget( m_filenameLabel );
// vl->addLayout( hl );
// Gain
m_gainKnob = new Sf2Knob( this );
m_gainKnob->setHintText( tr("Gain:"), "" );
m_gainKnob->move( 86, 55 );
// vl->addWidget( m_gainKnob );
// Reverb
// hl = new QHBoxLayout();
m_reverbButton = new PixmapButton( this );
m_reverbButton->setCheckable( true );
m_reverbButton->move( 14, 180 );
m_reverbButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "reverb_on" ) );
m_reverbButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "reverb_off" ) );
m_reverbButton->setToolTip(tr("Apply reverb (if supported)"));
m_reverbRoomSizeKnob = new Sf2Knob( this );
m_reverbRoomSizeKnob->setHintText( tr("Room size:"), "" );
m_reverbRoomSizeKnob->move( 93, 160 );
m_reverbDampingKnob = new Sf2Knob( this );
m_reverbDampingKnob->setHintText( tr("Damping:"), "" );
m_reverbDampingKnob->move( 130, 160 );
m_reverbWidthKnob = new Sf2Knob( this );
m_reverbWidthKnob->setHintText( tr("Width:"), "" );
m_reverbWidthKnob->move( 167, 160 );
m_reverbLevelKnob = new Sf2Knob( this );
m_reverbLevelKnob->setHintText( tr("Level:"), "" );
m_reverbLevelKnob->move( 204, 160 );
/* hl->addWidget( m_reverbOnLed );
hl->addWidget( m_reverbRoomSizeKnob );
hl->addWidget( m_reverbDampingKnob );
hl->addWidget( m_reverbWidthKnob );
hl->addWidget( m_reverbLevelKnob );
vl->addLayout( hl );
*/
// Chorus
// hl = new QHBoxLayout();
m_chorusButton = new PixmapButton( this );
m_chorusButton->setCheckable( true );
m_chorusButton->move( 14, 226 );
m_chorusButton->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "chorus_on" ) );
m_chorusButton->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "chorus_off" ) );
m_chorusButton->setToolTip(tr("Apply chorus (if supported)"));
m_chorusNumKnob = new Sf2Knob( this );
m_chorusNumKnob->setHintText( tr("Voices:"), "" );
m_chorusNumKnob->move( 93, 206 );
m_chorusLevelKnob = new Sf2Knob( this );
m_chorusLevelKnob->setHintText( tr("Level:"), "" );
m_chorusLevelKnob->move( 130 , 206 );
m_chorusSpeedKnob = new Sf2Knob( this );
m_chorusSpeedKnob->setHintText( tr("Speed:"), "" );
m_chorusSpeedKnob->move( 167 , 206 );
m_chorusDepthKnob = new Sf2Knob( this );
m_chorusDepthKnob->setHintText( tr("Depth:"), "" );
m_chorusDepthKnob->move( 204 , 206 );
/*
hl->addWidget( m_chorusOnLed );
hl->addWidget( m_chorusNumKnob);
hl->addWidget( m_chorusLevelKnob);
hl->addWidget( m_chorusSpeedKnob);
hl->addWidget( m_chorusDepthKnob);
vl->addLayout( hl );
*/
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
updateFilename();
}
void Sf2InstrumentView::modelChanged()
{
auto k = castModel<Sf2Instrument>();
m_bankNumLcd->setModel( &k->m_bankNum );
m_patchNumLcd->setModel( &k->m_patchNum );
m_gainKnob->setModel( &k->m_gain );
m_reverbButton->setModel( &k->m_reverbOn );
m_reverbRoomSizeKnob->setModel( &k->m_reverbRoomSize );
m_reverbDampingKnob->setModel( &k->m_reverbDamping );
m_reverbWidthKnob->setModel( &k->m_reverbWidth );
m_reverbLevelKnob->setModel( &k->m_reverbLevel );
m_chorusButton->setModel( &k->m_chorusOn );
m_chorusNumKnob->setModel( &k->m_chorusNum );
m_chorusLevelKnob->setModel( &k->m_chorusLevel );
m_chorusSpeedKnob->setModel( &k->m_chorusSpeed );
m_chorusDepthKnob->setModel( &k->m_chorusDepth );
connect( k, SIGNAL( fileChanged() ), this, SLOT( updateFilename() ) );
connect( k, SIGNAL( fileLoading() ), this, SLOT( invalidateFile() ) );
updateFilename();
}
void Sf2InstrumentView::updateFilename()
{
auto i = castModel<Sf2Instrument>();
QFontMetrics fm( m_filenameLabel->font() );
QString file = i->m_filename.endsWith( ".sf2", Qt::CaseInsensitive ) ?
i->m_filename.left( i->m_filename.length() - 4 ) :
i->m_filename;
m_filenameLabel->setText( fm.elidedText( file, Qt::ElideLeft, m_filenameLabel->width() ) );
// i->m_filename + "\nPatch: TODO" );
m_patchDialogButton->setEnabled( !i->m_filename.isEmpty() );
updatePatchName();
update();
}
void Sf2InstrumentView::updatePatchName()
{
auto i = castModel<Sf2Instrument>();
QFontMetrics fm( font() );
QString patch = i->getCurrentPatchName();
m_patchLabel->setText( fm.elidedText( patch, Qt::ElideLeft, m_patchLabel->width() ) );
update();
}
void Sf2InstrumentView::invalidateFile()
{
m_patchDialogButton->setEnabled( false );
}
void Sf2InstrumentView::showFileDialog()
{
auto k = castModel<Sf2Instrument>();
FileDialog ofd( nullptr, tr( "Open SoundFont file" ) );
ofd.setFileMode( FileDialog::ExistingFiles );
QStringList types;
types << tr( "SoundFont Files (*.sf2 *.sf3)" );
ofd.setNameFilters( types );
if( k->m_filename != "" )
{
QString f = PathUtil::toAbsolute( k->m_filename );
ofd.setDirectory( QFileInfo( f ).absolutePath() );
ofd.selectFile( QFileInfo( f ).fileName() );
}
else
{
ofd.setDirectory( ConfigManager::inst()->sf2Dir() );
}
m_fileDialogButton->setEnabled( false );
if( ofd.exec() == QDialog::Accepted && !ofd.selectedFiles().isEmpty() )
{
QString f = ofd.selectedFiles()[0];
if( f != "" )
{
k->openFile( f );
Engine::getSong()->setModified();
}
}
m_fileDialogButton->setEnabled( true );
}
void Sf2InstrumentView::showPatchDialog()
{
auto k = castModel<Sf2Instrument>();
PatchesDialog pd( this );
pd.setup( k->m_synth, 1, k->instrumentTrack()->name(), &k->m_bankNum, &k->m_patchNum, m_patchLabel );
pd.exec();
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return new Sf2Instrument( static_cast<InstrumentTrack *>( m ) );
}
}
} // namespace lmms
| 36,095
|
C++
|
.cpp
| 1,008
| 33.340278
| 144
| 0.71714
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,711
|
PatchesDialog.cpp
|
LMMS_lmms/plugins/Sf2Player/PatchesDialog.cpp
|
/*
* PatchesDialog.cpp - display sf2 patches
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "PatchesDialog.h"
#include <fluidsynth.h>
#include <QHeaderView>
//#include <QFileInfo>
#include <QLabel>
#include "fluidsynthshims.h"
namespace lmms::gui
{
// Custom list-view item (as for numerical sort purposes...)
class PatchItem : public QTreeWidgetItem
{
public:
// Constructor.
PatchItem( QTreeWidget *pListView,
QTreeWidgetItem *pItemAfter )
: QTreeWidgetItem( pListView, pItemAfter ) {}
// Sort/compare overriden method.
bool operator< ( const QTreeWidgetItem& other ) const override
{
int iColumn = QTreeWidgetItem::treeWidget()->sortColumn();
const QString& s1 = text( iColumn );
const QString& s2 = other.text( iColumn );
if( iColumn == 0 || iColumn == 2 )
{
return( s1.toInt() < s2.toInt() );
}
else
{
return( s1 < s2 );
}
}
};
// Constructor.
PatchesDialog::PatchesDialog( QWidget *pParent, Qt::WindowFlags wflags )
: QDialog( pParent, wflags )
{
// Setup UI struct...
setupUi( this );
m_pSynth = nullptr;
m_iChan = 0;
m_iBank = 0;
m_iProg = 0;
// Soundfonts list view...
QHeaderView *pHeader = m_progListView->header();
// pHeader->setResizeMode(QHeaderView::Custom);
pHeader->setDefaultAlignment(Qt::AlignLeft);
// pHeader->setDefaultSectionSize(200);
pHeader->setSectionsMovable(false);
pHeader->setStretchLastSection(true);
m_progListView->resizeColumnToContents(0); // Prog.
//pHeader->resizeSection(1, 200); // Name.
// Initial sort order...
m_bankListView->sortItems(0, Qt::AscendingOrder);
m_progListView->sortItems(0, Qt::AscendingOrder);
// UI connections...
QObject::connect(m_bankListView,
SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
SLOT(bankChanged()));
QObject::connect(m_progListView,
SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
SLOT(progChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
QObject::connect(m_progListView,
SIGNAL(itemActivated(QTreeWidgetItem*,int)),
SLOT(accept()));
QObject::connect(m_okButton,
SIGNAL(clicked()),
SLOT(accept()));
QObject::connect(m_cancelButton,
SIGNAL(clicked()),
SLOT(reject()));
}
// Dialog setup loader.
void PatchesDialog::setup ( fluid_synth_t * pSynth, int iChan,
const QString & _chanName,
LcdSpinBoxModel * _bankModel,
LcdSpinBoxModel * _progModel,
QLabel * _patchLabel )
{
// We'll going to changes the whole thing...
m_dirty = 0;
m_bankModel = _bankModel;
m_progModel = _progModel;
m_patchLabel = _patchLabel;
// Set the proper caption...
setWindowTitle( _chanName + " - Soundfont patches" );
// set m_pSynth to NULL so we don't trigger any progChanged events
m_pSynth = nullptr;
// Load bank list from actual synth stack...
m_bankListView->setSortingEnabled(false);
m_bankListView->clear();
// now it should be safe to set internal stuff
m_pSynth = pSynth;
m_iChan = iChan;
QTreeWidgetItem *pBankItem = nullptr;
// For all soundfonts (in reversed stack order) fill the available banks...
int cSoundFonts = ::fluid_synth_sfcount(m_pSynth);
for (int i = 0; i < cSoundFonts; i++) {
fluid_sfont_t *pSoundFont = ::fluid_synth_get_sfont(m_pSynth, i);
if (pSoundFont) {
#ifdef CONFIG_FLUID_BANK_OFFSET
int iBankOffset = ::fluid_synth_get_bank_offset(m_pSynth, fluid_sfont_get_id(pSoundFont));
#endif
fluid_sfont_iteration_start(pSoundFont);
#if FLUIDSYNTH_VERSION_MAJOR < 2
fluid_preset_t preset;
fluid_preset_t *pCurPreset = &preset;
#else
fluid_preset_t *pCurPreset = nullptr;
#endif
while ((pCurPreset = fluid_sfont_iteration_next_wrapper(pSoundFont, pCurPreset))) {
int iBank = fluid_preset_get_banknum(pCurPreset);
#ifdef CONFIG_FLUID_BANK_OFFSET
iBank += iBankOffset;
#endif
if (!findBankItem(iBank)) {
pBankItem = new PatchItem(m_bankListView, pBankItem);
if (pBankItem)
pBankItem->setText(0, QString::number(iBank));
}
}
}
}
m_bankListView->setSortingEnabled(true);
// Set the selected bank.
m_iBank = 0;
fluid_preset_t *pPreset = ::fluid_synth_get_channel_preset(m_pSynth, m_iChan);
if (pPreset) {
m_iBank = fluid_preset_get_banknum(pPreset);
#ifdef CONFIG_FLUID_BANK_OFFSET
m_iBank += ::fluid_synth_get_bank_offset(m_pSynth, fluid_sfont_get_id(fluid_preset_get_sfont(sfont)));
#endif
}
pBankItem = findBankItem(m_iBank);
m_bankListView->setCurrentItem(pBankItem);
m_bankListView->scrollToItem(pBankItem);
bankChanged();
// Set the selected program.
if (pPreset)
m_iProg = fluid_preset_get_num(pPreset);
QTreeWidgetItem *pProgItem = findProgItem(m_iProg);
m_progListView->setCurrentItem(pProgItem);
m_progListView->scrollToItem(pProgItem);
// Done with setup...
//m_iDirtySetup--;
}
// Stabilize current state form.
void PatchesDialog::stabilizeForm()
{
m_okButton->setEnabled(validateForm());
}
// Validate form fields.
bool PatchesDialog::validateForm()
{
bool bValid = true;
bValid = bValid && (m_bankListView->currentItem() != nullptr);
bValid = bValid && (m_progListView->currentItem() != nullptr);
return bValid;
}
// Realize a bank-program selection preset.
void PatchesDialog::setBankProg ( int iBank, int iProg )
{
if (m_pSynth == nullptr)
return;
// just select the synth's program preset...
::fluid_synth_bank_select(m_pSynth, m_iChan, iBank);
::fluid_synth_program_change(m_pSynth, m_iChan, iProg);
// Maybe this is needed to stabilize things around.
::fluid_synth_program_reset(m_pSynth);
}
// Validate form fields and accept it valid.
void PatchesDialog::accept()
{
if (validateForm()) {
// Unload from current selected dialog items.
int iBank = (m_bankListView->currentItem())->text(0).toInt();
int iProg = (m_progListView->currentItem())->text(0).toInt();
// And set it right away...
setBankProg(iBank, iProg);
if (m_dirty > 0) {
m_bankModel->setValue( iBank );
m_progModel->setValue( iProg );
m_patchLabel->setText( m_progListView->
currentItem()->text( 1 ) );
}
// Do remember preview state...
// if (m_pOptions)
// m_pOptions->bPresetPreview = m_ui.PreviewCheckBox->isChecked();
// We got it.
QDialog::accept();
}
}
// Reject settings (Cancel button slot).
void PatchesDialog::reject ()
{
// Reset selection to initial selection, if applicable...
if (m_dirty > 0)
setBankProg(m_bankModel->value(), m_progModel->value());
// Done (hopefully nothing).
QDialog::reject();
}
// Find the bank item of given bank number id.
QTreeWidgetItem *PatchesDialog::findBankItem ( int iBank )
{
QList<QTreeWidgetItem *> banks
= m_bankListView->findItems(
QString::number(iBank), Qt::MatchExactly, 0);
QListIterator<QTreeWidgetItem *> iter(banks);
if (iter.hasNext())
return iter.next();
else
return nullptr;
}
// Find the program item of given program number id.
QTreeWidgetItem *PatchesDialog::findProgItem ( int iProg )
{
QList<QTreeWidgetItem *> progs
= m_progListView->findItems(
QString::number(iProg), Qt::MatchExactly, 0);
QListIterator<QTreeWidgetItem *> iter(progs);
if (iter.hasNext())
return iter.next();
else
return nullptr;
}
// Bank change slot.
void PatchesDialog::bankChanged ()
{
if (m_pSynth == nullptr)
return;
QTreeWidgetItem *pBankItem = m_bankListView->currentItem();
if (pBankItem == nullptr)
return;
int iBankSelected = pBankItem->text(0).toInt();
// Clear up the program listview.
m_progListView->setSortingEnabled(false);
m_progListView->clear();
QTreeWidgetItem *pProgItem = nullptr;
// For all soundfonts (in reversed stack order) fill the available programs...
int cSoundFonts = ::fluid_synth_sfcount(m_pSynth);
for (int i = 0; i < cSoundFonts && !pProgItem; i++) {
fluid_sfont_t *pSoundFont = ::fluid_synth_get_sfont(m_pSynth, i);
if (pSoundFont) {
#ifdef CONFIG_FLUID_BANK_OFFSET
int iBankOffset = ::fluid_synth_get_bank_offset(m_pSynth, fluid_sfont_get_id(pSoundFont));
#endif
fluid_sfont_iteration_start(pSoundFont);
#if FLUIDSYNTH_VERSION_MAJOR < 2
fluid_preset_t preset;
fluid_preset_t *pCurPreset = &preset;
#else
fluid_preset_t *pCurPreset = nullptr;
#endif
while ((pCurPreset = fluid_sfont_iteration_next_wrapper(pSoundFont, pCurPreset))) {
int iBank = fluid_preset_get_banknum(pCurPreset);
#ifdef CONFIG_FLUID_BANK_OFFSET
iBank += iBankOffset;
#endif
int iProg = fluid_preset_get_num(pCurPreset);
if (iBank == iBankSelected && !findProgItem(iProg)) {
pProgItem = new PatchItem(m_progListView, pProgItem);
if (pProgItem) {
pProgItem->setText(0, QString::number(iProg));
pProgItem->setText(1, fluid_preset_get_name(pCurPreset));
//pProgItem->setText(2, QString::number(fluid_sfont_get_id(pSoundFont)));
//pProgItem->setText(3, QFileInfo(
// fluid_sfont_get_name(pSoundFont).baseName());
}
}
}
}
}
m_progListView->setSortingEnabled(true);
// Stabilize the form.
stabilizeForm();
}
// Program change slot.
void PatchesDialog::progChanged (QTreeWidgetItem * _curr, QTreeWidgetItem * _prev)
{
if (m_pSynth == nullptr || _curr == nullptr)
return;
// Which preview state...
if( validateForm() ) {
// Set current selection.
int iBank = (m_bankListView->currentItem())->text(0).toInt();
int iProg = _curr->text(0).toInt();
// And set it right away...
setBankProg(iBank, iProg);
// Now we're dirty nuff.
m_dirty++;
}
// Stabilize the form.
stabilizeForm();
}
} // namespace lmms::gui
| 10,244
|
C++
|
.cpp
| 317
| 29.690852
| 104
| 0.723963
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,712
|
Organic.cpp
|
LMMS_lmms/plugins/Organic/Organic.cpp
|
/*
* Organic.cpp - additive synthesizer for organ-like sounds
*
* Copyright (c) 2006-2008 Andreas Brandmaier <andy/at/brandmaier/dot/de>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Organic.h"
#include <QDomElement>
#include "Engine.h"
#include "AudioEngine.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "NotePlayHandle.h"
#include "Oscillator.h"
#include "PixmapButton.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT organic_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Organic",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Additive Synthesizer for organ-like sounds" ),
"Andreas Brandmaier <andreas/at/brandmaier.de>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
float * OrganicInstrument::s_harmonics = nullptr;
/***********************************************************************
*
* class OrganicInstrument
*
* lmms - plugin
*
***********************************************************************/
OrganicInstrument::OrganicInstrument( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &organic_plugin_descriptor ),
m_modulationAlgo(static_cast<int>(Oscillator::ModulationAlgo::SignalMix),
static_cast<int>(Oscillator::ModulationAlgo::SignalMix),
static_cast<int>(Oscillator::ModulationAlgo::SignalMix)),
m_fx1Model( 0.0f, 0.0f, 0.99f, 0.01f , this, tr( "Distortion" ) ),
m_volModel( 100.0f, 0.0f, 200.0f, 1.0f, this, tr( "Volume" ) )
{
m_numOscillators = NUM_OSCILLATORS;
m_osc = new OscillatorObject*[ m_numOscillators ];
for (int i=0; i < m_numOscillators; i++)
{
m_osc[i] = new OscillatorObject( this, i );
m_osc[i]->m_numOscillators = m_numOscillators;
// Connect events
connect( &m_osc[i]->m_oscModel, SIGNAL( dataChanged() ),
m_osc[i], SLOT ( oscButtonChanged() ) );
connect( &m_osc[i]->m_harmModel, SIGNAL( dataChanged() ),
m_osc[i], SLOT( updateDetuning() ) );
connect( &m_osc[i]->m_volModel, SIGNAL( dataChanged() ),
m_osc[i], SLOT( updateVolume() ) );
connect( &m_osc[i]->m_panModel, SIGNAL( dataChanged() ),
m_osc[i], SLOT( updateVolume() ) );
connect( &m_osc[i]->m_detuneModel, SIGNAL( dataChanged() ),
m_osc[i], SLOT( updateDetuning() ) );
m_osc[i]->updateVolume();
}
/* m_osc[0]->m_harmonic = log2f( 0.5f ); // one octave below
m_osc[1]->m_harmonic = log2f( 0.75f ); // a fifth below
m_osc[2]->m_harmonic = log2f( 1.0f ); // base freq
m_osc[3]->m_harmonic = log2f( 2.0f ); // first overtone
m_osc[4]->m_harmonic = log2f( 3.0f ); // second overtone
m_osc[5]->m_harmonic = log2f( 4.0f ); // .
m_osc[6]->m_harmonic = log2f( 5.0f ); // .
m_osc[7]->m_harmonic = log2f( 6.0f ); // .*/
if( s_harmonics == nullptr )
{
s_harmonics = new float[ NUM_HARMONICS ];
s_harmonics[0] = log2f( 0.5f );
s_harmonics[1] = log2f( 0.75f );
s_harmonics[2] = log2f( 1.0f );
s_harmonics[3] = log2f( 2.0f );
s_harmonics[4] = log2f( 3.0f );
s_harmonics[5] = log2f( 4.0f );
s_harmonics[6] = log2f( 5.0f );
s_harmonics[7] = log2f( 6.0f );
s_harmonics[8] = log2f( 7.0f );
s_harmonics[9] = log2f( 8.0f );
s_harmonics[10] = log2f( 9.0f );
s_harmonics[11] = log2f( 10.0f );
s_harmonics[12] = log2f( 11.0f );
s_harmonics[13] = log2f( 12.0f );
s_harmonics[14] = log2f( 13.0f );
s_harmonics[15] = log2f( 14.0f );
s_harmonics[16] = log2f( 15.0f );
s_harmonics[17] = log2f( 16.0f );
}
for (int i=0; i < m_numOscillators; i++) {
m_osc[i]->updateVolume();
m_osc[i]->updateDetuning();
}
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ),
this, SLOT( updateAllDetuning() ) );
}
OrganicInstrument::~OrganicInstrument()
{
delete[] m_osc;
}
void OrganicInstrument::saveSettings(QDomDocument& doc, QDomElement& elem)
{
elem.setAttribute("num_osc", QString::number(m_numOscillators));
m_fx1Model.saveSettings(doc, elem, "foldback");
m_volModel.saveSettings(doc, elem, "vol");
for (int i = 0; i < m_numOscillators; ++i)
{
const auto is = QString::number(i);
m_osc[i]->m_volModel.saveSettings(doc, elem, "vol" + is);
m_osc[i]->m_panModel.saveSettings(doc, elem, "pan" + is);
m_osc[i]->m_harmModel.saveSettings(doc, elem, "newharmonic" + is);
m_osc[i]->m_detuneModel.saveSettings(doc, elem, "newdetune" + is);
m_osc[i]->m_oscModel.saveSettings(doc, elem, "wavetype" + is);
}
}
void OrganicInstrument::loadSettings(const QDomElement& elem)
{
for (int i = 0; i < m_numOscillators; ++i)
{
const auto is = QString::number(i);
m_osc[i]->m_volModel.loadSettings(elem, "vol" + is);
if (elem.hasAttribute("detune" + is) || !elem.firstChildElement("detune" + is).isNull())
{
m_osc[i]->m_detuneModel.loadSettings(elem, "detune" + is);
m_osc[i]->m_detuneModel.setValue(m_osc[i]->m_detuneModel.value() * 12); // compat
}
else
{
m_osc[i]->m_detuneModel.loadSettings(elem, "newdetune" + is);
}
m_osc[i]->m_panModel.loadSettings(elem, "pan" + is);
m_osc[i]->m_oscModel.loadSettings(elem, "wavetype" + is);
if (elem.hasAttribute("newharmonic" + is) || !elem.firstChildElement("newharmonic" + is).isNull())
{
m_osc[i]->m_harmModel.loadSettings(elem, "newharmonic" + is);
}
else
{
m_osc[i]->m_harmModel.setValue(static_cast<float>(i));
}
}
m_volModel.loadSettings(elem, "vol");
m_fx1Model.loadSettings(elem, "foldback");
}
QString OrganicInstrument::nodeName() const
{
return( organic_plugin_descriptor.name );
}
void OrganicInstrument::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
if (!_n->m_pluginData)
{
auto oscs_l = std::array<Oscillator*, NUM_OSCILLATORS>{};
auto oscs_r = std::array<Oscillator*, NUM_OSCILLATORS>{};
_n->m_pluginData = new oscPtr;
for( int i = m_numOscillators - 1; i >= 0; --i )
{
static_cast<oscPtr *>( _n->m_pluginData )->phaseOffsetLeft[i]
= rand() / ( RAND_MAX + 1.0f );
static_cast<oscPtr *>( _n->m_pluginData )->phaseOffsetRight[i]
= rand() / ( RAND_MAX + 1.0f );
// initialise ocillators
if( i == m_numOscillators - 1 )
{
// create left oscillator
oscs_l[i] = new Oscillator(
&m_osc[i]->m_waveShape,
&m_modulationAlgo,
_n->frequency(),
m_osc[i]->m_detuningLeft,
static_cast<oscPtr *>( _n->m_pluginData )->phaseOffsetLeft[i],
m_osc[i]->m_volumeLeft );
// create right oscillator
oscs_r[i] = new Oscillator(
&m_osc[i]->m_waveShape,
&m_modulationAlgo,
_n->frequency(),
m_osc[i]->m_detuningRight,
static_cast<oscPtr *>( _n->m_pluginData )->phaseOffsetRight[i],
m_osc[i]->m_volumeRight );
}
else
{
// create left oscillator
oscs_l[i] = new Oscillator(
&m_osc[i]->m_waveShape,
&m_modulationAlgo,
_n->frequency(),
m_osc[i]->m_detuningLeft,
static_cast<oscPtr *>( _n->m_pluginData )->phaseOffsetLeft[i],
m_osc[i]->m_volumeLeft,
oscs_l[i + 1] );
// create right oscillator
oscs_r[i] = new Oscillator(
&m_osc[i]->m_waveShape,
&m_modulationAlgo,
_n->frequency(),
m_osc[i]->m_detuningRight,
static_cast<oscPtr *>( _n->m_pluginData )->phaseOffsetRight[i],
m_osc[i]->m_volumeRight,
oscs_r[i + 1] );
}
}
static_cast<oscPtr *>( _n->m_pluginData )->oscLeft = oscs_l[0];
static_cast<oscPtr *>( _n->m_pluginData )->oscRight = oscs_r[0];
}
Oscillator * osc_l = static_cast<oscPtr *>( _n->m_pluginData )->oscLeft;
Oscillator * osc_r = static_cast<oscPtr *>( _n->m_pluginData)->oscRight;
osc_l->update( _working_buffer + offset, frames, 0 );
osc_r->update( _working_buffer + offset, frames, 1 );
// -- fx section --
// fxKnob is [0;1]
float t = m_fx1Model.value();
for (auto i = std::size_t{0}; i < frames + offset; i++)
{
_working_buffer[i][0] = waveshape( _working_buffer[i][0], t ) *
m_volModel.value() / 100.0f;
_working_buffer[i][1] = waveshape( _working_buffer[i][1], t ) *
m_volModel.value() / 100.0f;
}
// -- --
}
void OrganicInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<Oscillator *>( static_cast<oscPtr *>(
_n->m_pluginData )->oscLeft );
delete static_cast<Oscillator *>( static_cast<oscPtr *>(
_n->m_pluginData )->oscRight );
delete static_cast<oscPtr *>( _n->m_pluginData );
}
/*float inline OrganicInstrument::foldback(float in, float threshold)
{
if (in>threshold || in<-threshold)
{
in= fabs(fabs(fmod(in - threshold, threshold*4)) - threshold*2) - threshold;
}
return in;
}
*/
float inline OrganicInstrument::waveshape(float in, float amount)
{
float k = 2.0f * amount / ( 1.0f - amount );
return( ( 1.0f + k ) * in / ( 1.0f + k * fabs( in ) ) );
}
void OrganicInstrument::randomiseSettings()
{
for( int i = 0; i < m_numOscillators; i++ )
{
m_osc[i]->m_volModel.setValue( intRand( 0, 100 ) );
m_osc[i]->m_detuneModel.setValue( intRand( -5, 5 ) );
m_osc[i]->m_panModel.setValue( 0 );
m_osc[i]->m_oscModel.setValue( intRand( 0, 5 ) );
}
}
void OrganicInstrument::updateAllDetuning()
{
for( int i = 0; i < m_numOscillators; ++i )
{
m_osc[i]->updateDetuning();
}
}
int OrganicInstrument::intRand( int min, int max )
{
// int randn = min+int((max-min)*rand()/(RAND_MAX + 1.0));
// cout << randn << endl;
int randn = ( rand() % (max - min) ) + min;
return( randn );
}
gui::PluginView * OrganicInstrument::instantiateView( QWidget * _parent )
{
return( new gui::OrganicInstrumentView( this, _parent ) );
}
namespace gui
{
class OrganicKnob : public Knob
{
public:
OrganicKnob( QWidget * _parent ) :
Knob( KnobType::Styled, _parent )
{
setFixedSize( 21, 21 );
}
};
OrganicInstrumentView::OrganicInstrumentView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent ),
m_oscKnobs( nullptr )
{
auto oi = castModel<OrganicInstrument>();
setAutoFillBackground( true );
QPalette pal;
static auto s_artwork = PLUGIN_NAME::getIconPixmap("artwork");
pal.setBrush(backgroundRole(), s_artwork);
setPalette( pal );
// setup knob for FX1
m_fx1Knob = new OrganicKnob( this );
m_fx1Knob->move( 15, 201 );
m_fx1Knob->setFixedSize( 37, 47 );
m_fx1Knob->setHintText( tr( "Distortion:" ), QString() );
m_fx1Knob->setObjectName( "fx1Knob" );
// setup volume-knob
m_volKnob = new OrganicKnob( this );
m_volKnob->setVolumeKnob( true );
m_volKnob->move( 60, 201 );
m_volKnob->setFixedSize( 37, 47 );
m_volKnob->setHintText( tr( "Volume:" ), "%" );
m_volKnob->setObjectName( "volKnob" );
// randomise
m_randBtn = new PixmapButton( this, tr( "Randomise" ) );
m_randBtn->move( 148, 224 );
m_randBtn->setActiveGraphic( PLUGIN_NAME::getIconPixmap(
"randomise_pressed" ) );
m_randBtn->setInactiveGraphic( PLUGIN_NAME::getIconPixmap(
"randomise" ) );
connect( m_randBtn, SIGNAL ( clicked() ),
oi, SLOT( randomiseSettings() ) );
}
OrganicInstrumentView::~OrganicInstrumentView()
{
delete[] m_oscKnobs;
}
void OrganicInstrumentView::modelChanged()
{
auto oi = castModel<OrganicInstrument>();
const float y=91.0f;
const float rowHeight = 26.0f;
const float x=53.0f;
const float colWidth = 24.0f;
m_numOscillators = oi->m_numOscillators;
m_fx1Knob->setModel( &oi->m_fx1Model );
m_volKnob->setModel( &oi->m_volModel );
if( m_oscKnobs != nullptr )
{
delete[] m_oscKnobs;
}
m_oscKnobs = new OscillatorKnobs[ m_numOscillators ];
// Create knobs, now that we know how many to make
for( int i = 0; i < m_numOscillators; ++i )
{
// setup harmonic knob
Knob * harmKnob = new OrganicKnob( this );
harmKnob->move( x + i * colWidth, y - rowHeight );
harmKnob->setObjectName( "harmKnob" );
connect( &oi->m_osc[i]->m_harmModel, SIGNAL( dataChanged() ),
this, SLOT( updateKnobHint() ) );
// setup waveform-knob
Knob * oscKnob = new OrganicKnob( this );
oscKnob->move( x + i * colWidth, y );
connect( &oi->m_osc[i]->m_oscModel, SIGNAL( dataChanged() ),
this, SLOT( updateKnobHint() ) );
oscKnob->setHintText( tr( "Osc %1 waveform:" ).arg( i + 1 ), QString() );
// setup volume-knob
auto volKnob = new Knob(KnobType::Styled, this);
volKnob->setVolumeKnob( true );
volKnob->move( x + i * colWidth, y + rowHeight*1 );
volKnob->setFixedSize( 21, 21 );
volKnob->setHintText( tr( "Osc %1 volume:" ).arg(
i + 1 ), "%" );
// setup panning-knob
Knob * panKnob = new OrganicKnob( this );
panKnob->move( x + i * colWidth, y + rowHeight*2 );
panKnob->setHintText( tr("Osc %1 panning:").arg(
i + 1 ), "" );
// setup knob for fine-detuning
Knob * detuneKnob = new OrganicKnob( this );
detuneKnob->move( x + i * colWidth, y + rowHeight*3 );
detuneKnob->setHintText( tr( "Osc %1 stereo detuning" ).arg( i + 1 )
, " " +
tr( "cents" ) );
m_oscKnobs[i] = OscillatorKnobs( harmKnob, volKnob, oscKnob, panKnob, detuneKnob );
// Attach to models
m_oscKnobs[i].m_harmKnob->setModel( &oi->m_osc[i]->m_harmModel );
m_oscKnobs[i].m_volKnob->setModel( &oi->m_osc[i]->m_volModel );
m_oscKnobs[i].m_oscKnob->setModel( &oi->m_osc[i]->m_oscModel );
m_oscKnobs[i].m_panKnob->setModel( &oi->m_osc[i]->m_panModel );
m_oscKnobs[i].m_detuneKnob->setModel( &oi->m_osc[i]->m_detuneModel );
}
updateKnobHint();
}
void OrganicInstrumentView::updateKnobHint()
{
auto oi = castModel<OrganicInstrument>();
for( int i = 0; i < m_numOscillators; ++i )
{
const float harm = oi->m_osc[i]->m_harmModel.value();
const float wave = oi->m_osc[i]->m_oscModel.value();
m_oscKnobs[i].m_harmKnob->setHintText( tr( "Osc %1 harmonic:" ).arg( i + 1 ), " (" +
HARMONIC_NAMES[ static_cast<int>( harm ) ] + ")" );
m_oscKnobs[i].m_oscKnob->setHintText( tr( "Osc %1 waveform:" ).arg( i + 1 ), " (" +
WAVEFORM_NAMES[ static_cast<int>( wave ) ] + ")" );
}
}
} // namespace gui
OscillatorObject::OscillatorObject( Model * _parent, int _index ) :
Model( _parent ),
m_waveShape( static_cast<int>(Oscillator::WaveShape::Sine), 0, Oscillator::NumWaveShapes-1, this ),
m_oscModel( 0.0f, 0.0f, 5.0f, 1.0f,
this, tr( "Osc %1 waveform" ).arg( _index + 1 ) ),
m_harmModel( static_cast<float>( _index ), 0.0f, 17.0f, 1.0f,
this, tr( "Osc %1 harmonic" ).arg( _index + 1 ) ),
m_volModel( 100.0f, 0.0f, 100.0f, 1.0f,
this, tr( "Osc %1 volume" ).arg( _index + 1 ) ),
m_panModel( DefaultPanning, PanningLeft, PanningRight, 1.0f,
this, tr( "Osc %1 panning" ).arg( _index + 1 ) ),
m_detuneModel( 0.0f, -1200.0f, 1200.0f, 1.0f,
this, tr( "Osc %1 stereo detuning" ).arg( _index + 1 ) )
{
}
void OscillatorObject::oscButtonChanged()
{
static auto shapes = std::array
{
Oscillator::WaveShape::Sine,
Oscillator::WaveShape::Saw,
Oscillator::WaveShape::Square,
Oscillator::WaveShape::Triangle,
Oscillator::WaveShape::MoogSaw,
Oscillator::WaveShape::Exponential
} ;
m_waveShape.setValue( static_cast<float>(shapes[(int)roundf( m_oscModel.value() )]) );
}
void OscillatorObject::updateVolume()
{
m_volumeLeft = ( 1.0f - m_panModel.value() / (float)PanningRight )
* m_volModel.value() / m_numOscillators / 100.0f;
m_volumeRight = ( 1.0f + m_panModel.value() / (float)PanningRight )
* m_volModel.value() / m_numOscillators / 100.0f;
}
void OscillatorObject::updateDetuning()
{
m_detuningLeft = powf( 2.0f, OrganicInstrument::s_harmonics[ static_cast<int>( m_harmModel.value() ) ]
+ (float)m_detuneModel.value() * CENT ) /
Engine::audioEngine()->outputSampleRate();
m_detuningRight = powf( 2.0f, OrganicInstrument::s_harmonics[ static_cast<int>( m_harmModel.value() ) ]
- (float)m_detuneModel.value() * CENT ) /
Engine::audioEngine()->outputSampleRate();
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return( new OrganicInstrument( static_cast<InstrumentTrack *>( m ) ) );
}
}
/*
* some notes & ideas for the future of this plugin:
*
* - 32.692 Hz in the bass to 5919.85 Hz of treble in a Hammond organ
* => implement harmonic foldback
*
m_osc[i].m_oscModel->setInitValue( 0.0f );
* - randomize preset
*/
} // namespace lmms
| 16,994
|
C++
|
.cpp
| 486
| 31.981481
| 104
| 0.660492
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,713
|
StereoDelay.cpp
|
LMMS_lmms/plugins/Delay/StereoDelay.cpp
|
/*
* stereodelay.cpp - defination of StereoDelay class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "StereoDelay.h"
#include "lmms_basics.h"
#include "SampleFrame.h"
namespace lmms
{
StereoDelay::StereoDelay( int maxTime, int sampleRate )
{
m_buffer = 0;
m_maxTime = static_cast<float>(maxTime);
m_maxLength = maxTime * sampleRate;
m_length = static_cast<float>(m_maxLength);
m_writeIndex = 0;
m_feedback = 0.0f;
setSampleRate( sampleRate );
}
StereoDelay::~StereoDelay()
{
if( m_buffer )
{
delete[] m_buffer;
}
}
void StereoDelay::tick( SampleFrame& frame )
{
m_writeIndex = ( m_writeIndex + 1 ) % ( int )m_maxLength;
int readIndex = m_writeIndex - static_cast<int>(m_length);
if (readIndex < 0 ) { readIndex += m_maxLength; }
float lOut = m_buffer[ readIndex ][ 0 ];
float rOut = m_buffer[ readIndex ] [1 ];
m_buffer[ m_writeIndex ][ 0 ] = frame[ 0 ] + ( lOut * m_feedback );
m_buffer[ m_writeIndex ][ 1 ] = frame[ 1 ] + ( rOut * m_feedback );
frame[ 0 ] = lOut;
frame[ 1 ] = rOut;
}
void StereoDelay::setSampleRate( int sampleRate )
{
if( m_buffer )
{
delete[] m_buffer;
}
int bufferSize = ( int )( sampleRate * m_maxTime );
m_buffer = new SampleFrame[bufferSize];
for( int i = 0 ; i < bufferSize ; i++)
{
m_buffer[i][0] = 0.0;
m_buffer[i][1] = 0.0;
}
}
} // namespace lmms
| 2,174
|
C++
|
.cpp
| 72
| 28.083333
| 75
| 0.702742
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,714
|
DelayControls.cpp
|
LMMS_lmms/plugins/Delay/DelayControls.cpp
|
/*
* delaycontrols.cpp - definition of DelayControls class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "DelayControls.h"
#include "DelayEffect.h"
#include "Engine.h"
namespace lmms
{
DelayControls::DelayControls( DelayEffect* effect ):
EffectControls( effect ),
m_effect ( effect ),
m_delayTimeModel(0.5f, 0.01f, 5.f, 0.0001f, 5000.f, this, tr("Delay samples")) ,
m_feedbackModel(0.0f, 0.0f, 1.0f, 0.01f, this, tr("Feedback")),
m_lfoTimeModel(2.f, 0.01f, 5.f, 0.0001f, 20000.f, this, tr("LFO frequency")),
m_lfoAmountModel(0.f, 0.f, 0.5f, 0.0001f, 2000.f, this, tr("LFO amount")),
m_outGainModel(0.f, -60.f, 20.f, 0.01f, this, tr("Output gain"))
{
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( changeSampleRate() ) );
m_outPeakL = 0.0;
m_outPeakR = 0.0;
}
void DelayControls::loadSettings( const QDomElement &_this )
{
m_delayTimeModel.loadSettings(_this, "DelayTimeSamples" );
m_feedbackModel.loadSettings( _this, "FeebackAmount" );
m_lfoTimeModel.loadSettings( _this , "LfoFrequency");
m_lfoAmountModel.loadSettings( _this, "LfoAmount");
m_outGainModel.loadSettings( _this, "OutGain" );
}
void DelayControls::saveSettings( QDomDocument& doc, QDomElement& _this )
{
m_delayTimeModel.saveSettings( doc, _this, "DelayTimeSamples" );
m_feedbackModel.saveSettings( doc, _this ,"FeebackAmount" );
m_lfoTimeModel.saveSettings( doc, _this, "LfoFrequency" );
m_lfoAmountModel.saveSettings( doc, _this ,"LfoAmount" );
m_outGainModel.saveSettings( doc, _this, "OutGain" );
}
void DelayControls::changeSampleRate()
{
m_effect->changeSampleRate();
}
} // namespace lmms
| 2,489
|
C++
|
.cpp
| 63
| 37.555556
| 99
| 0.739311
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,715
|
DelayEffect.cpp
|
LMMS_lmms/plugins/Delay/DelayEffect.cpp
|
/*
* delayeffect.cpp - definition of the DelayEffect class. The Delay Plugin
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "DelayEffect.h"
#include "Engine.h"
#include "embed.h"
#include "Lfo.h"
#include "lmms_math.h"
#include "plugin_export.h"
#include "StereoDelay.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT delay_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Delay",
QT_TRANSLATE_NOOP( "PluginBrowser", "A native delay plugin" ),
"Dave French <contact/dot/dave/dot/french3/at/googlemail/dot/com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
DelayEffect::DelayEffect( Model* parent, const Plugin::Descriptor::SubPluginFeatures::Key* key ) :
Effect( &delay_plugin_descriptor, parent, key ),
m_delayControls( this )
{
m_delay = 0;
m_delay = new StereoDelay( 20, Engine::audioEngine()->outputSampleRate() );
m_lfo = new Lfo( Engine::audioEngine()->outputSampleRate() );
m_outGain = 1.0;
}
DelayEffect::~DelayEffect()
{
if( m_delay )
{
delete m_delay;
}
if( m_lfo )
{
delete m_lfo;
}
}
Effect::ProcessStatus DelayEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const float sr = Engine::audioEngine()->outputSampleRate();
const float d = dryLevel();
const float w = wetLevel();
SampleFrame peak;
float length = m_delayControls.m_delayTimeModel.value();
float amplitude = m_delayControls.m_lfoAmountModel.value() * sr;
float lfoTime = 1.0 / m_delayControls.m_lfoTimeModel.value();
float feedback = m_delayControls.m_feedbackModel.value();
ValueBuffer *lengthBuffer = m_delayControls.m_delayTimeModel.valueBuffer();
ValueBuffer *feedbackBuffer = m_delayControls.m_feedbackModel.valueBuffer();
ValueBuffer *lfoTimeBuffer = m_delayControls.m_lfoTimeModel.valueBuffer();
ValueBuffer *lfoAmountBuffer = m_delayControls.m_lfoAmountModel.valueBuffer();
int lengthInc = lengthBuffer ? 1 : 0;
int amplitudeInc = lfoAmountBuffer ? 1 : 0;
int lfoTimeInc = lfoTimeBuffer ? 1 : 0;
int feedbackInc = feedbackBuffer ? 1 : 0;
float *lengthPtr = lengthBuffer ? &( lengthBuffer->values()[ 0 ] ) : &length;
float *amplitudePtr = lfoAmountBuffer ? &( lfoAmountBuffer->values()[ 0 ] ) : &litude;
float *lfoTimePtr = lfoTimeBuffer ? &( lfoTimeBuffer->values()[ 0 ] ) : &lfoTime;
float *feedbackPtr = feedbackBuffer ? &( feedbackBuffer->values()[ 0 ] ) : &feedback;
if( m_delayControls.m_outGainModel.isValueChanged() )
{
m_outGain = dbfsToAmp( m_delayControls.m_outGainModel.value() );
}
for (fpp_t f = 0; f < frames; ++f)
{
auto& currentFrame = buf[f];
const auto dryS = currentFrame;
// Prepare delay for current sample
m_delay->setFeedback( *feedbackPtr );
m_lfo->setFrequency( *lfoTimePtr );
m_currentLength = static_cast<int>(*lengthPtr * Engine::audioEngine()->outputSampleRate());
m_delay->setLength( m_currentLength + ( *amplitudePtr * ( float )m_lfo->tick() ) );
// Process the wet signal
m_delay->tick( currentFrame );
currentFrame *= m_outGain;
// Calculate peak of wet signal
peak = peak.absMax(currentFrame);
// Dry/wet mix
currentFrame = dryS * d + currentFrame * w;
lengthPtr += lengthInc;
amplitudePtr += amplitudeInc;
lfoTimePtr += lfoTimeInc;
feedbackPtr += feedbackInc;
}
m_delayControls.m_outPeakL = peak.left();
m_delayControls.m_outPeakR = peak.right();
return ProcessStatus::ContinueIfNotQuiet;
}
void DelayEffect::changeSampleRate()
{
m_lfo->setSampleRate( Engine::audioEngine()->outputSampleRate() );
m_delay->setSampleRate( Engine::audioEngine()->outputSampleRate() );
}
extern "C"
{
//needed for getting plugin out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new DelayEffect( parent , static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( data ) );
}
}}
} // namespace lmms
| 4,689
|
C++
|
.cpp
| 131
| 33.633588
| 108
| 0.738448
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
19,716
|
Lfo.cpp
|
LMMS_lmms/plugins/Delay/Lfo.cpp
|
/*
* lfo.cpp - defination of Lfo class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Lfo.h"
#include <cmath>
namespace lmms
{
Lfo::Lfo( int samplerate )
{
m_samplerate = samplerate;
m_twoPiOverSr = F_2PI / samplerate;
}
float Lfo::tick()
{
float output = sinf( m_phase );
m_phase += m_increment;
return output;
}
} // namespace lmms
| 1,189
|
C++
|
.cpp
| 39
| 28.487179
| 75
| 0.740773
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,717
|
DelayControlsDialog.cpp
|
LMMS_lmms/plugins/Delay/DelayControlsDialog.cpp
|
/*
* delaycontrolsdialog.cpp - definition of DelayControlsDialog class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "AutomatableModel.h"
#include "DelayControlsDialog.h"
#include "DelayControls.h"
#include "embed.h"
#include "TempoSyncKnob.h"
#include "../Eq/EqFader.h"
#include <QMouseEvent>
#include <QPainter>
namespace lmms::gui
{
DelayControlsDialog::DelayControlsDialog( DelayControls *controls ) :
EffectControlDialog( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 300, 208 );
auto sampleDelayKnob = new TempoSyncKnob(KnobType::Bright26, this);
sampleDelayKnob->move( 10,14 );
sampleDelayKnob->setVolumeKnob( false );
sampleDelayKnob->setModel( &controls->m_delayTimeModel );
sampleDelayKnob->setLabel( tr( "DELAY" ) );
sampleDelayKnob->setHintText( tr( "Delay time" ) + " ", " s" );
auto feedbackKnob = new Knob(KnobType::Bright26, this);
feedbackKnob->move( 11, 58 );
feedbackKnob->setVolumeKnob( true) ;
feedbackKnob->setModel( &controls->m_feedbackModel);
feedbackKnob->setLabel( tr( "FDBK" ) );
feedbackKnob->setHintText( tr ( "Feedback amount" ) + " " , "" );
auto lfoFreqKnob = new TempoSyncKnob(KnobType::Bright26, this);
lfoFreqKnob->move( 11, 119 );
lfoFreqKnob->setVolumeKnob( false );
lfoFreqKnob->setModel( &controls->m_lfoTimeModel );
lfoFreqKnob->setLabel( tr( "RATE" ) );
lfoFreqKnob->setHintText( tr ( "LFO frequency") + " ", " s" );
auto lfoAmtKnob = new TempoSyncKnob(KnobType::Bright26, this);
lfoAmtKnob->move( 11, 159 );
lfoAmtKnob->setVolumeKnob( false );
lfoAmtKnob->setModel( &controls->m_lfoAmountModel );
lfoAmtKnob->setLabel( tr( "AMNT" ) );
lfoAmtKnob->setHintText( tr ( "LFO amount" ) + " " , " s" );
auto outFader
= new EqFader(&controls->m_outGainModel, tr("Out gain"), this, &controls->m_outPeakL, &controls->m_outPeakR);
outFader->setMaximumHeight( 196 );
outFader->move( 263, 45 );
outFader->setDisplayConversion( false );
outFader->setHintText( tr( "Gain" ), "dBFS" );
auto pad = new XyPad(this, &controls->m_feedbackModel, &controls->m_delayTimeModel);
pad->resize( 200, 200 );
pad->move( 50, 5 );
}
XyPad::XyPad(QWidget *parent, FloatModel *xModel, FloatModel *yModel) :
QWidget( parent ),
m_xModel( xModel ),
m_yModel( yModel ),
m_acceptInput( false )
{
connect( m_xModel, SIGNAL( dataChanged() ) , this, SLOT( update() ) );
connect( m_yModel, SIGNAL( dataChanged() ) , this, SLOT( update() ) );
}
void XyPad::paintEvent(QPaintEvent *event)
{
QPainter painter( this );
//Draw Frequecy maker lines
painter.setPen( QPen( QColor( 200, 200, 200, 200 ), 8, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin ) );
painter.setRenderHint( QPainter::Antialiasing, true );
float xRange = m_xModel->maxValue() - m_xModel->minValue();
float xInc = xRange / width();
int xPos = ( m_xModel->value() - m_xModel->minValue() ) / xInc;
float yRange = m_yModel->maxValue() - m_yModel->minValue();
float yInc = yRange / height();
int yPos = ( m_yModel->value() - m_yModel->minValue() ) / yInc;
painter.drawPoint( xPos, yPos );
}
void XyPad::mousePressEvent(QMouseEvent *event)
{
m_acceptInput = true;
}
void XyPad::mouseReleaseEvent(QMouseEvent *event)
{
m_acceptInput = false;
}
void XyPad::mouseMoveEvent(QMouseEvent *event)
{
if( m_acceptInput && (event->x() >= 0) && ( event->x() < width() )
&& ( event->y() >= 0) && ( event->y() < height() ) )
{
//set xmodel
float xRange = m_xModel->maxValue() - m_xModel->minValue();
float xInc = xRange / width();
m_xModel->setValue( m_xModel->minValue() + ( event->x() * xInc ) );
//set ymodel
float yRange = m_yModel->maxValue() - m_yModel->minValue();
float yInc = yRange / height();
m_yModel->setValue( m_yModel->minValue() + ( event->y() * yInc ) );
}
}
} // namespace lmms::gui
| 4,728
|
C++
|
.cpp
| 122
| 36.540984
| 111
| 0.708598
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,718
|
MidiImport.cpp
|
LMMS_lmms/plugins/MidiImport/MidiImport.cpp
|
/*
* MidiImport.cpp - support for importing MIDI files
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDir>
#include <QApplication>
#include <QFile>
#include <QMessageBox>
#include <QProgressDialog>
#include <sstream>
#include <unordered_map>
#include "MidiImport.h"
#include "TrackContainer.h"
#include "InstrumentTrack.h"
#include "AutomationTrack.h"
#include "AutomationClip.h"
#include "ConfigManager.h"
#include "MidiClip.h"
#include "Instrument.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "TimePos.h"
#include "debug.h"
#include "Song.h"
#include "plugin_export.h"
#include "portsmf/allegro.h"
namespace lmms
{
#define makeID(_c0, _c1, _c2, _c3) \
( 0 | \
( ( _c0 ) | ( ( _c1 ) << 8 ) | ( ( _c2 ) << 16 ) | ( ( _c3 ) << 24 ) ) )
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT midiimport_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"MIDI Import",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Filter for importing MIDI-files into LMMS" ),
"Tobias Doerffel <tobydox/at/users/dot/sf/dot/net>",
0x0100,
Plugin::Type::ImportFilter,
nullptr,
nullptr,
nullptr,
} ;
}
MidiImport::MidiImport( const QString & _file ) :
ImportFilter( _file, &midiimport_plugin_descriptor ),
m_events(),
m_timingDivision( 0 )
{
}
bool MidiImport::tryImport( TrackContainer* tc )
{
if( openFile() == false )
{
return false;
}
#ifdef LMMS_HAVE_FLUIDSYNTH
if (gui::getGUI() != nullptr &&
ConfigManager::inst()->sf2File().isEmpty() )
{
QMessageBox::information(gui::getGUI()->mainWindow(),
tr( "Setup incomplete" ),
tr( "You have not set up a default soundfont in "
"the settings dialog (Edit->Settings). "
"Therefore no sound will be played back after "
"importing this MIDI file. You should download "
"a General MIDI soundfont, specify it in "
"settings dialog and try again." ) );
}
#else
if (gui::getGUI() != nullptr)
{
QMessageBox::information(gui::getGUI()->mainWindow(),
tr( "Setup incomplete" ),
tr( "You did not compile LMMS with support for "
"SoundFont2 player, which is used to add default "
"sound to imported MIDI files. "
"Therefore no sound will be played back after "
"importing this MIDI file." ) );
}
#endif
switch( readID() )
{
case makeID( 'M', 'T', 'h', 'd' ):
printf( "MidiImport::tryImport(): found MThd\n");
return readSMF( tc );
case makeID( 'R', 'I', 'F', 'F' ):
printf( "MidiImport::tryImport(): found RIFF\n");
return readRIFF( tc );
default:
printf( "MidiImport::tryImport(): not a Standard MIDI "
"file\n" );
return false;
}
}
class smfMidiCC
{
public:
smfMidiCC() :
at( nullptr ),
ap( nullptr ),
lastPos( 0 )
{ }
AutomationTrack * at;
AutomationClip * ap;
TimePos lastPos;
smfMidiCC & create( TrackContainer* tc, QString tn )
{
if( !at )
{
// Keep LMMS responsive, for now the import runs
// in the main thread. This should probably be
// removed if that ever changes.
qApp->processEvents();
at = dynamic_cast<AutomationTrack *>( Track::create( Track::Type::Automation, tc ) );
}
if( tn != "") {
at->setName( tn );
}
return *this;
}
void clear()
{
at = nullptr;
ap = nullptr;
lastPos = 0;
}
smfMidiCC & putValue( TimePos time, AutomatableModel * objModel, float value )
{
if( !ap || time > lastPos + DefaultTicksPerBar )
{
TimePos pPos = TimePos( time.getBar(), 0 );
ap = dynamic_cast<AutomationClip*>(
at->createClip(pPos));
ap->addObject( objModel );
}
lastPos = time;
time = time - ap->startPosition();
ap->putValue( time, value, false );
ap->changeLength( TimePos( time.getBar() + 1, 0 ) );
return *this;
}
};
class smfMidiChannel
{
public:
smfMidiChannel() :
it( nullptr ),
p( nullptr ),
it_inst( nullptr ),
isSF2( false ),
hasNotes( false )
{ }
InstrumentTrack * it;
MidiClip* p;
Instrument * it_inst;
bool isSF2;
bool hasNotes;
QString trackName;
smfMidiChannel * create( TrackContainer* tc, QString tn )
{
if( !it ) {
// Keep LMMS responsive
qApp->processEvents();
it = dynamic_cast<InstrumentTrack *>( Track::create( Track::Type::Instrument, tc ) );
#ifdef LMMS_HAVE_FLUIDSYNTH
it_inst = it->loadInstrument( "sf2player" );
if( it_inst )
{
isSF2 = true;
it_inst->loadFile( ConfigManager::inst()->sf2File() );
it_inst->childModel( "bank" )->setValue( 0 );
it_inst->childModel( "patch" )->setValue( 0 );
}
else
{
it_inst = it->loadInstrument( "patman" );
}
#else
it_inst = it->loadInstrument( "patman" );
#endif
trackName = tn;
if( trackName != "") {
it->setName( tn );
}
// General MIDI default
it->pitchRangeModel()->setInitValue( 2 );
// Create a default pattern
p = dynamic_cast<MidiClip*>(it->createClip(0));
}
return this;
}
void addNote( Note & n )
{
if (!p)
{
p = dynamic_cast<MidiClip*>(it->createClip(0));
}
p->addNote(n, false);
hasNotes = true;
}
void splitMidiClips()
{
MidiClip * newMidiClip = nullptr;
TimePos lastEnd(0);
p->rearrangeAllNotes();
for (auto n : p->notes())
{
if (!newMidiClip || n->pos() > lastEnd + DefaultTicksPerBar)
{
TimePos pPos = TimePos(n->pos().getBar(), 0);
newMidiClip = dynamic_cast<MidiClip*>(it->createClip(pPos));
}
lastEnd = n->pos() + n->length();
Note newNote(*n);
newNote.setPos(n->pos(newMidiClip->startPosition()));
newMidiClip->addNote(newNote, false);
}
delete p;
p = nullptr;
}
};
bool MidiImport::readSMF( TrackContainer* tc )
{
const int MIDI_CC_COUNT = 128 + 1; // 0-127 (128) + pitch bend
const int preTrackSteps = 2;
QProgressDialog pd( TrackContainer::tr( "Importing MIDI-file..." ),
TrackContainer::tr("Cancel"), 0, preTrackSteps, gui::getGUI()->mainWindow());
pd.setWindowTitle( TrackContainer::tr( "Please wait..." ) );
pd.setWindowModality(Qt::WindowModal);
pd.setMinimumDuration( 0 );
pd.setValue( 0 );
std::istringstream stream(readAllData().toStdString());
auto seq = new Alg_seq(stream, true);
seq->convert_to_beats();
pd.setMaximum( seq->tracks() + preTrackSteps );
pd.setValue( 1 );
// 128 CC + Pitch Bend
auto ccs = std::array<smfMidiCC, MIDI_CC_COUNT>{};
// channel to CC object for program changes
std::unordered_map<long, smfMidiCC> pcs;
// channels can be set out of 256 range
// using unordered_map should fix most invalid loads and crashes while loading
std::unordered_map<long, smfMidiChannel> chs;
// NOTE: unordered_map::operator[] creates a new element if none exists
MeterModel & timeSigMM = Engine::getSong()->getTimeSigModel();
auto nt = dynamic_cast<AutomationTrack*>(Track::create(Track::Type::Automation, Engine::getSong()));
nt->setName(tr("MIDI Time Signature Numerator"));
auto dt = dynamic_cast<AutomationTrack*>(Track::create(Track::Type::Automation, Engine::getSong()));
dt->setName(tr("MIDI Time Signature Denominator"));
auto timeSigNumeratorPat = new AutomationClip(nt);
timeSigNumeratorPat->setDisplayName(tr("Numerator"));
timeSigNumeratorPat->addObject(&timeSigMM.numeratorModel());
auto timeSigDenominatorPat = new AutomationClip(dt);
timeSigDenominatorPat->setDisplayName(tr("Denominator"));
timeSigDenominatorPat->addObject(&timeSigMM.denominatorModel());
// TODO: adjust these to Time.Sig changes
double beatsPerBar = 4;
double ticksPerBeat = DefaultTicksPerBar / beatsPerBar;
// Time-sig changes
Alg_time_sigs * timeSigs = &seq->time_sig;
for( int s = 0; s < timeSigs->length(); ++s )
{
Alg_time_sig timeSig = (*timeSigs)[s];
timeSigNumeratorPat->putValue(timeSig.beat * ticksPerBeat, timeSig.num);
timeSigDenominatorPat->putValue(timeSig.beat * ticksPerBeat, timeSig.den);
}
// manually call otherwise the pattern shows being 1 bar
timeSigNumeratorPat->updateLength();
timeSigDenominatorPat->updateLength();
pd.setValue( 2 );
// Tempo stuff
auto tt = dynamic_cast<AutomationTrack*>(Track::create(Track::Type::Automation, Engine::getSong()));
tt->setName(tr("Tempo"));
auto tap = new AutomationClip(tt);
tap->setDisplayName(tr("Tempo"));
tap->addObject(&Engine::getSong()->tempoModel());
if( tap )
{
tap->clear();
Alg_time_map * timeMap = seq->get_time_map();
Alg_beats & beats = timeMap->beats;
for( int i = 0; i < beats.len - 1; i++ )
{
Alg_beat_ptr b = &(beats[i]);
double tempo = ( beats[i + 1].beat - b->beat ) /
( beats[i + 1].time - beats[i].time );
tap->putValue( b->beat * ticksPerBeat, tempo * 60.0 );
}
if( timeMap->last_tempo_flag )
{
Alg_beat_ptr b = &( beats[beats.len - 1] );
tap->putValue( b->beat * ticksPerBeat, timeMap->last_tempo * 60.0 );
}
}
// Update the tempo to avoid crash when playing a project imported
// via the command line
Engine::updateFramesPerTick();
// Song events
for( int e = 0; e < seq->length(); ++e )
{
Alg_event_ptr evt = (*seq)[e];
if( evt->is_update() )
{
printf("Unhandled SONG update: %d %f %s\n",
evt->get_type_code(), evt->time, evt->get_attribute() );
}
}
// Tracks
for( int t = 0; t < seq->tracks(); ++t )
{
QString trackName = QString( tr( "Track" ) + " %1" ).arg( t );
Alg_track_ptr trk = seq->track( t );
pd.setValue( t + preTrackSteps );
for (auto& cc : ccs)
{
cc.clear();
}
// Now look at events
for( int e = 0; e < trk->length(); ++e )
{
Alg_event_ptr evt = (*trk)[e];
if( evt->chan == -1 )
{
bool handled = false;
if( evt->is_update() )
{
QString attr = evt->get_attribute();
// seqnames is a track0 identifier (see allegro code)
if (attr == (t == 0 ? "seqnames" : "tracknames")
&& evt->get_update_type() == 's')
{
trackName = evt->get_string_value();
handled = true;
}
}
if( !handled ) {
// Write debug output
printf("MISSING GLOBAL HANDLER\n");
printf(" Chn: %d, Type Code: %d, Time: %f", (int) evt->chan,
evt->get_type_code(), evt->time );
if ( evt->is_update() )
{
printf( ", Update Type: %s", evt->get_attribute() );
if ( evt->get_update_type() == 'a' )
{
printf( ", Atom: %s", evt->get_atom_value() );
}
}
printf( "\n" );
}
}
else if (evt->is_note())
{
smfMidiChannel * ch = chs[evt->chan].create( tc, trackName );
auto noteEvt = dynamic_cast<Alg_note_ptr>(evt);
int ticks = noteEvt->get_duration() * ticksPerBeat;
Note n( (ticks < 1 ? 1 : ticks ),
noteEvt->get_start_time() * ticksPerBeat,
noteEvt->get_identifier(),
noteEvt->get_loud() * (200.f / 127.f)); // Map from MIDI velocity to LMMS volume
ch->addNote( n );
}
else if( evt->is_update() )
{
smfMidiChannel * ch = chs[evt->chan].create( tc, trackName );
double time = evt->time*ticksPerBeat;
QString update( evt->get_attribute() );
if( update == "programi" )
{
long prog = evt->get_integer_value();
if( ch->isSF2 )
{
auto& pc = pcs[evt->chan];
AutomatableModel* objModel = ch->it_inst->childModel("patch");
if (pc.at == nullptr) {
pc.create(tc, trackName + " > " + objModel->displayName());
}
pc.putValue(time, objModel, prog);
}
else {
const QString num = QString::number( prog );
const QString filter = QString().fill( '0', 3 - num.length() ) + num + "*.pat";
const QString dir = "/usr/share/midi/"
"freepats/Tone_000/";
const QStringList files = QDir( dir ).
entryList( QStringList( filter ) );
if( ch->it_inst && !files.empty() )
{
ch->it_inst->loadFile( dir+files.front() );
}
}
}
else if( update.startsWith( "control" ) || update == "bendr" )
{
int ccid = update.mid( 7, update.length()-8 ).toInt();
if( update == "bendr" )
{
ccid = 128;
}
if( ccid <= 128 )
{
double cc = evt->get_real_value();
AutomatableModel * objModel = nullptr;
switch( ccid )
{
case 0:
if( ch->isSF2 && ch->it_inst )
{
objModel = ch->it_inst->childModel( "bank" );
printf("BANK SELECT %f %d\n", cc, (int)(cc*127.0));
cc *= 127.0f;
}
break;
case 7:
objModel = ch->it->volumeModel();
cc *= 100.0f;
break;
case 10:
objModel = ch->it->panningModel();
cc = cc * 200.f - 100.0f;
break;
case 128:
objModel = ch->it->pitchModel();
cc = cc * 100.0f;
break;
default:
//TODO: something useful for other CCs
break;
}
if( objModel )
{
if( time == 0 && objModel )
{
objModel->setInitValue( cc );
}
else
{
if( ccs[ccid].at == nullptr ) {
ccs[ccid].create( tc, trackName + " > " + (
objModel != nullptr ?
objModel->displayName() :
QString("CC %1").arg(ccid) ) );
}
ccs[ccid].putValue( time, objModel, cc );
}
}
}
}
else {
printf("Unhandled update: %d %d %f %s\n", (int) evt->chan,
evt->get_type_code(), evt->time, evt->get_attribute() );
}
}
}
}
delete seq;
for( auto& c: chs )
{
if (c.second.hasNotes)
{
c.second.splitMidiClips();
}
else if (c.second.it)
{
printf(" Should remove empty track\n");
// must delete trackView first - but where is it?
//tc->removeTrack( chs[c].it );
//it->deleteLater();
}
// Set channel 10 to drums as per General MIDI's orders
if (c.first % 16l == 9 /* channel 10 */
&& c.second.hasNotes && c.second.it_inst && c.second.isSF2)
{
c.second.it_inst->childModel("bank")->setValue(128);
c.second.it_inst->childModel("patch")->setValue(0);
}
}
return true;
}
bool MidiImport::readRIFF( TrackContainer* tc )
{
// skip file length
skip( 4 );
// check file type ("RMID" = RIFF MIDI)
if( readID() != makeID( 'R', 'M', 'I', 'D' ) )
{
invalid_format:
qWarning( "MidiImport::readRIFF(): invalid file format" );
return false;
}
// search for "data" chunk
while( true )
{
const int id = readID();
const int len = read32LE();
if( file().atEnd() )
{
data_not_found:
qWarning( "MidiImport::readRIFF(): data chunk not found" );
return false;
}
if( id == makeID( 'd', 'a', 't', 'a' ) )
{
break;
}
if( len < 0 )
{
goto data_not_found;
}
skip( ( len + 1 ) & ~1 );
}
// the "data" chunk must contain data in SMF format
if( readID() != makeID( 'M', 'T', 'h', 'd' ) )
{
goto invalid_format;
}
return readSMF( tc );
}
void MidiImport::error()
{
printf( "MidiImport::readTrack(): invalid MIDI data (offset %#x)\n",
(unsigned int) file().pos() );
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *, void * _data )
{
return new MidiImport( QString::fromUtf8(
static_cast<const char *>( _data ) ) );
}
}
} // namespace lmms
| 16,040
|
C++
|
.cpp
| 556
| 24.597122
| 101
| 0.623943
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,728
|
VecControlsDialog.cpp
|
LMMS_lmms/plugins/Vectorscope/VecControlsDialog.cpp
|
/*
* VecControlsDialog.cpp - definition of VecControlsDialog class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "VecControlsDialog.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "Knob.h"
#include "LedCheckBox.h"
#include "VecControls.h"
#include "Vectorscope.h"
#include "VectorView.h"
namespace lmms::gui
{
// The entire GUI layout is built here.
VecControlsDialog::VecControlsDialog(VecControls *controls) :
EffectControlDialog(controls),
m_controls(controls)
{
auto master_layout = new QVBoxLayout;
master_layout->setContentsMargins(0, 2, 0, 0);
setLayout(master_layout);
// Visualizer widget
// The size of 768 pixels seems to offer a good balance of speed, accuracy and trace thickness.
auto display = new VectorView(controls, m_controls->m_effect->getBuffer(), 768, this);
master_layout->addWidget(display);
// Config area located inside visualizer
auto internal_layout = new QVBoxLayout(display);
auto config_layout = new QHBoxLayout();
auto switch_layout = new QVBoxLayout();
internal_layout->addStretch();
internal_layout->addLayout(config_layout);
config_layout->addLayout(switch_layout);
// High-quality switch
auto highQualityButton = new LedCheckBox(tr("HQ"), this);
highQualityButton->setToolTip(tr("Double the resolution and simulate continuous analog-like trace."));
highQualityButton->setCheckable(true);
highQualityButton->setModel(&controls->m_highQualityModel);
switch_layout->addWidget(highQualityButton);
// Log. scale switch
auto logarithmicButton = new LedCheckBox(tr("Log. scale"), this);
logarithmicButton->setToolTip(tr("Display amplitude on logarithmic scale to better see small values."));
logarithmicButton->setCheckable(true);
logarithmicButton->setModel(&controls->m_logarithmicModel);
switch_layout->addWidget(logarithmicButton);
config_layout->addStretch();
// Persistence knob
auto persistenceKnob = new Knob(KnobType::Small17, this);
persistenceKnob->setModel(&controls->m_persistenceModel);
persistenceKnob->setLabel(tr("Persist."));
persistenceKnob->setToolTip(tr("Trace persistence: higher amount means the trace will stay bright for longer time."));
persistenceKnob->setHintText(tr("Trace persistence"), "");
config_layout->addWidget(persistenceKnob);
}
// Suggest the best widget size.
QSize VecControlsDialog::sizeHint() const
{
return QSize(275, 300);
}
} // namespace lmms::gui
| 3,217
|
C++
|
.cpp
| 79
| 38.772152
| 119
| 0.778668
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,729
|
Vectorscope.cpp
|
LMMS_lmms/plugins/Vectorscope/Vectorscope.cpp
|
/*
* Vectorscope.cpp - definition of Vectorscope class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Vectorscope.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C" {
Plugin::Descriptor PLUGIN_EXPORT vectorscope_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"Vectorscope",
QT_TRANSLATE_NOOP("PluginBrowser", "A stereo field visualizer."),
"Martin Pavelek <he29/dot/HS/at/gmail/dot/com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
};
}
Vectorscope::Vectorscope(Model *parent, const Plugin::Descriptor::SubPluginFeatures::Key *key) :
Effect(&vectorscope_plugin_descriptor, parent, key),
m_controls(this),
// Buffer is sized to cover 4* the current maximum LMMS audio buffer size,
// so that it has some reserve space in case GUI thresd is busy.
m_inputBuffer(4 * m_maxBufferSize)
{
}
// Take audio data and store them for processing and display in the GUI thread.
Effect::ProcessStatus Vectorscope::processImpl(SampleFrame* buf, const fpp_t frames)
{
// Skip processing if the controls dialog isn't visible, it would only waste CPU cycles.
if (m_controls.isViewVisible())
{
// To avoid processing spikes on audio thread, data are stored in
// a lockless ringbuffer and processed in a separate thread.
m_inputBuffer.write(buf, frames);
}
return ProcessStatus::Continue;
}
extern "C" {
// needed for getting plugin out of shared lib
PLUGIN_EXPORT Plugin *lmms_plugin_main(Model *parent, void *data)
{
return new Vectorscope(parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(data));
}
}
} // namespace lmms
| 2,480
|
C++
|
.cpp
| 70
| 33.3
| 104
| 0.755843
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,730
|
VecControls.cpp
|
LMMS_lmms/plugins/Vectorscope/VecControls.cpp
|
/*
* VecControls.cpp - definition of VecControls class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "VecControls.h"
#include <QDomElement>
#include "VecControlsDialog.h"
#include "Vectorscope.h"
namespace lmms
{
VecControls::VecControls(Vectorscope *effect) :
EffectControls(effect),
m_effect(effect),
// initialize models and set default values
m_persistenceModel(0.5f, 0.0f, 1.0f, 0.05f, this, tr("Display persistence amount")),
m_logarithmicModel(false, this, tr("Logarithmic scale")),
m_highQualityModel(false, this, tr("High quality"))
{
// Colors (percentages include sRGB gamma correction)
m_colorFG = QColor(60, 255, 130, 255); // ~LMMS green
m_colorGrid = QColor(76, 80, 84, 128); // ~60 % gray (slightly cold / blue), 50 % transparent
m_colorLabels = QColor(76, 80, 84, 255); // ~60 % gray (slightly cold / blue)
m_colorOutline = QColor(30, 34, 38, 255); // ~40 % gray (slightly cold / blue)
}
// Create the VecControlDialog widget which handles display of GUI elements.
gui::EffectControlDialog* VecControls::createView()
{
return new gui::VecControlsDialog(this);
}
void VecControls::loadSettings(const QDomElement &element)
{
m_persistenceModel.loadSettings(element, "Persistence");
m_logarithmicModel.loadSettings(element, "Logarithmic");
m_highQualityModel.loadSettings(element, "HighQuality");
}
void VecControls::saveSettings(QDomDocument &document, QDomElement &element)
{
m_persistenceModel.saveSettings(document, element, "Persistence");
m_logarithmicModel.saveSettings(document, element, "Logarithmic");
m_highQualityModel.saveSettings(document, element, "HighQuality");
}
} // namespace lmms
| 2,480
|
C++
|
.cpp
| 61
| 38.754098
| 95
| 0.760399
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,731
|
VectorView.cpp
|
LMMS_lmms/plugins/Vectorscope/VectorView.cpp
|
/* VectorView.cpp - implementation of VectorView class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "VectorView.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <QImage>
#include <QPainter>
#include "ColorChooser.h"
#include "GuiApplication.h"
#include "FontHelper.h"
#include "MainWindow.h"
#include "VecControls.h"
namespace lmms::gui
{
VectorView::VectorView(VecControls *controls, LocklessRingBuffer<SampleFrame> *inputBuffer, unsigned short displaySize, QWidget *parent) :
QWidget(parent),
m_controls(controls),
m_inputBuffer(inputBuffer),
m_bufferReader(*inputBuffer),
m_displaySize(displaySize),
m_zoom(1.f),
m_persistTimestamp(0),
m_zoomTimestamp(0),
m_oldHQ(m_controls->m_highQualityModel.value()),
m_oldX(m_displaySize / 2),
m_oldY(m_displaySize / 2)
{
setMinimumSize(200, 200);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
connect(getGUI()->mainWindow(), SIGNAL(periodicUpdate()), this, SLOT(periodicUpdate()));
m_displayBuffer.resize(sizeof qRgb(0,0,0) * m_displaySize * m_displaySize, 0);
#ifdef VEC_DEBUG
m_executionAvg = 0;
#endif
}
// Compose and draw all the content; called by Qt.
void VectorView::paintEvent(QPaintEvent *event)
{
#ifdef VEC_DEBUG
unsigned int drawTime = std::chrono::high_resolution_clock::now().time_since_epoch().count();
#endif
// All drawing done in this method, local variables are sufficient for the boundary
const int displayTop = 2;
const int displayBottom = height() - 2;
const int displayLeft = 2;
const int displayRight = width() - 2;
const int displayWidth = displayRight - displayLeft;
const int displayHeight = displayBottom - displayTop;
const float centerX = displayLeft + (displayWidth / 2.f);
const float centerY = displayTop + (displayWidth / 2.f);
const int margin = 4;
const int gridCorner = 30;
// Setup QPainter and font sizes
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QFont normalFont, boldFont;
boldFont.setBold(true);
const int labelWidth = 26;
const int labelHeight = 26;
bool hq = m_controls->m_highQualityModel.value();
// Clear display buffer if quality setting was changed
if (hq != m_oldHQ)
{
m_oldHQ = hq;
for (std::size_t i = 0; i < m_displayBuffer.size(); i++)
{
m_displayBuffer.data()[i] = 0;
}
}
// Dim stored image based on persistence setting and elapsed time.
// Update period is limited to 50 ms (20 FPS) for non-HQ mode and 10 ms (100 FPS) for HQ mode.
const unsigned int currentTimestamp = std::chrono::duration_cast<std::chrono::milliseconds>
(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count();
const unsigned int elapsed = currentTimestamp - m_persistTimestamp;
const unsigned int threshold = hq ? 10 : 50;
if (elapsed > threshold)
{
m_persistTimestamp = currentTimestamp;
// Non-HQ mode uses half the resolution → use limited buffer space.
const std::size_t useableBuffer = hq ? m_displayBuffer.size() : m_displayBuffer.size() / 4;
// The knob value is interpreted on log. scale, otherwise the effect would ramp up too slowly.
// Persistence value specifies fraction of light intensity that remains after 10 ms.
// → Compensate it based on elapsed time (exponential decay).
const float persist = log10(1 + 9 * m_controls->m_persistenceModel.value());
const float persistPerFrame = pow(persist, elapsed / 10.f);
// Note that for simplicity and performance reasons, this implementation only dims all stored
// values by a given factor. A true simulation would also do the inverse of desaturation that
// occurs in high-intensity traces in HQ mode.
for (std::size_t i = 0; i < useableBuffer; i++)
{
m_displayBuffer.data()[i] *= persistPerFrame;
}
}
// Get new samples from the lockless input FIFO buffer
auto inBuffer = m_bufferReader.read_max(m_inputBuffer->capacity());
std::size_t frameCount = inBuffer.size();
// Draw new points on top
const bool logScale = m_controls->m_logarithmicModel.value();
const unsigned short activeSize = hq ? m_displaySize : m_displaySize / 2;
// Helper lambda functions for better readability
// Make sure pixel stays within display bounds:
auto saturate = [=](short pixelPos) {return qBound((short)0, pixelPos, (short)(activeSize - 1));};
// Take existing pixel and brigthen it. Very bright light should reduce saturation and become
// white. This effect is easily approximated by capping elementary colors to 255 individually.
auto updatePixel = [&](unsigned short x, unsigned short y, QColor addedColor)
{
QColor currentColor = ((QRgb*)m_displayBuffer.data())[x + y * activeSize];
currentColor.setRed(std::min(currentColor.red() + addedColor.red(), 255));
currentColor.setGreen(std::min(currentColor.green() + addedColor.green(), 255));
currentColor.setBlue(std::min(currentColor.blue() + addedColor.blue(), 255));
((QRgb*)m_displayBuffer.data())[x + y * activeSize] = currentColor.rgb();
};
if (hq)
{
// High quality mode: check distance between points and draw a line.
// The longer the line is, the dimmer, simulating real electron trace on luminescent screen.
for (std::size_t frame = 0; frame < frameCount; frame++)
{
float left = 0.0f;
float right = 0.0f;
float inLeft = inBuffer[frame][0] * m_zoom;
float inRight = inBuffer[frame][1] * m_zoom;
// Scale left and right channel from (-1.0, 1.0) to display range
if (logScale)
{
// To better preserve shapes, the log scale is applied to the distance from origin,
// not the individual channels.
const float distance = sqrt(inLeft * inLeft + inRight * inRight);
const float distanceLog = log10(1 + 9 * std::abs(distance));
const float angleCos = inLeft / distance;
const float angleSin = inRight / distance;
left = distanceLog * angleCos * (activeSize - 1) / 4;
right = distanceLog * angleSin * (activeSize - 1) / 4;
}
else
{
left = inLeft * (activeSize - 1) / 4;
right = inRight * (activeSize - 1) / 4;
}
// Rotate display coordinates 45 degrees, flip Y axis and make sure the result stays within bounds
int x = saturate(right - left + activeSize / 2.f);
int y = saturate(activeSize - (right + left + activeSize / 2.f));
// Estimate number of points needed to fill space between the old and new pixel. Cap at 100.
unsigned char points = std::min((int)sqrt((m_oldX - x) * (m_oldX - x) + (m_oldY - y) * (m_oldY - y)), 100);
// Large distance = dim trace. The curve for darker() is choosen so that:
// - no movement (0 points) actually _increases_ brightness slightly,
// - one point between samples = returns exactly the specified color,
// - one to 99 points between samples = follows a sharp "1/x" decaying curve,
// - 100 points between samples = returns approximately 5 % brightness.
// Everything else is discarded (by the 100 point cap) because there is not much to see anyway.
QColor addedColor = m_controls->m_colorFG.darker(75 + 20 * points).rgb();
// Draw the new pixel: the beam sweeps across area that may have been excited before
// → add new value to existing pixel state.
updatePixel(x, y, addedColor);
// Draw interpolated points between the old pixel and the new one
int newX = right - left + activeSize / 2.f;
int newY = activeSize - (right + left + activeSize / 2.f);
for (unsigned char i = 1; i < points; i++)
{
x = saturate(((points - i) * m_oldX + i * newX) / points);
y = saturate(((points - i) * m_oldY + i * newY) / points);
updatePixel(x, y, addedColor);
}
m_oldX = newX;
m_oldY = newY;
}
}
else
{
// To improve performance, non-HQ mode uses smaller display size and only
// one full-color pixel per sample.
for (std::size_t frame = 0; frame < frameCount; frame++)
{
float left = 0.0f;
float right = 0.0f;
float inLeft = inBuffer[frame][0] * m_zoom;
float inRight = inBuffer[frame][1] * m_zoom;
if (logScale) {
const float distance = sqrt(inLeft * inLeft + inRight * inRight);
const float distanceLog = log10(1 + 9 * std::abs(distance));
const float angleCos = inLeft / distance;
const float angleSin = inRight / distance;
left = distanceLog * angleCos * (activeSize - 1) / 4;
right = distanceLog * angleSin * (activeSize - 1) / 4;
} else {
left = inLeft * (activeSize - 1) / 4;
right = inRight * (activeSize - 1) / 4;
}
int x = saturate(right - left + activeSize / 2.f);
int y = saturate(activeSize - (right + left + activeSize / 2.f));
((QRgb*)m_displayBuffer.data())[x + y * activeSize] = m_controls->m_colorFG.rgb();
}
}
// Draw background
painter.fillRect(displayLeft, displayTop, displayWidth, displayHeight, QColor(0,0,0));
// Draw the final image
QImage temp = QImage(m_displayBuffer.data(),
activeSize,
activeSize,
QImage::Format_RGB32);
temp.setDevicePixelRatio(devicePixelRatio());
painter.drawImage(displayLeft, displayTop,
temp.scaledToWidth(displayWidth * devicePixelRatio(),
Qt::SmoothTransformation));
// Draw the grid and labels
painter.setPen(QPen(m_controls->m_colorGrid, 1.5, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawEllipse(QPointF(centerX, centerY), displayWidth / 2.f, displayWidth / 2.f);
painter.setPen(QPen(m_controls->m_colorGrid, 1.5, Qt::DotLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawLine(QPointF(centerX, centerY), QPointF(displayLeft + gridCorner, displayTop + gridCorner));
painter.drawLine(QPointF(centerX, centerY), QPointF(displayRight - gridCorner, displayTop + gridCorner));
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.setFont(adjustedToPixelSize(boldFont, 26));
painter.drawText(displayLeft + margin, displayTop,
labelWidth, labelHeight, Qt::AlignLeft | Qt::AlignTop | Qt::TextDontClip,
QString("L"));
painter.drawText(displayRight - margin - labelWidth, displayTop,
labelWidth, labelHeight, Qt::AlignRight| Qt::AlignTop | Qt::TextDontClip,
QString("R"));
// Draw the outline
painter.setPen(QPen(m_controls->m_colorOutline, 2, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawRoundedRect(1, 1, width() - 2, height() - 2, 2.f, 2.f);
// Draw zoom info if changed within last second (re-using timestamp acquired for dimming)
if (currentTimestamp - m_zoomTimestamp < 1000)
{
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.setFont(normalFont);
painter.drawText(displayWidth / 2 - 50, displayBottom - 20, 100, 16, Qt::AlignCenter,
QString("Zoom: ").append(std::to_string((int)round(m_zoom * 100)).c_str()).append(" %"));
}
// Optionally measure drawing performance
#ifdef VEC_DEBUG
drawTime = std::chrono::high_resolution_clock::now().time_since_epoch().count() - drawTime;
m_executionAvg = 0.95f * m_executionAvg + 0.05f * drawTime / 1000000.f;
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.setFont(normalFont);
painter.drawText(displayWidth / 2 - 50, displayBottom - 16, 100, 16, Qt::AlignLeft,
QString("Exec avg.: ").append(std::to_string(m_executionAvg).substr(0, 5).c_str()).append(" ms"));
#endif
}
// Periodically trigger repaint and check if the widget is visible
void VectorView::periodicUpdate()
{
m_visible = isVisible();
if (m_visible) {update();}
}
// Allow to change color on double-click.
// More of an Easter egg, to avoid cluttering the interface with non-essential functionality.
void VectorView::mouseDoubleClickEvent(QMouseEvent *event)
{
auto colorDialog = new ColorChooser(m_controls->m_colorFG, this);
if (colorDialog->exec())
{
m_controls->m_colorFG = colorDialog->currentColor();
}
}
// Change zoom level using the mouse wheel
void VectorView::wheelEvent(QWheelEvent *event)
{
// Go through integers to avoid accumulating errors
const unsigned short old_zoom = round(100 * m_zoom);
// Min-max bounds are 20 and 1000 %, step for 15°-increment mouse wheel is 20 %
const unsigned short new_zoom = qBound(20, old_zoom + event->angleDelta().y() / 6, 1000);
m_zoom = new_zoom / 100.f;
event->accept();
m_zoomTimestamp = std::chrono::duration_cast<std::chrono::milliseconds>
(
std::chrono::high_resolution_clock::now().time_since_epoch()
).count();
}
} // namespace lmms::gui
| 13,187
|
C++
|
.cpp
| 292
| 42.253425
| 138
| 0.718078
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,732
|
ArrayVectorTest.cpp
|
LMMS_lmms/tests/src/core/ArrayVectorTest.cpp
|
/*
* ArrayVectorTest.cpp
*
* Copyright (c) 2023 Dominic Clark
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "ArrayVector.h"
#include <QObject>
#include <QtTest/QtTest>
#include <array>
#include <iterator>
using lmms::ArrayVector;
struct ShouldNotConstruct
{
ShouldNotConstruct() { QFAIL("should not construct"); }
};
struct ShouldNotDestruct
{
~ShouldNotDestruct() { QFAIL("should not destruct"); }
};
enum class Construction { Default, Copy, Move, CopyAssign, MoveAssign };
struct Constructible
{
Constructible() : construction{Construction::Default} {}
Constructible(const Constructible&) : construction{Construction::Copy} {}
Constructible(Constructible&&) : construction{Construction::Move} {}
Constructible& operator=(const Constructible&) { construction = Construction::CopyAssign; return *this; }
Constructible& operator=(Constructible&&) { construction = Construction::MoveAssign; return *this; }
Construction construction;
};
struct DestructorCheck
{
~DestructorCheck() { *destructed = true; }
bool* destructed;
};
class ArrayVectorTest : public QObject
{
Q_OBJECT
private slots:
void defaultConstructorTest()
{
// Ensure no elements are constructed
const auto v = ArrayVector<ShouldNotConstruct, 1>();
// Ensure the container is empty
QVERIFY(v.empty());
}
void copyConstructorTest()
{
{
// Ensure all elements are copy constructed
const auto v = ArrayVector<Constructible, 1>{{}};
const auto copy = v;
for (const auto& element : copy) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure corresponding elements are used
const auto v = ArrayVector<int, 5>{1, 2, 3};
const auto copy = v;
const auto expected = std::array{1, 2, 3};
QVERIFY(std::equal(copy.begin(), copy.end(), expected.begin(), expected.end()));
}
}
void moveConstructorTest()
{
{
// Ensure all elements are move constructed
auto v = ArrayVector<Constructible, 1>{{}};
const auto moved = std::move(v);
for (const auto& element : moved) {
QCOMPARE(element.construction, Construction::Move);
}
}
{
// Ensure corresponding elements are used
auto v = ArrayVector<int, 5>{1, 2, 3};
const auto moved = std::move(v);
const auto expected = std::array{1, 2, 3};
QVERIFY(std::equal(moved.begin(), moved.end(), expected.begin(), expected.end()));
// Move construction should leave the source empty
QVERIFY(v.empty());
}
}
void fillValueConstructorTest()
{
// Ensure all elements are copy constructed
const auto v = ArrayVector<Constructible, 2>(1, {});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Copy);
}
// Ensure the container has the correct size
QCOMPARE(v.size(), std::size_t{1});
}
void fillDefaultConstructorTest()
{
// Ensure all elements are copy constructed
const auto v = ArrayVector<Constructible, 2>(1);
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Default);
}
// Ensure the container has the correct size
QCOMPARE(v.size(), std::size_t{1});
}
void rangeConstructorTest()
{
{
// Ensure the elements are copy constructed from normal iterators
const auto data = std::array{Constructible{}};
const auto v = ArrayVector<Constructible, 1>(data.begin(), data.end());
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure the elements are move constructed from move iterators
auto data = std::array{Constructible{}};
const auto v = ArrayVector<Constructible, 1>(
std::move_iterator{data.begin()}, std::move_iterator{data.end()});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Move);
}
}
{
// Ensure corresponding elements are used
const auto data = std::array{1, 2, 3};
const auto v = ArrayVector<int, 5>(data.begin(), data.end());
QVERIFY(std::equal(v.begin(), v.end(), data.begin(), data.end()));
}
}
void initializerListConstructorTest()
{
// Ensure the container is constructed with the correct data
const auto v = ArrayVector<int, 5>{1, 2, 3};
const auto expected = std::array{1, 2, 3};
QVERIFY(std::equal(v.begin(), v.end(), expected.begin(), expected.end()));
}
void destructorTest()
{
{
// Should not call destructors for space without elements
const auto v = ArrayVector<ShouldNotDestruct, 1>{};
}
{
// Should call destructors for all elements
auto destructed = false;
{
const auto v = ArrayVector<DestructorCheck, 1>{{&destructed}};
}
QVERIFY(destructed);
}
}
void copyAssignmentTest()
{
{
// Self-assignment should not change the contents
auto v = ArrayVector<int, 5>{1, 2, 3};
const auto oldValue = v;
v = v;
QCOMPARE(v, oldValue);
}
{
// Assignment to a larger container should copy assign
const auto src = ArrayVector<Constructible, 5>(3);
auto dst = ArrayVector<Constructible, 5>(5);
dst = src;
QCOMPARE(dst.size(), std::size_t{3});
for (const auto& element : dst) {
QCOMPARE(element.construction, Construction::CopyAssign);
}
}
{
// Assignment to a smaller container should copy construct
const auto src = ArrayVector<Constructible, 5>(3);
auto dst = ArrayVector<Constructible, 5>{};
dst = src;
QCOMPARE(dst.size(), std::size_t{3});
for (const auto& element : dst) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure corresponding elements are used
const auto src = ArrayVector<int, 5>{1, 2, 3};
auto dst = ArrayVector<int, 5>{};
dst = src;
QCOMPARE(dst, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void moveAssignmentTest()
{
{
// Self-assignment should not change the contents
//// Please note the following:
//// https://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#2468
//// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81159
auto v = ArrayVector<int, 5>{1, 2, 3};
const auto oldValue = v;
#if __GNUC__ >= 13
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wself-move"
#endif
v = std::move(v);
#if __GNUC__ >= 13
# pragma GCC diagnostic pop
#endif
QCOMPARE(v, oldValue);
}
{
// Assignment to a larger container should move assign
auto src = ArrayVector<Constructible, 5>(3);
auto dst = ArrayVector<Constructible, 5>(5);
dst = std::move(src);
QCOMPARE(dst.size(), std::size_t{3});
for (const auto& element : dst) {
QCOMPARE(element.construction, Construction::MoveAssign);
}
}
{
// Assignment to a smaller container should move construct
auto src = ArrayVector<Constructible, 5>(3);
auto dst = ArrayVector<Constructible, 5>{};
dst = std::move(src);
QCOMPARE(dst.size(), std::size_t{3});
for (const auto& element : dst) {
QCOMPARE(element.construction, Construction::Move);
}
}
{
// Ensure corresponding elements are used
auto src = ArrayVector<int, 5>{1, 2, 3};
auto dst = ArrayVector<int, 5>{};
dst = std::move(src);
QCOMPARE(dst, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void initializerListAssignmentTest()
{
{
// Assignment to a larger container should copy assign
auto v = ArrayVector<Constructible, 2>(2);
v = {Constructible{}};
QCOMPARE(v.size(), std::size_t{1});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::CopyAssign);
}
}
{
// Assignment to a smaller container should copy construct
auto v = ArrayVector<Constructible, 2>{};
v = {Constructible{}};
QCOMPARE(v.size(), std::size_t{1});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure corresponding elements are used
auto v = ArrayVector<int, 5>{};
v = {1, 2, 3};
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void fillValueAssignTest()
{
{
// Assignment to a larger container should copy assign
auto v = ArrayVector<Constructible, 5>(5);
v.assign(3, {});
QCOMPARE(v.size(), std::size_t{3});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::CopyAssign);
}
}
{
// Assignment to a smaller container should copy construct
auto v = ArrayVector<Constructible, 5>{};
v.assign(3, {});
QCOMPARE(v.size(), std::size_t{3});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure correct value is filled
auto v = ArrayVector<int, 5>{};
v.assign(3, 1);
QCOMPARE(v, (ArrayVector<int, 5>{1, 1, 1}));
}
}
void rangeAssignTest()
{
{
// Assignment to a larger container should copy assign
const auto data = std::array{Constructible{}};
auto v = ArrayVector<Constructible, 2>(2);
v.assign(data.begin(), data.end());
QCOMPARE(v.size(), std::size_t{1});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::CopyAssign);
}
}
{
// Assignment to a smaller container should copy construct
const auto data = std::array{Constructible{}};
auto v = ArrayVector<Constructible, 2>{};
v.assign(data.begin(), data.end());
QCOMPARE(v.size(), std::size_t{1});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure correct value is filled
const auto data = std::array{1, 2, 3};
auto v = ArrayVector<int, 5>{};
v.assign(data.begin(), data.end());
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void atTest()
{
{
// Non-const version
auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v.at(1), 2);
QVERIFY_EXCEPTION_THROWN(v.at(3), std::out_of_range);
}
{
// Const version
const auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v.at(1), 2);
QVERIFY_EXCEPTION_THROWN(v.at(3), std::out_of_range);
}
}
void subscriptTest()
{
{
// Non-const version
auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v[1], 2);
}
{
// Const version
const auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v[1], 2);
}
}
void frontTest()
{
{
// Non-const version
auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v.front(), 1);
}
{
// Const version
const auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v.front(), 1);
}
}
void backTest()
{
{
// Non-const version
auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v.back(), 3);
}
{
// Const version
const auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v.back(), 3);
}
}
void dataTest()
{
{
// Non-const version
auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v.data(), &v.front());
}
{
// Const version
const auto v = ArrayVector<int, 5>{1, 2, 3};
QCOMPARE(v.data(), &v.front());
}
}
void beginEndTest()
{
const auto expected = std::array{1, 2, 3};
{
// Non-const version
auto v = ArrayVector<int, 5>{1, 2, 3};
QVERIFY(std::equal(v.begin(), v.end(), expected.begin(), expected.end()));
QVERIFY(std::equal(v.cbegin(), v.cend(), expected.begin(), expected.end()));
}
{
// Const version
const auto v = ArrayVector<int, 5>{1, 2, 3};
QVERIFY(std::equal(v.begin(), v.end(), expected.begin(), expected.end()));
}
}
void rbeginRendTest()
{
const auto expected = std::array{3, 2, 1};
{
// Non-const version
auto v = ArrayVector<int, 5>{1, 2, 3};
QVERIFY(std::equal(v.rbegin(), v.rend(), expected.begin(), expected.end()));
QVERIFY(std::equal(v.crbegin(), v.crend(), expected.begin(), expected.end()));
}
{
// Const version
const auto v = ArrayVector<int, 5>{1, 2, 3};
QVERIFY(std::equal(v.rbegin(), v.rend(), expected.begin(), expected.end()));
}
}
void emptyFullSizeMaxCapacityTest()
{
auto v = ArrayVector<int, 2>{};
QVERIFY(v.empty());
QVERIFY(!v.full());
QCOMPARE(v.size(), std::size_t{0});
QCOMPARE(v.max_size(), std::size_t{2});
QCOMPARE(v.capacity(), std::size_t{2});
v.push_back(1);
QVERIFY(!v.empty());
QVERIFY(!v.full());
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v.max_size(), std::size_t{2});
QCOMPARE(v.capacity(), std::size_t{2});
v.push_back(2);
QVERIFY(!v.empty());
QVERIFY(v.full());
QCOMPARE(v.size(), std::size_t{2});
QCOMPARE(v.max_size(), std::size_t{2});
QCOMPARE(v.capacity(), std::size_t{2});
auto empty = ArrayVector<int, 0>{};
QVERIFY(empty.empty());
QVERIFY(empty.full());
QCOMPARE(empty.size(), std::size_t{0});
QCOMPARE(empty.max_size(), std::size_t{0});
QCOMPARE(empty.capacity(), std::size_t{0});
}
void insertValueTest()
{
{
// Copy
const auto data = Constructible{};
auto v = ArrayVector<Constructible, 1>{};
v.insert(v.cbegin(), data);
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v[0].construction, Construction::Copy);
}
{
// Move
auto v = ArrayVector<Constructible, 1>{};
v.insert(v.cbegin(), Constructible{});
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v[0].construction, Construction::Move);
}
{
// Ensure the correct value is used (copy)
const auto data = 1;
auto v = ArrayVector<int, 5>{2, 3};
v.insert(v.cbegin(), data);
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
{
// Ensure the correct value is used (move)
auto v = ArrayVector<int, 5>{2, 3};
v.insert(v.cbegin(), 1);
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void insertFillValueTest()
{
{
// Insertion should copy construct
auto v = ArrayVector<Constructible, 5>{};
v.insert(v.cbegin(), 3, {});
QCOMPARE(v.size(), std::size_t{3});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure correct value is filled
auto v = ArrayVector<int, 5>{1, 3};
v.insert(v.cbegin() + 1, 3, 2);
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 2, 2, 3}));
}
}
void insertRangeTest()
{
{
// Insertion should copy construct
const auto data = std::array{Constructible{}};
auto v = ArrayVector<Constructible, 2>{};
v.insert(v.cbegin(), data.begin(), data.end());
QCOMPARE(v.size(), std::size_t{1});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure correct value is filled
const auto data = std::array{2, 3};
auto v = ArrayVector<int, 5>{1, 4};
v.insert(v.cbegin() + 1, data.begin(), data.end());
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3, 4}));
}
}
void insertInitializerListTest()
{
{
// Insertion should copy construct
auto v = ArrayVector<Constructible, 2>{};
v.insert(v.cbegin(), {Constructible{}});
QCOMPARE(v.size(), std::size_t{1});
for (const auto& element : v) {
QCOMPARE(element.construction, Construction::Copy);
}
}
{
// Ensure corresponding elements are used
auto v = ArrayVector<int, 5>{1, 4};
v.insert(v.cbegin() + 1, {2, 3});
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3, 4}));
}
}
void emplaceTest()
{
{
// Ensure the value is constructed in-place
auto v = ArrayVector<Constructible, 1>{};
v.emplace(v.cbegin());
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v[0].construction, Construction::Default);
}
{
// Ensure the correct value is used (move)
auto v = ArrayVector<int, 5>{2, 3};
v.emplace(v.cbegin(), 1);
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void eraseTest()
{
{
// Ensure destructors are run
auto destructed = false;
auto v = ArrayVector<DestructorCheck, 1>{{&destructed}};
v.erase(v.cbegin());
QVERIFY(destructed);
}
{
// Ensure the result is correct
auto v = ArrayVector<int, 5>{10, 1, 2, 3};
v.erase(v.cbegin());
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void eraseRangeTest()
{
{
// Ensure destructors are run
auto destructed = false;
auto v = ArrayVector<DestructorCheck, 1>{{&destructed}};
v.erase(v.cbegin(), v.cend());
QVERIFY(destructed);
}
{
// Ensure the result is correct
auto v = ArrayVector<int, 5>{1, 20, 21, 2, 3};
v.erase(v.cbegin() + 1, v.cbegin() + 3);
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void pushBackTest()
{
{
// Copy
const auto data = Constructible{};
auto v = ArrayVector<Constructible, 1>{};
v.push_back(data);
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v[0].construction, Construction::Copy);
}
{
// Move
auto v = ArrayVector<Constructible, 1>{};
v.push_back({});
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v[0].construction, Construction::Move);
}
{
// Ensure the correct value is used (copy)
const auto data = 3;
auto v = ArrayVector<int, 5>{1, 2};
v.push_back(data);
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
{
// Ensure the correct value is used (move)
auto v = ArrayVector<int, 5>{1, 2};
v.push_back(3);
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void emplaceBackTest()
{
{
// Ensure the value is constructed in-place
auto v = ArrayVector<Constructible, 1>{};
v.emplace_back();
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v[0].construction, Construction::Default);
}
{
// Ensure the correct value is used (move)
auto v = ArrayVector<int, 5>{1, 2};
v.emplace_back(3);
QCOMPARE(v, (ArrayVector<int, 5>{1, 2, 3}));
}
}
void popBackTest()
{
{
// Ensure destructors are run
auto destructed = false;
auto v = ArrayVector<DestructorCheck, 1>{{&destructed}};
v.pop_back();
QVERIFY(destructed);
}
{
// Ensure the result is correct
auto v = ArrayVector<int, 5>{1, 2, 3};
v.pop_back();
QCOMPARE(v, (ArrayVector<int, 5>{1, 2}));
}
}
void resizeDefaultTest()
{
{
// Smaller
auto destructed = false;
auto v = ArrayVector<DestructorCheck, 1>{{&destructed}};
QCOMPARE(v.size(), std::size_t{1});
v.resize(0);
QCOMPARE(v.size(), std::size_t{0});
QVERIFY(destructed);
}
{
// Bigger
auto v = ArrayVector<Constructible, 1>{};
QCOMPARE(v.size(), std::size_t{0});
v.resize(1);
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v[0].construction, Construction::Default);
}
{
// Too big
auto v = ArrayVector<int, 1>{};
QVERIFY_EXCEPTION_THROWN(v.resize(2), std::length_error);
}
}
void resizeValueTest()
{
{
// Smaller
auto dummy = false;
auto destructed = false;
auto v = ArrayVector<DestructorCheck, 1>{{&destructed}};
QCOMPARE(v.size(), std::size_t{1});
v.resize(0, {&dummy});
QCOMPARE(v.size(), std::size_t{0});
QVERIFY(destructed);
}
{
// Bigger
auto v = ArrayVector<Constructible, 1>{};
QCOMPARE(v.size(), std::size_t{0});
v.resize(1, {});
QCOMPARE(v.size(), std::size_t{1});
QCOMPARE(v[0].construction, Construction::Copy);
}
{
// Too big
auto v = ArrayVector<int, 1>{};
QVERIFY_EXCEPTION_THROWN(v.resize(2), std::length_error);
}
{
// Ensure the correct value is used
auto v = ArrayVector<int, 1>{};
v.resize(1, 1);
QCOMPARE(v, (ArrayVector<int, 1>{1}));
}
}
void clearTest()
{
{
// Ensure destructors are run
auto destructed = false;
auto v = ArrayVector<DestructorCheck, 1>{{&destructed}};
v.clear();
QVERIFY(destructed);
}
{
// Ensure the result is correct
auto v = ArrayVector<int, 5>{1, 2, 3};
v.clear();
QCOMPARE(v, (ArrayVector<int, 5>{}));
}
}
void memberSwapTest()
{
auto a = ArrayVector<int, 5>{1, 2, 3, 4};
auto b = ArrayVector<int, 5>{2, 4, 6};
const auto aOriginal = a;
const auto bOriginal = b;
a.swap(b);
QCOMPARE(a, bOriginal);
QCOMPARE(b, aOriginal);
}
void freeSwapTest()
{
auto a = ArrayVector<int, 5>{1, 2, 3, 4};
auto b = ArrayVector<int, 5>{2, 4, 6};
const auto aOriginal = a;
const auto bOriginal = b;
swap(a, b);
QCOMPARE(a, bOriginal);
QCOMPARE(b, aOriginal);
}
void comparisonTest()
{
const auto v = ArrayVector<int, 5>{1, 2, 3};
const auto l = ArrayVector<int, 5>{1, 2, 2};
const auto e = ArrayVector<int, 5>{1, 2, 3};
const auto g = ArrayVector<int, 5>{1, 3, 3};
QVERIFY(l < v);
QVERIFY(!(e < v));
QVERIFY(!(g < v));
QVERIFY(l <= v);
QVERIFY(e <= v);
QVERIFY(!(g <= v));
QVERIFY(!(l > v));
QVERIFY(!(e > v));
QVERIFY(g > v);
QVERIFY(!(l >= v));
QVERIFY(e >= v);
QVERIFY(g >= v);
QVERIFY(!(l == v));
QVERIFY(e == v);
QVERIFY(!(g == v));
QVERIFY(l != v);
QVERIFY(!(e != v));
QVERIFY(g != v);
}
};
QTEST_GUILESS_MAIN(ArrayVectorTest)
#include "ArrayVectorTest.moc"
| 21,122
|
C++
|
.cpp
| 780
| 23.765385
| 106
| 0.649771
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,733
|
RelativePathsTest.cpp
|
LMMS_lmms/tests/src/core/RelativePathsTest.cpp
|
/*
* RelativePathsTest.cpp
*
* Copyright (c) 2017 Tres Finocchiaro <tres/dot/finocchiaro/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDir>
#include <QObject>
#include <QtTest/QtTest>
#include "ConfigManager.h"
#include "PathUtil.h"
#include "SampleBuffer.h"
class RelativePathsTest : public QObject
{
Q_OBJECT
private slots:
void PathUtilComparisonTests()
{
using namespace lmms;
QFileInfo fi(ConfigManager::inst()->factorySamplesDir() + "/drums/kick01.ogg");
QVERIFY(fi.exists());
QString absPath = fi.absoluteFilePath();
QString oldRelPath = "drums/kick01.ogg";
QString relPath = PathUtil::basePrefix(PathUtil::Base::FactorySample) + "drums/kick01.ogg";
QString fuzPath = absPath;
fuzPath.replace(relPath, "drums/.///kick01.ogg");
//Test nicely formatted paths
QCOMPARE(PathUtil::toShortestRelative(absPath), relPath);
QCOMPARE(PathUtil::toAbsolute(relPath), absPath);
//Test upgrading old paths
QCOMPARE(PathUtil::toShortestRelative(oldRelPath), relPath);
QCOMPARE(PathUtil::toAbsolute(oldRelPath), absPath);
//Test weird but valid paths
QCOMPARE(PathUtil::toShortestRelative(fuzPath), relPath);
QCOMPARE(PathUtil::toAbsolute(fuzPath), absPath);
//Empty paths should stay empty
QString empty = QString("");
QCOMPARE(PathUtil::stripPrefix(""), empty);
QCOMPARE(PathUtil::cleanName(""), empty);
QCOMPARE(PathUtil::toAbsolute(""), empty);
QCOMPARE(PathUtil::toShortestRelative(""), empty);
}
};
QTEST_GUILESS_MAIN(RelativePathsTest)
#include "RelativePathsTest.moc"
| 2,303
|
C++
|
.cpp
| 62
| 34.822581
| 93
| 0.761094
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,734
|
ProjectVersionTest.cpp
|
LMMS_lmms/tests/src/core/ProjectVersionTest.cpp
|
/*
* ProjectVersionTest.cpp
*
* Copyright (c) 2015 Lukas W <lukaswhl/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "ProjectVersion.h"
#include <QtTest/QtTest>
class ProjectVersionTest : public QObject
{
Q_OBJECT
private slots:
void ProjectVersionComparisonTests()
{
using namespace lmms;
QVERIFY(ProjectVersion("1.1.0", ProjectVersion::CompareType::Minor) > "1.0.3");
QVERIFY(ProjectVersion("1.1.0", ProjectVersion::CompareType::Major) < "2.1.0");
QVERIFY(ProjectVersion("1.1.0", ProjectVersion::CompareType::Release) > "0.2.1");
QVERIFY(ProjectVersion("1.1.4", ProjectVersion::CompareType::Release) < "1.1.10");
QVERIFY(ProjectVersion("1.1.0", ProjectVersion::CompareType::Minor) == "1.1.5");
QVERIFY( ! ( ProjectVersion("3.1.0", ProjectVersion::CompareType::Minor) < "2.2.5" ) );
QVERIFY( ! ( ProjectVersion("2.5.0", ProjectVersion::CompareType::Release) < "2.2.5" ) );
//A pre-release version has lower precedence than a normal version
QVERIFY(ProjectVersion("1.1.0") > "1.1.0-alpha");
//But higher precedence than the previous version
QVERIFY(ProjectVersion("1.1.0-alpha") > "1.0.0");
//Identifiers with letters or hyphens are compare lexically in ASCII sort order
QVERIFY(ProjectVersion("1.1.0-alpha") < "1.1.0-beta");
QVERIFY(ProjectVersion("1.2.0-rc1") < "1.2.0-rc2");
//Build metadata MUST be ignored when determining version precedence
QVERIFY(ProjectVersion("1.2.2") == "1.2.2+metadata");
QVERIFY(ProjectVersion("1.0.0-alpha") < "1.0.0-alpha.1");
QVERIFY(ProjectVersion("1.0.0-alpha.1") < "1.0.0-alpha.beta");
QVERIFY(ProjectVersion("1.0.0-alpha.beta") < "1.0.0-beta");
QVERIFY(ProjectVersion("1.0.0-beta.2") < "1.0.0-beta.11");
//Test workaround for old, nonstandard version numbers
QVERIFY(ProjectVersion("1.2.2.42") == "1.2.3-42");
QVERIFY(ProjectVersion("1.2.2.42") > "1.2.2.21");
//Ensure that newer versions of the same format aren't upgraded
//in order to discourage use of incorrect versioning
QVERIFY(ProjectVersion("1.2.3.42") == "1.2.3");
//CompareVersion "All" should compare every identifier
QVERIFY(
ProjectVersion("1.0.0-a.b.c.d.e.f.g.h.i.j.k.l", ProjectVersion::CompareType::All)
< "1.0.0-a.b.c.d.e.f.g.h.i.j.k.m"
);
//Prerelease identifiers may contain hyphens
QVERIFY(ProjectVersion("1.0.0-Alpha-1.2") > "1.0.0-Alpha-1.1");
//We shouldn't crash on invalid versions
QVERIFY(ProjectVersion("1-invalid") == "1.0.0-invalid");
QVERIFY(ProjectVersion("") == "0.0.0");
//Numeric identifiers are smaller than non-numeric identiiers
QVERIFY(ProjectVersion("1.0.0-alpha") > "1.0.0-1");
//An identifier of the form "-x" is non-numeric, not negative
QVERIFY(ProjectVersion("1.0.0-alpha.-1") > "1.0.0-alpha.1");
}
};
QTEST_GUILESS_MAIN(ProjectVersionTest)
#include "ProjectVersionTest.moc"
| 3,572
|
C++
|
.cpp
| 76
| 44.486842
| 91
| 0.716127
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,735
|
AutomatableModelTest.cpp
|
LMMS_lmms/tests/src/core/AutomatableModelTest.cpp
|
/*
* AutomatableModelTest.cpp
*
* Copyright (c) 2019-2020 Johannes Lorenz <j.git$$$lorenz-ho.me, $$$=@>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QtTest/QtTest>
#include "AutomatableModel.h"
#include "ComboBoxModel.h"
#include "Engine.h"
class AutomatableModelTest : public QObject
{
Q_OBJECT
public:
bool m1Changed, m2Changed;
void resetChanged() { m1Changed = m2Changed = false; }
private slots: // helper slots
void onM1Changed() { m1Changed = true; }
void onM2Changed() { m2Changed = true; }
private slots: // tests
//! Test that upcast and exact casts work,
//! but no downcast or any other casts
void initTestCase()
{
using namespace lmms;
Engine::init(true);
}
void cleanupTestCase()
{
using namespace lmms;
Engine::destroy();
}
void CastTests()
{
using namespace lmms;
ComboBoxModel comboModel;
AutomatableModel* amPtr = &comboModel;
QVERIFY(nullptr == amPtr->dynamicCast<FloatModel>()); // not a parent class
QCOMPARE(&comboModel, amPtr->dynamicCast<AutomatableModel>()); // parent class
QCOMPARE(&comboModel, amPtr->dynamicCast<IntModel>()); // parent class
QCOMPARE(&comboModel, amPtr->dynamicCast<ComboBoxModel>()); // same class
IntModel intModel;
IntModel* imPtr = &intModel;
QVERIFY(nullptr == imPtr->dynamicCast<FloatModel>()); // not a parent class
QCOMPARE(&intModel, imPtr->dynamicCast<AutomatableModel>()); // parent class
QCOMPARE(&intModel, imPtr->dynamicCast<IntModel>()); // same class
QVERIFY(nullptr == imPtr->dynamicCast<ComboBoxModel>()); // child class
}
void LinkTests()
{
using namespace lmms;
BoolModel m1(false), m2(false);
QObject::connect(&m1, SIGNAL(dataChanged()),
this, SLOT(onM1Changed()));
QObject::connect(&m2, SIGNAL(dataChanged()),
this, SLOT(onM2Changed()));
resetChanged();
AutomatableModel::linkModels(&m1, &m1);
QVERIFY(!m1Changed); // cannot link to itself
QVERIFY(!m2Changed);
resetChanged();
AutomatableModel::linkModels(&m1, &m2);
QVERIFY(m1Changed); // since m1 takes the value of m2
QVERIFY(!m2Changed); // the second model is the source
resetChanged();
AutomatableModel::linkModels(&m1, &m2);
QVERIFY(!m1Changed); // it's already linked
QVERIFY(!m2Changed);
resetChanged();
BoolModel m3(false);
m1.setValue(1.f);
m2.setValue(1.f);
AutomatableModel::linkModels(&m1, &m2);
QVERIFY(m1.value());
QVERIFY(m2.value());
QVERIFY(!m3.value());
AutomatableModel::linkModels(&m2, &m3); // drag m3, drop on m2
// m2 should take m3's (0) value
// due to a bug(?), this does not happen
QVERIFY(m2.value());
QVERIFY(!m3.value());
}
};
QTEST_GUILESS_MAIN(AutomatableModelTest)
#include "AutomatableModelTest.moc"
| 3,451
|
C++
|
.cpp
| 102
| 31.294118
| 80
| 0.729811
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,736
|
MathTest.cpp
|
LMMS_lmms/tests/src/core/MathTest.cpp
|
/*
* MathTest.cpp
*
* Copyright (c) 2023 Johannes Lorenz <jlsf2013$users.sourceforge.net, $=@>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDir>
#include <QObject>
#include <QtTest/QtTest>
#include "lmms_math.h"
class MathTest : public QObject
{
Q_OBJECT
private slots:
void NumDigitsTest()
{
using namespace lmms;
QCOMPARE(numDigitsAsInt(1.f), 1);
QCOMPARE(numDigitsAsInt(9.9f), 2);
QCOMPARE(numDigitsAsInt(10.f), 2);
QCOMPARE(numDigitsAsInt(0.f), 1);
QCOMPARE(numDigitsAsInt(-100.f), 4);
QCOMPARE(numDigitsAsInt(-99.f), 3);
QCOMPARE(numDigitsAsInt(-0.4f), 1); // there is no "-0" for LED spinbox
QCOMPARE(numDigitsAsInt(-0.99f), 2);
QCOMPARE(numDigitsAsInt(1000000000), 10);
QCOMPARE(numDigitsAsInt(-1000000000), 11);
QCOMPARE(numDigitsAsInt(900000000), 9);
QCOMPARE(numDigitsAsInt(-900000000), 10);
}
};
QTEST_GUILESS_MAIN(MathTest)
#include "MathTest.moc"
| 1,657
|
C++
|
.cpp
| 50
| 31.02
| 75
| 0.746101
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,737
|
AutomationTrackTest.cpp
|
LMMS_lmms/tests/src/tracks/AutomationTrackTest.cpp
|
/*
* AutomationTrackTest.cpp
*
* Copyright (c) 2017 Lukas W <lukaswhl/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QtTest/QtTest>
#include "QCoreApplication"
#include "AutomationClip.h"
#include "AutomationTrack.h"
#include "DetuningHelper.h"
#include "InstrumentTrack.h"
#include "MidiClip.h"
#include "PatternClip.h"
#include "PatternTrack.h"
#include "PatternStore.h"
#include "TrackContainer.h"
#include "Engine.h"
#include "Song.h"
class AutomationTrackTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase()
{
using namespace lmms;
Engine::init(true);
}
void cleanupTestCase()
{
using namespace lmms;
Engine::destroy();
}
void testClipLinear()
{
using namespace lmms;
AutomationClip c(nullptr);
c.setProgressionType(AutomationClip::ProgressionType::Linear);
c.putValue(0, 0.0, false);
c.putValue(100, 1.0, false);
QCOMPARE(c.valueAt(0), 0.0f);
QCOMPARE(c.valueAt(25), 0.25f);
QCOMPARE(c.valueAt(50), 0.5f);
QCOMPARE(c.valueAt(75), 0.75f);
QCOMPARE(c.valueAt(100), 1.0f);
QCOMPARE(c.valueAt(150), 1.0f);
}
void testClipDiscrete()
{
using namespace lmms;
AutomationClip c(nullptr);
c.setProgressionType(AutomationClip::ProgressionType::Discrete);
c.putValue(0, 0.0, false);
c.putValue(100, 1.0, false);
QCOMPARE(c.valueAt(0), 0.0f);
QCOMPARE(c.valueAt(50), 0.0f);
QCOMPARE(c.valueAt(100), 1.0f);
QCOMPARE(c.valueAt(150), 1.0f);
}
void testClips()
{
using namespace lmms;
FloatModel model;
auto song = Engine::getSong();
AutomationTrack track(song);
AutomationClip c1(&track);
c1.setProgressionType(AutomationClip::ProgressionType::Linear);
c1.putValue(0, 0.0, false);
c1.putValue(10, 1.0, false);
c1.movePosition(0);
c1.addObject(&model);
AutomationClip c2(&track);
c2.setProgressionType(AutomationClip::ProgressionType::Linear);
c2.putValue(0, 0.0, false);
c2.putValue(100, 1.0, false);
c2.movePosition(100);
c2.addObject(&model);
AutomationClip c3(&track);
c3.addObject(&model);
//XXX: Why is this even necessary?
c3.clear();
QCOMPARE(song->automatedValuesAt( 0)[&model], 0.0f);
QCOMPARE(song->automatedValuesAt( 5)[&model], 0.5f);
QCOMPARE(song->automatedValuesAt( 10)[&model], 1.0f);
QCOMPARE(song->automatedValuesAt( 50)[&model], 1.0f);
QCOMPARE(song->automatedValuesAt(100)[&model], 0.0f);
QCOMPARE(song->automatedValuesAt(150)[&model], 0.5f);
}
void testLengthRespected()
{
using namespace lmms;
FloatModel model;
auto song = Engine::getSong();
AutomationTrack track(song);
AutomationClip c(&track);
c.setProgressionType(AutomationClip::ProgressionType::Linear);
c.addObject(&model);
c.putValue(0, 0.0, false);
c.putValue(100, 1.0, false);
c.changeLength(100);
QCOMPARE(song->automatedValuesAt( 0)[&model], 0.0f);
QCOMPARE(song->automatedValuesAt( 50)[&model], 0.5f);
QCOMPARE(song->automatedValuesAt(100)[&model], 1.0f);
c.changeLength(50);
QCOMPARE(song->automatedValuesAt( 0)[&model], 0.0f);
QCOMPARE(song->automatedValuesAt( 50)[&model], 0.5f);
QCOMPARE(song->automatedValuesAt(100)[&model], 0.5f);
}
void testInlineAutomation()
{
using namespace lmms;
auto song = Engine::getSong();
InstrumentTrack instrumentTrack(song);
MidiClip midiClip(&instrumentTrack);
midiClip.changeLength(TimePos(4, 0));
Note* note = midiClip.addNote(Note(TimePos(4, 0)), false);
note->createDetuning();
DetuningHelper* dh = note->detuning();
auto clip = dh->automationClip();
clip->setProgressionType( AutomationClip::ProgressionType::Linear );
clip->putValue(TimePos(0, 0), 0.0);
clip->putValue(TimePos(4, 0), 1.0);
QCOMPARE(clip->valueAt(TimePos(0, 0)), 0.0f);
QCOMPARE(clip->valueAt(TimePos(1, 0)), 0.25f);
QCOMPARE(clip->valueAt(TimePos(2, 0)), 0.5f);
QCOMPARE(clip->valueAt(TimePos(4, 0)), 1.0f);
}
void testPatternTrack()
{
using namespace lmms;
auto song = Engine::getSong();
auto patternStore = Engine::patternStore();
PatternTrack patternTrack(song);
AutomationTrack automationTrack(patternStore);
automationTrack.createClipsForPattern(patternStore->numOfPatterns() - 1);
QVERIFY(automationTrack.numOfClips());
auto c1 = dynamic_cast<AutomationClip*>(automationTrack.getClip(0));
QVERIFY(c1);
FloatModel model;
c1->setProgressionType(AutomationClip::ProgressionType::Linear);
c1->putValue(0, 0.0, false);
c1->putValue(10, 1.0, false);
c1->addObject(&model);
QCOMPARE(patternStore->automatedValuesAt( 0, patternTrack.patternIndex())[&model], 0.0f);
QCOMPARE(patternStore->automatedValuesAt( 5, patternTrack.patternIndex())[&model], 0.5f);
QCOMPARE(patternStore->automatedValuesAt(10, patternTrack.patternIndex())[&model], 1.0f);
QCOMPARE(patternStore->automatedValuesAt(50, patternTrack.patternIndex())[&model], 1.0f);
PatternTrack patternTrack2(song);
QCOMPARE(patternStore->automatedValuesAt(5, patternTrack.patternIndex())[&model], 0.5f);
QVERIFY(! patternStore->automatedValuesAt(5, patternTrack2.patternIndex()).size());
PatternClip clip(&patternTrack);
clip.changeLength(TimePos::ticksPerBar() * 2);
clip.movePosition(0);
QCOMPARE(song->automatedValuesAt(0)[&model], 0.0f);
QCOMPARE(song->automatedValuesAt(5)[&model], 0.5f);
QCOMPARE(song->automatedValuesAt(TimePos::ticksPerBar() + 5)[&model], 0.5f);
}
void testGlobalAutomation()
{
using namespace lmms;
// Global automation should not have priority, see https://github.com/LMMS/lmms/issues/4268
// Tests regression caused by 75077f6200a5aee3a5821aae48a3b8466ed8714a
auto song = Engine::getSong();
auto globalTrack = song->globalAutomationTrack();
AutomationClip globalClip(globalTrack);
AutomationTrack localTrack(song);
AutomationClip localClip(&localTrack);
FloatModel model;
globalClip.setProgressionType(AutomationClip::ProgressionType::Discrete);
localClip.setProgressionType(AutomationClip::ProgressionType::Discrete);
globalClip.addObject(&model);
localClip.addObject(&model);
globalClip.putValue(0, 100.0f, false);
localClip.putValue(0, 50.0f, false);
QCOMPARE(song->automatedValuesAt(0)[&model], 50.0f);
}
};
QTEST_GUILESS_MAIN(AutomationTrackTest)
#include "AutomationTrackTest.moc"
| 6,976
|
C++
|
.cpp
| 196
| 32.795918
| 93
| 0.746657
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,738
|
Controller.cpp
|
LMMS_lmms/src/core/Controller.cpp
|
/*
* Controller.cpp - implementation of class controller which handles
* remote-control of AutomatableModels
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail.com>
* Copyright (c) 2014 Lukas W <lukaswhl/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include <vector>
#include "AudioEngine.h"
#include "ControllerConnection.h"
#include "ControllerDialog.h"
#include "LfoController.h"
#include "MidiController.h"
#include "PeakController.h"
namespace lmms
{
long Controller::s_periods = 0;
std::vector<Controller*> Controller::s_controllers;
Controller::Controller( ControllerType _type, Model * _parent,
const QString & _display_name ) :
Model( _parent, _display_name ),
JournallingObject(),
m_valueBuffer( Engine::audioEngine()->framesPerPeriod() ),
m_bufferLastUpdated( -1 ),
m_connectionCount( 0 ),
m_type( _type )
{
if( _type != ControllerType::Dummy && _type != ControllerType::Midi )
{
s_controllers.push_back(this);
// Determine which name to use
for ( uint i=s_controllers.size(); ; i++ )
{
QString new_name = QString( tr( "Controller %1" ) )
.arg( i );
// Check if name is already in use
bool name_used = false;
for (Controller * controller : s_controllers)
{
if ( controller->name() == new_name )
{
name_used = true;
break;
}
}
if ( ! name_used )
{
m_name = new_name;
break;
}
}
}
updateValueBuffer();
}
Controller::~Controller()
{
auto it = std::find(s_controllers.begin(), s_controllers.end(), this);
if (it != s_controllers.end())
{
s_controllers.erase(it);
}
m_valueBuffer.clear();
// Remove connections by destroyed signal
}
// Get current value, with an offset into the current buffer for sample exactness
float Controller::currentValue( int _offset )
{
if( _offset == 0 || isSampleExact() )
{
m_currentValue = fittedValue( value( _offset ) );
}
return m_currentValue;
}
float Controller::value( int offset )
{
if( m_bufferLastUpdated != s_periods )
{
updateValueBuffer();
}
return m_valueBuffer.values()[ offset ];
}
ValueBuffer * Controller::valueBuffer()
{
if( m_bufferLastUpdated != s_periods )
{
updateValueBuffer();
}
return &m_valueBuffer;
}
void Controller::updateValueBuffer()
{
m_valueBuffer.fill(0.5f);
m_bufferLastUpdated = s_periods;
}
// Get position in frames
unsigned int Controller::runningFrames()
{
return s_periods * Engine::audioEngine()->framesPerPeriod();
}
// Get position in seconds
float Controller::runningTime()
{
return runningFrames() / Engine::audioEngine()->outputSampleRate();
}
void Controller::triggerFrameCounter()
{
for (Controller * controller : s_controllers)
{
// This signal is for updating values for both stubborn knobs and for
// painting. If we ever get all the widgets to use or at least check
// currentValue() then we can throttle the signal and only use it for
// GUI.
emit controller->valueChanged();
}
s_periods ++;
//emit s_signaler.triggerValueChanged();
}
void Controller::resetFrameCounter()
{
for (Controller * controller : s_controllers)
{
controller->m_bufferLastUpdated = 0;
}
s_periods = 0;
}
Controller * Controller::create( ControllerType _ct, Model * _parent )
{
static Controller * dummy = nullptr;
Controller * c = nullptr;
switch( _ct )
{
case ControllerType::Dummy:
if (!dummy)
dummy = new Controller( ControllerType::Dummy, nullptr,
QString() );
c = dummy;
break;
case ControllerType::Lfo:
c = new class LfoController( _parent );
break;
case ControllerType::Peak:
//Already instantiated in EffectChain::loadSettings()
Q_ASSERT( false );
break;
case ControllerType::Midi:
c = new class MidiController( _parent );
break;
default:
break;
}
return( c );
}
Controller * Controller::create( const QDomElement & _this, Model * _parent )
{
const auto controllerType = static_cast<ControllerType>(_this.attribute("type").toInt());
auto controller = controllerType == ControllerType::Peak
? PeakController::getControllerBySetting(_this)
: create(controllerType, _parent);
if (controller) { controller->restoreState(_this); }
return controller;
}
bool Controller::hasModel( const Model * m ) const
{
for (QObject * c : children())
{
auto am = qobject_cast<AutomatableModel*>(c);
if( am != nullptr )
{
if( am == m )
{
return true;
}
ControllerConnection * cc = am->controllerConnection();
if( cc != nullptr && cc->getController()->hasModel( m ) )
{
return true;
}
}
}
return false;
}
void Controller::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
_this.setAttribute( "type", static_cast<int>(type()) );
_this.setAttribute( "name", name() );
}
void Controller::loadSettings( const QDomElement & _this )
{
if( static_cast<ControllerType>(_this.attribute( "type" ).toInt()) != type() )
{
qWarning( "controller-type does not match controller-type of "
"settings-node!\n" );
}
setName( _this.attribute( "name" ) );
}
QString Controller::nodeName() const
{
return( "Controller" );
}
gui::ControllerDialog * Controller::createDialog( QWidget * _parent )
{
auto d = new gui::ControllerDialog(this, _parent);
return d;
}
void Controller::addConnection( ControllerConnection * )
{
m_connectionCount++;
}
void Controller::removeConnection( ControllerConnection * )
{
m_connectionCount--;
Q_ASSERT( m_connectionCount >= 0 );
}
int Controller::connectionCount() const{
return m_connectionCount;
}
} // namespace lmms
| 6,358
|
C++
|
.cpp
| 236
| 24.322034
| 90
| 0.713836
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,739
|
FileSearch.cpp
|
LMMS_lmms/src/core/FileSearch.cpp
|
/*
* FileSearch.cpp - File system search task
*
* Copyright (c) 2024 saker
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "FileSearch.h"
#include <atomic>
#include <chrono>
#include <lmmsconfig.h>
#include <thread>
namespace lmms {
FileSearch::FileSearch(const QString& filter, const QStringList& paths, const QStringList& extensions,
const QStringList& excludedPaths, QDir::Filters dirFilters, QDir::SortFlags sortFlags)
: m_filter(filter)
, m_paths(paths)
, m_extensions(extensions)
, m_excludedPaths(excludedPaths)
, m_dirFilters(dirFilters)
, m_sortFlags(sortFlags)
{
}
void FileSearch::operator()()
{
auto stack = QFileInfoList{};
for (const auto& path : m_paths)
{
if (m_excludedPaths.contains(path)) { continue; }
auto dir = QDir{path};
stack.append(dir.entryInfoList(m_dirFilters, m_sortFlags));
while (!stack.empty())
{
if (m_cancel.load(std::memory_order_relaxed)) { return; }
const auto info = stack.takeFirst();
const auto entryPath = info.absoluteFilePath();
if (m_excludedPaths.contains(entryPath)) { continue; }
const auto name = info.fileName();
const auto validFile = info.isFile() && m_extensions.contains(info.suffix(), Qt::CaseInsensitive);
const auto passesFilter = name.contains(m_filter, Qt::CaseInsensitive);
if ((validFile || info.isDir()) && passesFilter)
{
std::this_thread::sleep_for(std::chrono::milliseconds{MillisecondsBetweenResults});
emit foundMatch(this, entryPath);
}
if (info.isDir())
{
dir.setPath(entryPath);
const auto entries = dir.entryInfoList(m_dirFilters, m_sortFlags);
// Reverse to maintain the sorting within this directory when popped
std::for_each(entries.rbegin(), entries.rend(), [&stack](const auto& entry) { stack.push_front(entry); });
}
}
}
emit searchCompleted(this);
}
void FileSearch::cancel()
{
m_cancel.store(true, std::memory_order_relaxed);
}
} // namespace lmms
| 2,691
|
C++
|
.cpp
| 77
| 32.285714
| 110
| 0.734206
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,740
|
AudioEngine.cpp
|
LMMS_lmms/src/core/AudioEngine.cpp
|
/*
* AudioEngine.cpp - device-independent audio engine for LMMS
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "AudioEngine.h"
#include "MixHelpers.h"
#include "denormals.h"
#include "lmmsconfig.h"
#include "AudioEngineWorkerThread.h"
#include "AudioPort.h"
#include "Mixer.h"
#include "Song.h"
#include "EnvelopeAndLfoParameters.h"
#include "NotePlayHandle.h"
#include "ConfigManager.h"
#include "SamplePlayHandle.h"
// platform-specific audio-interface-classes
#include "AudioAlsa.h"
#include "AudioJack.h"
#include "AudioOss.h"
#include "AudioSndio.h"
#include "AudioPortAudio.h"
#include "AudioSoundIo.h"
#include "AudioPulseAudio.h"
#include "AudioSdl.h"
#include "AudioDummy.h"
// platform-specific midi-interface-classes
#include "MidiAlsaRaw.h"
#include "MidiAlsaSeq.h"
#include "MidiJack.h"
#include "MidiOss.h"
#include "MidiSndio.h"
#include "MidiWinMM.h"
#include "MidiApple.h"
#include "MidiDummy.h"
#include "BufferManager.h"
namespace lmms
{
using LocklessListElement = LocklessList<PlayHandle*>::Element;
static thread_local bool s_renderingThread = false;
AudioEngine::AudioEngine( bool renderOnly ) :
m_renderOnly( renderOnly ),
m_framesPerPeriod( DEFAULT_BUFFER_SIZE ),
m_baseSampleRate(std::max(ConfigManager::inst()->value("audioengine", "samplerate").toInt(), 44100)),
m_inputBufferRead( 0 ),
m_inputBufferWrite( 1 ),
m_outputBufferRead(nullptr),
m_outputBufferWrite(nullptr),
m_workers(),
m_numWorkers( QThread::idealThreadCount()-1 ),
m_newPlayHandles( PlayHandle::MaxNumber ),
m_qualitySettings(qualitySettings::Interpolation::Linear),
m_masterGain( 1.0f ),
m_audioDev( nullptr ),
m_oldAudioDev( nullptr ),
m_audioDevStartFailed( false ),
m_profiler(),
m_clearSignal(false)
{
for( int i = 0; i < 2; ++i )
{
m_inputBufferFrames[i] = 0;
m_inputBufferSize[i] = DEFAULT_BUFFER_SIZE * 100;
m_inputBuffer[i] = new SampleFrame[ DEFAULT_BUFFER_SIZE * 100 ];
zeroSampleFrames(m_inputBuffer[i], m_inputBufferSize[i]);
}
// determine FIFO size and number of frames per period
int fifoSize = 1;
// if not only rendering (that is, using the GUI), load the buffer
// size from user configuration
if( renderOnly == false )
{
m_framesPerPeriod =
( fpp_t ) ConfigManager::inst()->value( "audioengine", "framesperaudiobuffer" ).toInt();
// if the value read from user configuration is not set or
// lower than the minimum allowed, use the default value and
// save it to the configuration
if( m_framesPerPeriod < MINIMUM_BUFFER_SIZE )
{
ConfigManager::inst()->setValue( "audioengine",
"framesperaudiobuffer",
QString::number( DEFAULT_BUFFER_SIZE ) );
m_framesPerPeriod = DEFAULT_BUFFER_SIZE;
}
// lmms works with chunks of size DEFAULT_BUFFER_SIZE (256) and only the final mix will use the actual
// buffer size. Plugins don't see a larger buffer size than 256. If m_framesPerPeriod is larger than
// DEFAULT_BUFFER_SIZE, it's set to DEFAULT_BUFFER_SIZE and the rest is handled by an increased fifoSize.
else if( m_framesPerPeriod > DEFAULT_BUFFER_SIZE )
{
fifoSize = m_framesPerPeriod / DEFAULT_BUFFER_SIZE;
m_framesPerPeriod = DEFAULT_BUFFER_SIZE;
}
}
// allocte the FIFO from the determined size
m_fifo = new Fifo( fifoSize );
// now that framesPerPeriod is fixed initialize global BufferManager
BufferManager::init( m_framesPerPeriod );
m_outputBufferRead = std::make_unique<SampleFrame[]>(m_framesPerPeriod);
m_outputBufferWrite = std::make_unique<SampleFrame[]>(m_framesPerPeriod);
for( int i = 0; i < m_numWorkers+1; ++i )
{
auto wt = new AudioEngineWorkerThread(this);
if( i < m_numWorkers )
{
wt->start( QThread::TimeCriticalPriority );
}
m_workers.push_back( wt );
}
}
AudioEngine::~AudioEngine()
{
for( int w = 0; w < m_numWorkers; ++w )
{
m_workers[w]->quit();
}
AudioEngineWorkerThread::startAndWaitForJobs();
for( int w = 0; w < m_numWorkers; ++w )
{
m_workers[w]->wait( 500 );
}
while( m_fifo->available() )
{
delete[] m_fifo->read();
}
delete m_fifo;
delete m_midiClient;
delete m_audioDev;
for (const auto& input : m_inputBuffer)
{
delete[] input;
}
}
void AudioEngine::initDevices()
{
bool success_ful = false;
if( m_renderOnly ) {
m_audioDev = new AudioDummy( success_ful, this );
m_audioDevName = AudioDummy::name();
m_midiClient = new MidiDummy;
m_midiClientName = MidiDummy::name();
} else {
m_audioDev = tryAudioDevices();
m_midiClient = tryMidiClients();
}
// Loading audio device may have changed the sample rate
emit sampleRateChanged();
}
void AudioEngine::startProcessing(bool needsFifo)
{
if (needsFifo)
{
m_fifoWriter = new fifoWriter( this, m_fifo );
m_fifoWriter->start( QThread::HighPriority );
}
else
{
m_fifoWriter = nullptr;
}
m_audioDev->startProcessing();
}
void AudioEngine::stopProcessing()
{
if( m_fifoWriter != nullptr )
{
m_fifoWriter->finish();
m_fifoWriter->wait();
m_audioDev->stopProcessing();
delete m_fifoWriter;
m_fifoWriter = nullptr;
}
else
{
m_audioDev->stopProcessing();
}
}
bool AudioEngine::criticalXRuns() const
{
return cpuLoad() >= 99 && Engine::getSong()->isExporting() == false;
}
void AudioEngine::pushInputFrames( SampleFrame* _ab, const f_cnt_t _frames )
{
requestChangeInModel();
f_cnt_t frames = m_inputBufferFrames[ m_inputBufferWrite ];
auto size = m_inputBufferSize[m_inputBufferWrite];
SampleFrame* buf = m_inputBuffer[ m_inputBufferWrite ];
if( frames + _frames > size )
{
size = std::max(size * 2, frames + _frames);
auto ab = new SampleFrame[size];
memcpy( ab, buf, frames * sizeof( SampleFrame ) );
delete [] buf;
m_inputBufferSize[ m_inputBufferWrite ] = size;
m_inputBuffer[ m_inputBufferWrite ] = ab;
buf = ab;
}
memcpy( &buf[ frames ], _ab, _frames * sizeof( SampleFrame ) );
m_inputBufferFrames[ m_inputBufferWrite ] += _frames;
doneChangeInModel();
}
void AudioEngine::renderStageNoteSetup()
{
AudioEngineProfiler::Probe profilerProbe(m_profiler, AudioEngineProfiler::DetailType::NoteSetup);
if( m_clearSignal )
{
m_clearSignal = false;
clearInternal();
}
// remove all play-handles that have to be deleted and delete
// them if they still exist...
// maybe this algorithm could be optimized...
ConstPlayHandleList::Iterator it_rem = m_playHandlesToRemove.begin();
while( it_rem != m_playHandlesToRemove.end() )
{
PlayHandleList::Iterator it = std::find( m_playHandles.begin(), m_playHandles.end(), *it_rem );
if( it != m_playHandles.end() )
{
( *it )->audioPort()->removePlayHandle( ( *it ) );
if( ( *it )->type() == PlayHandle::Type::NotePlayHandle )
{
NotePlayHandleManager::release( (NotePlayHandle*) *it );
}
else delete *it;
m_playHandles.erase( it );
}
it_rem = m_playHandlesToRemove.erase( it_rem );
}
swapBuffers();
// prepare master mix (clear internal buffers etc.)
Mixer * mixer = Engine::mixer();
mixer->prepareMasterMix();
// create play-handles for new notes, samples etc.
Engine::getSong()->processNextBuffer();
// add all play-handles that have to be added
for( LocklessListElement * e = m_newPlayHandles.popList(); e; )
{
m_playHandles += e->value;
LocklessListElement * next = e->next;
m_newPlayHandles.free( e );
e = next;
}
}
void AudioEngine::renderStageInstruments()
{
AudioEngineProfiler::Probe profilerProbe(m_profiler, AudioEngineProfiler::DetailType::Instruments);
AudioEngineWorkerThread::fillJobQueue(m_playHandles);
AudioEngineWorkerThread::startAndWaitForJobs();
}
void AudioEngine::renderStageEffects()
{
AudioEngineProfiler::Probe profilerProbe(m_profiler, AudioEngineProfiler::DetailType::Effects);
// STAGE 2: process effects of all instrument- and sampletracks
AudioEngineWorkerThread::fillJobQueue(m_audioPorts);
AudioEngineWorkerThread::startAndWaitForJobs();
// removed all play handles which are done
for( PlayHandleList::Iterator it = m_playHandles.begin();
it != m_playHandles.end(); )
{
if( ( *it )->affinityMatters() &&
( *it )->affinity() != QThread::currentThread() )
{
++it;
continue;
}
if( ( *it )->isFinished() )
{
( *it )->audioPort()->removePlayHandle( ( *it ) );
if( ( *it )->type() == PlayHandle::Type::NotePlayHandle )
{
NotePlayHandleManager::release( (NotePlayHandle*) *it );
}
else delete *it;
it = m_playHandles.erase( it );
}
else
{
++it;
}
}
}
void AudioEngine::renderStageMix()
{
AudioEngineProfiler::Probe profilerProbe(m_profiler, AudioEngineProfiler::DetailType::Mixing);
Mixer *mixer = Engine::mixer();
mixer->masterMix(m_outputBufferWrite.get());
MixHelpers::multiply(m_outputBufferWrite.get(), m_masterGain, m_framesPerPeriod);
emit nextAudioBuffer(m_outputBufferRead.get());
// and trigger LFOs
EnvelopeAndLfoParameters::instances()->trigger();
Controller::triggerFrameCounter();
AutomatableModel::incrementPeriodCounter();
}
const SampleFrame* AudioEngine::renderNextBuffer()
{
const auto lock = std::lock_guard{m_changeMutex};
m_profiler.startPeriod();
s_renderingThread = true;
renderStageNoteSetup(); // STAGE 0: clear old play handles and buffers, setup new play handles
renderStageInstruments(); // STAGE 1: run and render all play handles
renderStageEffects(); // STAGE 2: process effects of all instrument- and sampletracks
renderStageMix(); // STAGE 3: do master mix in mixer
s_renderingThread = false;
m_profiler.finishPeriod(outputSampleRate(), m_framesPerPeriod);
return m_outputBufferRead.get();
}
void AudioEngine::swapBuffers()
{
m_inputBufferWrite = (m_inputBufferWrite + 1) % 2;
m_inputBufferRead = (m_inputBufferRead + 1) % 2;
m_inputBufferFrames[m_inputBufferWrite] = 0;
std::swap(m_outputBufferRead, m_outputBufferWrite);
zeroSampleFrames(m_outputBufferWrite.get(), m_framesPerPeriod);
}
void AudioEngine::clear()
{
m_clearSignal = true;
}
void AudioEngine::clearNewPlayHandles()
{
requestChangeInModel();
for( LocklessListElement * e = m_newPlayHandles.popList(); e; )
{
LocklessListElement * next = e->next;
m_newPlayHandles.free( e );
e = next;
}
doneChangeInModel();
}
// removes all play-handles. this is necessary, when the song is stopped ->
// all remaining notes etc. would be played until their end
void AudioEngine::clearInternal()
{
// TODO: m_midiClient->noteOffAll();
for (auto ph : m_playHandles)
{
if (ph->type() != PlayHandle::Type::InstrumentPlayHandle)
{
m_playHandlesToRemove.push_back(ph);
}
}
}
void AudioEngine::changeQuality(const struct qualitySettings & qs)
{
// don't delete the audio-device
stopProcessing();
m_qualitySettings = qs;
emit sampleRateChanged();
emit qualitySettingsChanged();
startProcessing();
}
void AudioEngine::doSetAudioDevice( AudioDevice * _dev )
{
// TODO: Use shared_ptr here in the future.
// Currently, this is safe, because this is only called by
// ProjectRenderer, and after ProjectRenderer calls this function,
// it does not access the old device anymore.
if( m_audioDev != m_oldAudioDev ) {delete m_audioDev;}
if( _dev )
{
m_audioDev = _dev;
}
else
{
printf( "param _dev == NULL in AudioEngine::setAudioDevice(...). "
"Trying any working audio-device\n" );
m_audioDev = tryAudioDevices();
}
}
void AudioEngine::setAudioDevice(AudioDevice * _dev,
const struct qualitySettings & _qs,
bool _needs_fifo,
bool startNow)
{
stopProcessing();
m_qualitySettings = _qs;
doSetAudioDevice( _dev );
emit qualitySettingsChanged();
emit sampleRateChanged();
if (startNow) {startProcessing( _needs_fifo );}
}
void AudioEngine::storeAudioDevice()
{
if( !m_oldAudioDev )
{
m_oldAudioDev = m_audioDev;
}
}
void AudioEngine::restoreAudioDevice()
{
if( m_oldAudioDev && m_audioDev != m_oldAudioDev )
{
stopProcessing();
delete m_audioDev;
m_audioDev = m_oldAudioDev;
emit sampleRateChanged();
startProcessing();
}
m_oldAudioDev = nullptr;
}
void AudioEngine::removeAudioPort(AudioPort * port)
{
requestChangeInModel();
auto it = std::find(m_audioPorts.begin(), m_audioPorts.end(), port);
if (it != m_audioPorts.end())
{
m_audioPorts.erase(it);
}
doneChangeInModel();
}
bool AudioEngine::addPlayHandle( PlayHandle* handle )
{
// Only add play handles if we have the CPU capacity to process them.
// Instrument play handles are not added during playback, but when the
// associated instrument is created, so add those unconditionally.
if (handle->type() == PlayHandle::Type::InstrumentPlayHandle || !criticalXRuns())
{
m_newPlayHandles.push( handle );
handle->audioPort()->addPlayHandle( handle );
return true;
}
if( handle->type() == PlayHandle::Type::NotePlayHandle )
{
NotePlayHandleManager::release( (NotePlayHandle*)handle );
}
else delete handle;
return false;
}
void AudioEngine::removePlayHandle(PlayHandle * ph)
{
requestChangeInModel();
// check thread affinity as we must not delete play-handles
// which were created in a thread different than the audio engine thread
if (ph->affinityMatters() && ph->affinity() == QThread::currentThread())
{
ph->audioPort()->removePlayHandle(ph);
bool removedFromList = false;
// Check m_newPlayHandles first because doing it the other way around
// creates a race condition
for( LocklessListElement * e = m_newPlayHandles.first(),
* ePrev = nullptr; e; ePrev = e, e = e->next )
{
if (e->value == ph)
{
if( ePrev )
{
ePrev->next = e->next;
}
else
{
m_newPlayHandles.setFirst( e->next );
}
m_newPlayHandles.free( e );
removedFromList = true;
break;
}
}
// Now check m_playHandles
PlayHandleList::Iterator it = std::find(m_playHandles.begin(), m_playHandles.end(), ph);
if (it != m_playHandles.end())
{
m_playHandles.erase(it);
removedFromList = true;
}
// Only deleting PlayHandles that were actually found in the list
// "fixes crash when previewing a preset under high load"
// (See tobydox's 2008 commit 4583e48)
if ( removedFromList )
{
if (ph->type() == PlayHandle::Type::NotePlayHandle)
{
NotePlayHandleManager::release(dynamic_cast<NotePlayHandle*>(ph));
}
else { delete ph; }
}
}
else
{
m_playHandlesToRemove.push_back(ph);
}
doneChangeInModel();
}
void AudioEngine::removePlayHandlesOfTypes(Track * track, PlayHandle::Types types)
{
requestChangeInModel();
PlayHandleList::Iterator it = m_playHandles.begin();
while( it != m_playHandles.end() )
{
if ((*it)->isFromTrack(track) && ((*it)->type() & types))
{
( *it )->audioPort()->removePlayHandle( ( *it ) );
if( ( *it )->type() == PlayHandle::Type::NotePlayHandle )
{
NotePlayHandleManager::release( (NotePlayHandle*) *it );
}
else delete *it;
it = m_playHandles.erase( it );
}
else
{
++it;
}
}
doneChangeInModel();
}
void AudioEngine::requestChangeInModel()
{
if (s_renderingThread) { return; }
m_changeMutex.lock();
}
void AudioEngine::doneChangeInModel()
{
if (s_renderingThread) { return; }
m_changeMutex.unlock();
}
bool AudioEngine::isAudioDevNameValid(QString name)
{
#ifdef LMMS_HAVE_SDL
if (name == AudioSdl::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_ALSA
if (name == AudioAlsa::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_PULSEAUDIO
if (name == AudioPulseAudio::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_OSS
if (name == AudioOss::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_SNDIO
if (name == AudioSndio::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_JACK
if (name == AudioJack::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_PORTAUDIO
if (name == AudioPortAudio::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_SOUNDIO
if (name == AudioSoundIo::name())
{
return true;
}
#endif
if (name == AudioDummy::name())
{
return true;
}
return false;
}
bool AudioEngine::isMidiDevNameValid(QString name)
{
#ifdef LMMS_HAVE_ALSA
if (name == MidiAlsaSeq::name() || name == MidiAlsaRaw::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_JACK
if (name == MidiJack::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_OSS
if (name == MidiOss::name())
{
return true;
}
#endif
#ifdef LMMS_HAVE_SNDIO
if (name == MidiSndio::name())
{
return true;
}
#endif
#ifdef LMMS_BUILD_WIN32
if (name == MidiWinMM::name())
{
return true;
}
#endif
#ifdef LMMS_BUILD_APPLE
if (name == MidiApple::name())
{
return true;
}
#endif
if (name == MidiDummy::name())
{
return true;
}
return false;
}
AudioDevice * AudioEngine::tryAudioDevices()
{
bool success_ful = false;
AudioDevice * dev = nullptr;
QString dev_name = ConfigManager::inst()->value( "audioengine", "audiodev" );
if( !isAudioDevNameValid( dev_name ) )
{
dev_name = "";
}
m_audioDevStartFailed = false;
#ifdef LMMS_HAVE_SDL
if( dev_name == AudioSdl::name() || dev_name == "" )
{
dev = new AudioSdl( success_ful, this );
if( success_ful )
{
m_audioDevName = AudioSdl::name();
return dev;
}
delete dev;
}
#endif
#ifdef LMMS_HAVE_ALSA
if( dev_name == AudioAlsa::name() || dev_name == "" )
{
dev = new AudioAlsa( success_ful, this );
if( success_ful )
{
m_audioDevName = AudioAlsa::name();
return dev;
}
delete dev;
}
#endif
#ifdef LMMS_HAVE_PULSEAUDIO
if( dev_name == AudioPulseAudio::name() || dev_name == "" )
{
dev = new AudioPulseAudio( success_ful, this );
if( success_ful )
{
m_audioDevName = AudioPulseAudio::name();
return dev;
}
delete dev;
}
#endif
#ifdef LMMS_HAVE_OSS
if( dev_name == AudioOss::name() || dev_name == "" )
{
dev = new AudioOss( success_ful, this );
if( success_ful )
{
m_audioDevName = AudioOss::name();
return dev;
}
delete dev;
}
#endif
#ifdef LMMS_HAVE_SNDIO
if( dev_name == AudioSndio::name() || dev_name == "" )
{
dev = new AudioSndio( success_ful, this );
if( success_ful )
{
m_audioDevName = AudioSndio::name();
return dev;
}
delete dev;
}
#endif
#ifdef LMMS_HAVE_JACK
if( dev_name == AudioJack::name() || dev_name == "" )
{
dev = new AudioJack( success_ful, this );
if( success_ful )
{
m_audioDevName = AudioJack::name();
return dev;
}
delete dev;
}
#endif
#ifdef LMMS_HAVE_PORTAUDIO
if( dev_name == AudioPortAudio::name() || dev_name == "" )
{
dev = new AudioPortAudio( success_ful, this );
if( success_ful )
{
m_audioDevName = AudioPortAudio::name();
return dev;
}
delete dev;
}
#endif
#ifdef LMMS_HAVE_SOUNDIO
if( dev_name == AudioSoundIo::name() || dev_name == "" )
{
dev = new AudioSoundIo( success_ful, this );
if( success_ful )
{
m_audioDevName = AudioSoundIo::name();
return dev;
}
delete dev;
}
#endif
// add more device-classes here...
//dev = new audioXXXX( SAMPLE_RATES[m_qualityLevel], success_ful, this );
//if( sucess_ful )
//{
// return dev;
//}
//delete dev
if( dev_name != AudioDummy::name() )
{
printf( "No audio-driver working - falling back to dummy-audio-"
"driver\nYou can render your songs and listen to the output "
"files...\n" );
m_audioDevStartFailed = true;
}
m_audioDevName = AudioDummy::name();
return new AudioDummy( success_ful, this );
}
MidiClient * AudioEngine::tryMidiClients()
{
QString client_name = ConfigManager::inst()->value( "audioengine", "mididev" );
if( !isMidiDevNameValid( client_name ) )
{
client_name = "";
}
#ifdef LMMS_HAVE_ALSA
if( client_name == MidiAlsaSeq::name() || client_name == "" )
{
auto malsas = new MidiAlsaSeq;
if( malsas->isRunning() )
{
m_midiClientName = MidiAlsaSeq::name();
return malsas;
}
delete malsas;
}
if( client_name == MidiAlsaRaw::name() || client_name == "" )
{
auto malsar = new MidiAlsaRaw;
if( malsar->isRunning() )
{
m_midiClientName = MidiAlsaRaw::name();
return malsar;
}
delete malsar;
}
#endif
#ifdef LMMS_HAVE_JACK
if( client_name == MidiJack::name() || client_name == "" )
{
auto mjack = new MidiJack;
if( mjack->isRunning() )
{
m_midiClientName = MidiJack::name();
return mjack;
}
delete mjack;
}
#endif
#ifdef LMMS_HAVE_OSS
if( client_name == MidiOss::name() || client_name == "" )
{
auto moss = new MidiOss;
if( moss->isRunning() )
{
m_midiClientName = MidiOss::name();
return moss;
}
delete moss;
}
#endif
#ifdef LMMS_HAVE_SNDIO
if( client_name == MidiSndio::name() || client_name == "" )
{
MidiSndio * msndio = new MidiSndio;
if( msndio->isRunning() )
{
m_midiClientName = MidiSndio::name();
return msndio;
}
delete msndio;
}
#endif
#ifdef LMMS_BUILD_WIN32
if( client_name == MidiWinMM::name() || client_name == "" )
{
MidiWinMM * mwmm = new MidiWinMM;
// if( moss->isRunning() )
{
m_midiClientName = MidiWinMM::name();
return mwmm;
}
delete mwmm;
}
#endif
#ifdef LMMS_BUILD_APPLE
printf( "trying midi apple...\n" );
if( client_name == MidiApple::name() || client_name == "" )
{
MidiApple * mapple = new MidiApple;
m_midiClientName = MidiApple::name();
printf( "Returning midi apple\n" );
return mapple;
}
printf( "midi apple didn't work: client_name=%s\n", client_name.toUtf8().constData());
#endif
if(client_name != MidiDummy::name())
{
if (client_name.isEmpty())
{
printf("Unknown MIDI-client. ");
}
else
{
printf("Couldn't create %s MIDI-client. ", client_name.toUtf8().constData());
}
printf("Will use dummy-MIDI-client.\n");
}
m_midiClientName = MidiDummy::name();
return new MidiDummy;
}
AudioEngine::fifoWriter::fifoWriter( AudioEngine* audioEngine, Fifo * fifo ) :
m_audioEngine( audioEngine ),
m_fifo( fifo ),
m_writing( true )
{
setObjectName("AudioEngine::fifoWriter");
}
void AudioEngine::fifoWriter::finish()
{
m_writing = false;
}
void AudioEngine::fifoWriter::run()
{
disable_denormals();
const fpp_t frames = m_audioEngine->framesPerPeriod();
while( m_writing )
{
auto buffer = new SampleFrame[frames];
const SampleFrame* b = m_audioEngine->renderNextBuffer();
memcpy(buffer, b, frames * sizeof(SampleFrame));
m_fifo->write(buffer);
}
// Let audio backend stop processing
m_fifo->write(nullptr);
m_fifo->waitUntilRead();
}
} // namespace lmms
| 23,121
|
C++
|
.cpp
| 885
| 23.524294
| 107
| 0.707273
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,741
|
SampleRecordHandle.cpp
|
LMMS_lmms/src/core/SampleRecordHandle.cpp
|
/*
* SampleRecordHandle.cpp - implementation of class SampleRecordHandle
*
* Copyright (c) 2008 Csaba Hruska <csaba.hruska/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SampleRecordHandle.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "PatternTrack.h"
#include "SampleBuffer.h"
#include "SampleClip.h"
#include "debug.h"
namespace lmms
{
SampleRecordHandle::SampleRecordHandle( SampleClip* clip ) :
PlayHandle( Type::SamplePlayHandle ),
m_framesRecorded( 0 ),
m_minLength( clip->length() ),
m_track( clip->getTrack() ),
m_patternTrack( nullptr ),
m_clip( clip )
{
}
SampleRecordHandle::~SampleRecordHandle()
{
if (!m_buffers.empty()) { m_clip->setSampleBuffer(createSampleBuffer()); }
while( !m_buffers.empty() )
{
delete[] m_buffers.front().first;
m_buffers.erase( m_buffers.begin() );
}
m_clip->setRecord( false );
}
void SampleRecordHandle::play( SampleFrame* /*_working_buffer*/ )
{
const SampleFrame* recbuf = Engine::audioEngine()->inputBuffer();
const f_cnt_t frames = Engine::audioEngine()->inputBufferFrames();
writeBuffer( recbuf, frames );
m_framesRecorded += frames;
TimePos len = (tick_t)( m_framesRecorded / Engine::framesPerTick() );
if( len > m_minLength )
{
// m_clip->changeLength( len );
m_minLength = len;
}
}
bool SampleRecordHandle::isFinished() const
{
return false;
}
bool SampleRecordHandle::isFromTrack( const Track * _track ) const
{
return (m_track == _track || m_patternTrack == _track);
}
f_cnt_t SampleRecordHandle::framesRecorded() const
{
return( m_framesRecorded );
}
std::shared_ptr<const SampleBuffer> SampleRecordHandle::createSampleBuffer()
{
const f_cnt_t frames = framesRecorded();
// create buffer to store all recorded buffers in
auto bigBuffer = std::vector<SampleFrame>(frames);
// now copy all buffers into big buffer
auto framesCopied = 0;
for (const auto& [buf, numFrames] : m_buffers)
{
std::copy_n(buf, numFrames, bigBuffer.begin() + framesCopied);
framesCopied += numFrames;
}
// create according sample-buffer out of big buffer
return std::make_shared<const SampleBuffer>(std::move(bigBuffer), Engine::audioEngine()->inputSampleRate());
}
void SampleRecordHandle::writeBuffer( const SampleFrame* _ab, const f_cnt_t _frames )
{
auto buf = new SampleFrame[_frames];
for( f_cnt_t frame = 0; frame < _frames; ++frame )
{
for( ch_cnt_t chnl = 0; chnl < DEFAULT_CHANNELS; ++chnl )
{
buf[frame][chnl] = _ab[frame][chnl];
}
}
m_buffers.push_back( qMakePair( buf, _frames ) );
}
} // namespace lmms
| 3,323
|
C++
|
.cpp
| 104
| 29.817308
| 109
| 0.735137
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,742
|
fft_helpers.cpp
|
LMMS_lmms/src/core/fft_helpers.cpp
|
/*
* fft_helpers.cpp - some functions around FFT analysis
*
* Copyright (c) 2008-2012 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2019 Martin Pavelek <he29.HS/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "fft_helpers.h"
#include <cmath>
#include "lmms_constants.h"
namespace lmms
{
/* Returns biggest value from abs_spectrum[spec_size] array.
*
* return -1 on error, otherwise the maximum value
*/
float maximum(const float *abs_spectrum, unsigned int spec_size)
{
if (abs_spectrum == nullptr) {return -1;}
if (spec_size == 0) {return -1;}
float maxi = 0;
for (unsigned int i = 0; i < spec_size; i++)
{
if (abs_spectrum[i] > maxi) {maxi = abs_spectrum[i];}
}
return maxi;
}
float maximum(const std::vector<float> &abs_spectrum)
{
return maximum(abs_spectrum.data(), abs_spectrum.size());
}
/* Normalize the array of absolute magnitudes to a 0..1 range.
* Block size refers to FFT block size before any zero padding.
*
* return -1 on error, 0 on success
*/
int normalize(const float *abs_spectrum, float *norm_spectrum, unsigned int bin_count, unsigned int block_size)
{
if (abs_spectrum == nullptr || norm_spectrum == nullptr) {return -1;}
if (bin_count == 0 || block_size == 0) {return -1;}
block_size /= 2;
for (unsigned int i = 0; i < bin_count; i++)
{
norm_spectrum[i] = abs_spectrum[i] / block_size;
}
return 0;
}
int normalize(const std::vector<float> &abs_spectrum, std::vector<float> &norm_spectrum, unsigned int block_size)
{
if (abs_spectrum.size() != norm_spectrum.size()) {return -1;}
return normalize(abs_spectrum.data(), norm_spectrum.data(), abs_spectrum.size(), block_size);
}
/* Check if the spectrum contains any non-zero value.
*
* return 1 if spectrum contains any non-zero value
* return 0 otherwise
*/
int notEmpty(const std::vector<float> &spectrum)
{
for (float s : spectrum)
{
if (s != 0) {return 1;}
}
return 0;
}
/* Precompute an FFT window function for later real-time use.
*
* return -1 on error
*/
int precomputeWindow(float *window, unsigned int length, FFTWindow type, bool normalized)
{
if (window == nullptr) {return -1;}
float gain = 0;
float a0;
float a1;
float a2;
float a3;
// constants taken from
// https://en.wikipedia.org/wiki/Window_function#AList_of_window_functions
switch (type)
{
default:
case FFTWindow::Rectangular:
for (unsigned int i = 0; i < length; i++) {window[i] = 1.0;}
gain = 1;
return 0;
case FFTWindow::BlackmanHarris:
a0 = 0.35875f;
a1 = 0.48829f;
a2 = 0.14128f;
a3 = 0.01168f;
break;
case FFTWindow::Hamming:
a0 = 0.54f;
a1 = 1.0 - a0;
a2 = 0;
a3 = 0;
break;
case FFTWindow::Hanning:
a0 = 0.5;
a1 = 1.0 - a0;
a2 = 0;
a3 = 0;
break;
}
// common computation for cosine-sum based windows
for (unsigned int i = 0; i < length; i++)
{
window[i] = (a0 - a1 * cos(2 * F_PI * i / ((float)length - 1.0))
+ a2 * cos(4 * F_PI * i / ((float)length - 1.0))
- a3 * cos(6 * F_PI * i / ((float)length - 1.0)));
gain += window[i];
}
// apply amplitude correction
gain /= (float) length;
for (unsigned int i = 0; i < length; i++) {window[i] /= gain;}
return 0;
}
/* Compute absolute values of complex_buffer, save to absspec_buffer.
* Take care that - compl_len is not bigger than complex_buffer!
* - absspec buffer is big enough!
*
* return 0 on success, else -1
*/
int absspec(const fftwf_complex *complex_buffer, float *absspec_buffer, unsigned int compl_length)
{
if (complex_buffer == nullptr || absspec_buffer == nullptr) {return -1;}
if (compl_length == 0) {return -1;}
for (unsigned int i = 0; i < compl_length; i++)
{
absspec_buffer[i] = (float)sqrt(complex_buffer[i][0] * complex_buffer[i][0]
+ complex_buffer[i][1] * complex_buffer[i][1]);
}
return 0;
}
/* Build fewer subbands from many absolute spectrum values.
* Take care that - compressedbands[] array num_new elements long
* - num_old > num_new
*
* return 0 on success, else -1
*/
int compressbands(const float *absspec_buffer, float *compressedband, int num_old, int num_new, int bottom, int top)
{
if (absspec_buffer == nullptr || compressedband == nullptr) {return -1;}
if (num_old < num_new) {return -1;}
if (num_old <= 0 || num_new <= 0) {return -1;}
if (bottom < 0) {bottom = 0;}
if (top >= num_old) {top = num_old - 1;}
int usefromold = num_old - (num_old - top) - bottom;
float ratio = (float)usefromold / (float)num_new;
// for each new subband
for (int i = 0; i < num_new; i++)
{
compressedband[i] = 0;
float j_min = (i * ratio) + bottom;
if (j_min < 0) { j_min = static_cast<float>(bottom); }
float j_max = j_min + ratio;
for (float j = std::floor(j_min); j <= j_max; j++)
{
compressedband[i] += absspec_buffer[(int)j];
}
}
return 0;
}
} // namespace lmms
| 5,639
|
C++
|
.cpp
| 182
| 28.571429
| 116
| 0.674419
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,743
|
Clipboard.cpp
|
LMMS_lmms/src/core/Clipboard.cpp
|
/*
* Clipboard.cpp - the clipboard for clips, notes etc.
*
* Copyright (c) 2004-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QApplication>
#include <QClipboard>
#include <QMimeData>
#include "Clipboard.h"
namespace lmms::Clipboard
{
const QMimeData * getMimeData()
{
return QApplication::clipboard()->mimeData( QClipboard::Clipboard );
}
bool hasFormat( MimeType mT )
{
return getMimeData()->hasFormat( mimeType( mT ) );
}
void copyString( const QString & str, MimeType mT )
{
auto content = new QMimeData;
content->setData( mimeType( mT ), str.toUtf8() );
QApplication::clipboard()->setMimeData( content, QClipboard::Clipboard );
}
QString getString( MimeType mT )
{
return QString( getMimeData()->data( mimeType( mT ) ) );
}
void copyStringPair( const QString & key, const QString & value )
{
QString finalString = key + ":" + value;
auto content = new QMimeData;
content->setData( mimeType( MimeType::StringPair ), finalString.toUtf8() );
QApplication::clipboard()->setMimeData( content, QClipboard::Clipboard );
}
QString decodeKey( const QMimeData * mimeData )
{
return( QString::fromUtf8( mimeData->data( mimeType( MimeType::StringPair ) ) ).section( ':', 0, 0 ) );
}
QString decodeValue( const QMimeData * mimeData )
{
return( QString::fromUtf8( mimeData->data( mimeType( MimeType::StringPair ) ) ).section( ':', 1, -1 ) );
}
} // namespace lmms::Clipboard
| 2,260
|
C++
|
.cpp
| 63
| 33.285714
| 106
| 0.730129
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,744
|
Oscillator.cpp
|
LMMS_lmms/src/core/Oscillator.cpp
|
/*
* Oscillator.cpp - implementation of powerful oscillator-class
*
* Copyright (c) 2004-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* 2018 Dave French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Oscillator.h"
#include <algorithm>
#if !defined(__MINGW32__) && !defined(__MINGW64__)
#include <thread>
#endif
#include "BufferManager.h"
#include "Engine.h"
#include "AudioEngine.h"
#include "AutomatableModel.h"
#include "fftw3.h"
#include "fft_helpers.h"
namespace lmms
{
void Oscillator::waveTableInit()
{
createFFTPlans();
generateWaveTables();
// The oscillator FFT plans remain throughout the application lifecycle
// due to being expensive to create, and being used whenever a userwave form is changed
// deleted in main.cpp main()
}
Oscillator::Oscillator(const IntModel *wave_shape_model,
const IntModel *mod_algo_model,
const float &freq,
const float &detuning_div_samplerate,
const float &phase_offset,
const float &volume,
Oscillator *sub_osc) :
m_waveShapeModel(wave_shape_model),
m_modulationAlgoModel(mod_algo_model),
m_freq(freq),
m_detuning_div_samplerate(detuning_div_samplerate),
m_volume(volume),
m_ext_phaseOffset(phase_offset),
m_subOsc(sub_osc),
m_phaseOffset(phase_offset),
m_phase(phase_offset),
m_userWave(nullptr),
m_useWaveTable(false),
m_isModulator(false)
{
}
void Oscillator::update(SampleFrame* ab, const fpp_t frames, const ch_cnt_t chnl, bool modulator)
{
if (m_freq >= Engine::audioEngine()->outputSampleRate() / 2)
{
zeroSampleFrames(ab, frames);
return;
}
// If this oscillator is used to PM or PF modulate another oscillator, take a note.
// The sampling functions will check this variable and avoid using band-limited
// wavetables, since they contain ringing that would lead to unexpected results.
m_isModulator = modulator;
if (m_subOsc != nullptr)
{
switch (static_cast<ModulationAlgo>(m_modulationAlgoModel->value()))
{
case ModulationAlgo::PhaseModulation:
updatePM(ab, frames, chnl);
break;
case ModulationAlgo::AmplitudeModulation:
updateAM(ab, frames, chnl);
break;
case ModulationAlgo::SignalMix:
default:
updateMix(ab, frames, chnl);
break;
case ModulationAlgo::SynchronizedBySubOsc:
updateSync(ab, frames, chnl);
break;
case ModulationAlgo::FrequencyModulation:
updateFM(ab, frames, chnl);
}
}
else
{
updateNoSub(ab, frames, chnl);
}
}
void Oscillator::generateSawWaveTable(int bands, sample_t* table, int firstBand)
{
// sawtooth wave contain both even and odd harmonics
// hence sinewaves are added for all bands
// https://en.wikipedia.org/wiki/Sawtooth_wave
for (int i = 0; i < OscillatorConstants::WAVETABLE_LENGTH; i++)
{
// add offset to the position index to match phase of the non-wavetable saw wave; precompute "/ period"
const float imod = (i - OscillatorConstants::WAVETABLE_LENGTH / 2.f) / OscillatorConstants::WAVETABLE_LENGTH;
for (int n = firstBand; n <= bands; n++)
{
table[i] += (n % 2 ? 1.0f : -1.0f) / n * sinf(F_2PI * n * imod) / F_PI_2;
}
}
}
void Oscillator::generateTriangleWaveTable(int bands, sample_t* table, int firstBand)
{
// triangle waves contain only odd harmonics
// hence sinewaves are added for alternate bands
// https://en.wikipedia.org/wiki/Triangle_wave
for (int i = 0; i < OscillatorConstants::WAVETABLE_LENGTH; i++)
{
for (int n = firstBand | 1; n <= bands; n += 2)
{
table[i] += (n & 2 ? -1.0f : 1.0f) / powf(n, 2.0f) *
sinf(F_2PI * n * i / (float)OscillatorConstants::WAVETABLE_LENGTH) / (F_PI_SQR / 8);
}
}
}
void Oscillator::generateSquareWaveTable(int bands, sample_t* table, int firstBand)
{
// square waves only contain odd harmonics,
// at diffrent levels when compared to triangle waves
// https://en.wikipedia.org/wiki/Square_wave
for (int i = 0; i < OscillatorConstants::WAVETABLE_LENGTH; i++)
{
for (int n = firstBand | 1; n <= bands; n += 2)
{
table[i] += (1.0f / n) * sinf(F_2PI * i * n / OscillatorConstants::WAVETABLE_LENGTH) / (F_PI / 4);
}
}
}
// Expects waveform converted to frequency domain to be present in the spectrum buffer
void Oscillator::generateFromFFT(int bands, sample_t* table)
{
// Keep only specified number of bands, set the rest to zero.
// Add a +1 offset to the requested number of bands, since the first "useful" frequency falls into bin 1.
// I.e., for bands = 1, keeping just bin 0 (center 0 Hz, +- 4 Hz) makes no sense, it would not produce any tone.
for (int i = bands + 1; i < OscillatorConstants::WAVETABLE_LENGTH * 2 - bands; i++)
{
s_specBuf[i][0] = 0.0f;
s_specBuf[i][1] = 0.0f;
}
//ifft
fftwf_execute(s_ifftPlan);
//normalize and copy to result buffer
normalize(s_sampleBuffer.data(), table, OscillatorConstants::WAVETABLE_LENGTH, 2*OscillatorConstants::WAVETABLE_LENGTH + 1);
}
std::unique_ptr<OscillatorConstants::waveform_t> Oscillator::generateAntiAliasUserWaveTable(const SampleBuffer* sampleBuffer)
{
auto userAntiAliasWaveTable = std::make_unique<OscillatorConstants::waveform_t>();
for (int i = 0; i < OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT; ++i)
{
// TODO: This loop seems to be doing the same thing for each iteration of the outer loop,
// and could probably be moved out of it
for (int j = 0; j < OscillatorConstants::WAVETABLE_LENGTH; ++j)
{
s_sampleBuffer[j] = Oscillator::userWaveSample(
sampleBuffer, static_cast<float>(j) / OscillatorConstants::WAVETABLE_LENGTH);
}
fftwf_execute(s_fftPlan);
Oscillator::generateFromFFT(OscillatorConstants::MAX_FREQ / freqFromWaveTableBand(i), (*userAntiAliasWaveTable)[i].data());
}
return userAntiAliasWaveTable;
}
sample_t Oscillator::s_waveTables
[Oscillator::NumWaveShapeTables]
[OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT]
[OscillatorConstants::WAVETABLE_LENGTH];
fftwf_plan Oscillator::s_fftPlan;
fftwf_plan Oscillator::s_ifftPlan;
fftwf_complex * Oscillator::s_specBuf;
std::array<float, OscillatorConstants::WAVETABLE_LENGTH> Oscillator::s_sampleBuffer;
void Oscillator::createFFTPlans()
{
Oscillator::s_specBuf = ( fftwf_complex * ) fftwf_malloc( ( OscillatorConstants::WAVETABLE_LENGTH * 2 + 1 ) * sizeof( fftwf_complex ) );
Oscillator::s_fftPlan = fftwf_plan_dft_r2c_1d(OscillatorConstants::WAVETABLE_LENGTH, s_sampleBuffer.data(), s_specBuf, FFTW_MEASURE );
Oscillator::s_ifftPlan = fftwf_plan_dft_c2r_1d(OscillatorConstants::WAVETABLE_LENGTH, s_specBuf, s_sampleBuffer.data(), FFTW_MEASURE);
// initialize s_specBuf content to zero, since the values are used in a condition inside generateFromFFT()
for (int i = 0; i < OscillatorConstants::WAVETABLE_LENGTH * 2 + 1; i++)
{
s_specBuf[i][0] = 0.0f;
s_specBuf[i][1] = 0.0f;
}
}
void Oscillator::destroyFFTPlans()
{
fftwf_destroy_plan(s_fftPlan);
fftwf_destroy_plan(s_ifftPlan);
fftwf_free(s_specBuf);
}
void Oscillator::generateWaveTables()
{
// Generate tables for simple shaped (constructed by summing sine waves).
// Start from the table that contains the least number of bands, and re-use each table in the following
// iteration, adding more bands in each step and avoiding repeated computation of earlier bands.
using generator_t = void (*)(int, sample_t*, int);
auto simpleGen = [](WaveShape shape, generator_t generator)
{
const int shapeID = static_cast<std::size_t>(shape) - FirstWaveShapeTable;
int lastBands = 0;
// Clear the first wave table
std::fill(
std::begin(s_waveTables[shapeID][OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT - 1]),
std::end(s_waveTables[shapeID][OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT - 1]),
0.f);
for (int i = OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT - 1; i >= 0; i--)
{
const int bands = OscillatorConstants::MAX_FREQ / freqFromWaveTableBand(i);
generator(bands, s_waveTables[shapeID][i], lastBands + 1);
lastBands = bands;
if (i)
{
std::copy(
s_waveTables[shapeID][i],
s_waveTables[shapeID][i] + OscillatorConstants::WAVETABLE_LENGTH,
s_waveTables[shapeID][i - 1]);
}
}
};
// FFT-based wave shapes: make standard wave table without band limit, convert to frequency domain, remove bands
// above maximum frequency and convert back to time domain.
auto fftGen = []()
{
// Generate moogSaw tables
for (int i = 0; i < OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT; ++i)
{
for (int i = 0; i < OscillatorConstants::WAVETABLE_LENGTH; ++i)
{
Oscillator::s_sampleBuffer[i] = moogSawSample((float)i / (float)OscillatorConstants::WAVETABLE_LENGTH);
}
fftwf_execute(s_fftPlan);
generateFromFFT(OscillatorConstants::MAX_FREQ / freqFromWaveTableBand(i), s_waveTables[static_cast<std::size_t>(WaveShape::MoogSaw) - FirstWaveShapeTable][i]);
}
// Generate exponential tables
for (int i = 0; i < OscillatorConstants::WAVE_TABLES_PER_WAVEFORM_COUNT; ++i)
{
for (int i = 0; i < OscillatorConstants::WAVETABLE_LENGTH; ++i)
{
s_sampleBuffer[i] = expSample((float)i / (float)OscillatorConstants::WAVETABLE_LENGTH);
}
fftwf_execute(s_fftPlan);
generateFromFFT(OscillatorConstants::MAX_FREQ / freqFromWaveTableBand(i), s_waveTables[static_cast<std::size_t>(WaveShape::Exponential) - FirstWaveShapeTable][i]);
}
};
// TODO: Mingw compilers currently do not support std::thread. There are some 3rd-party workarounds available,
// but since threading is not essential in this case, it is easier and more reliable to simply generate
// the wavetables serially. Remove the the check and #else branch once std::thread is well supported.
#if !defined(__MINGW32__) && !defined(__MINGW64__)
std::thread sawThread(simpleGen, WaveShape::Saw, generateSawWaveTable);
std::thread squareThread(simpleGen, WaveShape::Square, generateSquareWaveTable);
std::thread triangleThread(simpleGen, WaveShape::Triangle, generateTriangleWaveTable);
std::thread fftThread(fftGen);
sawThread.join();
squareThread.join();
triangleThread.join();
fftThread.join();
#else
simpleGen(WaveShape::Saw, generateSawWaveTable);
simpleGen(WaveShape::Square, generateSquareWaveTable);
simpleGen(WaveShape::Triangle, generateTriangleWaveTable);
fftGen();
#endif
}
void Oscillator::updateNoSub( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
switch( static_cast<WaveShape>(m_waveShapeModel->value()) )
{
case WaveShape::Sine:
default:
updateNoSub<WaveShape::Sine>( _ab, _frames, _chnl );
break;
case WaveShape::Triangle:
updateNoSub<WaveShape::Triangle>( _ab, _frames, _chnl );
break;
case WaveShape::Saw:
updateNoSub<WaveShape::Saw>( _ab, _frames, _chnl );
break;
case WaveShape::Square:
updateNoSub<WaveShape::Square>( _ab, _frames, _chnl );
break;
case WaveShape::MoogSaw:
updateNoSub<WaveShape::MoogSaw>( _ab, _frames, _chnl );
break;
case WaveShape::Exponential:
updateNoSub<WaveShape::Exponential>( _ab, _frames, _chnl );
break;
case WaveShape::WhiteNoise:
updateNoSub<WaveShape::WhiteNoise>( _ab, _frames, _chnl );
break;
case WaveShape::UserDefined:
updateNoSub<WaveShape::UserDefined>( _ab, _frames, _chnl );
break;
}
}
void Oscillator::updatePM( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
switch( static_cast<WaveShape>(m_waveShapeModel->value()) )
{
case WaveShape::Sine:
default:
updatePM<WaveShape::Sine>( _ab, _frames, _chnl );
break;
case WaveShape::Triangle:
updatePM<WaveShape::Triangle>( _ab, _frames, _chnl );
break;
case WaveShape::Saw:
updatePM<WaveShape::Saw>( _ab, _frames, _chnl );
break;
case WaveShape::Square:
updatePM<WaveShape::Square>( _ab, _frames, _chnl );
break;
case WaveShape::MoogSaw:
updatePM<WaveShape::MoogSaw>( _ab, _frames, _chnl );
break;
case WaveShape::Exponential:
updatePM<WaveShape::Exponential>( _ab, _frames, _chnl );
break;
case WaveShape::WhiteNoise:
updatePM<WaveShape::WhiteNoise>( _ab, _frames, _chnl );
break;
case WaveShape::UserDefined:
updatePM<WaveShape::UserDefined>( _ab, _frames, _chnl );
break;
}
}
void Oscillator::updateAM( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
switch( static_cast<WaveShape>(m_waveShapeModel->value()) )
{
case WaveShape::Sine:
default:
updateAM<WaveShape::Sine>( _ab, _frames, _chnl );
break;
case WaveShape::Triangle:
updateAM<WaveShape::Triangle>( _ab, _frames, _chnl );
break;
case WaveShape::Saw:
updateAM<WaveShape::Saw>( _ab, _frames, _chnl );
break;
case WaveShape::Square:
updateAM<WaveShape::Square>( _ab, _frames, _chnl );
break;
case WaveShape::MoogSaw:
updateAM<WaveShape::MoogSaw>( _ab, _frames, _chnl );
break;
case WaveShape::Exponential:
updateAM<WaveShape::Exponential>( _ab, _frames, _chnl );
break;
case WaveShape::WhiteNoise:
updateAM<WaveShape::WhiteNoise>( _ab, _frames, _chnl );
break;
case WaveShape::UserDefined:
updateAM<WaveShape::UserDefined>( _ab, _frames, _chnl );
break;
}
}
void Oscillator::updateMix( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
switch( static_cast<WaveShape>(m_waveShapeModel->value()) )
{
case WaveShape::Sine:
default:
updateMix<WaveShape::Sine>( _ab, _frames, _chnl );
break;
case WaveShape::Triangle:
updateMix<WaveShape::Triangle>( _ab, _frames, _chnl );
break;
case WaveShape::Saw:
updateMix<WaveShape::Saw>( _ab, _frames, _chnl );
break;
case WaveShape::Square:
updateMix<WaveShape::Square>( _ab, _frames, _chnl );
break;
case WaveShape::MoogSaw:
updateMix<WaveShape::MoogSaw>( _ab, _frames, _chnl );
break;
case WaveShape::Exponential:
updateMix<WaveShape::Exponential>( _ab, _frames, _chnl );
break;
case WaveShape::WhiteNoise:
updateMix<WaveShape::WhiteNoise>( _ab, _frames, _chnl );
break;
case WaveShape::UserDefined:
updateMix<WaveShape::UserDefined>( _ab, _frames, _chnl );
break;
}
}
void Oscillator::updateSync( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
switch( static_cast<WaveShape>(m_waveShapeModel->value()) )
{
case WaveShape::Sine:
default:
updateSync<WaveShape::Sine>( _ab, _frames, _chnl );
break;
case WaveShape::Triangle:
updateSync<WaveShape::Triangle>( _ab, _frames, _chnl );
break;
case WaveShape::Saw:
updateSync<WaveShape::Saw>( _ab, _frames, _chnl );
break;
case WaveShape::Square:
updateSync<WaveShape::Square>( _ab, _frames, _chnl );
break;
case WaveShape::MoogSaw:
updateSync<WaveShape::MoogSaw>( _ab, _frames, _chnl );
break;
case WaveShape::Exponential:
updateSync<WaveShape::Exponential>( _ab, _frames, _chnl );
break;
case WaveShape::WhiteNoise:
updateSync<WaveShape::WhiteNoise>( _ab, _frames, _chnl );
break;
case WaveShape::UserDefined:
updateSync<WaveShape::UserDefined>( _ab, _frames, _chnl );
break;
}
}
void Oscillator::updateFM( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
switch( static_cast<WaveShape>(m_waveShapeModel->value()) )
{
case WaveShape::Sine:
default:
updateFM<WaveShape::Sine>( _ab, _frames, _chnl );
break;
case WaveShape::Triangle:
updateFM<WaveShape::Triangle>( _ab, _frames, _chnl );
break;
case WaveShape::Saw:
updateFM<WaveShape::Saw>( _ab, _frames, _chnl );
break;
case WaveShape::Square:
updateFM<WaveShape::Square>( _ab, _frames, _chnl );
break;
case WaveShape::MoogSaw:
updateFM<WaveShape::MoogSaw>( _ab, _frames, _chnl );
break;
case WaveShape::Exponential:
updateFM<WaveShape::Exponential>( _ab, _frames, _chnl );
break;
case WaveShape::WhiteNoise:
updateFM<WaveShape::WhiteNoise>( _ab, _frames, _chnl );
break;
case WaveShape::UserDefined:
updateFM<WaveShape::UserDefined>( _ab, _frames, _chnl );
break;
}
}
// should be called every time phase-offset is changed...
inline void Oscillator::recalcPhase()
{
if (!approximatelyEqual(m_phaseOffset, m_ext_phaseOffset))
{
m_phase -= m_phaseOffset;
m_phaseOffset = m_ext_phaseOffset;
m_phase += m_phaseOffset;
}
m_phase = absFraction( m_phase );
}
inline bool Oscillator::syncOk( float _osc_coeff )
{
const float v1 = m_phase;
m_phase += _osc_coeff;
// check whether m_phase is in next period
return( floorf( m_phase ) > floorf( v1 ) );
}
float Oscillator::syncInit( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
if( m_subOsc != nullptr )
{
m_subOsc->update( _ab, _frames, _chnl );
}
recalcPhase();
return m_freq * m_detuning_div_samplerate;
}
// if we have no sub-osc, we can't do any modulation... just get our samples
template<Oscillator::WaveShape W>
void Oscillator::updateNoSub( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
recalcPhase();
const float osc_coeff = m_freq * m_detuning_div_samplerate;
for( fpp_t frame = 0; frame < _frames; ++frame )
{
_ab[frame][_chnl] = getSample<W>( m_phase ) * m_volume;
m_phase += osc_coeff;
}
}
// do pm by using sub-osc as modulator
template<Oscillator::WaveShape W>
void Oscillator::updatePM( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
m_subOsc->update( _ab, _frames, _chnl, true );
recalcPhase();
const float osc_coeff = m_freq * m_detuning_div_samplerate;
for( fpp_t frame = 0; frame < _frames; ++frame )
{
_ab[frame][_chnl] = getSample<W>( m_phase +
_ab[frame][_chnl] )
* m_volume;
m_phase += osc_coeff;
}
}
// do am by using sub-osc as modulator
template<Oscillator::WaveShape W>
void Oscillator::updateAM( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
m_subOsc->update( _ab, _frames, _chnl, false );
recalcPhase();
const float osc_coeff = m_freq * m_detuning_div_samplerate;
for( fpp_t frame = 0; frame < _frames; ++frame )
{
_ab[frame][_chnl] *= getSample<W>( m_phase ) * m_volume;
m_phase += osc_coeff;
}
}
// do mix by using sub-osc as mix-sample
template<Oscillator::WaveShape W>
void Oscillator::updateMix( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
m_subOsc->update( _ab, _frames, _chnl, false );
recalcPhase();
const float osc_coeff = m_freq * m_detuning_div_samplerate;
for( fpp_t frame = 0; frame < _frames; ++frame )
{
_ab[frame][_chnl] += getSample<W>( m_phase ) * m_volume;
m_phase += osc_coeff;
}
}
// sync with sub-osc (every time sub-osc starts new period, we also start new
// period)
template<Oscillator::WaveShape W>
void Oscillator::updateSync( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
const float sub_osc_coeff = m_subOsc->syncInit( _ab, _frames, _chnl );
recalcPhase();
const float osc_coeff = m_freq * m_detuning_div_samplerate;
for( fpp_t frame = 0; frame < _frames ; ++frame )
{
if( m_subOsc->syncOk( sub_osc_coeff ) )
{
m_phase = m_phaseOffset;
}
_ab[frame][_chnl] = getSample<W>( m_phase ) * m_volume;
m_phase += osc_coeff;
}
}
// do fm by using sub-osc as modulator
template<Oscillator::WaveShape W>
void Oscillator::updateFM( SampleFrame* _ab, const fpp_t _frames,
const ch_cnt_t _chnl )
{
m_subOsc->update( _ab, _frames, _chnl, true );
recalcPhase();
const float osc_coeff = m_freq * m_detuning_div_samplerate;
const float sampleRateCorrection = 44100.0f / Engine::audioEngine()->outputSampleRate();
for( fpp_t frame = 0; frame < _frames; ++frame )
{
m_phase += _ab[frame][_chnl] * sampleRateCorrection;
_ab[frame][_chnl] = getSample<W>( m_phase ) * m_volume;
m_phase += osc_coeff;
}
}
template<>
inline sample_t Oscillator::getSample<Oscillator::WaveShape::Sine>(const float sample)
{
const float current_freq = m_freq * m_detuning_div_samplerate * Engine::audioEngine()->outputSampleRate();
if (!m_useWaveTable || current_freq < OscillatorConstants::MAX_FREQ)
{
return sinSample(sample);
}
else
{
return 0;
}
}
template<>
inline sample_t Oscillator::getSample<Oscillator::WaveShape::Triangle>(
const float _sample )
{
if (m_useWaveTable && !m_isModulator)
{
return wtSample(s_waveTables[static_cast<std::size_t>(WaveShape::Triangle) - FirstWaveShapeTable],_sample);
}
else
{
return triangleSample(_sample);
}
}
template<>
inline sample_t Oscillator::getSample<Oscillator::WaveShape::Saw>(
const float _sample )
{
if (m_useWaveTable && !m_isModulator)
{
return wtSample(s_waveTables[static_cast<std::size_t>(WaveShape::Saw) - FirstWaveShapeTable], _sample);
}
else
{
return sawSample(_sample);
}
}
template<>
inline sample_t Oscillator::getSample<Oscillator::WaveShape::Square>(
const float _sample )
{
if (m_useWaveTable && !m_isModulator)
{
return wtSample(s_waveTables[static_cast<std::size_t>(WaveShape::Square) - FirstWaveShapeTable], _sample);
}
else
{
return squareSample(_sample);
}
}
template<>
inline sample_t Oscillator::getSample<Oscillator::WaveShape::MoogSaw>(
const float _sample )
{
if (m_useWaveTable && !m_isModulator)
{
return wtSample(s_waveTables[static_cast<std::size_t>(WaveShape::MoogSaw) - FirstWaveShapeTable], _sample);
}
else
{
return moogSawSample(_sample);
}
}
template<>
inline sample_t Oscillator::getSample<Oscillator::WaveShape::Exponential>(
const float _sample )
{
if (m_useWaveTable && !m_isModulator)
{
return wtSample(s_waveTables[static_cast<std::size_t>(WaveShape::Exponential) - FirstWaveShapeTable], _sample);
}
else
{
return expSample(_sample);
}
}
template<>
inline sample_t Oscillator::getSample<Oscillator::WaveShape::WhiteNoise>(
const float _sample )
{
return( noiseSample( _sample ) );
}
template<>
inline sample_t Oscillator::getSample<Oscillator::WaveShape::UserDefined>(
const float _sample )
{
if (m_useWaveTable && m_userAntiAliasWaveTable && !m_isModulator)
{
return wtSample(m_userAntiAliasWaveTable.get(), _sample);
}
else
{
return userWaveSample(m_userWave.get(), _sample);
}
}
} // namespace lmms
| 22,774
|
C++
|
.cpp
| 687
| 30.334789
| 166
| 0.715477
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,745
|
ComboBoxModel.cpp
|
LMMS_lmms/src/core/ComboBoxModel.cpp
|
/*
* ComboBoxModel.cpp - implementation of ComboBoxModel
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "ComboBoxModel.h"
#include <cassert>
namespace lmms
{
void ComboBoxModel::addItem(QString item, std::unique_ptr<PixmapLoader> loader)
{
m_items.emplace_back(std::move(item), std::move(loader));
setRange( 0, m_items.size() - 1 );
}
void ComboBoxModel::replaceItem(std::size_t index, QString item, std::unique_ptr<PixmapLoader> loader)
{
assert(index < m_items.size());
m_items[index] = Item(std::move(item), std::move(loader));
emit propertiesChanged();
}
void ComboBoxModel::clear()
{
setRange( 0, 0 );
m_items.clear();
emit propertiesChanged();
}
int ComboBoxModel::findText( const QString& txt ) const
{
for( auto it = m_items.begin(); it != m_items.end(); ++it )
{
if( ( *it ).first == txt )
{
return it - m_items.begin();
}
}
return -1;
}
} // namespace lmms
| 1,745
|
C++
|
.cpp
| 56
| 29.053571
| 102
| 0.728905
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
19,746
|
AutomationClip.cpp
|
LMMS_lmms/src/core/AutomationClip.cpp
|
/*
* AutomationClip.cpp - implementation of class AutomationClip which
* holds dynamic values
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2006-2008 Javier Serrano Polo <jasp00/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "AutomationClip.h"
#include "AutomationNode.h"
#include "AutomationClipView.h"
#include "AutomationTrack.h"
#include "LocaleHelper.h"
#include "Note.h"
#include "PatternStore.h"
#include "ProjectJournal.h"
#include "Song.h"
#include <cmath>
namespace lmms
{
int AutomationClip::s_quantization = 1;
const float AutomationClip::DEFAULT_MIN_VALUE = 0;
const float AutomationClip::DEFAULT_MAX_VALUE = 1;
AutomationClip::AutomationClip( AutomationTrack * _auto_track ) :
Clip( _auto_track ),
#if (QT_VERSION < QT_VERSION_CHECK(5,14,0))
m_clipMutex(QMutex::Recursive),
#endif
m_autoTrack( _auto_track ),
m_objects(),
m_tension( 1.0 ),
m_progressionType( ProgressionType::Discrete ),
m_dragging( false ),
m_isRecording( false ),
m_lastRecordedValue( 0 )
{
changeLength( TimePos( 1, 0 ) );
if( getTrack() )
{
switch( getTrack()->trackContainer()->type() )
{
case TrackContainer::Type::Pattern:
setAutoResize( true );
break;
case TrackContainer::Type::Song:
// move down
default:
setAutoResize( false );
break;
}
}
}
AutomationClip::AutomationClip( const AutomationClip & _clip_to_copy ) :
Clip( _clip_to_copy.m_autoTrack ),
#if (QT_VERSION < QT_VERSION_CHECK(5,14,0))
m_clipMutex(QMutex::Recursive),
#endif
m_autoTrack( _clip_to_copy.m_autoTrack ),
m_objects( _clip_to_copy.m_objects ),
m_tension( _clip_to_copy.m_tension ),
m_progressionType( _clip_to_copy.m_progressionType )
{
// Locks the mutex of the copied AutomationClip to make sure it
// doesn't change while it's being copied
QMutexLocker m(&_clip_to_copy.m_clipMutex);
for( timeMap::const_iterator it = _clip_to_copy.m_timeMap.begin();
it != _clip_to_copy.m_timeMap.end(); ++it )
{
// Copies the automation node (in/out values and in/out tangents)
m_timeMap[POS(it)] = it.value();
// Sets the node's clip to this one
m_timeMap[POS(it)].setClip(this);
}
if (!getTrack()){ return; }
switch( getTrack()->trackContainer()->type() )
{
case TrackContainer::Type::Pattern:
setAutoResize( true );
break;
case TrackContainer::Type::Song:
// move down
default:
setAutoResize( false );
break;
}
}
bool AutomationClip::addObject( AutomatableModel * _obj, bool _search_dup )
{
QMutexLocker m(&m_clipMutex);
if (_search_dup && std::find(m_objects.begin(), m_objects.end(), _obj) != m_objects.end())
{
return false;
}
// the automation track is unconnected and there is nothing in the track
if (m_objects.empty() && hasAutomation() == false)
{
// then initialize first value
putValue( TimePos(0), _obj->inverseScaledValue( _obj->value<float>() ), false );
}
m_objects.push_back(_obj);
connect( _obj, SIGNAL(destroyed(lmms::jo_id_t)),
this, SLOT(objectDestroyed(lmms::jo_id_t)),
Qt::DirectConnection );
emit dataChanged();
return true;
}
void AutomationClip::setProgressionType(
ProgressionType _new_progression_type )
{
QMutexLocker m(&m_clipMutex);
if ( _new_progression_type == ProgressionType::Discrete ||
_new_progression_type == ProgressionType::Linear ||
_new_progression_type == ProgressionType::CubicHermite )
{
m_progressionType = _new_progression_type;
emit dataChanged();
}
}
void AutomationClip::setTension( QString _new_tension )
{
QMutexLocker m(&m_clipMutex);
bool ok;
float nt = LocaleHelper::toFloat(_new_tension, & ok);
if( ok && nt > -0.01 && nt < 1.01 )
{
m_tension = nt;
}
}
const AutomatableModel * AutomationClip::firstObject() const
{
QMutexLocker m(&m_clipMutex);
AutomatableModel* model;
if (!m_objects.empty() && (model = m_objects.front()) != nullptr)
{
return model;
}
static FloatModel fm(0, DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE, 0.001f);
return &fm;
}
const AutomationClip::objectVector& AutomationClip::objects() const
{
QMutexLocker m(&m_clipMutex);
return m_objects;
}
TimePos AutomationClip::timeMapLength() const
{
QMutexLocker m(&m_clipMutex);
TimePos one_bar = TimePos(1, 0);
if (m_timeMap.isEmpty()) { return one_bar; }
timeMap::const_iterator it = m_timeMap.end();
auto last_tick = static_cast<tick_t>(POS(it - 1));
// if last_tick is 0 (single item at tick 0)
// return length as a whole bar to prevent disappearing Clip
if (last_tick == 0) { return one_bar; }
return TimePos(last_tick);
}
void AutomationClip::updateLength()
{
// Do not resize down in case user manually extended up
changeLength(std::max(length(), timeMapLength()));
}
/**
* @brief Puts an automation node on the timeMap with the given value.
* The inValue and outValue of the created node will be the same.
* @param TimePos time to add the node to
* @param Float inValue and outValue of the node
* @param Boolean True to quantize the position (defaults to true)
* @param Boolean True to ignore unquantized surrounding nodes (defaults to true)
* @return TimePos of the recently added automation node
*/
TimePos AutomationClip::putValue(
const TimePos & time,
const float value,
const bool quantPos,
const bool ignoreSurroundingPoints
)
{
QMutexLocker m(&m_clipMutex);
cleanObjects();
TimePos newTime = quantPos ? Note::quantized(time, quantization()) : time;
// Create a node or replace the existing one on newTime
m_timeMap[newTime] = AutomationNode(this, value, newTime);
timeMap::iterator it = m_timeMap.find(newTime);
// Remove control points that are covered by the new points
// quantization value. Control Key to override
if (!ignoreSurroundingPoints)
{
// We need to check that to avoid removing nodes from
// newTime + 1 to newTime (removing the node we are adding)
if (quantization() > 1)
{
// Remove nodes between the quantization points, them not
// being included
removeNodes(newTime + 1, newTime + quantization() - 1);
}
}
if (it != m_timeMap.begin()) { --it; }
generateTangents(it, 3);
updateLength();
emit dataChanged();
return newTime;
}
/**
* @brief Puts an automation node on the timeMap with the given inValue
* and outValue.
* @param TimePos time to add the node to
* @param Float inValue of the node
* @param Float outValue of the node
* @param Boolean True to quantize the position (defaults to true)
* @param Boolean True to ignore unquantized surrounding nodes (defaults to true)
* @return TimePos of the recently added automation node
*/
TimePos AutomationClip::putValues(
const TimePos & time,
const float inValue,
const float outValue,
const bool quantPos,
const bool ignoreSurroundingPoints
)
{
QMutexLocker m(&m_clipMutex);
cleanObjects();
TimePos newTime = quantPos ? Note::quantized(time, quantization()) : time;
// Create a node or replace the existing one on newTime
m_timeMap[newTime] = AutomationNode(this, inValue, outValue, newTime);
timeMap::iterator it = m_timeMap.find(newTime);
// Remove control points that are covered by the new points
// quantization value. Control Key to override
if (!ignoreSurroundingPoints)
{
// We need to check that to avoid removing nodes from
// newTime + 1 to newTime (removing the node we are adding)
if (quantization() > 1)
{
// Remove nodes between the quantization points, them not
// being included
removeNodes(newTime + 1, newTime + quantization() - 1);
}
}
if (it != m_timeMap.begin()) { --it; }
generateTangents(it, 3);
updateLength();
emit dataChanged();
return newTime;
}
void AutomationClip::removeNode(const TimePos & time)
{
QMutexLocker m(&m_clipMutex);
cleanObjects();
m_timeMap.remove( time );
timeMap::iterator it = m_timeMap.lowerBound(time);
if( it != m_timeMap.begin() )
{
--it;
}
generateTangents(it, 3);
updateLength();
emit dataChanged();
}
/**
* @brief Removes all automation nodes between the given ticks
* @param Int first tick of the range
* @param Int second tick of the range
*/
void AutomationClip::removeNodes(const int tick0, const int tick1)
{
if (tick0 == tick1)
{
removeNode(TimePos(tick0));
return;
}
auto start = TimePos(std::min(tick0, tick1));
auto end = TimePos(std::max(tick0, tick1));
// Make a list of TimePos with nodes to be removed
// because we can't simply remove the nodes from
// the timeMap while we are iterating it.
std::vector<TimePos> nodesToRemove;
for (auto it = m_timeMap.lowerBound(start), endIt = m_timeMap.upperBound(end); it != endIt; ++it)
{
nodesToRemove.push_back(POS(it));
}
for (auto node: nodesToRemove)
{
removeNode(node);
}
}
/**
* @brief Resets the outValues of all automation nodes between the given ticks
* @param Int first tick of the range
* @param Int second tick of the range
*/
void AutomationClip::resetNodes(const int tick0, const int tick1)
{
if (tick0 == tick1)
{
auto it = m_timeMap.find(TimePos(tick0));
if (it != m_timeMap.end()) { it.value().resetOutValue(); }
return;
}
auto start = TimePos(std::min(tick0, tick1));
auto end = TimePos(std::max(tick0, tick1));
for (auto it = m_timeMap.lowerBound(start), endIt = m_timeMap.upperBound(end); it != endIt; ++it)
{
it.value().resetOutValue();
}
}
void AutomationClip::resetTangents(const int tick0, const int tick1)
{
if (tick0 == tick1)
{
auto it = m_timeMap.find(TimePos(tick0));
if (it != m_timeMap.end())
{
it.value().setLockedTangents(false);
generateTangents(it, 1);
}
return;
}
TimePos start = TimePos(std::min(tick0, tick1));
TimePos end = TimePos(std::max(tick0, tick1));
for (auto it = m_timeMap.lowerBound(start), endIt = m_timeMap.upperBound(end); it != endIt; ++it)
{
it.value().setLockedTangents(false);
generateTangents(it, 1);
}
}
void AutomationClip::recordValue(TimePos time, float value)
{
QMutexLocker m(&m_clipMutex);
if( value != m_lastRecordedValue )
{
putValue( time, value, true );
m_lastRecordedValue = value;
}
else if( valueAt( time ) != value )
{
removeNode(time);
}
}
/**
* @brief Set the position of the point that is being dragged.
* Calling this function will also automatically set m_dragging to true.
* When applyDragValue() is called, m_dragging is set back to false.
* @param TimePos of the node being dragged
* @param Float with the value to assign to the point being dragged
* @param Boolean. True to snip x position
* @param Boolean. True to ignore unquantized surrounding nodes
* @return TimePos with current time of the dragged value
*/
TimePos AutomationClip::setDragValue(
const TimePos & time,
const float value,
const bool quantPos,
const bool controlKey
)
{
QMutexLocker m(&m_clipMutex);
if (m_dragging == false)
{
TimePos newTime = quantPos ? Note::quantized(time, quantization()) : time;
// We will keep the same outValue only if it's different from the
// inValue
m_dragKeepOutValue = false;
// We will set the tangents back to what they were if the node had
// its tangents locked
m_dragLockedTan = false;
// Check if we already have a node on the position we are dragging
// and if we do, store the outValue so the discrete jump can be kept
// and information about the tangents
timeMap::iterator it = m_timeMap.find(newTime);
if (it != m_timeMap.end())
{
// If we don't have a discrete jump, the outValue will be the
// same as the inValue
if (OFFSET(it) != 0)
{
m_dragKeepOutValue = true;
m_dragOutValue = OUTVAL(it);
}
// For the tangents, we will only keep them if the tangents were
// locked
if (LOCKEDTAN(it))
{
m_dragLockedTan = true;
m_dragInTan = INTAN(it);
m_dragOutTan = OUTTAN(it);
}
}
this->removeNode(newTime);
m_oldTimeMap = m_timeMap;
m_dragging = true;
}
//Restore to the state before it the point were being dragged
m_timeMap = m_oldTimeMap;
generateTangents();
TimePos returnedPos;
if (m_dragKeepOutValue)
{
returnedPos = this->putValues(time, value, m_dragOutValue, quantPos, controlKey);
}
else
{
returnedPos = this->putValue(time, value, quantPos, controlKey);
}
// Set the tangents on the newly created node if they were locked
// before dragging
if (m_dragLockedTan)
{
timeMap::iterator it = m_timeMap.find(returnedPos);
if (it != m_timeMap.end())
{
it.value().setInTangent(m_dragInTan);
it.value().setOutTangent(m_dragOutTan);
it.value().setLockedTangents(true);
}
}
return returnedPos;
}
/**
* @brief After the point is dragged, this function is called to apply the change.
*/
void AutomationClip::applyDragValue()
{
QMutexLocker m(&m_clipMutex);
m_dragging = false;
}
float AutomationClip::valueAt( const TimePos & _time ) const
{
QMutexLocker m(&m_clipMutex);
if( m_timeMap.isEmpty() )
{
return 0;
}
// If we have a node at that time, just return its value
if (m_timeMap.contains(_time))
{
// When the time is exactly the node's time, we want the inValue
return m_timeMap[_time].getInValue();
}
// lowerBound returns next value with equal or greater key. Since we already
// checked if the key contains a node, we know the returned node has a greater
// key than _time. Therefore we take the previous element to calculate the current value
timeMap::const_iterator v = m_timeMap.lowerBound(_time);
if( v == m_timeMap.begin() )
{
return 0;
}
if( v == m_timeMap.end() )
{
// When the time is after the last node, we want the outValue of it
return OUTVAL(v - 1);
}
return valueAt(v - 1, _time - POS(v - 1));
}
// This method will get the value at an offset from a node, so we use the outValue of
// that node and the inValue of the next node for the calculations.
float AutomationClip::valueAt( timeMap::const_iterator v, int offset ) const
{
QMutexLocker m(&m_clipMutex);
// We never use it with offset 0, but doesn't hurt to return a correct
// value if we do
if (offset == 0) { return INVAL(v); }
if (m_progressionType == ProgressionType::Discrete)
{
return OUTVAL(v);
}
else if( m_progressionType == ProgressionType::Linear )
{
float slope =
(INVAL(v + 1) - OUTVAL(v))
/ (POS(v + 1) - POS(v));
return OUTVAL(v) + offset * slope;
}
else /* ProgressionType::CubicHermite */
{
// Implements a Cubic Hermite spline as explained at:
// http://en.wikipedia.org/wiki/Cubic_Hermite_spline#Unit_interval_.280.2C_1.29
//
// Note that we are not interpolating a 2 dimensional point over
// time as the article describes. We are interpolating a single
// value: y. To make this work we map the values of x that this
// segment spans to values of t for t = 0.0 -> 1.0 and scale the
// tangents _m1 and _m2
int numValues = (POS(v + 1) - POS(v));
float t = (float) offset / (float) numValues;
float m1 = OUTTAN(v) * numValues * m_tension;
float m2 = INTAN(v + 1) * numValues * m_tension;
auto t2 = pow(t, 2);
auto t3 = pow(t, 3);
return (2 * t3 - 3 * t2 + 1) * OUTVAL(v)
+ (t3 - 2 * t2 + t) * m1
+ (-2 * t3 + 3 * t2) * INVAL(v + 1)
+ (t3 - t2) * m2;
}
}
float *AutomationClip::valuesAfter( const TimePos & _time ) const
{
QMutexLocker m(&m_clipMutex);
timeMap::const_iterator v = m_timeMap.lowerBound(_time);
if( v == m_timeMap.end() || (v+1) == m_timeMap.end() )
{
return nullptr;
}
int numValues = POS(v + 1) - POS(v);
auto ret = new float[numValues];
for( int i = 0; i < numValues; i++ )
{
ret[i] = valueAt( v, i );
}
return ret;
}
void AutomationClip::flipY(int min, int max)
{
QMutexLocker m(&m_clipMutex);
bool changedTimeMap = false;
for (auto it = m_timeMap.begin(); it != m_timeMap.end(); ++it)
{
// Get distance from IN/OUT values to max value
float inValDist = max - INVAL(it);
float outValDist = max - OUTVAL(it);
// To flip, that will be the new distance between
// the IN/OUT values and the min value
it.value().setInValue(min + inValDist);
it.value().setOutValue(min + outValDist);
changedTimeMap = true;
}
if (changedTimeMap)
{
generateTangents();
emit dataChanged();
}
}
void AutomationClip::flipY()
{
flipY(getMin(), getMax());
}
void AutomationClip::flipX(int length)
{
QMutexLocker m(&m_clipMutex);
timeMap::const_iterator it = m_timeMap.lowerBound(0);
if (it == m_timeMap.end()) { return; }
// Temporary map where we will store the flipped version
// of our clip
timeMap tempMap;
float tempValue = 0;
float tempOutValue = 0;
// We know the QMap isn't empty, making this safe:
float realLength = m_timeMap.lastKey();
// If we have a positive length, we want to flip the area covered by that
// length, even if it goes beyond the clip. A negative length means that
// we just want to flip the nodes we have
if (length >= 0 && length != realLength)
{
// If length to be flipped is bigger than the real length
if (realLength < length)
{
// We are flipping an area that goes beyond the last node. So we add a node to the
// beginning of the flipped timeMap representing the value of the end of the area
tempValue = valueAt(length);
tempMap[0] = AutomationNode(this, tempValue, 0);
// Now flip the nodes we have in relation to the length
do
{
// We swap the inValue and outValue when flipping horizontally
tempValue = OUTVAL(it);
tempOutValue = INVAL(it);
auto newTime = TimePos(length - POS(it));
tempMap[newTime] = AutomationNode(this, tempValue, tempOutValue, newTime);
++it;
} while (it != m_timeMap.end());
}
else // If the length to be flipped is smaller than the real length
{
do
{
TimePos newTime;
// Only flips the length to be flipped and keep the remaining values in place
// We also only swap the inValue and outValue if we are flipping the node
if (POS(it) <= length)
{
newTime = length - POS(it);
tempValue = OUTVAL(it);
tempOutValue = INVAL(it);
}
else
{
newTime = POS(it);
tempValue = INVAL(it);
tempOutValue = OUTVAL(it);
}
tempMap[newTime] = AutomationNode(this, tempValue, tempOutValue, newTime);
++it;
} while (it != m_timeMap.end());
}
}
else // Length to be flipped is the same as the real length
{
do
{
// Swap the inValue and outValue
tempValue = OUTVAL(it);
tempOutValue = INVAL(it);
auto newTime = TimePos(realLength - POS(it));
tempMap[newTime] = AutomationNode(this, tempValue, tempOutValue, newTime);
++it;
} while (it != m_timeMap.end());
}
m_timeMap.clear();
m_timeMap = tempMap;
cleanObjects();
generateTangents();
emit dataChanged();
}
void AutomationClip::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
QMutexLocker m(&m_clipMutex);
_this.setAttribute( "pos", startPosition() );
_this.setAttribute( "len", length() );
_this.setAttribute( "name", name() );
_this.setAttribute( "prog", QString::number( static_cast<int>(progressionType()) ) );
_this.setAttribute( "tens", QString::number( getTension() ) );
_this.setAttribute( "mute", QString::number( isMuted() ) );
if (const auto& c = color())
{
_this.setAttribute("color", c->name());
}
for( timeMap::const_iterator it = m_timeMap.begin();
it != m_timeMap.end(); ++it )
{
QDomElement element = _doc.createElement( "time" );
element.setAttribute("pos", POS(it));
element.setAttribute("value", INVAL(it));
element.setAttribute("outValue", OUTVAL(it));
element.setAttribute("inTan", INTAN(it));
element.setAttribute("outTan", OUTTAN(it));
element.setAttribute("lockedTan", static_cast<int>(LOCKEDTAN(it)));
_this.appendChild( element );
}
for (const auto& object : m_objects)
{
if (object)
{
QDomElement element = _doc.createElement( "object" );
element.setAttribute("id", ProjectJournal::idToSave(object->id()));
_this.appendChild(element);
}
}
}
void AutomationClip::loadSettings( const QDomElement & _this )
{
QMutexLocker m(&m_clipMutex);
// Legacy compatibility: Previously tangents were not stored in
// the project file. So if any node doesn't have tangent information
// we will generate the tangents
bool shouldGenerateTangents = false;
clear();
movePosition( _this.attribute( "pos" ).toInt() );
setName( _this.attribute( "name" ) );
setProgressionType( static_cast<ProgressionType>( _this.attribute(
"prog" ).toInt() ) );
setTension( _this.attribute( "tens" ) );
setMuted(_this.attribute( "mute", QString::number( false ) ).toInt() );
for( QDomNode node = _this.firstChild(); !node.isNull();
node = node.nextSibling() )
{
QDomElement element = node.toElement();
if( element.isNull() )
{
continue;
}
if( element.tagName() == "time" )
{
int timeMapPos = element.attribute("pos").toInt();
float timeMapInValue = LocaleHelper::toFloat(element.attribute("value"));
float timeMapOutValue = LocaleHelper::toFloat(element.attribute("outValue"));
m_timeMap[timeMapPos] = AutomationNode(this, timeMapInValue, timeMapOutValue, timeMapPos);
// Load tangents if there is information about it (it's enough to check for either inTan or outTan)
if (element.hasAttribute("inTan"))
{
float inTan = LocaleHelper::toFloat(element.attribute("inTan"));
float outTan = LocaleHelper::toFloat(element.attribute("outTan"));
bool lockedTan = static_cast<bool>(element.attribute("lockedTan", "0").toInt());
m_timeMap[timeMapPos].setInTangent(inTan);
m_timeMap[timeMapPos].setOutTangent(outTan);
m_timeMap[timeMapPos].setLockedTangents(lockedTan);
}
else
{
shouldGenerateTangents = true;
}
}
else if( element.tagName() == "object" )
{
m_idsToResolve.push_back(element.attribute("id").toInt());
}
}
if (_this.hasAttribute("color"))
{
setColor(QColor{_this.attribute("color")});
}
int len = _this.attribute( "len" ).toInt();
if( len <= 0 )
{
// TODO: Handle with an upgrade method
updateLength();
}
else
{
changeLength( len );
}
if (shouldGenerateTangents) { generateTangents(); }
}
QString AutomationClip::name() const
{
QMutexLocker m(&m_clipMutex);
if( !Clip::name().isEmpty() )
{
return Clip::name();
}
if (!m_objects.empty() && m_objects.front() != nullptr)
{
return m_objects.front()->fullDisplayName();
}
return tr( "Drag a control while pressing <%1>" ).arg(UI_CTRL_KEY);
}
gui::ClipView * AutomationClip::createView( gui::TrackView * _tv )
{
QMutexLocker m(&m_clipMutex);
return new gui::AutomationClipView( this, _tv );
}
bool AutomationClip::isAutomated( const AutomatableModel * _m )
{
auto l = combineAllTracks();
for (const auto track : l)
{
if (track->type() == Track::Type::Automation || track->type() == Track::Type::HiddenAutomation)
{
for (const auto& clip : track->getClips())
{
const auto a = dynamic_cast<const AutomationClip*>(clip);
if( a && a->hasAutomation() )
{
for (const auto& object : a->m_objects)
{
if (object == _m)
{
return true;
}
}
}
}
}
}
return false;
}
/**
* @brief returns a list of all the automation clips that are connected to a specific model
* @param _m the model we want to look for
*/
std::vector<AutomationClip *> AutomationClip::clipsForModel(const AutomatableModel* _m)
{
std::vector<AutomationClip *> clips;
auto l = combineAllTracks();
// go through all tracks...
for (const auto track : l)
{
// we want only automation tracks...
if (track->type() == Track::Type::Automation || track->type() == Track::Type::HiddenAutomation )
{
// go through all the clips...
for (const auto& trackClip : track->getClips())
{
auto a = dynamic_cast<AutomationClip*>(trackClip);
// check that the clip has automation
if( a && a->hasAutomation() )
{
// now check is the clip is connected to the model we want by going through all the connections
// of the clip
bool has_object = false;
for (const auto& object : a->m_objects)
{
if (object == _m)
{
has_object = true;
}
}
// if the clips is connected to the model, add it to the list
if (has_object) { clips.push_back(a); }
}
}
}
}
return clips;
}
AutomationClip * AutomationClip::globalAutomationClip(
AutomatableModel * _m )
{
AutomationTrack * t = Engine::getSong()->globalAutomationTrack();
for (const auto& clip : t->getClips())
{
auto a = dynamic_cast<AutomationClip*>(clip);
if( a )
{
for (const auto& object : a->m_objects)
{
if (object == _m) { return a; }
}
}
}
auto a = new AutomationClip(t);
a->addObject( _m, false );
return a;
}
void AutomationClip::resolveAllIDs()
{
auto l = combineAllTracks();
for (const auto& track : l)
{
if (track->type() == Track::Type::Automation || track->type() == Track::Type::HiddenAutomation)
{
for (const auto& clip : track->getClips())
{
auto a = dynamic_cast<AutomationClip*>(clip);
if( a )
{
for (const auto& id : a->m_idsToResolve)
{
JournallingObject* o = Engine::projectJournal()->journallingObject(id);
if( o && dynamic_cast<AutomatableModel *>( o ) )
{
a->addObject( dynamic_cast<AutomatableModel *>( o ), false );
}
else
{
// FIXME: Remove this block once the automation system gets fixed
// This is a temporary fix for https://github.com/LMMS/lmms/issues/3781
o = Engine::projectJournal()->journallingObject(ProjectJournal::idFromSave(id));
if( o && dynamic_cast<AutomatableModel *>( o ) )
{
a->addObject( dynamic_cast<AutomatableModel *>( o ), false );
}
else
{
// FIXME: Remove this block once the automation system gets fixed
// This is a temporary fix for https://github.com/LMMS/lmms/issues/4781
o = Engine::projectJournal()->journallingObject(ProjectJournal::idToSave(id));
if( o && dynamic_cast<AutomatableModel *>( o ) )
{
a->addObject( dynamic_cast<AutomatableModel *>( o ), false );
}
}
}
}
a->m_idsToResolve.clear();
a->dataChanged();
}
}
}
}
}
void AutomationClip::clear()
{
QMutexLocker m(&m_clipMutex);
m_timeMap.clear();
emit dataChanged();
}
void AutomationClip::objectDestroyed( jo_id_t _id )
{
QMutexLocker m(&m_clipMutex);
// TODO: distict between temporary removal (e.g. LADSPA controls
// when switching samplerate) and real deletions because in the latter
// case we had to remove ourselves if we're the global automation
// clip of the destroyed object
m_idsToResolve.push_back(_id);
for (auto objIt = m_objects.begin(); objIt != m_objects.end(); objIt++)
{
Q_ASSERT( !(*objIt).isNull() );
if( (*objIt)->id() == _id )
{
//Assign to objIt so that this loop work even break; is removed.
objIt = m_objects.erase( objIt );
break;
}
}
emit dataChanged();
}
void AutomationClip::cleanObjects()
{
QMutexLocker m(&m_clipMutex);
for( objectVector::iterator it = m_objects.begin(); it != m_objects.end(); )
{
if( *it )
{
++it;
}
else
{
it = m_objects.erase( it );
}
}
}
void AutomationClip::generateTangents()
{
generateTangents(m_timeMap.begin(), m_timeMap.size());
}
// We have two tangents, one for the left side of the node and one for the right side
// of the node (in case we have discrete value jumps in the middle of a curve).
// If the inValue and outValue of a node are the same, consequently the inTangent and
// outTangent values of the node will be the same too.
void AutomationClip::generateTangents(timeMap::iterator it, int numToGenerate)
{
QMutexLocker m(&m_clipMutex);
for (int i = 0; i < numToGenerate && it != m_timeMap.end(); ++i, ++it)
{
// Skip the node if it has locked tangents (were manually edited)
if (LOCKEDTAN(it))
{
continue;
}
if (it + 1 == m_timeMap.end())
{
// Previously, the last value's tangent was always set to 0. That logic was kept for both tangents
// of the last node
it.value().setInTangent(0);
it.value().setOutTangent(0);
}
else if (it == m_timeMap.begin())
{
// On the first node there's no curve behind it, so we will only calculate the outTangent
// and inTangent will be set to 0.
float tangent = (INVAL(it + 1) - OUTVAL(it)) / (POS(it + 1) - POS(it));
it.value().setInTangent(0);
it.value().setOutTangent(tangent);
}
else
{
// When we are in a node that is in the middle of two other nodes, we need to check if we
// have a discrete jump at this node. If we do not, then we can calculate the tangents normally.
// If we do have a discrete jump, then we have to calculate the tangents differently for each side
// of the curve.
// TODO: This behavior means that a very small difference between the inValue and outValue can
// result in a big change in the curve. In the future, allowing the user to manually adjust
// the tangents would be better.
if (OFFSET(it) == 0)
{
float inTangent = (INVAL(it + 1) - OUTVAL(it - 1)) / (POS(it + 1) - POS(it - 1));
it.value().setInTangent(inTangent);
// inTangent == outTangent in this case
it.value().setOutTangent(inTangent);
}
else
{
// Calculate the left side of the curve
float inTangent = (INVAL(it) - OUTVAL(it - 1)) / (POS(it) - POS(it - 1));
// Calculate the right side of the curve
float outTangent = (INVAL(it + 1) - OUTVAL(it)) / (POS(it + 1) - POS(it));
it.value().setInTangent(inTangent);
it.value().setOutTangent(outTangent);
}
}
}
}
std::vector<Track*> AutomationClip::combineAllTracks()
{
std::vector<Track*> combinedTrackList;
auto& songTracks = Engine::getSong()->tracks();
auto& patternStoreTracks = Engine::patternStore()->tracks();
combinedTrackList.insert(combinedTrackList.end(), songTracks.begin(), songTracks.end());
combinedTrackList.insert(combinedTrackList.end(), patternStoreTracks.begin(), patternStoreTracks.end());
combinedTrackList.push_back(Engine::getSong()->globalAutomationTrack());
return combinedTrackList;
}
} // namespace lmms
| 30,901
|
C++
|
.cpp
| 990
| 28.193939
| 105
| 0.695928
|
LMMS/lmms
| 7,989
| 994
| 1,122
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.