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,747
|
AutomationNode.cpp
|
LMMS_lmms/src/core/AutomationNode.cpp
|
/*
* AutomationClip.cpp - Implementation of class AutomationNode which
* holds information on a single automation clip node
*
* Copyright (c) 2020 Ian Caio <iancaio_dev/at/hotmail.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 "AutomationNode.h"
#include "AutomationClip.h"
namespace lmms
{
// Dummy constructor for the QMap
AutomationNode::AutomationNode() :
m_clip(nullptr),
m_pos(0),
m_inValue(0),
m_outValue(0),
m_inTangent(0),
m_outTangent(0),
m_lockedTangents(false)
{
}
AutomationNode::AutomationNode(AutomationClip* clip, float value, int pos) :
m_clip(clip),
m_pos(pos),
m_inValue(value),
m_outValue(value),
m_inTangent(0),
m_outTangent(0),
m_lockedTangents(false)
{
}
AutomationNode::AutomationNode(AutomationClip* clip, float inValue, float outValue, int pos) :
m_clip(clip),
m_pos(pos),
m_inValue(inValue),
m_outValue(outValue),
m_inTangent(0),
m_outTangent(0),
m_lockedTangents(false)
{
}
/**
* @brief Sets the inValue of an automation node
* @param Float value to be assigned
*/
void AutomationNode::setInValue(float value)
{
m_inValue = value;
// Recalculate the tangents from neighbor nodes
AutomationClip::timeMap & tm = m_clip->getTimeMap();
// Get an iterator pointing to this node
AutomationClip::timeMap::iterator it = tm.lowerBound(m_pos);
// If it's not the first node, get the one immediately behind it
if (it != tm.begin()) { --it; }
// Generate tangents from the previously, current and next nodes
m_clip->generateTangents(it, 3);
}
/**
* @brief Sets the outValue of an automation node
* @param Float value to be assigned
*/
void AutomationNode::setOutValue(float value)
{
m_outValue = value;
// Recalculate the tangents from neighbor nodes
AutomationClip::timeMap & tm = m_clip->getTimeMap();
// Get an iterator pointing to this node
AutomationClip::timeMap::iterator it = tm.lowerBound(m_pos);
// If it's not the first node, get the one immediately behind it
if (it != tm.begin()) { --it; }
// Generate tangents from the previously, current and next nodes
m_clip->generateTangents(it, 3);
}
/**
* @brief Resets the outValue so it matches inValue
*/
void AutomationNode::resetOutValue()
{
// Calls setOutValue so it also takes care of generating
// the tangents
setOutValue(m_inValue);
}
} // namespace lmms
| 3,086
|
C++
|
.cpp
| 101
| 28.712871
| 94
| 0.743771
|
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,748
|
InstrumentPlayHandle.cpp
|
LMMS_lmms/src/core/InstrumentPlayHandle.cpp
|
/*
* InstrumentPlayHandle.cpp - play-handle for driving an instrument
*
* 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 "InstrumentPlayHandle.h"
#include "Instrument.h"
#include "InstrumentTrack.h"
#include "Engine.h"
#include "AudioEngine.h"
namespace lmms
{
InstrumentPlayHandle::InstrumentPlayHandle(Instrument * instrument, InstrumentTrack* instrumentTrack) :
PlayHandle(Type::InstrumentPlayHandle),
m_instrument(instrument)
{
setAudioPort(instrumentTrack->audioPort());
}
void InstrumentPlayHandle::play(SampleFrame* working_buffer)
{
InstrumentTrack * instrumentTrack = m_instrument->instrumentTrack();
// ensure that all our nph's have been processed first
auto nphv = NotePlayHandle::nphsOfInstrumentTrack(instrumentTrack, true);
bool nphsLeft;
do
{
nphsLeft = false;
for (const auto& handle : nphv)
{
if (handle->state() != ThreadableJob::ProcessingState::Done && !handle->isFinished())
{
nphsLeft = true;
const_cast<NotePlayHandle*>(handle)->process();
}
}
}
while (nphsLeft);
m_instrument->play(working_buffer);
// Process the audio buffer that the instrument has just worked on...
const fpp_t frames = Engine::audioEngine()->framesPerPeriod();
instrumentTrack->processAudioBuffer(working_buffer, frames, nullptr);
}
bool InstrumentPlayHandle::isFromTrack(const Track* track) const
{
return m_instrument->isFromTrack(track);
}
} // namespace lmms
| 2,247
|
C++
|
.cpp
| 65
| 32.4
| 103
| 0.768096
|
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,749
|
Instrument.cpp
|
LMMS_lmms/src/core/Instrument.cpp
|
/*
* Instrument.cpp - base-class for all instrument-plugins (synths, samplers etc)
*
* Copyright (c) 2005-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 "Instrument.h"
#include <cmath>
#include "DummyInstrument.h"
#include "InstrumentTrack.h"
#include "lmms_basics.h"
#include "lmms_constants.h"
namespace lmms
{
Instrument::Instrument(InstrumentTrack * _instrument_track,
const Descriptor * _descriptor,
const Descriptor::SubPluginFeatures::Key *key,
Flags flags) :
Plugin(_descriptor, nullptr/* _instrument_track*/, key),
m_instrumentTrack( _instrument_track ),
m_flags(flags)
{
}
void Instrument::play( SampleFrame* )
{
}
void Instrument::deleteNotePluginData( NotePlayHandle * )
{
}
f_cnt_t Instrument::beatLen( NotePlayHandle * ) const
{
return( 0 );
}
Instrument *Instrument::instantiate(const QString &_plugin_name,
InstrumentTrack *_instrument_track, const Descriptor::SubPluginFeatures::Key *key, bool keyFromDnd)
{
if(keyFromDnd)
Q_ASSERT(!key);
// copy from above // TODO! common cleaner func
Plugin * p = Plugin::instantiateWithKey(_plugin_name, _instrument_track, key, keyFromDnd);
if(dynamic_cast<Instrument *>(p))
return dynamic_cast<Instrument *>(p);
delete p;
return( new DummyInstrument( _instrument_track ) );
}
bool Instrument::isFromTrack( const Track * _track ) const
{
return( m_instrumentTrack == _track );
}
// helper function for Instrument::applyFadeIn
static int countZeroCrossings(SampleFrame* buf, fpp_t start, fpp_t frames)
{
// zero point crossing counts of all channels
auto zeroCrossings = std::array<int, DEFAULT_CHANNELS>{};
// maximum zero point crossing of all channels
int maxZeroCrossings = 0;
// determine the zero point crossing counts
for (fpp_t f = start; f < frames; ++f)
{
for (ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch)
{
// we don't want to count [-1, 0, 1] as two crossings
if ((buf[f - 1][ch] <= 0.0 && buf[f][ch] > 0.0) ||
(buf[f - 1][ch] >= 0.0 && buf[f][ch] < 0.0))
{
++zeroCrossings[ch];
if (zeroCrossings[ch] > maxZeroCrossings)
{
maxZeroCrossings = zeroCrossings[ch];
}
}
}
}
return maxZeroCrossings;
}
// helper function for Instrument::applyFadeIn
fpp_t getFadeInLength(float maxLength, fpp_t frames, int zeroCrossings)
{
// calculate the length of the fade in
// Length is inversely proportional to the max of zeroCrossings,
// because for low frequencies, we need a longer fade in to
// prevent clicking.
return (fpp_t) (maxLength / ((float) zeroCrossings / ((float) frames / 128.0f) + 1.0f));
}
void Instrument::applyFadeIn(SampleFrame* buf, NotePlayHandle * n)
{
const static float MAX_FADE_IN_LENGTH = 85.0;
f_cnt_t total = n->totalFramesPlayed();
if (total == 0)
{
const fpp_t frames = n->framesLeftForCurrentPeriod();
const f_cnt_t offset = n->offset();
// We need to skip the first sample because it almost always
// produces a zero crossing; it's not helpful while
// determining the fade in length. Hence 1
int maxZeroCrossings = countZeroCrossings(buf, offset + 1, offset + frames);
fpp_t length = getFadeInLength(MAX_FADE_IN_LENGTH, frames, maxZeroCrossings);
n->m_fadeInLength = length;
// apply fade in
length = length < frames ? length : frames;
for (fpp_t f = 0; f < length; ++f)
{
for (ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch)
{
buf[offset + f][ch] *= 0.5 - 0.5 * cosf(F_PI * (float) f / (float) n->m_fadeInLength);
}
}
}
else if (total < n->m_fadeInLength)
{
const fpp_t frames = n->framesLeftForCurrentPeriod();
int new_zc = countZeroCrossings(buf, 1, frames);
fpp_t new_length = getFadeInLength(MAX_FADE_IN_LENGTH, frames, new_zc);
for (fpp_t f = 0; f < frames; ++f)
{
for (ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch)
{
float currentLength = n->m_fadeInLength * (1.0f - (float) f / frames) + new_length * ((float) f / frames);
buf[f][ch] *= 0.5 - 0.5 * cosf(F_PI * (float) (total + f) / currentLength);
if (total + f >= currentLength)
{
n->m_fadeInLength = currentLength;
return;
}
}
}
n->m_fadeInLength = new_length;
}
}
void Instrument::applyRelease( SampleFrame* buf, const NotePlayHandle * _n )
{
const auto fpp = Engine::audioEngine()->framesPerPeriod();
const auto releaseFrames = desiredReleaseFrames();
const auto endFrame = _n->framesLeft();
const auto startFrame = endFrame - std::min(endFrame, releaseFrames);
for (auto f = startFrame; f < endFrame && f < fpp; f++)
{
const float fac = (float)(endFrame - f) / (float)releaseFrames;
for (ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ch++)
{
buf[f][ch] *= fac;
}
}
}
float Instrument::computeReleaseTimeMsByFrameCount(f_cnt_t frames) const
{
return frames / getSampleRate() * 1000.;
}
sample_rate_t Instrument::getSampleRate() const
{
return Engine::audioEngine()->outputSampleRate();
}
QString Instrument::fullDisplayName() const
{
return instrumentTrack()->displayName();
}
} // namespace lmms
| 5,803
|
C++
|
.cpp
| 174
| 30.793103
| 110
| 0.708095
|
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,750
|
SerializingObject.cpp
|
LMMS_lmms/src/core/SerializingObject.cpp
|
/*
* SerializingObject.cpp - implementation of SerializingObject
*
* Copyright (c) 2008-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 <QDomElement>
#include "SerializingObject.h"
namespace lmms
{
SerializingObject::SerializingObject() :
m_hook( nullptr )
{
}
SerializingObject::~SerializingObject()
{
if( m_hook )
{
m_hook->m_hookedIn = nullptr;
}
}
QDomElement SerializingObject::saveState( QDomDocument& doc, QDomElement& parent )
{
QDomElement element = doc.createElement( nodeName() );
parent.appendChild( element );
saveSettings( doc, element );
if( hook() )
{
hook()->saveSettings( doc, element );
}
return element;
}
void SerializingObject::restoreState( const QDomElement& element )
{
loadSettings( element );
if( hook() )
{
hook()->loadSettings( element );
}
}
void SerializingObject::setHook( SerializingObjectHook* hook )
{
if( m_hook )
{
m_hook->m_hookedIn = nullptr;
}
m_hook = hook;
if( m_hook )
{
m_hook->m_hookedIn = this;
}
}
void SerializingObject::saveSettings( QDomDocument& doc, QDomElement& element )
{
Q_UNUSED(doc)
Q_UNUSED(element)
}
void SerializingObject::loadSettings( const QDomElement& element )
{
Q_UNUSED(element)
}
} // namespace lmms
| 2,054
|
C++
|
.cpp
| 79
| 23.835443
| 82
| 0.75
|
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,751
|
SampleClip.cpp
|
LMMS_lmms/src/core/SampleClip.cpp
|
/*
* SampleClip.cpp
*
* 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 "SampleClip.h"
#include <QDomElement>
#include <QFileInfo>
#include "PathUtil.h"
#include "SampleBuffer.h"
#include "SampleClipView.h"
#include "SampleLoader.h"
#include "SampleTrack.h"
#include "TimeLineWidget.h"
namespace lmms
{
SampleClip::SampleClip(Track* _track, Sample sample, bool isPlaying)
: Clip(_track)
, m_sample(std::move(sample))
, m_isPlaying(false)
{
saveJournallingState( false );
setSampleFile( "" );
restoreJournallingState();
// we need to receive bpm-change-events, because then we have to
// change length of this Clip
connect( Engine::getSong(), SIGNAL(tempoChanged(lmms::bpm_t)),
this, SLOT(updateLength()), Qt::DirectConnection );
connect( Engine::getSong(), SIGNAL(timeSignatureChanged(int,int)),
this, SLOT(updateLength()));
//playbutton clicked or space key / on Export Song set isPlaying to false
connect( Engine::getSong(), SIGNAL(playbackStateChanged()),
this, SLOT(playbackPositionChanged()), Qt::DirectConnection );
//care about loops and jumps
connect( Engine::getSong(), SIGNAL(updateSampleTracks()),
this, SLOT(playbackPositionChanged()), Qt::DirectConnection );
//care about mute Clips
connect( this, SIGNAL(dataChanged()), this, SLOT(playbackPositionChanged()));
//care about mute track
connect( getTrack()->getMutedModel(), SIGNAL(dataChanged()),
this, SLOT(playbackPositionChanged()), Qt::DirectConnection );
//care about Clip position
connect( this, SIGNAL(positionChanged()), this, SLOT(updateTrackClips()));
switch( getTrack()->trackContainer()->type() )
{
case TrackContainer::Type::Pattern:
setAutoResize( true );
break;
case TrackContainer::Type::Song:
// move down
default:
setAutoResize( false );
break;
}
updateTrackClips();
}
SampleClip::SampleClip(Track* track)
: SampleClip(track, Sample(), false)
{
}
SampleClip::SampleClip(const SampleClip& orig) :
SampleClip(orig.getTrack(), orig.m_sample, orig.m_isPlaying)
{
}
SampleClip::~SampleClip()
{
auto sampletrack = dynamic_cast<SampleTrack*>(getTrack());
if ( sampletrack )
{
sampletrack->updateClips();
}
}
void SampleClip::changeLength( const TimePos & _length )
{
Clip::changeLength(std::max(static_cast<int>(_length), 1));
}
void SampleClip::changeLengthToSampleLength()
{
int length = m_sample.sampleSize() / Engine::framesPerTick();
changeLength(length);
}
const QString& SampleClip::sampleFile() const
{
return m_sample.sampleFile();
}
bool SampleClip::hasSampleFileLoaded(const QString & filename) const
{
return m_sample.sampleFile() == filename;
}
void SampleClip::setSampleBuffer(std::shared_ptr<const SampleBuffer> sb)
{
{
const auto guard = Engine::audioEngine()->requestChangesGuard();
m_sample = Sample(std::move(sb));
}
updateLength();
emit sampleChanged();
Engine::getSong()->setModified();
}
void SampleClip::setSampleFile(const QString& sf)
{
int length = 0;
if (!sf.isEmpty())
{
//Otherwise set it to the sample's length
m_sample = Sample(gui::SampleLoader::createBufferFromFile(sf));
length = sampleLength();
}
if (length == 0)
{
//If there is no sample, make the clip a bar long
float nom = Engine::getSong()->getTimeSigModel().getNumerator();
float den = Engine::getSong()->getTimeSigModel().getDenominator();
length = DefaultTicksPerBar * (nom / den);
}
changeLength(length);
setStartTimeOffset(0);
emit sampleChanged();
emit playbackPositionChanged();
}
void SampleClip::toggleRecord()
{
m_recordModel.setValue( !m_recordModel.value() );
emit dataChanged();
}
void SampleClip::playbackPositionChanged()
{
Engine::audioEngine()->removePlayHandlesOfTypes( getTrack(), PlayHandle::Type::SamplePlayHandle );
auto st = dynamic_cast<SampleTrack*>(getTrack());
st->setPlayingClips( false );
}
void SampleClip::updateTrackClips()
{
auto sampletrack = dynamic_cast<SampleTrack*>(getTrack());
if( sampletrack)
{
sampletrack->updateClips();
}
}
bool SampleClip::isPlaying() const
{
return m_isPlaying;
}
void SampleClip::setIsPlaying(bool isPlaying)
{
m_isPlaying = isPlaying;
}
void SampleClip::updateLength()
{
emit sampleChanged();
Engine::getSong()->setModified();
}
TimePos SampleClip::sampleLength() const
{
return static_cast<int>(m_sample.sampleSize() / Engine::framesPerTick(m_sample.sampleRate()));
}
void SampleClip::setSampleStartFrame(f_cnt_t startFrame)
{
m_sample.setStartFrame(startFrame);
}
void SampleClip::setSamplePlayLength(f_cnt_t length)
{
m_sample.setEndFrame(length);
}
void SampleClip::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
if( _this.parentNode().nodeName() == "clipboard" )
{
_this.setAttribute( "pos", -1 );
}
else
{
_this.setAttribute( "pos", startPosition() );
}
_this.setAttribute( "len", length() );
_this.setAttribute( "muted", isMuted() );
_this.setAttribute( "src", sampleFile() );
_this.setAttribute( "off", startTimeOffset() );
if( sampleFile() == "" )
{
QString s;
_this.setAttribute("data", m_sample.toBase64());
}
_this.setAttribute( "sample_rate", m_sample.sampleRate());
if (const auto& c = color())
{
_this.setAttribute("color", c->name());
}
if (m_sample.reversed())
{
_this.setAttribute("reversed", "true");
}
// TODO: start- and end-frame
}
void SampleClip::loadSettings( const QDomElement & _this )
{
if( _this.attribute( "pos" ).toInt() >= 0 )
{
movePosition( _this.attribute( "pos" ).toInt() );
}
if (const auto srcFile = _this.attribute("src"); !srcFile.isEmpty())
{
if (QFileInfo(PathUtil::toAbsolute(srcFile)).exists())
{
setSampleFile(srcFile);
}
else { Engine::getSong()->collectError(QString("%1: %2").arg(tr("Sample not found"), srcFile)); }
}
if( sampleFile().isEmpty() && _this.hasAttribute( "data" ) )
{
auto sampleRate = _this.hasAttribute("sample_rate") ? _this.attribute("sample_rate").toInt() :
Engine::audioEngine()->outputSampleRate();
auto buffer = gui::SampleLoader::createBufferFromBase64(_this.attribute("data"), sampleRate);
m_sample = Sample(std::move(buffer));
}
changeLength( _this.attribute( "len" ).toInt() );
setMuted( _this.attribute( "muted" ).toInt() );
setStartTimeOffset( _this.attribute( "off" ).toInt() );
if (_this.hasAttribute("color"))
{
setColor(QColor{_this.attribute("color")});
}
if(_this.hasAttribute("reversed"))
{
m_sample.setReversed(true);
emit wasReversed(); // tell SampleClipView to update the view
}
}
gui::ClipView * SampleClip::createView( gui::TrackView * _tv )
{
return new gui::SampleClipView( this, _tv );
}
} // namespace lmms
| 7,473
|
C++
|
.cpp
| 251
| 27.494024
| 99
| 0.731492
|
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,752
|
NotePlayHandle.cpp
|
LMMS_lmms/src/core/NotePlayHandle.cpp
|
/*
* NotePlayHandle.cpp - implementation of class NotePlayHandle which manages
* playback of a single note by an instrument
*
* 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 "NotePlayHandle.h"
#include "AudioEngine.h"
#include "BasicFilters.h"
#include "DetuningHelper.h"
#include "InstrumentSoundShaping.h"
#include "InstrumentTrack.h"
#include "Instrument.h"
#include "Song.h"
namespace lmms
{
NotePlayHandle::BaseDetuning::BaseDetuning( DetuningHelper *detuning ) :
m_value( detuning ? detuning->automationClip()->valueAt( 0 ) : 0 )
{
}
NotePlayHandle::NotePlayHandle( InstrumentTrack* instrumentTrack,
const f_cnt_t _offset,
const f_cnt_t _frames,
const Note& n,
NotePlayHandle *parent,
int midiEventChannel,
Origin origin ) :
PlayHandle( PlayHandle::Type::NotePlayHandle, _offset ),
Note( n.length(), n.pos(), n.key(), n.getVolume(), n.getPanning(), n.detuning() ),
m_pluginData( nullptr ),
m_instrumentTrack( instrumentTrack ),
m_frames( 0 ),
m_totalFramesPlayed( 0 ),
m_framesBeforeRelease( 0 ),
m_releaseFramesToDo( 0 ),
m_releaseFramesDone( 0 ),
m_subNotes(),
m_released( false ),
m_releaseStarted( false ),
m_hasMidiNote( false ),
m_hasParent( parent != nullptr ),
m_parent( parent ),
m_hadChildren( false ),
m_muted( false ),
m_patternTrack( nullptr ),
m_origTempo( Engine::getSong()->getTempo() ),
m_origBaseNote( instrumentTrack->baseNote() ),
m_frequency( 0 ),
m_unpitchedFrequency( 0 ),
m_baseDetuning( nullptr ),
m_songGlobalParentOffset( 0 ),
m_midiChannel( midiEventChannel >= 0 ? midiEventChannel : instrumentTrack->midiPort()->realOutputChannel() ),
m_origin( origin ),
m_frequencyNeedsUpdate( false )
{
lock();
if( hasParent() == false )
{
m_baseDetuning = new BaseDetuning( detuning() );
m_instrumentTrack->m_processHandles.push_back( this );
}
else
{
m_baseDetuning = parent->m_baseDetuning;
parent->m_subNotes.push_back( this );
parent->m_hadChildren = true;
m_patternTrack = parent->m_patternTrack;
parent->setUsesBuffer( false );
}
updateFrequency();
setFrames( _frames );
// inform attached components about new MIDI note (used for recording in Piano Roll)
if( m_origin == Origin::MidiInput )
{
m_instrumentTrack->midiNoteOn( *this );
}
if (m_instrumentTrack->instrument() && m_instrumentTrack->instrument()->isSingleStreamed())
{
setUsesBuffer( false );
}
setAudioPort( instrumentTrack->audioPort() );
unlock();
}
NotePlayHandle::~NotePlayHandle()
{
lock();
noteOff( 0 );
if( hasParent() == false )
{
delete m_baseDetuning;
m_instrumentTrack->m_processHandles.removeAll( this );
}
else
{
m_parent->m_subNotes.removeOne( this );
}
if( m_pluginData != nullptr )
{
m_instrumentTrack->deleteNotePluginData( this );
}
if( m_instrumentTrack->m_notes[key()] == this )
{
m_instrumentTrack->m_notes[key()] = nullptr;
}
m_subNotes.clear();
if( buffer() ) releaseBuffer();
unlock();
}
void NotePlayHandle::setVolume( volume_t _volume )
{
Note::setVolume( _volume );
const int baseVelocity = m_instrumentTrack->midiPort()->baseVelocity();
m_instrumentTrack->processOutEvent( MidiEvent( MidiKeyPressure, midiChannel(), midiKey(), midiVelocity( baseVelocity ) ) );
}
void NotePlayHandle::setPanning( panning_t panning )
{
Note::setPanning( panning );
}
int NotePlayHandle::midiKey() const
{
return key() - m_origBaseNote + instrumentTrack()->baseNote();
}
void NotePlayHandle::play( SampleFrame* _working_buffer )
{
if (m_muted)
{
return;
}
// if the note offset falls over to next period, then don't start playback yet
if( offset() >= Engine::audioEngine()->framesPerPeriod() )
{
setOffset( offset() - Engine::audioEngine()->framesPerPeriod() );
return;
}
lock();
// Don't play the note if it falls outside of the user defined key range
// TODO: handle the range check by Microtuner, and if the key becomes "not mapped", save the current frequency
// so that the note release can finish playing using a valid frequency instead of a 1 Hz placeholder
if (key() < m_instrumentTrack->m_firstKeyModel.value() ||
key() > m_instrumentTrack->m_lastKeyModel.value())
{
// Release the note in case it started playing before going out of range
noteOff(0);
// Exit if the note did not start playing before going out of range (i.e. there is no need to play release)
if (m_totalFramesPlayed == 0)
{
unlock();
return;
}
}
/* It is possible for NotePlayHandle::noteOff to be called before NotePlayHandle::play,
* which results in a note-on message being sent without a subsequent note-off message.
* Therefore, we check here whether the note has already been released before sending
* the note-on message. */
if( !m_released
&& m_totalFramesPlayed == 0 && !m_hasMidiNote
&& ( hasParent() || ! m_instrumentTrack->isArpeggioEnabled() ) )
{
m_hasMidiNote = true;
const int baseVelocity = m_instrumentTrack->midiPort()->baseVelocity();
// send MidiNoteOn event
m_instrumentTrack->processOutEvent(
MidiEvent( MidiNoteOn, midiChannel(), midiKey(), midiVelocity( baseVelocity ) ),
TimePos::fromFrames( offset(), Engine::framesPerTick() ),
offset() );
}
if( m_frequencyNeedsUpdate )
{
updateFrequency();
}
// number of frames that can be played this period
f_cnt_t framesThisPeriod = m_totalFramesPlayed == 0
? Engine::audioEngine()->framesPerPeriod() - offset()
: Engine::audioEngine()->framesPerPeriod();
// check if we start release during this period
if( m_released == false &&
instrumentTrack()->isSustainPedalPressed() == false &&
m_totalFramesPlayed + framesThisPeriod > m_frames )
{
noteOff( m_totalFramesPlayed == 0
? ( m_frames + offset() ) // if we have noteon and noteoff during the same period, take offset in account for release frame
: ( m_frames - m_totalFramesPlayed ) ); // otherwise, the offset is already negated and can be ignored
}
// under some circumstances we're called even if there's nothing to play
// therefore do an additional check which fixes crash e.g. when
// decreasing release of an instrument-track while the note is active
if( framesLeft() > 0 )
{
// play note!
m_instrumentTrack->playNote( this, _working_buffer );
}
if( m_released && (!instrumentTrack()->isSustainPedalPressed() ||
m_releaseStarted) )
{
m_releaseStarted = true;
f_cnt_t todo = framesThisPeriod;
// if this note is base-note for arpeggio, always set
// m_releaseFramesToDo to bigger value than m_releaseFramesDone
// because we do not allow NotePlayHandle::isFinished() to be true
// until all sub-notes are completely played and no new ones
// are inserted by arpAndChordsTabWidget::processNote()
if( ! m_subNotes.isEmpty() )
{
m_releaseFramesToDo = m_releaseFramesDone + 2 * Engine::audioEngine()->framesPerPeriod();
}
// look whether we have frames left to be done before release
if( m_framesBeforeRelease )
{
// yes, then look whether these samples can be played
// within one audio-buffer
if( m_framesBeforeRelease <= framesThisPeriod )
{
// yes, then we did less releaseFramesDone
todo -= m_framesBeforeRelease;
m_framesBeforeRelease = 0;
}
else
{
// no, then just decrease framesBeforeRelease
// and wait for next loop... (we're not in
// release-phase yet)
todo = 0;
m_framesBeforeRelease -= framesThisPeriod;
}
}
// look whether we're in release-phase
if( todo && m_releaseFramesDone < m_releaseFramesToDo )
{
// check whether we have to do more frames in current
// loop than left in current loop
if( m_releaseFramesToDo - m_releaseFramesDone >= todo )
{
// yes, then increase number of release-frames
// done
m_releaseFramesDone += todo;
}
else
{
// no, we did all in this loop!
m_releaseFramesDone = m_releaseFramesToDo;
}
}
}
// update internal data
m_totalFramesPlayed += framesThisPeriod;
unlock();
}
f_cnt_t NotePlayHandle::framesLeft() const
{
if( instrumentTrack()->isSustainPedalPressed() )
{
return 4 * Engine::audioEngine()->framesPerPeriod();
}
else if( m_released && actualReleaseFramesToDo() == 0 )
{
return m_framesBeforeRelease;
}
else if( m_released )
{
return m_framesBeforeRelease + m_releaseFramesToDo - m_releaseFramesDone;
}
return m_frames+actualReleaseFramesToDo()-m_totalFramesPlayed;
}
fpp_t NotePlayHandle::framesLeftForCurrentPeriod() const
{
if( m_totalFramesPlayed == 0 )
{
return static_cast<fpp_t>(std::min<f_cnt_t>(framesLeft(), Engine::audioEngine()->framesPerPeriod() - offset()));
}
return static_cast<fpp_t>(std::min<f_cnt_t>(framesLeft(), Engine::audioEngine()->framesPerPeriod()));
}
bool NotePlayHandle::isFromTrack( const Track * _track ) const
{
return m_instrumentTrack == _track || m_patternTrack == _track;
}
void NotePlayHandle::noteOff( const f_cnt_t _s )
{
if( m_released )
{
return;
}
m_released = true;
// first note-off all sub-notes
for( NotePlayHandle * n : m_subNotes )
{
n->lock();
n->noteOff( _s );
n->unlock();
}
// then set some variables indicating release-state
m_framesBeforeRelease = _s;
m_releaseFramesToDo = std::max<f_cnt_t>(0, actualReleaseFramesToDo());
if( m_hasMidiNote )
{
m_hasMidiNote = false;
// send MidiNoteOff event
m_instrumentTrack->processOutEvent(
MidiEvent( MidiNoteOff, midiChannel(), midiKey(), 0 ),
TimePos::fromFrames( _s, Engine::framesPerTick() ),
_s );
}
// inform attached components about MIDI finished (used for recording in Piano Roll)
if (!instrumentTrack()->isSustainPedalPressed())
{
if( m_origin == Origin::MidiInput )
{
setLength( TimePos( static_cast<f_cnt_t>( totalFramesPlayed() / Engine::framesPerTick() ) ) );
m_instrumentTrack->midiNoteOff( *this );
}
}
}
f_cnt_t NotePlayHandle::actualReleaseFramesToDo() const
{
return m_instrumentTrack->m_soundShaping.releaseFrames();
}
void NotePlayHandle::setFrames( const f_cnt_t _frames )
{
m_frames = _frames;
if( m_frames == 0 )
{
m_frames = m_instrumentTrack->beatLen( this );
}
m_origFrames = m_frames;
}
float NotePlayHandle::volumeLevel( const f_cnt_t _frame )
{
return m_instrumentTrack->m_soundShaping.volumeLevel( this, _frame );
}
void NotePlayHandle::mute()
{
// mute all sub-notes
for (const auto& subNote : m_subNotes)
{
subNote->mute();
}
m_muted = true;
}
int NotePlayHandle::index() const
{
const PlayHandleList & playHandles = Engine::audioEngine()->playHandles();
int idx = 0;
for (const auto& playHandle : playHandles)
{
const auto nph = dynamic_cast<const NotePlayHandle*>(playHandle);
if( nph == nullptr || nph->m_instrumentTrack != m_instrumentTrack || nph->isReleased() || nph->hasParent() )
{
continue;
}
if( nph == this )
{
return idx;
}
++idx;
}
return -1;
}
ConstNotePlayHandleList NotePlayHandle::nphsOfInstrumentTrack( const InstrumentTrack * _it, bool _all_ph )
{
const PlayHandleList & playHandles = Engine::audioEngine()->playHandles();
ConstNotePlayHandleList cnphv;
for (const auto& playHandle : playHandles)
{
const auto nph = dynamic_cast<const NotePlayHandle*>(playHandle);
if( nph != nullptr && nph->m_instrumentTrack == _it && ( ( nph->isReleased() == false && nph->hasParent() == false ) || _all_ph == true ) )
{
cnphv.push_back( nph );
}
}
return cnphv;
}
bool NotePlayHandle::operator==( const NotePlayHandle & _nph ) const
{
return length() == _nph.length() &&
pos() == _nph.pos() &&
key() == _nph.key() &&
getVolume() == _nph.getVolume() &&
getPanning() == _nph.getPanning() &&
m_instrumentTrack == _nph.m_instrumentTrack &&
m_frames == _nph.m_frames &&
offset() == _nph.offset() &&
m_totalFramesPlayed == _nph.m_totalFramesPlayed &&
m_released == _nph.m_released &&
m_hasParent == _nph.m_hasParent &&
m_origBaseNote == _nph.m_origBaseNote &&
m_muted == _nph.m_muted &&
m_midiChannel == _nph.m_midiChannel &&
m_origin == _nph.m_origin;
}
void NotePlayHandle::updateFrequency()
{
int masterPitch = m_instrumentTrack->m_useMasterPitchModel.value() ? Engine::getSong()->masterPitch() : 0;
int baseNote = m_instrumentTrack->baseNoteModel()->value();
float detune = m_baseDetuning->value();
float instrumentPitch = m_instrumentTrack->pitchModel()->value();
if (m_instrumentTrack->m_microtuner.enabled())
{
// custom key mapping and scale: get frequency from the microtuner
const auto transposedKey = key() + masterPitch;
if (m_instrumentTrack->isKeyMapped(transposedKey))
{
const auto frequency = m_instrumentTrack->m_microtuner.keyToFreq(transposedKey, baseNote);
m_frequency = frequency * powf(2.f, (detune + instrumentPitch / 100) / 12.f);
m_unpitchedFrequency = frequency * powf(2.f, detune / 12.f);
}
else
{
m_frequency = m_unpitchedFrequency = 0;
}
}
else
{
// default key mapping and 12-TET frequency computation with default 440 Hz base note frequency
const float pitch = (key() - baseNote + masterPitch + detune) / 12.0f;
m_frequency = DefaultBaseFreq * powf(2.0f, pitch + instrumentPitch / (100 * 12.0f));
m_unpitchedFrequency = DefaultBaseFreq * powf(2.0f, pitch);
}
for (auto it : m_subNotes)
{
it->updateFrequency();
}
}
void NotePlayHandle::processTimePos(const TimePos& time, float pitchValue, bool isRecording)
{
if (!detuning() || time < songGlobalParentOffset() + pos()) { return; }
if (isRecording && m_origin == Origin::MidiInput)
{
detuning()->automationClip()->recordValue(time - songGlobalParentOffset() - pos(), pitchValue / 100);
}
else
{
const float v = detuning()->automationClip()->valueAt(time - songGlobalParentOffset() - pos());
if (!approximatelyEqual(v, m_baseDetuning->value()))
{
m_baseDetuning->setValue(v);
updateFrequency();
}
}
}
void NotePlayHandle::resize( const bpm_t _new_tempo )
{
if (origin() == Origin::MidiInput ||
(origin() == Origin::NoteStacking && m_parent->origin() == Origin::MidiInput))
{
// Don't resize notes from MIDI input - they should continue to play
// until the key is released, and their large duration can cause
// overflows in this method.
return;
}
double completed = m_totalFramesPlayed / (double) m_frames;
double new_frames = m_origFrames * m_origTempo / (double) _new_tempo;
m_frames = (f_cnt_t)new_frames;
m_totalFramesPlayed = (f_cnt_t)( completed * new_frames );
for (const auto& subNote : m_subNotes)
{
subNote->resize(_new_tempo);
}
}
NotePlayHandle ** NotePlayHandleManager::s_available;
QReadWriteLock NotePlayHandleManager::s_mutex;
std::atomic_int NotePlayHandleManager::s_availableIndex;
int NotePlayHandleManager::s_size;
void NotePlayHandleManager::init()
{
s_available = new NotePlayHandle*[INITIAL_NPH_CACHE];
auto n = static_cast<NotePlayHandle *>(std::malloc(sizeof(NotePlayHandle) * INITIAL_NPH_CACHE));
for( int i=0; i < INITIAL_NPH_CACHE; ++i )
{
s_available[ i ] = n;
++n;
}
s_availableIndex = INITIAL_NPH_CACHE - 1;
s_size = INITIAL_NPH_CACHE;
}
NotePlayHandle * NotePlayHandleManager::acquire( InstrumentTrack* instrumentTrack,
const f_cnt_t offset,
const f_cnt_t frames,
const Note& noteToPlay,
NotePlayHandle* parent,
int midiEventChannel,
NotePlayHandle::Origin origin )
{
// TODO: use some lockless data structures
s_mutex.lockForWrite();
if (s_availableIndex < 0) { extend(NPH_CACHE_INCREMENT); }
NotePlayHandle * nph = s_available[s_availableIndex--];
s_mutex.unlock();
new( (void*)nph ) NotePlayHandle( instrumentTrack, offset, frames, noteToPlay, parent, midiEventChannel, origin );
return nph;
}
void NotePlayHandleManager::release( NotePlayHandle * nph )
{
nph->NotePlayHandle::~NotePlayHandle();
s_mutex.lockForRead();
s_available[++s_availableIndex] = nph;
s_mutex.unlock();
}
void NotePlayHandleManager::extend( int c )
{
s_size += c;
auto tmp = new NotePlayHandle*[s_size];
delete[] s_available;
s_available = tmp;
auto n = static_cast<NotePlayHandle *>(std::malloc(sizeof(NotePlayHandle) * c));
for( int i=0; i < c; ++i )
{
s_available[++s_availableIndex] = n;
++n;
}
}
void NotePlayHandleManager::free()
{
delete[] s_available;
}
} // namespace lmms
| 17,089
|
C++
|
.cpp
| 532
| 29.421053
| 141
| 0.715635
|
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,753
|
Mixer.cpp
|
LMMS_lmms/src/core/Mixer.cpp
|
/*
* Mixer.cpp - effect mixer for LMMS
*
* Copyright (c) 2008-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 <QDomElement>
#include "AudioEngine.h"
#include "AudioEngineWorkerThread.h"
#include "BufferManager.h"
#include "Mixer.h"
#include "MixHelpers.h"
#include "Song.h"
#include "InstrumentTrack.h"
#include "PatternStore.h"
#include "SampleTrack.h"
#include "TrackContainer.h" // For TrackContainer::TrackList typedef
namespace lmms
{
MixerRoute::MixerRoute( MixerChannel * from, MixerChannel * to, float amount ) :
m_from( from ),
m_to( to ),
m_amount(amount, 0, 1, 0.001f, nullptr,
tr("Amount to send from channel %1 to channel %2").arg(m_from->m_channelIndex).arg(m_to->m_channelIndex))
{
//qDebug( "created: %d to %d", m_from->m_channelIndex, m_to->m_channelIndex );
// create send amount model
}
void MixerRoute::updateName()
{
m_amount.setDisplayName(
tr( "Amount to send from channel %1 to channel %2" ).arg( m_from->m_channelIndex ).arg( m_to->m_channelIndex ) );
}
MixerChannel::MixerChannel( int idx, Model * _parent ) :
m_fxChain( nullptr ),
m_hasInput( false ),
m_stillRunning( false ),
m_peakLeft( 0.0f ),
m_peakRight( 0.0f ),
m_buffer( new SampleFrame[Engine::audioEngine()->framesPerPeriod()] ),
m_muteModel( false, _parent ),
m_soloModel( false, _parent ),
m_volumeModel(1.f, 0.f, 2.f, 0.001f, _parent),
m_name(),
m_lock(),
m_channelIndex( idx ),
m_queued( false ),
m_dependenciesMet(0)
{
zeroSampleFrames(m_buffer, Engine::audioEngine()->framesPerPeriod());
}
MixerChannel::~MixerChannel()
{
delete[] m_buffer;
}
inline void MixerChannel::processed()
{
for( const MixerRoute * receiverRoute : m_sends )
{
if( receiverRoute->receiver()->m_muted == false )
{
receiverRoute->receiver()->incrementDeps();
}
}
}
void MixerChannel::incrementDeps()
{
const auto i = m_dependenciesMet++ + 1;
if( i >= m_receives.size() && ! m_queued )
{
m_queued = true;
AudioEngineWorkerThread::addJob( this );
}
}
void MixerChannel::unmuteForSolo()
{
//TODO: Recursively activate every channel, this channel sends to
m_muteModel.setValue(false);
}
void MixerChannel::doProcessing()
{
const fpp_t fpp = Engine::audioEngine()->framesPerPeriod();
if( m_muted == false )
{
for( MixerRoute * senderRoute : m_receives )
{
MixerChannel * sender = senderRoute->sender();
FloatModel * sendModel = senderRoute->amount();
if( ! sendModel ) qFatal( "Error: no send model found from %d to %d", senderRoute->senderIndex(), m_channelIndex );
if( sender->m_hasInput || sender->m_stillRunning )
{
// figure out if we're getting sample-exact input
ValueBuffer * sendBuf = sendModel->valueBuffer();
ValueBuffer * volBuf = sender->m_volumeModel.valueBuffer();
// mix it's output with this one's output
SampleFrame* ch_buf = sender->m_buffer;
// use sample-exact mixing if sample-exact values are available
if( ! volBuf && ! sendBuf ) // neither volume nor send has sample-exact data...
{
const float v = sender->m_volumeModel.value() * sendModel->value();
MixHelpers::addSanitizedMultiplied( m_buffer, ch_buf, v, fpp );
}
else if( volBuf && sendBuf ) // both volume and send have sample-exact data
{
MixHelpers::addSanitizedMultipliedByBuffers( m_buffer, ch_buf, volBuf, sendBuf, fpp );
}
else if( volBuf ) // volume has sample-exact data but send does not
{
const float v = sendModel->value();
MixHelpers::addSanitizedMultipliedByBuffer( m_buffer, ch_buf, v, volBuf, fpp );
}
else // vice versa
{
const float v = sender->m_volumeModel.value();
MixHelpers::addSanitizedMultipliedByBuffer( m_buffer, ch_buf, v, sendBuf, fpp );
}
m_hasInput = true;
}
}
const float v = m_volumeModel.value();
if( m_hasInput )
{
// only start fxchain when we have input...
m_fxChain.startRunning();
}
m_stillRunning = m_fxChain.processAudioBuffer( m_buffer, fpp, m_hasInput );
SampleFrame peakSamples = getAbsPeakValues(m_buffer, fpp);
m_peakLeft = std::max(m_peakLeft, peakSamples[0] * v);
m_peakRight = std::max(m_peakRight, peakSamples[1] * v);
}
else
{
m_peakLeft = m_peakRight = 0.0f;
}
// increment dependency counter of all receivers
processed();
}
Mixer::Mixer() :
Model( nullptr ),
JournallingObject(),
m_mixerChannels(),
m_lastSoloed(-1)
{
// create master channel
createChannel();
}
Mixer::~Mixer()
{
while (!m_mixerRoutes.empty())
{
deleteChannelSend(m_mixerRoutes.front());
}
while( m_mixerChannels.size() )
{
MixerChannel * f = m_mixerChannels[m_mixerChannels.size() - 1];
m_mixerChannels.pop_back();
delete f;
}
}
int Mixer::createChannel()
{
const int index = m_mixerChannels.size();
// create new channel
m_mixerChannels.push_back( new MixerChannel( index, this ) );
// reset channel state
clearChannel( index );
// if there is a soloed channel, mute the new track
if (m_lastSoloed != -1 && m_mixerChannels[m_lastSoloed]->m_soloModel.value())
{
m_mixerChannels[index]->m_muteBeforeSolo = m_mixerChannels[index]->m_muteModel.value();
m_mixerChannels[index]->m_muteModel.setValue(true);
}
return index;
}
void Mixer::activateSolo()
{
for (auto i = std::size_t{1}; i < m_mixerChannels.size(); ++i)
{
m_mixerChannels[i]->m_muteBeforeSolo = m_mixerChannels[i]->m_muteModel.value();
m_mixerChannels[i]->m_muteModel.setValue( true );
}
}
void Mixer::deactivateSolo()
{
for (auto i = std::size_t{1}; i < m_mixerChannels.size(); ++i)
{
m_mixerChannels[i]->m_muteModel.setValue( m_mixerChannels[i]->m_muteBeforeSolo );
}
}
void Mixer::toggledSolo()
{
int soloedChan = -1;
bool resetSolo = m_lastSoloed != -1;
//untoggle if lastsoloed is entered
if (resetSolo)
{
m_mixerChannels[m_lastSoloed]->m_soloModel.setValue( false );
}
//determine the soloed channel
for (auto i = std::size_t{0}; i < m_mixerChannels.size(); ++i)
{
if (m_mixerChannels[i]->m_soloModel.value() == true)
soloedChan = i;
}
// if no channel is soloed, unmute everything, else mute everything
if (soloedChan != -1)
{
if (resetSolo)
{
deactivateSolo();
activateSolo();
} else {
activateSolo();
}
// unmute the soloed chan and every channel it sends to
m_mixerChannels[soloedChan]->unmuteForSolo();
} else {
deactivateSolo();
}
m_lastSoloed = soloedChan;
}
void Mixer::deleteChannel( int index )
{
// channel deletion is performed between mixer rounds
Engine::audioEngine()->requestChangeInModel();
// go through every instrument and adjust for the channel index change
TrackContainer::TrackList tracks;
auto& songTracks = Engine::getSong()->tracks();
auto& patternStoreTracks = Engine::patternStore()->tracks();
tracks.insert(tracks.end(), songTracks.begin(), songTracks.end());
tracks.insert(tracks.end(), patternStoreTracks.begin(), patternStoreTracks.end());
for( Track* t : tracks )
{
if( t->type() == Track::Type::Instrument )
{
auto inst = dynamic_cast<InstrumentTrack*>(t);
int val = inst->mixerChannelModel()->value(0);
if( val == index )
{
// we are deleting this track's channel send
// send to master
inst->mixerChannelModel()->setValue(0);
}
else if( val > index )
{
// subtract 1 to make up for the missing channel
inst->mixerChannelModel()->setValue(val-1);
}
}
else if( t->type() == Track::Type::Sample )
{
auto strk = dynamic_cast<SampleTrack*>(t);
int val = strk->mixerChannelModel()->value(0);
if( val == index )
{
// we are deleting this track's channel send
// send to master
strk->mixerChannelModel()->setValue(0);
}
else if( val > index )
{
// subtract 1 to make up for the missing channel
strk->mixerChannelModel()->setValue(val-1);
}
}
}
MixerChannel * ch = m_mixerChannels[index];
// delete all of this channel's sends and receives
while (!ch->m_sends.empty())
{
deleteChannelSend(ch->m_sends.front());
}
while (!ch->m_receives.empty())
{
deleteChannelSend(ch->m_receives.front());
}
// if m_lastSoloed was our index, reset it
if (m_lastSoloed == index) { m_lastSoloed = -1; }
// if m_lastSoloed is > delete index, it will move left
else if (m_lastSoloed > index) { --m_lastSoloed; }
// actually delete the channel
m_mixerChannels.erase(m_mixerChannels.begin() + index);
delete ch;
for (auto i = static_cast<std::size_t>(index); i < m_mixerChannels.size(); ++i)
{
validateChannelName( i, i + 1 );
// set correct channel index
m_mixerChannels[i]->m_channelIndex = i;
// now check all routes and update names of the send models
for( MixerRoute * r : m_mixerChannels[i]->m_sends )
{
r->updateName();
}
for( MixerRoute * r : m_mixerChannels[i]->m_receives )
{
r->updateName();
}
}
Engine::audioEngine()->doneChangeInModel();
}
void Mixer::moveChannelLeft( int index )
{
// can't move master or first channel
if (index <= 1 || static_cast<std::size_t>(index) >= m_mixerChannels.size())
{
return;
}
// channels to swap
int a = index - 1, b = index;
// check if m_lastSoloed is one of our swaps
if (m_lastSoloed == a) { m_lastSoloed = b; }
else if (m_lastSoloed == b) { m_lastSoloed = a; }
// go through every instrument and adjust for the channel index change
const TrackContainer::TrackList& songTrackList = Engine::getSong()->tracks();
const TrackContainer::TrackList& patternTrackList = Engine::patternStore()->tracks();
for (const auto& trackList : {songTrackList, patternTrackList})
{
for (const auto& track : trackList)
{
if (track->type() == Track::Type::Instrument)
{
auto inst = (InstrumentTrack*)track;
int val = inst->mixerChannelModel()->value(0);
if( val == a )
{
inst->mixerChannelModel()->setValue(b);
}
else if( val == b )
{
inst->mixerChannelModel()->setValue(a);
}
}
else if (track->type() == Track::Type::Sample)
{
auto strk = (SampleTrack*)track;
int val = strk->mixerChannelModel()->value(0);
if( val == a )
{
strk->mixerChannelModel()->setValue(b);
}
else if( val == b )
{
strk->mixerChannelModel()->setValue(a);
}
}
}
}
// Swap positions in array
qSwap(m_mixerChannels[index], m_mixerChannels[index - 1]);
// Update m_channelIndex of both channels
m_mixerChannels[index]->m_channelIndex = index;
m_mixerChannels[index - 1]->m_channelIndex = index -1;
}
void Mixer::moveChannelRight( int index )
{
moveChannelLeft( index + 1 );
}
MixerRoute * Mixer::createChannelSend( mix_ch_t fromChannel, mix_ch_t toChannel,
float amount )
{
// qDebug( "requested: %d to %d", fromChannel, toChannel );
// find the existing connection
MixerChannel * from = m_mixerChannels[fromChannel];
MixerChannel * to = m_mixerChannels[toChannel];
for (const auto& send : from->m_sends)
{
if (send->receiver() == to)
{
// simply adjust the amount
send->amount()->setValue(amount);
return send;
}
}
// connection does not exist. create a new one
return createRoute( from, to, amount );
}
MixerRoute * Mixer::createRoute( MixerChannel * from, MixerChannel * to, float amount )
{
if( from == to )
{
return nullptr;
}
Engine::audioEngine()->requestChangeInModel();
auto route = new MixerRoute(from, to, amount);
// add us to from's sends
from->m_sends.push_back(route);
// add us to to's receives
to->m_receives.push_back(route);
// add us to mixer's list
Engine::mixer()->m_mixerRoutes.push_back(route);
Engine::audioEngine()->doneChangeInModel();
return route;
}
// delete the connection made by createChannelSend
void Mixer::deleteChannelSend( mix_ch_t fromChannel, mix_ch_t toChannel )
{
// delete the send
MixerChannel * from = m_mixerChannels[fromChannel];
MixerChannel * to = m_mixerChannels[toChannel];
// find and delete the send entry
for (const auto& send : from->m_sends)
{
if (send->receiver() == to)
{
deleteChannelSend(send);
break;
}
}
}
void Mixer::deleteChannelSend( MixerRoute * route )
{
Engine::audioEngine()->requestChangeInModel();
auto removeFromMixerRoute = [route](MixerRouteVector& routeVec)
{
auto it = std::find(routeVec.begin(), routeVec.end(), route);
if (it != routeVec.end()) { routeVec.erase(it); }
};
// remove us from from's sends
removeFromMixerRoute(route->sender()->m_sends);
// remove us from to's receives
removeFromMixerRoute(route->receiver()->m_receives);
// remove us from mixer's list
removeFromMixerRoute(Engine::mixer()->m_mixerRoutes);
delete route;
Engine::audioEngine()->doneChangeInModel();
}
bool Mixer::isInfiniteLoop( mix_ch_t sendFrom, mix_ch_t sendTo )
{
if( sendFrom == sendTo ) return true;
MixerChannel * from = m_mixerChannels[sendFrom];
MixerChannel * to = m_mixerChannels[sendTo];
bool b = checkInfiniteLoop( from, to );
return b;
}
bool Mixer::checkInfiniteLoop( MixerChannel * from, MixerChannel * to )
{
// can't send master to anything
if( from == m_mixerChannels[0] )
{
return true;
}
// can't send channel to itself
if( from == to )
{
return true;
}
// follow sendTo's outputs recursively looking for something that sends
// to sendFrom
for (const auto& send : to->m_sends)
{
if (checkInfiniteLoop(from, send->receiver()))
{
return true;
}
}
return false;
}
// how much does fromChannel send its output to the input of toChannel?
FloatModel * Mixer::channelSendModel( mix_ch_t fromChannel, mix_ch_t toChannel )
{
if( fromChannel == toChannel )
{
return nullptr;
}
const MixerChannel * from = m_mixerChannels[fromChannel];
const MixerChannel * to = m_mixerChannels[toChannel];
for( MixerRoute * route : from->m_sends )
{
if( route->receiver() == to )
{
return route->amount();
}
}
return nullptr;
}
void Mixer::mixToChannel( const SampleFrame* _buf, mix_ch_t _ch )
{
if( m_mixerChannels[_ch]->m_muteModel.value() == false )
{
m_mixerChannels[_ch]->m_lock.lock();
MixHelpers::add( m_mixerChannels[_ch]->m_buffer, _buf, Engine::audioEngine()->framesPerPeriod() );
m_mixerChannels[_ch]->m_hasInput = true;
m_mixerChannels[_ch]->m_lock.unlock();
}
}
void Mixer::prepareMasterMix()
{
zeroSampleFrames(m_mixerChannels[0]->m_buffer, Engine::audioEngine()->framesPerPeriod());
}
void Mixer::masterMix( SampleFrame* _buf )
{
const int fpp = Engine::audioEngine()->framesPerPeriod();
// add the channels that have no dependencies (no incoming senders, ie.
// no receives) to the jobqueue. The channels that have receives get
// added when their senders get processed, which is detected by
// dependency counting.
// also instantly add all muted channels as they don't need to care
// about their senders, and can just increment the deps of their
// recipients right away.
AudioEngineWorkerThread::resetJobQueue( AudioEngineWorkerThread::JobQueue::OperationMode::Dynamic );
for( MixerChannel * ch : m_mixerChannels )
{
ch->m_muted = ch->m_muteModel.value();
if( ch->m_muted ) // instantly "process" muted channels
{
ch->processed();
ch->done();
}
else if( ch->m_receives.size() == 0 )
{
ch->m_queued = true;
AudioEngineWorkerThread::addJob( ch );
}
}
while (m_mixerChannels[0]->state() != ThreadableJob::ProcessingState::Done)
{
bool found = false;
for( MixerChannel * ch : m_mixerChannels )
{
const auto s = ch->state();
if (s == ThreadableJob::ProcessingState::Queued
|| s == ThreadableJob::ProcessingState::InProgress)
{
found = true;
break;
}
}
if( !found )
{
break;
}
AudioEngineWorkerThread::startAndWaitForJobs();
}
// handle sample-exact data in master volume fader
ValueBuffer * volBuf = m_mixerChannels[0]->m_volumeModel.valueBuffer();
if( volBuf )
{
for( int f = 0; f < fpp; f++ )
{
m_mixerChannels[0]->m_buffer[f][0] *= volBuf->values()[f];
m_mixerChannels[0]->m_buffer[f][1] *= volBuf->values()[f];
}
}
const float v = volBuf
? 1.0f
: m_mixerChannels[0]->m_volumeModel.value();
MixHelpers::addSanitizedMultiplied( _buf, m_mixerChannels[0]->m_buffer, v, fpp );
// clear all channel buffers and
// reset channel process state
for( int i = 0; i < numChannels(); ++i)
{
zeroSampleFrames(m_mixerChannels[i]->m_buffer, Engine::audioEngine()->framesPerPeriod());
m_mixerChannels[i]->reset();
m_mixerChannels[i]->m_queued = false;
// also reset hasInput
m_mixerChannels[i]->m_hasInput = false;
m_mixerChannels[i]->m_dependenciesMet = 0;
}
}
void Mixer::clear()
{
while( m_mixerChannels.size() > 1 )
{
deleteChannel(1);
}
clearChannel(0);
}
void Mixer::clearChannel(mix_ch_t index)
{
MixerChannel * ch = m_mixerChannels[index];
ch->m_fxChain.clear();
ch->m_volumeModel.setValue( 1.0f );
ch->m_muteModel.setValue( false );
ch->m_soloModel.setValue( false );
ch->m_name = ( index == 0 ) ? tr( "Master" ) : tr( "Channel %1" ).arg( index );
ch->m_volumeModel.setDisplayName( ch->m_name + ">" + tr( "Volume" ) );
ch->m_muteModel.setDisplayName( ch->m_name + ">" + tr( "Mute" ) );
ch->m_soloModel.setDisplayName( ch->m_name + ">" + tr( "Solo" ) );
ch->setColor(std::nullopt);
// send only to master
if( index > 0)
{
// delete existing sends
while (!ch->m_sends.empty())
{
deleteChannelSend(ch->m_sends.front());
}
// add send to master
createChannelSend( index, 0 );
}
// delete receives
while (!ch->m_receives.empty())
{
deleteChannelSend(ch->m_receives.front());
}
}
void Mixer::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
// save channels
for (auto i = std::size_t{0}; i < m_mixerChannels.size(); ++i)
{
MixerChannel * ch = m_mixerChannels[i];
QDomElement mixch = _doc.createElement( QString( "mixerchannel" ) );
_this.appendChild( mixch );
ch->m_fxChain.saveState( _doc, mixch );
ch->m_volumeModel.saveSettings( _doc, mixch, "volume" );
ch->m_muteModel.saveSettings( _doc, mixch, "muted" );
ch->m_soloModel.saveSettings( _doc, mixch, "soloed" );
mixch.setAttribute("num", static_cast<qulonglong>(i));
mixch.setAttribute( "name", ch->m_name );
if (const auto& color = ch->color()) { mixch.setAttribute("color", color->name()); }
// add the channel sends
for (const auto& send : ch->m_sends)
{
QDomElement sendsDom = _doc.createElement( QString( "send" ) );
mixch.appendChild( sendsDom );
sendsDom.setAttribute("channel", send->receiverIndex());
send->amount()->saveSettings(_doc, sendsDom, "amount");
}
}
}
// make sure we have at least num channels
void Mixer::allocateChannelsTo(int num)
{
if (num <= 0) { return; }
while (static_cast<std::size_t>(num) > m_mixerChannels.size() - 1)
{
createChannel();
// delete the default send to master
deleteChannelSend( m_mixerChannels.size()-1, 0 );
}
}
void Mixer::loadSettings( const QDomElement & _this )
{
clear();
QDomNode node = _this.firstChild();
while( ! node.isNull() )
{
QDomElement mixch = node.toElement();
// index of the channel we are about to load
int num = mixch.attribute( "num" ).toInt();
// allocate enough channels
allocateChannelsTo( num );
m_mixerChannels[num]->m_volumeModel.loadSettings( mixch, "volume" );
m_mixerChannels[num]->m_muteModel.loadSettings( mixch, "muted" );
m_mixerChannels[num]->m_soloModel.loadSettings( mixch, "soloed" );
m_mixerChannels[num]->m_name = mixch.attribute( "name" );
if (mixch.hasAttribute("color"))
{
m_mixerChannels[num]->setColor(QColor{mixch.attribute("color")});
}
m_mixerChannels[num]->m_fxChain.restoreState( mixch.firstChildElement(
m_mixerChannels[num]->m_fxChain.nodeName() ) );
// mixer sends
QDomNodeList chData = mixch.childNodes();
for (auto i = 0; i < chData.length(); ++i)
{
QDomElement chDataItem = chData.at(i).toElement();
if( chDataItem.nodeName() == QString( "send" ) )
{
int sendTo = chDataItem.attribute( "channel" ).toInt();
allocateChannelsTo( sendTo ) ;
MixerRoute * mxr = createChannelSend( num, sendTo, 1.0f );
if( mxr ) mxr->amount()->loadSettings( chDataItem, "amount" );
}
}
node = node.nextSibling();
}
emit dataChanged();
}
void Mixer::validateChannelName( int index, int oldIndex )
{
if( m_mixerChannels[index]->m_name == tr( "Channel %1" ).arg( oldIndex ) )
{
m_mixerChannels[index]->m_name = tr( "Channel %1" ).arg( index );
}
}
bool Mixer::isChannelInUse(int index)
{
// check if the index mixer channel receives audio from any other channel
if (!m_mixerChannels[index]->m_receives.empty())
{
return true;
}
// check if the destination mixer channel on any instrument or sample track is the index mixer channel
TrackContainer::TrackList tracks;
auto& songTracks = Engine::getSong()->tracks();
auto& patternStoreTracks = Engine::patternStore()->tracks();
tracks.insert(tracks.end(), songTracks.begin(), songTracks.end());
tracks.insert(tracks.end(), patternStoreTracks.begin(), patternStoreTracks.end());
for (const auto t : tracks)
{
if (t->type() == Track::Type::Instrument)
{
auto inst = dynamic_cast<InstrumentTrack*>(t);
if (inst->mixerChannelModel()->value() == index)
{
return true;
}
}
else if (t->type() == Track::Type::Sample)
{
auto strack = dynamic_cast<SampleTrack*>(t);
if (strack->mixerChannelModel()->value() == index)
{
return true;
}
}
}
return false;
}
} // namespace lmms
| 22,121
|
C++
|
.cpp
| 729
| 27.578875
| 118
| 0.694231
|
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,754
|
ConfigManager.cpp
|
LMMS_lmms/src/core/ConfigManager.cpp
|
/*
* ConfigManager.cpp - implementation of class ConfigManager
*
* 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 <QDomElement>
#include <QDir>
#include <QMessageBox>
#include <QApplication>
#include <QStandardPaths>
#include <QTextStream>
#include "ConfigManager.h"
#include "MainWindow.h"
#include "ProjectVersion.h"
#include "GuiApplication.h"
#include "lmmsversion.h"
namespace lmms
{
// Vector with all the upgrade methods
const std::vector<ConfigManager::UpgradeMethod> ConfigManager::UPGRADE_METHODS = {
&ConfigManager::upgrade_1_1_90 , &ConfigManager::upgrade_1_1_91,
&ConfigManager::upgrade_1_2_2
};
static inline QString ensureTrailingSlash(const QString & s )
{
if(! s.isEmpty() && !s.endsWith('/') && !s.endsWith('\\'))
{
return s + '/';
}
return s;
}
ConfigManager * ConfigManager::s_instanceOfMe = nullptr;
ConfigManager::ConfigManager() :
m_version(defaultVersion()),
m_configVersion( UPGRADE_METHODS.size() )
{
if (QFileInfo::exists(qApp->applicationDirPath() + PORTABLE_MODE_FILE))
{
initPortableWorkingDir();
}
else
{
initInstalledWorkingDir();
}
m_dataDir = "data:/";
m_vstDir = m_workingDir + "vst/";
m_sf2Dir = m_workingDir + SF2_PATH;
m_gigDir = m_workingDir + GIG_PATH;
m_themeDir = defaultThemeDir();
if (std::getenv("LMMS_DATA_DIR"))
{
QDir::addSearchPath("data", QString::fromLocal8Bit(std::getenv("LMMS_DATA_DIR")));
}
initDevelopmentWorkingDir();
#ifdef LMMS_BUILD_WIN32
QDir::addSearchPath("data", qApp->applicationDirPath() + "/data/");
#else
QDir::addSearchPath("data", qApp->applicationDirPath().section('/', 0, -2) + "/share/lmms/");
#endif
}
ConfigManager::~ConfigManager()
{
saveConfigFile();
}
void ConfigManager::upgrade_1_1_90()
{
// Remove trailing " (bad latency!)" string which was once saved with PulseAudio
if(value("mixer", "audiodev").startsWith("PulseAudio ("))
{
setValue("mixer", "audiodev", "PulseAudio");
}
// MidiAlsaRaw used to store the device info as "Device" instead of "device"
if (value("MidiAlsaRaw", "device").isNull())
{
// copy "device" = "Device" and then delete the old "Device" (further down)
QString oldDevice = value("MidiAlsaRaw", "Device");
setValue("MidiAlsaRaw", "device", oldDevice);
}
if (!value("MidiAlsaRaw", "device").isNull())
{
// delete the old "Device" in the case that we just copied it to "device"
// or if the user somehow set both the "Device" and "device" fields
deleteValue("MidiAlsaRaw", "Device");
}
}
void ConfigManager::upgrade_1_1_91()
{
// rename displaydbv to displaydbfs
if (!value("app", "displaydbv").isNull())
{
setValue("app", "displaydbfs", value("app", "displaydbv"));
deleteValue("app", "displaydbv");
}
}
void ConfigManager::upgrade_1_2_2()
{
// Since mixer has been renamed to audioengine, we need to transfer the
// attributes from the old element to the new one
std::vector<QString> attrs = {
"audiodev", "mididev", "framesperaudiobuffer", "hqaudio", "samplerate"
};
for (auto attr : attrs)
{
if (!value("mixer", attr).isNull())
{
setValue("audioengine", attr, value("mixer", attr));
deleteValue("mixer", attr);
}
}
m_settings.remove("mixer");
}
void ConfigManager::upgrade()
{
// Skip the upgrade if versions match
if (m_version == LMMS_VERSION)
{
return;
}
// Runs all necessary upgrade methods
std::size_t max = std::min(static_cast<std::size_t>(m_configVersion), UPGRADE_METHODS.size());
std::for_each( UPGRADE_METHODS.begin() + max, UPGRADE_METHODS.end(),
[this](UpgradeMethod um)
{
(this->*um)();
}
);
ProjectVersion createdWith = m_version;
// Don't use old themes as they break the UI (i.e. 0.4 != 1.0, etc)
if (createdWith.setCompareType(ProjectVersion::CompareType::Minor) != LMMS_VERSION)
{
m_themeDir = defaultThemeDir();
}
// Bump the version, now that we are upgraded
m_version = LMMS_VERSION;
m_configVersion = UPGRADE_METHODS.size();
}
QString ConfigManager::defaultVersion() const
{
return LMMS_VERSION;
}
bool ConfigManager::enableBlockedPlugins()
{
const char* envVar = getenv("LMMS_ENABLE_BLOCKED_PLUGINS");
return (envVar && *envVar);
}
QStringList ConfigManager::availableVstEmbedMethods()
{
QStringList methods;
methods.append("none");
methods.append("qt");
#ifdef LMMS_BUILD_WIN32
methods.append("win32");
#endif
#ifdef LMMS_BUILD_LINUX
if (static_cast<QGuiApplication*>(QApplication::instance())->
platformName() == "xcb")
{
methods.append("xembed");
}
#endif
return methods;
}
QString ConfigManager::vstEmbedMethod() const
{
QStringList methods = availableVstEmbedMethods();
QString defaultMethod = *(methods.end() - 1);
QString currentMethod = value( "ui", "vstembedmethod", defaultMethod );
return methods.contains(currentMethod) ? currentMethod : defaultMethod;
}
bool ConfigManager::hasWorkingDir() const
{
return QDir(m_workingDir).exists();
}
void ConfigManager::setWorkingDir(const QString & workingDir)
{
m_workingDir = ensureTrailingSlash(QDir::cleanPath(workingDir));
}
void ConfigManager::setVSTDir(const QString & vstDir)
{
m_vstDir = ensureTrailingSlash(vstDir);
}
void ConfigManager::setLADSPADir(const QString & ladspaDir)
{
m_ladspaDir = ladspaDir;
}
void ConfigManager::setSTKDir(const QString & stkDir)
{
#ifdef LMMS_HAVE_STK
m_stkDir = ensureTrailingSlash(stkDir);
#endif
}
void ConfigManager::setSF2Dir(const QString & sf2Dir)
{
m_sf2Dir = sf2Dir;
}
void ConfigManager::setSF2File(const QString & sf2File)
{
#ifdef LMMS_HAVE_FLUIDSYNTH
m_sf2File = sf2File;
#endif
}
void ConfigManager::setGIGDir(const QString & gigDir)
{
m_gigDir = gigDir;
}
void ConfigManager::setThemeDir(const QString & themeDir)
{
m_themeDir = ensureTrailingSlash(themeDir);
}
void ConfigManager::setBackgroundPicFile(const QString & backgroundPicFile)
{
m_backgroundPicFile = backgroundPicFile;
}
void ConfigManager::createWorkingDir()
{
QDir().mkpath(m_workingDir);
QDir().mkpath(userProjectsDir());
QDir().mkpath(userTemplateDir());
QDir().mkpath(userSamplesDir());
QDir().mkpath(userPresetsDir());
QDir().mkpath(userGigDir());
QDir().mkpath(userSf2Dir());
QDir().mkpath(userVstDir());
QDir().mkpath(userLadspaDir());
}
void ConfigManager::addRecentlyOpenedProject(const QString & file)
{
QFileInfo recentFile(file);
if(recentFile.suffix().toLower() == "mmp" ||
recentFile.suffix().toLower() == "mmpz" ||
recentFile.suffix().toLower() == "mpt")
{
m_recentlyOpenedProjects.removeAll(file);
if(m_recentlyOpenedProjects.size() > 50)
{
m_recentlyOpenedProjects.removeLast();
}
m_recentlyOpenedProjects.push_front(file);
ConfigManager::inst()->saveConfigFile();
}
}
QString ConfigManager::value(const QString& cls, const QString& attribute, const QString& defaultVal) const
{
if (m_settings.find(cls) != m_settings.end())
{
for (const auto& setting : m_settings[cls])
{
if (setting.first == attribute)
{
return setting.second;
}
}
}
return defaultVal;
}
void ConfigManager::setValue(const QString & cls,
const QString & attribute,
const QString & value)
{
if(m_settings.contains(cls))
{
for(QPair<QString, QString>& pair : m_settings[cls])
{
if(pair.first == attribute)
{
if (pair.second != value)
{
pair.second = value;
emit valueChanged(cls, attribute, value);
}
return;
}
}
}
// not in map yet, so we have to add it...
m_settings[cls].push_back(qMakePair(attribute, value));
}
void ConfigManager::deleteValue(const QString & cls, const QString & attribute)
{
if(m_settings.contains(cls))
{
for(stringPairVector::iterator it = m_settings[cls].begin();
it != m_settings[cls].end(); ++it)
{
if((*it).first == attribute)
{
m_settings[cls].erase(it);
return;
}
}
}
}
void ConfigManager::loadConfigFile(const QString & configFile)
{
// read the XML file and create DOM tree
// Allow configuration file override through --config commandline option
if (!configFile.isEmpty())
{
m_lmmsRcFile = configFile;
}
QFile cfg_file(m_lmmsRcFile);
QDomDocument dom_tree;
if(cfg_file.open(QIODevice::ReadOnly))
{
QString errorString;
int errorLine, errorCol;
if(dom_tree.setContent(&cfg_file, false, &errorString, &errorLine, &errorCol))
{
// get the head information from the DOM
QDomElement root = dom_tree.documentElement();
QDomNode node = root.firstChild();
// Cache LMMS version
if (!root.attribute("version").isNull()) {
m_version = root.attribute("version");
}
// Get the version of the configuration file (for upgrade purposes)
if( root.attribute("configversion").isNull() )
{
m_configVersion = legacyConfigVersion(); // No configversion attribute found
}
else
{
bool success;
m_configVersion = root.attribute("configversion").toUInt(&success);
if( !success ) qWarning("Config Version conversion failure.");
}
// create the settings-map out of the DOM
while(!node.isNull())
{
if(node.isElement() &&
node.toElement().hasAttributes ())
{
stringPairVector attr;
QDomNamedNodeMap node_attr =
node.toElement().attributes();
for(int i = 0; i < node_attr.count();
++i)
{
QDomNode n = node_attr.item(i);
if(n.isAttr())
{
attr.push_back(qMakePair(n.toAttr().name(),
n.toAttr().value()));
}
}
m_settings[node.nodeName()] = attr;
}
else if(node.nodeName() == "recentfiles")
{
m_recentlyOpenedProjects.clear();
QDomNode n = node.firstChild();
while(!n.isNull())
{
if(n.isElement() && n.toElement().hasAttributes())
{
m_recentlyOpenedProjects <<
n.toElement().attribute("path");
}
n = n.nextSibling();
}
}
node = node.nextSibling();
}
if(value("paths", "theme") != "")
{
m_themeDir = value("paths", "theme");
#ifdef LMMS_BUILD_WIN32
// Detect a QDir/QFile hang on Windows
// see issue #3417 on github
bool badPath = (m_themeDir == "/" || m_themeDir == "\\");
#else
bool badPath = false;
#endif
if(badPath || !QDir(m_themeDir).exists() ||
!QFile(m_themeDir + "/style.css").exists())
{
m_themeDir = defaultThemeDir();
}
m_themeDir = ensureTrailingSlash(m_themeDir);
}
setWorkingDir(value("paths", "workingdir"));
setGIGDir(value("paths", "gigdir") == "" ? gigDir() : value("paths", "gigdir"));
setSF2Dir(value("paths", "sf2dir") == "" ? sf2Dir() : value("paths", "sf2dir"));
setVSTDir(value("paths", "vstdir"));
setLADSPADir(value("paths", "ladspadir"));
#ifdef LMMS_HAVE_STK
setSTKDir(value("paths", "stkdir"));
#endif
#ifdef LMMS_HAVE_FLUIDSYNTH
setSF2File(value("paths", "defaultsf2"));
#endif
setBackgroundPicFile(value("paths", "backgroundtheme"));
}
else if (gui::getGUI() != nullptr)
{
QMessageBox::warning(nullptr, gui::MainWindow::tr("Configuration file"),
gui::MainWindow::tr("Error while parsing configuration file at line %1:%2: %3").
arg(errorLine).
arg(errorCol).
arg(errorString));
}
cfg_file.close();
}
// Plugins are searched recursively, block problematic locations
if( m_vstDir.isEmpty() || m_vstDir == QDir::separator() || m_vstDir == "/" ||
m_vstDir == ensureTrailingSlash( QDir::homePath() ) ||
!QDir( m_vstDir ).exists() )
{
#ifdef LMMS_BUILD_WIN32
QString programFiles = QString::fromLocal8Bit(getenv("ProgramFiles"));
m_vstDir = programFiles + "/VstPlugins/";
#else
m_vstDir = m_workingDir + "plugins/vst/";
#endif
}
if(m_ladspaDir.isEmpty() )
{
m_ladspaDir = userLadspaDir();
}
#ifdef LMMS_HAVE_STK
if(m_stkDir.isEmpty() || m_stkDir == QDir::separator() || m_stkDir == "/" ||
!QDir(m_stkDir).exists())
{
#if defined(LMMS_BUILD_WIN32)
m_stkDir = m_dataDir + "stk/rawwaves/";
#else
// Look for bundled raw waves first
m_stkDir = qApp->applicationDirPath() + "/../share/stk/rawwaves/";
// Try system installations if not exists
if (!QDir(m_stkDir).exists())
{
m_stkDir = "/usr/local/share/stk/rawwaves/";
}
if (!QDir(m_stkDir).exists())
{
m_stkDir = "/usr/share/stk/rawwaves/";
}
#endif
}
#endif // LMMS_HAVE_STK
upgrade();
QStringList searchPaths;
if (std::getenv("LMMS_THEME_PATH"))
searchPaths << std::getenv("LMMS_THEME_PATH");
searchPaths << themeDir() << defaultThemeDir();
QDir::setSearchPaths("resources", searchPaths);
// Create any missing subdirectories in the working dir, but only if the working dir exists
if(hasWorkingDir())
{
createWorkingDir();
}
}
void ConfigManager::saveConfigFile()
{
setValue("paths", "theme", m_themeDir);
setValue("paths", "workingdir", m_workingDir);
setValue("paths", "vstdir", m_vstDir);
setValue("paths", "gigdir", m_gigDir);
setValue("paths", "sf2dir", m_sf2Dir);
setValue("paths", "ladspadir", m_ladspaDir);
#ifdef LMMS_HAVE_STK
setValue("paths", "stkdir", m_stkDir);
#endif
#ifdef LMMS_HAVE_FLUIDSYNTH
setValue("paths", "defaultsf2", m_sf2File);
#endif
setValue("paths", "backgroundtheme", m_backgroundPicFile);
QDomDocument doc("lmms-config-file");
QDomElement lmms_config = doc.createElement("lmms");
lmms_config.setAttribute("version", m_version);
lmms_config.setAttribute("configversion", m_configVersion);
doc.appendChild(lmms_config);
for (auto it = m_settings.begin(); it != m_settings.end(); ++it)
{
QDomElement n = doc.createElement(it.key());
for (const auto& [first, second] : *it)
{
n.setAttribute(first, second);
}
lmms_config.appendChild(n);
}
QDomElement recent_files = doc.createElement("recentfiles");
for (const auto& recentlyOpenedProject : m_recentlyOpenedProjects)
{
QDomElement n = doc.createElement("file");
n.setAttribute("path", recentlyOpenedProject);
recent_files.appendChild(n);
}
lmms_config.appendChild(recent_files);
QString xml = "<?xml version=\"1.0\"?>\n" + doc.toString(2);
QFile outfile(m_lmmsRcFile);
if(!outfile.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
using gui::MainWindow;
QString title, message;
title = MainWindow::tr("Could not open file");
message = MainWindow::tr("Could not open file %1 "
"for writing.\nPlease make "
"sure you have write "
"permission to the file and "
"the directory containing the "
"file and try again!"
).arg(m_lmmsRcFile);
if (gui::getGUI() != nullptr)
{
QMessageBox::critical(nullptr, title, message,
QMessageBox::Ok,
QMessageBox::NoButton);
}
return;
}
outfile.write(xml.toUtf8());
outfile.close();
}
void ConfigManager::initPortableWorkingDir()
{
QString applicationPath = qApp->applicationDirPath();
m_workingDir = applicationPath + "/lmms-workspace/";
m_lmmsRcFile = applicationPath + "/.lmmsrc.xml";
}
void ConfigManager::initInstalledWorkingDir()
{
m_workingDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/lmms/";
m_lmmsRcFile = QDir::home().absolutePath() +"/.lmmsrc.xml";
// Detect < 1.2.0 working directory as a courtesy
if ( QFileInfo( QDir::home().absolutePath() + "/lmms/projects/" ).exists() )
m_workingDir = QDir::home().absolutePath() + "/lmms/";
}
void ConfigManager::initDevelopmentWorkingDir()
{
// If we're in development (lmms is not installed) let's get the source and
// binary directories by reading the CMake Cache
QDir appPath = qApp->applicationDirPath();
// If in tests, get parent directory
if (appPath.dirName() == "tests") {
appPath.cdUp();
}
QFile cmakeCache(appPath.absoluteFilePath("CMakeCache.txt"));
if (cmakeCache.exists()) {
cmakeCache.open(QFile::ReadOnly);
QTextStream stream(&cmakeCache);
// Find the lines containing something like lmms_SOURCE_DIR:static=<dir>
// and lmms_BINARY_DIR:static=<dir>
int done = 0;
while(! stream.atEnd())
{
QString line = stream.readLine();
if (line.startsWith("lmms_SOURCE_DIR:")) {
QString srcDir = line.section('=', -1).trimmed();
QDir::addSearchPath("data", srcDir + "/data/");
done++;
}
if (line.startsWith("lmms_BINARY_DIR:")) {
m_lmmsRcFile = line.section('=', -1).trimmed() + QDir::separator() +
".lmmsrc.xml";
done++;
}
if (done == 2)
{
break;
}
}
cmakeCache.close();
}
}
// If configversion is not present, we will convert the LMMS version to the appropriate
// configuration file version for backwards compatibility.
unsigned int ConfigManager::legacyConfigVersion()
{
ProjectVersion createdWith = m_version;
createdWith.setCompareType(ProjectVersion::CompareType::Build);
if( createdWith < "1.1.90" )
{
return 0;
}
else if( createdWith < "1.1.91" )
{
return 1;
}
else
{
return 2;
}
}
} // namespace lmms
| 17,542
|
C++
|
.cpp
| 603
| 26.179104
| 107
| 0.702243
|
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,755
|
PresetPreviewPlayHandle.cpp
|
LMMS_lmms/src/core/PresetPreviewPlayHandle.cpp
|
/*
* PresetPreviewPlayHandle.cpp - implementation of class PresetPreviewPlayHandle
*
* 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 <QFileInfo>
#include "PresetPreviewPlayHandle.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "Instrument.h"
#include "InstrumentTrack.h"
#include "PluginFactory.h"
#include "ProjectJournal.h"
#include "TrackContainer.h"
#include <atomic>
namespace lmms
{
// invisible track-container which is needed as parent for preview-channels
class PreviewTrackContainer : public TrackContainer
{
public:
PreviewTrackContainer() :
m_previewInstrumentTrack( nullptr ),
m_previewNote( nullptr ),
m_dataMutex()
{
setJournalling( false );
m_previewInstrumentTrack = dynamic_cast<InstrumentTrack *>( Track::create( Track::Type::Instrument, this ) );
m_previewInstrumentTrack->setJournalling( false );
m_previewInstrumentTrack->setPreviewMode( true );
}
~PreviewTrackContainer() override = default;
QString nodeName() const override
{
return "previewtrackcontainer";
}
InstrumentTrack* previewInstrumentTrack()
{
return m_previewInstrumentTrack;
}
NotePlayHandle* previewNote()
{
return m_previewNote.load(std::memory_order_acquire);
}
void setPreviewNote( NotePlayHandle * _note )
{
m_previewNote.store(_note, std::memory_order_release);
}
bool testAndSetPreviewNote( NotePlayHandle * expectedVal, NotePlayHandle * newVal )
{
return m_previewNote.compare_exchange_strong(expectedVal, newVal);
}
void lockData()
{
m_dataMutex.lock();
}
void unlockData()
{
m_dataMutex.unlock();
}
bool isPreviewing()
{
bool ret = !m_dataMutex.tryLock();
if( ret == false )
{
m_dataMutex.unlock();
}
return ret;
}
private:
InstrumentTrack* m_previewInstrumentTrack;
std::atomic<NotePlayHandle*> m_previewNote;
QMutex m_dataMutex;
friend class PresetPreviewPlayHandle;
} ;
PreviewTrackContainer * PresetPreviewPlayHandle::s_previewTC;
PresetPreviewPlayHandle::PresetPreviewPlayHandle( const QString & _preset_file, bool _load_by_plugin, DataFile *dataFile ) :
PlayHandle( Type::PresetPreviewHandle ),
m_previewNote(nullptr)
{
setUsesBuffer( false );
s_previewTC->lockData();
Engine::audioEngine()->requestChangeInModel();
s_previewTC->setPreviewNote( nullptr );
s_previewTC->previewInstrumentTrack()->silenceAllNotes();
Engine::audioEngine()->doneChangeInModel();
const bool j = Engine::projectJournal()->isJournalling();
Engine::projectJournal()->setJournalling( false );
if( _load_by_plugin )
{
Instrument * i = s_previewTC->previewInstrumentTrack()->instrument();
const QString ext = QFileInfo( _preset_file ).
suffix().toLower();
if( i == nullptr || !i->descriptor()->supportsFileType( ext ) )
{
const PluginFactory::PluginInfoAndKey& infoAndKey =
getPluginFactory()->pluginSupportingExtension(ext);
i = s_previewTC->previewInstrumentTrack()->
loadInstrument(infoAndKey.info.name(), &infoAndKey.key);
}
if( i != nullptr )
{
i->loadFile( _preset_file );
}
}
else
{
bool dataFileCreated = false;
if( dataFile == 0 )
{
dataFile = new DataFile( _preset_file );
dataFileCreated = true;
}
s_previewTC->previewInstrumentTrack()->loadTrackSpecificSettings(
dataFile->content().firstChild().toElement());
if( dataFileCreated )
{
delete dataFile;
}
}
dataFile = 0;
// make sure, our preset-preview-track does not appear in any MIDI-
// devices list, so just disable receiving/sending MIDI-events at all
s_previewTC->previewInstrumentTrack()->
midiPort()->setMode( MidiPort::Mode::Disabled );
Engine::audioEngine()->requestChangeInModel();
// create note-play-handle for it
m_previewNote = NotePlayHandleManager::acquire(
s_previewTC->previewInstrumentTrack(), 0,
std::numeric_limits<f_cnt_t>::max() / 2,
Note( 0, 0, DefaultKey, 100 ) );
setAudioPort( s_previewTC->previewInstrumentTrack()->audioPort() );
s_previewTC->setPreviewNote( m_previewNote );
Engine::audioEngine()->addPlayHandle( m_previewNote );
Engine::audioEngine()->doneChangeInModel();
s_previewTC->unlockData();
Engine::projectJournal()->setJournalling( j );
}
PresetPreviewPlayHandle::~PresetPreviewPlayHandle()
{
Engine::audioEngine()->requestChangeInModel();
// not muted by other preset-preview-handle?
if (s_previewTC->testAndSetPreviewNote(m_previewNote, nullptr))
{
m_previewNote->noteOff();
}
Engine::audioEngine()->doneChangeInModel();
}
void PresetPreviewPlayHandle::play( SampleFrame* _working_buffer )
{
// Do nothing; the preview instrument is played by m_previewNote, which
// has been added to the audio engine
}
bool PresetPreviewPlayHandle::isFinished() const
{
return m_previewNote->isMuted();
}
bool PresetPreviewPlayHandle::isFromTrack( const Track * _track ) const
{
return s_previewTC && s_previewTC->previewInstrumentTrack() == _track;
}
void PresetPreviewPlayHandle::init()
{
if( !s_previewTC )
{
s_previewTC = new PreviewTrackContainer;
}
}
void PresetPreviewPlayHandle::cleanup()
{
delete s_previewTC;
s_previewTC = nullptr;
}
ConstNotePlayHandleList PresetPreviewPlayHandle::nphsOfInstrumentTrack(
const InstrumentTrack * _it )
{
ConstNotePlayHandleList cnphv;
if( s_previewTC->previewNote() != nullptr &&
s_previewTC->previewNote()->instrumentTrack() == _it )
{
cnphv.push_back( s_previewTC->previewNote() );
}
return cnphv;
}
bool PresetPreviewPlayHandle::isPreviewing()
{
if (s_previewTC) {
return s_previewTC->isPreviewing();
}
return false;
}
} // namespace lmms
| 6,388
|
C++
|
.cpp
| 210
| 27.919048
| 124
| 0.756628
|
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,756
|
LadspaControl.cpp
|
LMMS_lmms/src/core/LadspaControl.cpp
|
/*
* LadspaControl.cpp - model for controlling a LADSPA port
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* 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 <cstdio>
#include <QDomElement>
#include "LadspaControl.h"
#include "LadspaBase.h"
namespace lmms
{
LadspaControl::LadspaControl( Model * _parent, port_desc_t * _port,
bool _link ) :
Model( _parent ),
m_link( _link ),
m_port( _port ),
m_linkEnabledModel( _link, this, tr( "Link channels" ) ),
m_toggledModel( false, this, m_port->name ),
m_knobModel( 0, 0, 0, 1, this, m_port->name ),
m_tempoSyncKnobModel( 0, 0, 0, 1, m_port->max, this, m_port->name )
{
if( m_link )
{
connect( &m_linkEnabledModel, SIGNAL(dataChanged()),
this, SLOT(linkStateChanged()),
Qt::DirectConnection );
}
switch( m_port->data_type )
{
case BufferDataType::Toggled:
m_toggledModel.setInitValue(
static_cast<bool>( m_port->def ) );
connect( &m_toggledModel, SIGNAL(dataChanged()),
this, SLOT(ledChanged()));
if( m_port->def == 1.0f )
{
m_toggledModel.setValue( true );
}
// TODO: careful: we must prevent saved scales
m_toggledModel.setScaleLogarithmic( m_port->suggests_logscale );
break;
case BufferDataType::Integer:
case BufferDataType::Enum:
m_knobModel.setRange( static_cast<int>( m_port->max ),
static_cast<int>( m_port->min ),
1 + static_cast<int>( m_port->max -
m_port->min ) / 400 );
m_knobModel.setInitValue(
static_cast<int>( m_port->def ) );
connect( &m_knobModel, SIGNAL(dataChanged()),
this, SLOT(knobChanged()));
// TODO: careful: we must prevent saved scales
m_knobModel.setScaleLogarithmic( m_port->suggests_logscale );
break;
case BufferDataType::Floating:
m_knobModel.setRange( m_port->min, m_port->max,
( m_port->max - m_port->min )
/ ( m_port->name.toUpper() == "GAIN"
&& m_port->max == 10.0f ? 4000.0f :
( m_port->suggests_logscale ? 8000000.0f : 800000.0f ) ) );
m_knobModel.setInitValue( m_port->def );
connect( &m_knobModel, SIGNAL(dataChanged()),
this, SLOT(knobChanged()));
// TODO: careful: we must prevent saved scales
m_knobModel.setScaleLogarithmic( m_port->suggests_logscale );
break;
case BufferDataType::Time:
m_tempoSyncKnobModel.setRange( m_port->min, m_port->max,
( m_port->max -
m_port->min ) / 800.0f );
m_tempoSyncKnobModel.setInitValue( m_port->def );
connect( &m_tempoSyncKnobModel, SIGNAL(dataChanged()),
this, SLOT(tempoKnobChanged()));
// TODO: careful: we must prevent saved scales
m_tempoSyncKnobModel.setScaleLogarithmic( m_port->suggests_logscale );
break;
default:
break;
}
}
LADSPA_Data LadspaControl::value()
{
switch( m_port->data_type )
{
case BufferDataType::Toggled:
return static_cast<LADSPA_Data>( m_toggledModel.value() );
case BufferDataType::Integer:
case BufferDataType::Enum:
case BufferDataType::Floating:
return static_cast<LADSPA_Data>( m_knobModel.value() );
case BufferDataType::Time:
return static_cast<LADSPA_Data>( m_tempoSyncKnobModel.value() );
default:
qWarning( "LadspaControl::value(): BAD BAD BAD\n" );
break;
}
return 0;
}
ValueBuffer * LadspaControl::valueBuffer()
{
switch( m_port->data_type )
{
case BufferDataType::Toggled:
case BufferDataType::Integer:
case BufferDataType::Enum:
return nullptr;
case BufferDataType::Floating:
return m_knobModel.valueBuffer();
case BufferDataType::Time:
return m_tempoSyncKnobModel.valueBuffer();
default:
qWarning( "LadspaControl::valueBuffer(): BAD BAD BAD\n" );
break;
}
return nullptr;
}
void LadspaControl::setValue( LADSPA_Data _value )
{
switch( m_port->data_type )
{
case BufferDataType::Toggled:
m_toggledModel.setValue( static_cast<bool>( _value ) );
break;
case BufferDataType::Integer:
case BufferDataType::Enum:
m_knobModel.setValue( static_cast<int>( _value ) );
break;
case BufferDataType::Floating:
m_knobModel.setValue( static_cast<float>( _value ) );
break;
case BufferDataType::Time:
m_tempoSyncKnobModel.setValue( static_cast<float>(
_value ) );
break;
default:
printf("LadspaControl::setValue BAD BAD BAD\n");
break;
}
}
void LadspaControl::saveSettings( QDomDocument& doc,
QDomElement& parent,
const QString& name )
{
QDomElement e = doc.createElement( name );
if( m_link )
{
m_linkEnabledModel.saveSettings( doc, e, "link" );
}
switch( m_port->data_type )
{
case BufferDataType::Toggled:
m_toggledModel.saveSettings( doc, e, "data" );
break;
case BufferDataType::Integer:
case BufferDataType::Enum:
case BufferDataType::Floating:
m_knobModel.saveSettings( doc, e, "data" );
break;
case BufferDataType::Time:
m_tempoSyncKnobModel.saveSettings( doc, e, "data" );
break;
default:
printf("LadspaControl::saveSettings BAD BAD BAD\n");
break;
}
parent.appendChild( e );
}
void LadspaControl::loadSettings( const QDomElement& parent, const QString& name )
{
QString dataModelName = "data";
QString linkModelName = "link";
QDomElement e = parent.namedItem( name ).toElement();
if(e.isNull())
{
// the port exists in the current effect, but not in the
// savefile => it's a new port, so load the default value
if( m_link )
m_linkEnabledModel.setValue(m_linkEnabledModel.initValue());
switch( m_port->data_type )
{
case BufferDataType::Toggled:
m_toggledModel.setValue(m_toggledModel.initValue());
break;
case BufferDataType::Integer:
case BufferDataType::Enum:
case BufferDataType::Floating:
m_knobModel.setValue(m_knobModel.initValue());
break;
case BufferDataType::Time:
m_tempoSyncKnobModel.setValue(m_tempoSyncKnobModel.initValue());
break;
default:
printf("LadspaControl::loadSettings BAD BAD BAD\n");
break;
}
}
else
{
// COMPAT < 1.0.0: detect old data format where there's either no dedicated sub
// element or there's a direct sub element with automation link information
if( e.isNull() || e.hasAttribute( "id" ) )
{
dataModelName = name;
linkModelName = name + "link";
e = parent;
}
if( m_link )
{
m_linkEnabledModel.loadSettings( e, linkModelName );
}
switch( m_port->data_type )
{
case BufferDataType::Toggled:
m_toggledModel.loadSettings( e, dataModelName );
break;
case BufferDataType::Integer:
case BufferDataType::Enum:
case BufferDataType::Floating:
m_knobModel.loadSettings( e, dataModelName );
break;
case BufferDataType::Time:
m_tempoSyncKnobModel.loadSettings( e, dataModelName );
break;
default:
printf("LadspaControl::loadSettings BAD BAD BAD\n");
break;
}
}
}
void LadspaControl::linkControls( LadspaControl * _control )
{
switch( m_port->data_type )
{
case BufferDataType::Toggled:
BoolModel::linkModels( &m_toggledModel, _control->toggledModel() );
break;
case BufferDataType::Integer:
case BufferDataType::Enum:
case BufferDataType::Floating:
FloatModel::linkModels( &m_knobModel, _control->knobModel() );
break;
case BufferDataType::Time:
TempoSyncKnobModel::linkModels( &m_tempoSyncKnobModel,
_control->tempoSyncKnobModel() );
break;
default:
break;
}
}
void LadspaControl::ledChanged()
{
emit changed( m_port->port_id, static_cast<LADSPA_Data>(
m_toggledModel.value() ) );
}
void LadspaControl::knobChanged()
{
emit changed( m_port->port_id, static_cast<LADSPA_Data>(
m_knobModel.value() ) );
}
void LadspaControl::tempoKnobChanged()
{
emit changed( m_port->port_id, static_cast<LADSPA_Data>(
m_tempoSyncKnobModel.value() ) );
}
void LadspaControl::unlinkControls( LadspaControl * _control )
{
switch( m_port->data_type )
{
case BufferDataType::Toggled:
BoolModel::unlinkModels( &m_toggledModel, _control->toggledModel() );
break;
case BufferDataType::Integer:
case BufferDataType::Enum:
case BufferDataType::Floating:
FloatModel::unlinkModels( &m_knobModel, _control->knobModel() );
break;
case BufferDataType::Time:
TempoSyncKnobModel::unlinkModels( &m_tempoSyncKnobModel,
_control->tempoSyncKnobModel() );
break;
default:
break;
}
}
void LadspaControl::linkStateChanged()
{
emit linkChanged( m_port->control_id, m_linkEnabledModel.value() );
}
void LadspaControl::setLink( bool _state )
{
m_linkEnabledModel.setValue( _state );
}
} // namespace lmms
| 9,339
|
C++
|
.cpp
| 312
| 26.522436
| 82
| 0.7103
|
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,757
|
Timeline.cpp
|
LMMS_lmms/src/core/Timeline.cpp
|
/*
* Timeline.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 "Timeline.h"
#include <algorithm>
#include <tuple>
#include <QDomDocument>
#include <QDomElement>
namespace lmms {
void Timeline::setLoopBegin(TimePos begin)
{
std::tie(m_loopBegin, m_loopEnd) = std::minmax(begin, TimePos{m_loopEnd});
}
void Timeline::setLoopEnd(TimePos end)
{
std::tie(m_loopBegin, m_loopEnd) = std::minmax(TimePos{m_loopBegin}, end);
}
void Timeline::setLoopPoints(TimePos begin, TimePos end)
{
std::tie(m_loopBegin, m_loopEnd) = std::minmax(begin, end);
}
void Timeline::setLoopEnabled(bool enabled)
{
if (enabled != m_loopEnabled) {
m_loopEnabled = enabled;
emit loopEnabledChanged(m_loopEnabled);
}
}
void Timeline::setStopBehaviour(StopBehaviour behaviour)
{
if (behaviour != m_stopBehaviour) {
m_stopBehaviour = behaviour;
emit stopBehaviourChanged(m_stopBehaviour);
}
}
void Timeline::saveSettings(QDomDocument& doc, QDomElement& element)
{
element.setAttribute("lp0pos", static_cast<int>(loopBegin()));
element.setAttribute("lp1pos", static_cast<int>(loopEnd()));
element.setAttribute("lpstate", static_cast<int>(loopEnabled()));
element.setAttribute("stopbehaviour", static_cast<int>(stopBehaviour()));
}
void Timeline::loadSettings(const QDomElement& element)
{
setLoopPoints(
static_cast<TimePos>(element.attribute("lp0pos").toInt()),
static_cast<TimePos>(element.attribute("lp1pos").toInt())
);
setLoopEnabled(static_cast<bool>(element.attribute("lpstate").toInt()));
setStopBehaviour(static_cast<StopBehaviour>(element.attribute("stopbehaviour", "1").toInt()));
}
} // namespace lmms
| 2,412
|
C++
|
.cpp
| 71
| 32.126761
| 95
| 0.760842
|
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,758
|
LmmsSemaphore.cpp
|
LMMS_lmms/src/core/LmmsSemaphore.cpp
|
/*
* Semaphore.cpp - Semaphore implementation
*
* Copyright (c) 2022-2022 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.
*
*/
/*
* This code has been copied and adapted from https://github.com/drobilla/jalv
* File src/zix/sem.h
*/
#include "LmmsSemaphore.h"
#if defined(LMMS_BUILD_WIN32)
# include <limits.h>
#else
# include <errno.h>
#endif
#include <system_error>
namespace lmms {
#ifdef LMMS_BUILD_APPLE
Semaphore::Semaphore(unsigned val)
{
kern_return_t rval = semaphore_create(mach_task_self(), &m_sem, SYNC_POLICY_FIFO, val);
if(rval != 0) {
throw std::system_error(rval, std::system_category(), "Could not create semaphore");
}
}
Semaphore::~Semaphore()
{
semaphore_destroy(mach_task_self(), m_sem);
}
void Semaphore::post()
{
semaphore_signal(m_sem);
}
void Semaphore::wait()
{
kern_return_t rval = semaphore_wait(m_sem);
if (rval != KERN_SUCCESS) {
throw std::system_error(rval, std::system_category(), "Waiting for semaphore failed");
}
}
bool Semaphore::tryWait()
{
const mach_timespec_t zero = { 0, 0 };
return semaphore_timedwait(m_sem, zero) == KERN_SUCCESS;
}
#elif defined(LMMS_BUILD_WIN32)
Semaphore::Semaphore(unsigned initial)
{
if(CreateSemaphore(nullptr, initial, LONG_MAX, nullptr) == nullptr) {
throw std::system_error(GetLastError(), std::system_category(), "Could not create semaphore");
}
}
Semaphore::~Semaphore()
{
CloseHandle(m_sem);
}
void Semaphore::post()
{
ReleaseSemaphore(m_sem, 1, nullptr);
}
void Semaphore::wait()
{
if (WaitForSingleObject(m_sem, INFINITE) != WAIT_OBJECT_0) {
throw std::system_error(GetLastError(), std::system_category(), "Waiting for semaphore failed");
}
}
bool Semaphore::tryWait()
{
return WaitForSingleObject(m_sem, 0) == WAIT_OBJECT_0;
}
#else /* !defined(LMMS_BUILD_APPLE) && !defined(LMMS_BUILD_WIN32) */
Semaphore::Semaphore(unsigned initial)
{
if(sem_init(&m_sem, 0, initial) != 0) {
throw std::system_error(errno, std::generic_category(), "Could not create semaphore");
}
}
Semaphore::~Semaphore()
{
sem_destroy(&m_sem);
}
void Semaphore::post()
{
sem_post(&m_sem);
}
void Semaphore::wait()
{
while (sem_wait(&m_sem) != 0) {
if (errno != EINTR) {
throw std::system_error(errno, std::generic_category(), "Waiting for semaphore failed");
}
/* Otherwise, interrupted, so try again. */
}
}
bool Semaphore::tryWait()
{
return (sem_trywait(&m_sem) == 0);
}
#endif
} // namespace lmms
| 3,223
|
C++
|
.cpp
| 118
| 25.525424
| 98
| 0.724351
|
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,759
|
Plugin.cpp
|
LMMS_lmms/src/core/Plugin.cpp
|
/*
* Plugin.cpp - implementation of plugin-class including plugin-loader
*
* 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 "Plugin.h"
#include <QtGlobal>
#include <QDomElement>
#include <QLibrary>
#include <QMessageBox>
#include "embed.h"
#include "Engine.h"
#include "GuiApplication.h"
#include "DummyPlugin.h"
#include "AutomatableModel.h"
#include "Song.h"
#include "PluginFactory.h"
namespace lmms
{
static PixmapLoader dummyLoader;
static Plugin::Descriptor dummyPluginDescriptor =
{
"dummy",
"dummy",
QT_TRANSLATE_NOOP( "PluginBrowser", "no description" ),
"Tobias Doerffel <tobydox/at/users.sf.net>",
0x0100,
Plugin::Type::Undefined,
&dummyLoader,
nullptr
} ;
Plugin::Plugin(const Descriptor * descriptor, Model * parent, const
Descriptor::SubPluginFeatures::Key* key) :
Model(parent),
JournallingObject(),
m_descriptor(descriptor),
m_key(key ? *key : Descriptor::SubPluginFeatures::Key(m_descriptor))
{
if( m_descriptor == nullptr )
{
m_descriptor = &dummyPluginDescriptor;
}
}
template<class T>
T use_this_or(T this_param, T or_param)
{
return this_param ? this_param : or_param;
}
QString use_this_or(QString this_param, QString or_param)
{
return this_param.isNull() ? or_param : this_param;
}
QString Plugin::displayName() const
{
return Model::displayName().isEmpty() // currently always empty
? (m_descriptor->subPluginFeatures && m_key.isValid())
// get from sub plugin
? m_key.displayName()
// get from plugin
: m_descriptor->displayName
: Model::displayName();
}
const PixmapLoader* Plugin::logo() const
{
return (m_descriptor->subPluginFeatures && m_key.isValid())
? m_key.logo()
: m_descriptor->logo;
}
QString Plugin::Descriptor::SubPluginFeatures::Key::additionalFileExtensions() const
{
Q_ASSERT(isValid());
return desc->subPluginFeatures
// get from sub plugin
? desc->subPluginFeatures->additionalFileExtensions(*this)
// no sub plugin, so no *additional* file extensions
: QString();
}
QString Plugin::Descriptor::SubPluginFeatures::Key::displayName() const
{
Q_ASSERT(isValid());
return desc->subPluginFeatures
// get from sub plugin
? use_this_or(desc->subPluginFeatures->displayName(*this),
QString::fromUtf8(desc->displayName))
// get from plugin
: desc->displayName;
}
const PixmapLoader* Plugin::Descriptor::SubPluginFeatures::Key::logo() const
{
Q_ASSERT(isValid());
return desc->subPluginFeatures
? use_this_or(desc->subPluginFeatures->logo(*this), desc->logo)
: desc->logo;
}
QString Plugin::Descriptor::SubPluginFeatures::Key::description() const
{
Q_ASSERT(isValid());
return desc->subPluginFeatures
? use_this_or(desc->subPluginFeatures->description(*this),
QString::fromUtf8(desc->description))
: desc->description;
}
void Plugin::loadFile( const QString & )
{
}
AutomatableModel * Plugin::childModel( const QString & )
{
static FloatModel fm;
return &fm;
}
Plugin * Plugin::instantiateWithKey(const QString& pluginName, Model * parent,
const Descriptor::SubPluginFeatures::Key *key,
bool keyFromDnd)
{
if(keyFromDnd)
Q_ASSERT(!key);
const Descriptor::SubPluginFeatures::Key *keyPtr = keyFromDnd
? static_cast<Plugin::Descriptor::SubPluginFeatures::Key*>(Engine::pickDndPluginKey())
: key;
const PluginFactory::PluginInfo& pi = getPluginFactory()->pluginInfo(pluginName.toUtf8());
if(keyPtr)
{
// descriptor is not yet set when loading - set it now
Descriptor::SubPluginFeatures::Key keyCopy = *keyPtr;
keyCopy.desc = pi.descriptor;
return Plugin::instantiate(pluginName, parent, &keyCopy);
}
else
return Plugin::instantiate(pluginName, parent,
// the keys are never touched anywhere
const_cast<Descriptor::SubPluginFeatures::Key *>(keyPtr));
}
Plugin * Plugin::instantiate(const QString& pluginName, Model * parent,
void *data)
{
const PluginFactory::PluginInfo& pi = getPluginFactory()->pluginInfo(pluginName.toUtf8());
Plugin* inst;
if( pi.isNull() )
{
if (gui::getGUI() != nullptr)
{
QMessageBox::information( nullptr,
tr( "Plugin not found" ),
tr( "The plugin \"%1\" wasn't found or could not be loaded!\nReason: \"%2\"" ).
arg( pluginName ).arg( getPluginFactory()->errorString(pluginName) ),
QMessageBox::Ok | QMessageBox::Default );
}
inst = new DummyPlugin();
}
else
{
auto instantiationHook = reinterpret_cast<InstantiationHook>(pi.library->resolve("lmms_plugin_main"));
if (instantiationHook)
{
inst = instantiationHook(parent, data);
if(!inst) {
inst = new DummyPlugin();
}
}
else
{
if (gui::getGUI() != nullptr)
{
QMessageBox::information( nullptr,
tr( "Error while loading plugin" ),
tr( "Failed to load plugin \"%1\"!").arg( pluginName ),
QMessageBox::Ok | QMessageBox::Default );
}
inst = new DummyPlugin();
}
}
return inst;
}
void Plugin::collectErrorForUI( QString errMsg )
{
Engine::getSong()->collectError( errMsg );
}
gui::PluginView * Plugin::createView( QWidget * parent )
{
gui::PluginView * pv = instantiateView( parent );
if( pv != nullptr )
{
pv->setModel( this );
}
return pv;
}
Plugin::Descriptor::SubPluginFeatures::Key::Key( const QDomElement & key ) :
desc( nullptr ),
name( key.attribute( "key" ) ),
attributes()
{
QDomNodeList l = key.elementsByTagName( "attribute" );
for( int i = 0; !l.item( i ).isNull(); ++i )
{
QDomElement e = l.item( i ).toElement();
attributes[e.attribute( "name" )] = e.attribute( "value" );
}
}
QDomElement Plugin::Descriptor::SubPluginFeatures::Key::saveXML(
QDomDocument & doc ) const
{
QDomElement e = doc.createElement( "key" );
for( AttributeMap::ConstIterator it = attributes.begin();
it != attributes.end(); ++it )
{
QDomElement a = doc.createElement( "attribute" );
a.setAttribute( "name", it.key() );
a.setAttribute( "value", it.value() );
e.appendChild( a );
}
return e;
}
} // namespace lmms
| 6,783
|
C++
|
.cpp
| 231
| 26.766234
| 104
| 0.726739
|
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,760
|
main.cpp
|
LMMS_lmms/src/core/main.cpp
|
/*
* main.cpp - just main.cpp which is starting up app...
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2012-2013 Paul Giblock <p/at/pgiblock.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 "lmmsversion.h"
#include "versioninfo.h"
#include "denormals.h"
#include <QDebug>
#include <QFileInfo>
#include <QLocale>
#include <QTimer>
#include <QTranslator>
#include <QApplication>
#include <QMessageBox>
#include <QPushButton>
#include <QTextStream>
#ifdef LMMS_BUILD_WIN32
#include <windows.h>
#endif
#ifdef LMMS_HAVE_PROCESS_H
#include <process.h>
#endif
#ifdef LMMS_HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef LMMS_HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
#include <csignal>
#include "MainApplication.h"
#include "ConfigManager.h"
#include "DataFile.h"
#include "NotePlayHandle.h"
#include "embed.h"
#include "Engine.h"
#include "GuiApplication.h"
#include "ImportFilter.h"
#include "MainWindow.h"
#include "MixHelpers.h"
#include "OutputSettings.h"
#include "ProjectRenderer.h"
#include "RenderManager.h"
#include "Song.h"
#ifdef LMMS_DEBUG_FPE
#include <fenv.h> // For feenableexcept
#include <execinfo.h> // For backtrace and backtrace_symbols_fd
#include <unistd.h> // For STDERR_FILENO
#include <csignal> // To register the signal handler
#endif
#ifdef LMMS_DEBUG_FPE
void signalHandler( int signum ) {
// Get a back trace
void *array[10];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 10);
backtrace_symbols_fd(array, size, STDERR_FILENO);
// cleanup and close up stuff here
// terminate program
exit(signum);
}
#endif
static inline QString baseName( const QString & file )
{
return QFileInfo( file ).absolutePath() + "/" +
QFileInfo( file ).completeBaseName();
}
#ifdef LMMS_BUILD_WIN32
// Workaround for old MinGW
#ifdef __MINGW32__
extern "C" _CRTIMP errno_t __cdecl freopen_s(FILE** _File,
const char *_Filename, const char *_Mode, FILE *_Stream);
#endif
// For qInstallMessageHandler
void consoleMessageHandler(QtMsgType type,
const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
fprintf(stderr, "%s\n", localMsg.constData());
}
#endif // LMMS_BUILD_WIN32
inline void loadTranslation( const QString & tname,
const QString & dir = lmms::ConfigManager::inst()->localeDir() )
{
auto t = new QTranslator(QCoreApplication::instance());
QString name = tname + ".qm";
if (t->load(name, dir))
{
QCoreApplication::instance()->installTranslator(t);
}
}
void printVersion( char *executableName )
{
printf( "LMMS %s\n(%s %s, Qt %s, %s)\n\n"
"Copyright (c) %s\n\n"
"This program is free software; you can redistribute it and/or\n"
"modify it under the terms of the GNU General Public\n"
"License as published by the Free Software Foundation; either\n"
"version 2 of the License, or (at your option) any later version.\n\n"
"Try \"%s --help\" for more information.\n\n", LMMS_VERSION,
LMMS_BUILDCONF_PLATFORM, LMMS_BUILDCONF_MACHINE, QT_VERSION_STR, LMMS_BUILDCONF_COMPILER_VERSION,
LMMS_PROJECT_COPYRIGHT, executableName );
}
void printHelp()
{
printf( "LMMS %s\n"
"Copyright (c) %s\n\n"
"Usage: lmms [global options...] [<action> [action parameters...]]\n\n"
"Actions:\n"
" <no action> [options...] [<project>] Start LMMS in normal GUI mode\n"
" dump <in> Dump XML of compressed file <in>\n"
" compress <in> Compress file <in>\n"
" render <project> [options...] Render given project file\n"
" rendertracks <project> [options...] Render each track to a different file\n"
" upgrade <in> [out] Upgrade file <in> and save as <out>\n"
" Standard out is used if no output file\n"
" is specified\n"
" makebundle <in> [out] Make a project bundle from the project\n"
" file <in> saving the resulting bundle\n"
" as <out>\n"
"\nGlobal options:\n"
" --allowroot Bypass root user startup check (use with\n"
" caution).\n"
" -c, --config <configfile> Get the configuration from <configfile>\n"
" -h, --help Show this usage information and exit.\n"
" -v, --version Show version information and exit.\n"
"\nOptions if no action is given:\n"
" --geometry <geometry> Specify the size and position of\n"
" the main window\n"
" geometry is <xsizexysize+xoffset+yoffsety>.\n"
" --import <in> [-e] Import MIDI or Hydrogen file <in>.\n"
" If -e is specified lmms exits after importing the file.\n"
"\nOptions for \"render\" and \"rendertracks\":\n"
" -a, --float Use 32bit float bit depth\n"
" -b, --bitrate <bitrate> Specify output bitrate in KBit/s\n"
" Default: 160.\n"
" -f, --format <format> Specify format of render-output where\n"
" Format is either 'wav', 'flac', 'ogg' or 'mp3'.\n"
" -i, --interpolation <method> Specify interpolation method\n"
" Possible values:\n"
" - linear\n"
" - sincfastest (default)\n"
" - sincmedium\n"
" - sincbest\n"
" -l, --loop Render as a loop\n"
" -m, --mode Stereo mode used for MP3 export\n"
" Possible values: s, j, m\n"
" s: Stereo\n"
" j: Joint Stereo\n"
" m: Mono\n"
" Default: j\n"
" -o, --output <path> Render into <path>\n"
" For \"render\", provide a file path\n"
" For \"rendertracks\", provide a directory path\n"
" If not specified, render will overwrite the input file\n"
" For \"rendertracks\", this might be required\n"
" -p, --profile <out> Dump profiling information to file <out>\n"
" -s, --samplerate <samplerate> Specify output samplerate in Hz\n"
" Range: 44100 (default) to 192000\n"
" Possible values: 1, 2, 4, 8\n"
" Default: 2\n\n",
LMMS_VERSION, LMMS_PROJECT_COPYRIGHT );
}
void fileCheck( QString &file )
{
QFileInfo fileToCheck( file );
if( !fileToCheck.size() )
{
printf( "The file %s does not have any content.\n",
file.toUtf8().constData() );
exit( EXIT_FAILURE );
}
else if( fileToCheck.isDir() )
{
printf( "%s is a directory.\n",
file.toUtf8().constData() );
exit( EXIT_FAILURE );
}
}
int usageError(const QString& message)
{
qCritical().noquote() << QString("\n%1.\n\nTry \"%2 --help\" for more information.\n\n")
.arg( message ).arg( qApp->arguments()[0] );
return EXIT_FAILURE;
}
int noInputFileError()
{
return usageError( "No input file specified" );
}
int main( int argc, char * * argv )
{
using namespace lmms;
bool coreOnly = false;
bool fullscreen = true;
bool exitAfterImport = false;
bool allowRoot = false;
bool renderLoop = false;
bool renderTracks = false;
QString fileToLoad, fileToImport, renderOut, profilerOutputFile, configFile;
// first of two command-line parsing stages
for (int i = 1; i < argc; ++i)
{
QString arg = argv[i];
if (arg == "--help" || arg == "-h")
{
printHelp();
return EXIT_SUCCESS;
}
else if (arg == "--version" || arg == "-v")
{
printVersion(argv[0]);
return EXIT_SUCCESS;
}
else if (arg == "render" || arg == "--render" || arg == "-r" )
{
coreOnly = true;
}
else if (arg == "rendertracks" || arg == "--rendertracks")
{
coreOnly = true;
renderTracks = true;
}
else if (arg == "--allowroot")
{
allowRoot = true;
}
else if (arg == "--geometry" || arg == "-geometry")
{
if (arg == "--geometry")
{
// Delete the first "-" so Qt recognize the option
strcpy(argv[i], "-geometry");
}
// option -geometry is filtered by Qt later,
// so we need to check its presence now to
// determine, if the application should run in
// fullscreen mode (default, no -geometry given).
fullscreen = false;
}
}
#ifdef LMMS_DEBUG_FPE
// Enable exceptions for certain floating point results
// FE_UNDERFLOW is disabled for the time being
feenableexcept( FE_INVALID |
FE_DIVBYZERO |
FE_OVERFLOW /*|
FE_UNDERFLOW*/);
// Install the trap handler
// register signal SIGFPE and signal handler
signal(SIGFPE, signalHandler);
#endif
#ifdef LMMS_BUILD_WIN32
// Don't touch redirected streams here
// GetStdHandle should be called before AttachConsole
HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE hStdErr = GetStdHandle(STD_ERROR_HANDLE);
FILE *fIn, *fOut, *fErr;
// Enable console output if available
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
if (!hStdIn)
{
freopen_s(&fIn, "CONIN$", "r", stdin);
}
if (!hStdOut)
{
freopen_s(&fOut, "CONOUT$", "w", stdout);
}
if (!hStdErr)
{
freopen_s(&fErr, "CONOUT$", "w", stderr);
}
}
// Make Qt's debug message handlers work
qInstallMessageHandler(consoleMessageHandler);
#endif
#if defined(LMMS_HAVE_SYS_PRCTL_H) && defined(PR_SET_CHILD_SUBREAPER)
// Set the "child subreaper" attribute so that plugin child processes remain as lmms'
// children even when some wrapper process exits, as it may happen with wine
if (prctl(PR_SET_CHILD_SUBREAPER, 1))
{
perror("prctl(PR_SET_CHILD_SUBREAPER)");
}
#endif
// initialize memory managers
NotePlayHandleManager::init();
// intialize RNG
srand( getpid() + time( 0 ) );
disable_denormals();
#if !defined(LMMS_BUILD_WIN32) && !defined(LMMS_BUILD_HAIKU)
if ( ( getuid() == 0 || geteuid() == 0 ) && !allowRoot )
{
printf( "LMMS cannot be run as root.\nUse \"--allowroot\" to override.\n\n" );
return EXIT_FAILURE;
}
#endif
#ifdef LMMS_BUILD_LINUX
// don't let OS steal the menu bar. FIXME: only effective on Qt4
QCoreApplication::setAttribute( Qt::AA_DontUseNativeMenuBar );
#endif
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QCoreApplication * app = coreOnly ?
new QCoreApplication( argc, argv ) :
new gui::MainApplication(argc, argv);
AudioEngine::qualitySettings qs(AudioEngine::qualitySettings::Interpolation::Linear);
OutputSettings os( 44100, OutputSettings::BitRateSettings(160, false), OutputSettings::BitDepth::Depth16Bit, OutputSettings::StereoMode::JointStereo );
ProjectRenderer::ExportFileFormat eff = ProjectRenderer::ExportFileFormat::Wave;
// second of two command-line parsing stages
for( int i = 1; i < argc; ++i )
{
QString arg = argv[i];
if (arg == "upgrade" || arg == "--upgrade" || arg == "-u")
{
++i;
if( i == argc )
{
return noInputFileError();
}
DataFile dataFile( QString::fromLocal8Bit( argv[i] ) );
if( argc > i+1 ) // output file specified
{
dataFile.writeFile( QString::fromLocal8Bit( argv[i+1] ) );
}
else // no output file specified; use stdout
{
QTextStream ts( stdout );
dataFile.write( ts );
fflush( stdout );
}
return EXIT_SUCCESS;
}
else if (arg == "makebundle")
{
++i;
if (i == argc)
{
return noInputFileError();
}
DataFile dataFile(QString::fromLocal8Bit(argv[i]));
if (argc > i+1) // Project bundle file name given
{
printf("Making bundle\n");
dataFile.writeFile(QString::fromLocal8Bit(argv[i+1]), true);
return EXIT_SUCCESS;
}
else
{
return usageError("No project bundle name given");
}
}
else if( arg == "--allowroot" )
{
// Ignore, processed earlier
#ifdef LMMS_BUILD_WIN32
if( allowRoot )
{
printf( "\nOption \"--allowroot\" will be ignored on this platform.\n\n" );
}
#endif
}
else if( arg == "dump" || arg == "--dump" || arg == "-d" )
{
++i;
if( i == argc )
{
return noInputFileError();
}
QFile f( QString::fromLocal8Bit( argv[i] ) );
f.open( QIODevice::ReadOnly );
QString d = qUncompress( f.readAll() );
printf( "%s\n", d.toUtf8().constData() );
return EXIT_SUCCESS;
}
else if( arg == "compress" || arg == "--compress" )
{
++i;
if( i == argc )
{
return noInputFileError();
}
QFile f( QString::fromLocal8Bit( argv[i] ) );
f.open( QIODevice::ReadOnly );
QByteArray d = qCompress( f.readAll() ) ;
fwrite( d.constData(), sizeof(char), d.size(), stdout );
return EXIT_SUCCESS;
}
else if( arg == "render" || arg == "--render" || arg == "-r" ||
arg == "rendertracks" || arg == "--rendertracks" )
{
++i;
if( i == argc )
{
return noInputFileError();
}
fileToLoad = QString::fromLocal8Bit( argv[i] );
renderOut = fileToLoad;
}
else if( arg == "--loop" || arg == "-l" )
{
renderLoop = true;
}
else if( arg == "--output" || arg == "-o" )
{
++i;
if( i == argc )
{
return usageError( "No output file specified" );
}
renderOut = QString::fromLocal8Bit( argv[i] );
}
else if( arg == "--format" || arg == "-f" )
{
++i;
if( i == argc )
{
return usageError( "No output format specified" );
}
const QString ext = QString( argv[i] );
if( ext == "wav" )
{
eff = ProjectRenderer::ExportFileFormat::Wave;
}
#ifdef LMMS_HAVE_OGGVORBIS
else if( ext == "ogg" )
{
eff = ProjectRenderer::ExportFileFormat::Ogg;
}
#endif
#ifdef LMMS_HAVE_MP3LAME
else if( ext == "mp3" )
{
eff = ProjectRenderer::ExportFileFormat::MP3;
}
#endif
else if (ext == "flac")
{
eff = ProjectRenderer::ExportFileFormat::Flac;
}
else
{
return usageError( QString( "Invalid output format %1" ).arg( argv[i] ) );
}
}
else if( arg == "--samplerate" || arg == "-s" )
{
++i;
if( i == argc )
{
return usageError( "No samplerate specified" );
}
sample_rate_t sr = QString( argv[i] ).toUInt();
if( sr >= 44100 && sr <= 192000 )
{
os.setSampleRate(sr);
}
else
{
return usageError( QString( "Invalid samplerate %1" ).arg( argv[i] ) );
}
}
else if( arg == "--bitrate" || arg == "-b" )
{
++i;
if( i == argc )
{
return usageError( "No bitrate specified" );
}
int br = QString( argv[i] ).toUInt();
if( br >= 64 && br <= 384 )
{
OutputSettings::BitRateSettings bitRateSettings = os.getBitRateSettings();
bitRateSettings.setBitRate(br);
os.setBitRateSettings(bitRateSettings);
}
else
{
return usageError( QString( "Invalid bitrate %1" ).arg( argv[i] ) );
}
}
else if( arg == "--mode" || arg == "-m" )
{
++i;
if( i == argc )
{
return usageError( "No stereo mode specified" );
}
QString const mode( argv[i] );
if( mode == "s" )
{
os.setStereoMode(OutputSettings::StereoMode::Stereo);
}
else if( mode == "j" )
{
os.setStereoMode(OutputSettings::StereoMode::JointStereo);
}
else if( mode == "m" )
{
os.setStereoMode(OutputSettings::StereoMode::Mono);
}
else
{
return usageError( QString( "Invalid stereo mode %1" ).arg( argv[i] ) );
}
}
else if( arg =="--float" || arg == "-a" )
{
os.setBitDepth(OutputSettings::BitDepth::Depth32Bit);
}
else if( arg == "--interpolation" || arg == "-i" )
{
++i;
if( i == argc )
{
return usageError( "No interpolation method specified" );
}
const QString ip = QString( argv[i] );
if( ip == "linear" )
{
qs.interpolation = AudioEngine::qualitySettings::Interpolation::Linear;
}
else if( ip == "sincfastest" )
{
qs.interpolation = AudioEngine::qualitySettings::Interpolation::SincFastest;
}
else if( ip == "sincmedium" )
{
qs.interpolation = AudioEngine::qualitySettings::Interpolation::SincMedium;
}
else if( ip == "sincbest" )
{
qs.interpolation = AudioEngine::qualitySettings::Interpolation::SincBest;
}
else
{
return usageError( QString( "Invalid interpolation method %1" ).arg( argv[i] ) );
}
}
else if( arg == "--import" )
{
++i;
if( i == argc )
{
return usageError( "No file specified for importing" );
}
fileToImport = QString::fromLocal8Bit( argv[i] );
// exit after import? (only for debugging)
if( QString( argv[i + 1] ) == "-e" )
{
exitAfterImport = true;
++i;
}
}
else if( arg == "--profile" || arg == "-p" )
{
++i;
if( i == argc )
{
return usageError( "No profile specified" );
}
profilerOutputFile = QString::fromLocal8Bit( argv[i] );
}
else if( arg == "--config" || arg == "-c" )
{
++i;
if( i == argc )
{
return usageError( "No configuration file specified" );
}
configFile = QString::fromLocal8Bit( argv[i] );
}
else
{
if( argv[i][0] == '-' )
{
return usageError( QString( "Invalid option %1" ).arg( argv[i] ) );
}
fileToLoad = QString::fromLocal8Bit( argv[i] );
}
}
// Test file argument before continuing
if( !fileToLoad.isEmpty() )
{
fileCheck( fileToLoad );
}
else if( !fileToImport.isEmpty() )
{
fileCheck( fileToImport );
}
ConfigManager::inst()->loadConfigFile(configFile);
// Hidden settings
MixHelpers::setNaNHandler( ConfigManager::inst()->value( "app",
"nanhandler", "1" ).toInt() );
// set language
QString pos = ConfigManager::inst()->value( "app", "language" );
if( pos.isEmpty() )
{
pos = QLocale::system().name().left( 2 );
}
// load actual translation for LMMS
loadTranslation( pos );
// load translation for Qt-widgets/-dialogs
#ifdef QT_TRANSLATIONS_DIR
// load from the original path first
loadTranslation(QString("qt_") + pos, QT_TRANSLATIONS_DIR);
#endif
// override it with bundled/custom one, if exists
loadTranslation(QString("qt_") + pos, ConfigManager::inst()->localeDir());
#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sa.sa_flags = SA_SIGINFO;
if ( sigemptyset( &sa.sa_mask ) )
{
fprintf( stderr, "Signal initialization failed.\n" );
}
if ( sigaction( SIGPIPE, &sa, nullptr ) )
{
fprintf( stderr, "Signal initialization failed.\n" );
}
#endif
bool destroyEngine = false;
// if we have an output file for rendering, just render the song
// without starting the GUI
if( !renderOut.isEmpty() )
{
Engine::init( true );
destroyEngine = true;
printf( "Loading project...\n" );
Engine::getSong()->loadProject( fileToLoad );
if( Engine::getSong()->isEmpty() )
{
printf("The project %s is empty, aborting!\n", fileToLoad.toUtf8().constData() );
exit( EXIT_FAILURE );
}
printf( "Done\n" );
Engine::getSong()->setExportLoop( renderLoop );
// when rendering multiple tracks, renderOut is a directory
// otherwise, it is a file, so we need to append the file extension
if ( !renderTracks )
{
renderOut = baseName( renderOut ) +
ProjectRenderer::getFileExtensionFromFormat(eff);
}
// create renderer
auto r = new RenderManager(qs, os, eff, renderOut);
QCoreApplication::instance()->connect( r,
SIGNAL(finished()), SLOT(quit()));
// timer for progress-updates
auto t = new QTimer(r);
r->connect( t, SIGNAL(timeout()),
SLOT(updateConsoleProgress()));
t->start( 200 );
if( profilerOutputFile.isEmpty() == false )
{
Engine::audioEngine()->profiler().setOutputFile( profilerOutputFile );
}
// start now!
if ( renderTracks )
{
r->renderTracks();
}
else
{
r->renderProject();
}
}
else // otherwise, start the GUI
{
using namespace lmms::gui;
new GuiApplication();
// re-intialize RNG - shared libraries might have srand() or
// srandom() calls in their init procedure
srand( getpid() + time( 0 ) );
// recover a file?
QString recoveryFile = ConfigManager::inst()->recoveryFile();
bool recoveryFilePresent = QFileInfo( recoveryFile ).exists() &&
QFileInfo( recoveryFile ).isFile();
bool autoSaveEnabled =
ConfigManager::inst()->value( "ui", "enableautosave" ).toInt();
if( recoveryFilePresent )
{
QMessageBox mb;
mb.setWindowTitle( MainWindow::tr( "Project recovery" ) );
mb.setText( QString(
"<html>"
"<p style=\"margin-left:6\">%1</p>"
"<table cellpadding=\"3\">"
" <tr>"
" <td><b>%2</b></td>"
" <td>%3</td>"
" </tr>"
" <tr>"
" <td><b>%4</b></td>"
" <td>%5</td>"
" </tr>"
"</table>"
"</html>" ).arg(
MainWindow::tr( "There is a recovery file present. "
"It looks like the last session did not end "
"properly or another instance of LMMS is "
"already running. Do you want to recover the "
"project of this session?" ),
MainWindow::tr( "Recover" ),
MainWindow::tr( "Recover the file. Please don't run "
"multiple instances of LMMS when you do this." ),
MainWindow::tr( "Discard" ),
MainWindow::tr( "Launch a default session and delete "
"the restored files. This is not reversible." )
) );
mb.setIcon( QMessageBox::Warning );
mb.setWindowIcon( embed::getIconPixmap( "icon_small" ) );
mb.setWindowFlags( Qt::WindowCloseButtonHint );
// setting all buttons to the same roles allows us
// to have a custom layout
auto discard = mb.addButton(MainWindow::tr("Discard"), QMessageBox::AcceptRole);
auto recover = mb.addButton(MainWindow::tr("Recover"), QMessageBox::AcceptRole);
// have a hidden exit button
auto exit = mb.addButton("", QMessageBox::RejectRole);
exit->setVisible(false);
// set icons
recover->setIcon( embed::getIconPixmap( "recover" ) );
discard->setIcon( embed::getIconPixmap( "discard" ) );
mb.setDefaultButton( recover );
mb.setEscapeButton( exit );
mb.exec();
if( mb.clickedButton() == discard )
{
getGUI()->mainWindow()->sessionCleanup();
}
else if( mb.clickedButton() == recover ) // Recover
{
fileToLoad = recoveryFile;
getGUI()->mainWindow()->setSession( MainWindow::SessionState::Recover );
}
else // Exit
{
return EXIT_SUCCESS;
}
}
// first show the Main Window and then try to load given file
// [Settel] workaround: showMaximized() doesn't work with
// FVWM2 unless the window is already visible -> show() first
getGUI()->mainWindow()->show();
if( fullscreen )
{
getGUI()->mainWindow()->showMaximized();
}
// Handle macOS-style FileOpen QEvents
QString queuedFile = static_cast<MainApplication *>( app )->queuedFile();
if ( !queuedFile.isEmpty() ) {
fileToLoad = queuedFile;
}
if( !fileToLoad.isEmpty() )
{
if( fileToLoad == recoveryFile )
{
Engine::getSong()->createNewProjectFromTemplate( fileToLoad );
}
else
{
Engine::getSong()->loadProject( fileToLoad );
}
}
else if( !fileToImport.isEmpty() )
{
ImportFilter::import( fileToImport, Engine::getSong() );
if( exitAfterImport )
{
return EXIT_SUCCESS;
}
}
// If enabled, open last project if there is one. Else, create
// a new one.
else if( ConfigManager::inst()->
value( "app", "openlastproject" ).toInt() &&
!ConfigManager::inst()->
recentlyOpenedProjects().isEmpty() &&
!recoveryFilePresent )
{
QString f = ConfigManager::inst()->
recentlyOpenedProjects().first();
QFileInfo recentFile( f );
if ( recentFile.exists() &&
recentFile.suffix().toLower() != "mpt" )
{
Engine::getSong()->loadProject( f );
}
else
{
Engine::getSong()->createNewProject();
}
}
else
{
Engine::getSong()->createNewProject();
}
// Finally we start the auto save timer and also trigger the
// autosave one time as recover.mmp is a signal to possible other
// instances of LMMS.
if( autoSaveEnabled )
{
gui::getGUI()->mainWindow()->autoSaveTimerReset();
}
}
const int ret = app->exec();
delete app;
if( destroyEngine )
{
Engine::destroy();
}
// ProjectRenderer::updateConsoleProgress() doesn't return line after render
if( coreOnly )
{
printf( "\n" );
}
#ifdef LMMS_BUILD_WIN32
// Cleanup console
HWND hConsole = GetConsoleWindow();
if (hConsole)
{
SendMessage(hConsole, WM_CHAR, (WPARAM)VK_RETURN, (LPARAM)0);
FreeConsole();
}
#endif
NotePlayHandleManager::free();
return ret;
}
| 25,038
|
C++
|
.cpp
| 849
| 26.241461
| 152
| 0.644114
|
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,761
|
Song.cpp
|
LMMS_lmms/src/core/Song.cpp
|
/*
* Song.cpp - root of the model tree
*
* 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 "Song.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QMessageBox>
#include <algorithm>
#include <cmath>
#include "AutomationTrack.h"
#include "AutomationEditor.h"
#include "ConfigManager.h"
#include "ControllerRackView.h"
#include "ControllerConnection.h"
#include "EnvelopeAndLfoParameters.h"
#include "Mixer.h"
#include "MixerView.h"
#include "GuiApplication.h"
#include "ExportFilter.h"
#include "InstrumentTrack.h"
#include "Keymap.h"
#include "NotePlayHandle.h"
#include "MidiClip.h"
#include "PatternEditor.h"
#include "PatternStore.h"
#include "PatternTrack.h"
#include "PianoRoll.h"
#include "ProjectJournal.h"
#include "ProjectNotes.h"
#include "Scale.h"
#include "SongEditor.h"
#include "TimeLineWidget.h"
#include "PeakController.h"
namespace lmms
{
tick_t TimePos::s_ticksPerBar = DefaultTicksPerBar;
Song::Song() :
TrackContainer(),
m_globalAutomationTrack( dynamic_cast<AutomationTrack *>(
Track::create( Track::Type::HiddenAutomation,
this ) ) ),
m_tempoModel( DefaultTempo, MinTempo, MaxTempo, this, tr( "Tempo" ) ),
m_timeSigModel( this ),
m_oldTicksPerBar( DefaultTicksPerBar ),
m_masterVolumeModel( 100, 0, 200, this, tr( "Master volume" ) ),
m_masterPitchModel( 0, -12, 12, this, tr( "Master pitch" ) ),
m_nLoadingTrack( 0 ),
m_fileName(),
m_oldFileName(),
m_modified( false ),
m_loadOnLaunch( true ),
m_recording( false ),
m_exporting( false ),
m_exportLoop( false ),
m_renderBetweenMarkers( false ),
m_playing( false ),
m_paused( false ),
m_savingProject( false ),
m_loadingProject( false ),
m_isCancelled( false ),
m_playMode( PlayMode::None ),
m_length( 0 ),
m_midiClipToPlay( nullptr ),
m_loopMidiClip( false ),
m_elapsedTicks( 0 ),
m_elapsedBars( 0 ),
m_loopRenderCount(1),
m_loopRenderRemaining(1),
m_oldAutomatedValues()
{
for (double& millisecondsElapsed : m_elapsedMilliSeconds) { millisecondsElapsed = 0; }
connect( &m_tempoModel, SIGNAL(dataChanged()),
this, SLOT(setTempo()), Qt::DirectConnection );
connect( &m_tempoModel, SIGNAL(dataUnchanged()),
this, SLOT(setTempo()), Qt::DirectConnection );
connect( &m_timeSigModel, SIGNAL(dataChanged()),
this, SLOT(setTimeSignature()), Qt::DirectConnection );
connect( Engine::audioEngine(), SIGNAL(sampleRateChanged()), this,
SLOT(updateFramesPerTick()));
connect( &m_masterVolumeModel, SIGNAL(dataChanged()),
this, SLOT(masterVolumeChanged()), Qt::DirectConnection );
/* connect( &m_masterPitchModel, SIGNAL(dataChanged()),
this, SLOT(masterPitchChanged()));*/
qRegisterMetaType<lmms::Note>( "lmms::Note" );
setType( Type::Song );
for (auto& scale : m_scales) {scale = std::make_shared<Scale>();}
for (auto& keymap : m_keymaps) {keymap = std::make_shared<Keymap>();}
}
Song::~Song()
{
m_playing = false;
delete m_globalAutomationTrack;
}
void Song::masterVolumeChanged()
{
Engine::audioEngine()->setMasterGain( m_masterVolumeModel.value() / 100.0f );
}
void Song::setTempo()
{
Engine::audioEngine()->requestChangeInModel();
const auto tempo = (bpm_t)m_tempoModel.value();
PlayHandleList & playHandles = Engine::audioEngine()->playHandles();
for (const auto& playHandle : playHandles)
{
auto nph = dynamic_cast<NotePlayHandle*>(playHandle);
if( nph && !nph->isReleased() )
{
nph->lock();
nph->resize( tempo );
nph->unlock();
}
}
Engine::audioEngine()->doneChangeInModel();
Engine::updateFramesPerTick();
m_vstSyncController.setTempo( tempo );
emit tempoChanged( tempo );
}
void Song::setTimeSignature()
{
TimePos::setTicksPerBar( ticksPerBar() );
emit timeSignatureChanged( m_oldTicksPerBar, ticksPerBar() );
emit dataChanged();
m_oldTicksPerBar = ticksPerBar();
m_vstSyncController.setTimeSignature(
getTimeSigModel().getNumerator(), getTimeSigModel().getDenominator() );
}
void Song::savePlayStartPosition()
{
getTimeline().setPlayStartPosition(getPlayPos());
}
void Song::processNextBuffer()
{
m_vstSyncController.setPlaybackJumped(false);
// If nothing is playing, there is nothing to do
if (!m_playing) { return; }
// At the beginning of the song, we have to reset the LFOs
if (m_playMode == PlayMode::Song && getPlayPos() == 0)
{
EnvelopeAndLfoParameters::instances()->reset();
}
TrackList trackList;
int clipNum = -1; // The number of the clip that will be played
// Determine the list of tracks to play and the clip number
switch (m_playMode)
{
case PlayMode::Song:
trackList = tracks();
break;
case PlayMode::Pattern:
if (Engine::patternStore()->numOfPatterns() > 0)
{
clipNum = Engine::patternStore()->currentPattern();
trackList.push_back(PatternTrack::findPatternTrack(clipNum));
}
break;
case PlayMode::MidiClip:
if (m_midiClipToPlay)
{
clipNum = m_midiClipToPlay->getTrack()->getClipNum(m_midiClipToPlay);
trackList.push_back(m_midiClipToPlay->getTrack());
}
break;
default:
return;
}
// If the playback position is outside of the range [begin, end), move it to
// begin and inform interested parties.
// Returns true if the playback position was moved, else false.
const auto enforceLoop = [this](const TimePos& begin, const TimePos& end)
{
if (getPlayPos() < begin || getPlayPos() >= end)
{
setToTime(begin);
m_vstSyncController.setPlaybackJumped(true);
emit updateSampleTracks();
return true;
}
return false;
};
const auto& timeline = getTimeline();
const auto loopEnabled = !m_exporting && timeline.loopEnabled();
// Ensure playback begins within the loop if it is enabled
if (loopEnabled) { enforceLoop(timeline.loopBegin(), timeline.loopEnd()); }
// Inform VST plugins and sample tracks if the user moved the play head
if (getPlayPos().jumped())
{
m_vstSyncController.setPlaybackJumped(true);
emit updateSampleTracks();
getPlayPos().setJumped(false);
}
const auto framesPerTick = Engine::framesPerTick();
const auto framesPerPeriod = Engine::audioEngine()->framesPerPeriod();
f_cnt_t frameOffsetInPeriod = 0;
while (frameOffsetInPeriod < framesPerPeriod)
{
auto frameOffsetInTick = getPlayPos().currentFrame();
// If a whole tick has elapsed, update the frame and tick count, and check any loops
if (frameOffsetInTick >= framesPerTick)
{
// Transfer any whole ticks from the frame count to the tick count
const auto elapsedTicks = static_cast<int>(frameOffsetInTick / framesPerTick);
getPlayPos().setTicks(getPlayPos().getTicks() + elapsedTicks);
frameOffsetInTick -= elapsedTicks * framesPerTick;
getPlayPos().setCurrentFrame(frameOffsetInTick);
// If we are playing a pattern track, or a MIDI clip with no loop enabled,
// loop back to the beginning when we reach the end
if (m_playMode == PlayMode::Pattern)
{
enforceLoop(TimePos{0}, TimePos{Engine::patternStore()->lengthOfCurrentPattern(), 0});
}
else if (m_playMode == PlayMode::MidiClip && m_loopMidiClip && !loopEnabled)
{
enforceLoop(TimePos{0}, m_midiClipToPlay->length());
}
// Handle loop points, and inform VST plugins of the loop status
if (loopEnabled || (m_loopRenderRemaining > 1 && getPlayPos() >= timeline.loopBegin()))
{
m_vstSyncController.startCycle(
timeline.loopBegin().getTicks(), timeline.loopEnd().getTicks());
// Loop if necessary, and decrement the remaining loops if we did
if (enforceLoop(timeline.loopBegin(), timeline.loopEnd())
&& m_loopRenderRemaining > 1)
{
m_loopRenderRemaining--;
}
}
else
{
m_vstSyncController.stopCycle();
}
}
const f_cnt_t framesUntilNextPeriod = framesPerPeriod - frameOffsetInPeriod;
const auto framesUntilNextTick = static_cast<f_cnt_t>(std::ceil(framesPerTick - frameOffsetInTick));
// We want to proceed to the next buffer or tick, whichever is closer
const auto framesToPlay = std::min(framesUntilNextPeriod, framesUntilNextTick);
if (frameOffsetInPeriod == 0)
{
// First frame of buffer: update VST sync position.
// This must be done after we've corrected the frame/tick count,
// but before actually playing any frames.
m_vstSyncController.setAbsolutePosition(getPlayPos().getTicks()
+ getPlayPos().currentFrame() / static_cast<double>(framesPerTick));
m_vstSyncController.update();
}
if (static_cast<f_cnt_t>(frameOffsetInTick) == 0)
{
// First frame of tick: process automation and play tracks
processAutomations(trackList, getPlayPos(), framesToPlay);
processMetronome(frameOffsetInPeriod);
for (const auto track : trackList)
{
track->play(getPlayPos(), framesToPlay, frameOffsetInPeriod, clipNum);
}
}
// Update frame counters
frameOffsetInPeriod += framesToPlay;
frameOffsetInTick += framesToPlay;
getPlayPos().setCurrentFrame(frameOffsetInTick);
m_elapsedMilliSeconds[static_cast<std::size_t>(m_playMode)] += TimePos::ticksToMilliseconds(framesToPlay / framesPerTick, getTempo());
m_elapsedBars = getPlayPos(PlayMode::Song).getBar();
m_elapsedTicks = (getPlayPos(PlayMode::Song).getTicks() % ticksPerBar()) / 48;
}
}
void Song::processAutomations(const TrackList &tracklist, TimePos timeStart, fpp_t)
{
AutomatedValueMap values;
QSet<const AutomatableModel*> recordedModels;
TrackContainer* container = this;
int clipNum = -1;
switch (m_playMode)
{
case PlayMode::Song:
break;
case PlayMode::Pattern:
{
Q_ASSERT(tracklist.size() == 1);
Q_ASSERT(tracklist.at(0)->type() == Track::Type::Pattern);
auto patternTrack = dynamic_cast<PatternTrack*>(tracklist.at(0));
container = Engine::patternStore();
clipNum = patternTrack->patternIndex();
}
break;
default:
return;
}
values = container->automatedValuesAt(timeStart, clipNum);
const TrackList& tracks = container->tracks();
Track::clipVector clips;
for (Track* track : tracks)
{
if (track->type() == Track::Type::Automation) {
track->getClipsInRange(clips, 0, timeStart);
}
}
// Process recording
for (Clip* clip : clips)
{
auto p = dynamic_cast<AutomationClip *>(clip);
TimePos relTime = timeStart - p->startPosition();
if (p->isRecording() && relTime >= 0 && relTime < p->length())
{
const AutomatableModel* recordedModel = p->firstObject();
p->recordValue(relTime, recordedModel->value<float>());
recordedModels << recordedModel;
}
}
// Checks if an automated model stopped being automated by automation clip
// so we can move the control back to any connected controller again
for (auto it = m_oldAutomatedValues.begin(); it != m_oldAutomatedValues.end(); it++)
{
AutomatableModel * am = it.key();
if (am->controllerConnection() && !values.contains(am))
{
am->setUseControllerValue(true);
}
}
m_oldAutomatedValues = values;
// Apply values
for (auto it = values.begin(); it != values.end(); it++)
{
if (! recordedModels.contains(it.key()))
{
it.key()->setAutomatedValue(it.value());
}
else if (!it.key()->useControllerValue())
{
it.key()->setUseControllerValue(true);
}
}
}
void Song::processMetronome(size_t bufferOffset)
{
const auto currentPlayMode = playMode();
const auto supported = currentPlayMode == PlayMode::MidiClip
|| currentPlayMode == PlayMode::Song
|| currentPlayMode == PlayMode::Pattern;
if (!supported || m_exporting) { return; }
m_metronome.processTick(currentTick(), ticksPerBar(), m_timeSigModel.getNumerator(), bufferOffset);
}
void Song::setModified(bool value)
{
if( !m_loadingProject && m_modified != value)
{
m_modified = value;
emit modified();
}
}
bool Song::isExportDone() const
{
return !isExporting() || getPlayPos() >= m_exportSongEnd;
}
int Song::getExportProgress() const
{
TimePos pos = getPlayPos();
if (pos >= m_exportSongEnd)
{
return 100;
}
else if (pos <= m_exportSongBegin)
{
return 0;
}
else if (pos >= m_exportLoopEnd)
{
pos = (m_exportLoopBegin-m_exportSongBegin) + (m_exportLoopEnd - m_exportLoopBegin) *
m_loopRenderCount + (pos - m_exportLoopEnd);
}
else if ( pos >= m_exportLoopBegin )
{
pos = (m_exportLoopBegin-m_exportSongBegin) + ((m_exportLoopEnd - m_exportLoopBegin) *
(m_loopRenderCount - m_loopRenderRemaining)) + (pos - m_exportLoopBegin);
}
else
{
pos = (pos - m_exportSongBegin);
}
return (float)pos/(float)m_exportEffectiveLength*100.0f;
}
void Song::playSong()
{
m_recording = false;
if( isStopped() == false )
{
stop();
}
m_playMode = PlayMode::Song;
m_playing = true;
m_paused = false;
m_vstSyncController.setPlaybackState( true );
savePlayStartPosition();
emit playbackStateChanged();
}
void Song::record()
{
m_recording = true;
// TODO: Implement
}
void Song::playAndRecord()
{
playSong();
m_recording = true;
}
void Song::playPattern()
{
if( isStopped() == false )
{
stop();
}
m_playMode = PlayMode::Pattern;
m_playing = true;
m_paused = false;
m_vstSyncController.setPlaybackState( true );
savePlayStartPosition();
emit playbackStateChanged();
}
void Song::playMidiClip( const MidiClip* midiClipToPlay, bool loop )
{
if( isStopped() == false )
{
stop();
}
m_midiClipToPlay = midiClipToPlay;
m_loopMidiClip = loop;
if( m_midiClipToPlay != nullptr )
{
m_playMode = PlayMode::MidiClip;
m_playing = true;
m_paused = false;
}
savePlayStartPosition();
emit playbackStateChanged();
}
void Song::updateLength()
{
if (m_loadingProject) { return; }
m_length = 0;
m_tracksMutex.lockForRead();
for (auto track : tracks())
{
if (m_exporting && track->isMuted())
{
continue;
}
const bar_t cur = track->length();
if( cur > m_length )
{
m_length = cur;
}
}
m_tracksMutex.unlock();
emit lengthChanged( m_length );
}
void Song::setPlayPos( tick_t ticks, PlayMode playMode )
{
tick_t ticksFromPlayMode = getPlayPos(playMode).getTicks();
m_elapsedTicks += ticksFromPlayMode - ticks;
m_elapsedMilliSeconds[static_cast<std::size_t>(playMode)] += TimePos::ticksToMilliseconds( ticks - ticksFromPlayMode, getTempo() );
getPlayPos(playMode).setTicks( ticks );
getPlayPos(playMode).setCurrentFrame( 0.0f );
getPlayPos(playMode).setJumped( true );
// send a signal if playposition changes during playback
if( isPlaying() )
{
emit playbackPositionChanged();
emit updateSampleTracks();
}
}
void Song::togglePause()
{
if( m_paused == true )
{
m_playing = true;
m_paused = false;
}
else
{
m_playing = false;
m_paused = true;
Engine::audioEngine()->clear();
}
m_vstSyncController.setPlaybackState( m_playing );
emit playbackStateChanged();
}
void Song::stop()
{
// do not stop/reset things again if we're stopped already
if( m_playMode == PlayMode::None )
{
return;
}
using gui::TimeLineWidget;
// To avoid race conditions with the processing threads
Engine::audioEngine()->requestChangeInModel();
auto& timeline = getTimeline();
m_paused = false;
m_recording = true;
m_playing = false;
switch (timeline.stopBehaviour())
{
case Timeline::StopBehaviour::BackToZero:
getPlayPos().setTicks(0);
m_elapsedMilliSeconds[static_cast<std::size_t>(m_playMode)] = 0;
break;
case Timeline::StopBehaviour::BackToStart:
if (timeline.playStartPosition() >= 0)
{
getPlayPos().setTicks(timeline.playStartPosition().getTicks());
setToTime(timeline.playStartPosition());
timeline.setPlayStartPosition(-1);
}
break;
case Timeline::StopBehaviour::KeepPosition:
break;
}
m_elapsedMilliSeconds[static_cast<std::size_t>(PlayMode::None)] = m_elapsedMilliSeconds[static_cast<std::size_t>(m_playMode)];
getPlayPos(PlayMode::None).setTicks(getPlayPos().getTicks());
getPlayPos().setCurrentFrame( 0 );
m_vstSyncController.setPlaybackState( m_exporting );
m_vstSyncController.setAbsolutePosition(
getPlayPos().getTicks()
+ getPlayPos().currentFrame()
/ (double) Engine::framesPerTick() );
// remove all note-play-handles that are active
Engine::audioEngine()->clear();
// Moves the control of the models that were processed on the last frame
// back to their controllers.
for (auto it = m_oldAutomatedValues.begin(); it != m_oldAutomatedValues.end(); it++)
{
AutomatableModel * am = it.key();
am->setUseControllerValue(true);
}
m_oldAutomatedValues.clear();
m_playMode = PlayMode::None;
Engine::audioEngine()->doneChangeInModel();
emit stopped();
emit playbackStateChanged();
}
void Song::startExport()
{
stop();
m_exporting = true;
updateLength();
const auto& timeline = getTimeline(PlayMode::Song);
if (m_renderBetweenMarkers)
{
m_exportSongBegin = m_exportLoopBegin = timeline.loopBegin();
m_exportSongEnd = m_exportLoopEnd = timeline.loopEnd();
getPlayPos(PlayMode::Song).setTicks(timeline.loopBegin().getTicks());
}
else
{
m_exportSongEnd = TimePos(m_length, 0);
// Handle potentially ridiculous loop points gracefully.
if (m_loopRenderCount > 1 && timeline.loopEnd() > m_exportSongEnd)
{
m_exportSongEnd = timeline.loopEnd();
}
if (!m_exportLoop)
m_exportSongEnd += TimePos(1,0);
m_exportSongBegin = TimePos(0,0);
m_exportLoopBegin = timeline.loopBegin() < m_exportSongEnd && timeline.loopEnd() <= m_exportSongEnd
? timeline.loopBegin()
: TimePos{0};
m_exportLoopEnd = timeline.loopBegin() < m_exportSongEnd && timeline.loopEnd() <= m_exportSongEnd
? timeline.loopEnd()
: TimePos{0};
getPlayPos(PlayMode::Song).setTicks( 0 );
}
m_exportEffectiveLength = (m_exportLoopBegin - m_exportSongBegin) + (m_exportLoopEnd - m_exportLoopBegin)
* m_loopRenderCount + (m_exportSongEnd - m_exportLoopEnd);
m_loopRenderRemaining = m_loopRenderCount;
playSong();
m_vstSyncController.setPlaybackState( true );
}
void Song::stopExport()
{
stop();
m_exporting = false;
m_vstSyncController.setPlaybackState( m_playing );
}
void Song::insertBar()
{
m_tracksMutex.lockForRead();
for (Track* track: tracks())
{
// FIXME journal batch of tracks instead of each track individually
if (track->numOfClips() > 0) { track->addJournalCheckPoint(); }
track->insertBar(getPlayPos(PlayMode::Song));
}
m_tracksMutex.unlock();
}
void Song::removeBar()
{
m_tracksMutex.lockForRead();
for (Track* track: tracks())
{
// FIXME journal batch of tracks instead of each track individually
if (track->numOfClips() > 0) { track->addJournalCheckPoint(); }
track->removeBar(getPlayPos(PlayMode::Song));
}
m_tracksMutex.unlock();
}
void Song::addPatternTrack()
{
Track * t = Track::create(Track::Type::Pattern, this);
Engine::patternStore()->setCurrentPattern(dynamic_cast<PatternTrack*>(t)->patternIndex());
}
void Song::addSampleTrack()
{
( void )Track::create( Track::Type::Sample, this );
}
void Song::addAutomationTrack()
{
( void )Track::create( Track::Type::Automation, this );
}
bpm_t Song::getTempo()
{
return ( bpm_t )m_tempoModel.value();
}
AutomatedValueMap Song::automatedValuesAt(TimePos time, int clipNum) const
{
auto trackList = TrackList{m_globalAutomationTrack};
trackList.insert(trackList.end(), tracks().begin(), tracks().end());
return TrackContainer::automatedValuesFromTracks(trackList, time, clipNum);
}
void Song::clearProject()
{
using gui::getGUI;
Engine::projectJournal()->setJournalling( false );
if( m_playing )
{
stop();
}
for (auto i = std::size_t{0}; i < PlayModeCount; i++)
{
setPlayPos( 0, ( PlayMode )i );
}
Engine::audioEngine()->requestChangeInModel();
if( getGUI() != nullptr && getGUI()->patternEditor() )
{
getGUI()->patternEditor()->m_editor->clearAllTracks();
}
if( getGUI() != nullptr && getGUI()->songEditor() )
{
getGUI()->songEditor()->m_editor->clearAllTracks();
}
if( getGUI() != nullptr && getGUI()->mixerView() )
{
getGUI()->mixerView()->clear();
}
QCoreApplication::sendPostedEvents();
Engine::patternStore()->clearAllTracks();
clearAllTracks();
Engine::mixer()->clear();
if( getGUI() != nullptr && getGUI()->automationEditor() )
{
getGUI()->automationEditor()->setCurrentClip( nullptr );
}
if( getGUI() != nullptr && getGUI()->pianoRoll() )
{
getGUI()->pianoRoll()->reset();
}
m_tempoModel.reset();
m_masterVolumeModel.reset();
m_masterPitchModel.reset();
m_timeSigModel.reset();
// Clear the m_oldAutomatedValues AutomatedValueMap
m_oldAutomatedValues.clear();
AutomationClip::globalAutomationClip( &m_tempoModel )->clear();
AutomationClip::globalAutomationClip( &m_masterVolumeModel )->
clear();
AutomationClip::globalAutomationClip( &m_masterPitchModel )->
clear();
Engine::audioEngine()->doneChangeInModel();
if( getGUI() != nullptr && getGUI()->getProjectNotes() )
{
getGUI()->getProjectNotes()->clear();
}
removeAllControllers();
emit dataChanged();
Engine::projectJournal()->clearJournal();
Engine::projectJournal()->setJournalling( true );
}
// create new file
void Song::createNewProject()
{
QString defaultTemplate = ConfigManager::inst()->userTemplateDir()
+ "default.mpt";
if( QFile::exists( defaultTemplate ) )
{
createNewProjectFromTemplate( defaultTemplate );
return;
}
defaultTemplate = ConfigManager::inst()->factoryProjectsDir()
+ "templates/default.mpt";
if( QFile::exists( defaultTemplate ) )
{
createNewProjectFromTemplate( defaultTemplate );
return;
}
m_loadingProject = true;
clearProject();
Engine::projectJournal()->setJournalling( false );
m_oldFileName = "";
setProjectFileName("");
auto tripleOscTrack = Track::create(Track::Type::Instrument, this);
dynamic_cast<InstrumentTrack*>(tripleOscTrack)->loadInstrument("tripleoscillator");
auto kickerTrack = Track::create(Track::Type::Instrument, Engine::patternStore());
dynamic_cast<InstrumentTrack*>(kickerTrack)->loadInstrument("kicker");
Track::create( Track::Type::Sample, this );
Track::create( Track::Type::Pattern, this );
Track::create( Track::Type::Automation, this );
m_tempoModel.setInitValue( DefaultTempo );
m_timeSigModel.reset();
m_masterVolumeModel.setInitValue( 100 );
m_masterPitchModel.setInitValue( 0 );
QCoreApplication::instance()->processEvents();
m_loadingProject = false;
updateLength();
Engine::patternStore()->updateAfterTrackAdd();
Engine::projectJournal()->setJournalling( true );
QCoreApplication::sendPostedEvents();
setModified(false);
m_loadOnLaunch = false;
}
void Song::createNewProjectFromTemplate( const QString & templ )
{
loadProject( templ );
// clear file-name so that user doesn't overwrite template when
// saving...
m_oldFileName = "";
setProjectFileName("");
// update window title
m_loadOnLaunch = false;
}
// load given song
void Song::loadProject( const QString & fileName )
{
using gui::getGUI;
QDomNode node;
m_loadingProject = true;
Engine::projectJournal()->setJournalling( false );
m_oldFileName = m_fileName;
setProjectFileName(fileName);
DataFile dataFile( m_fileName );
bool cantLoadProject = false;
// if file could not be opened, head-node is null and we create
// new project
if( dataFile.head().isNull() )
{
cantLoadProject = true;
}
else
{
// We check if plugins contain local paths to prevent malicious code being
// added to project bundles and loaded with "local:" paths
if (dataFile.hasLocalPlugins())
{
cantLoadProject = true;
if (getGUI() != nullptr)
{
QMessageBox::critical(nullptr, tr("Aborting project load"),
tr("Project file contains local paths to plugins, which could be used to "
"run malicious code."));
}
else
{
QTextStream(stderr) << tr("Can't load project: "
"Project file contains local paths to plugins.")
#if (QT_VERSION >= QT_VERSION_CHECK(5,15,0))
<< Qt::endl;
#else
<< endl;
#endif
}
}
}
if (cantLoadProject)
{
if( m_loadOnLaunch )
{
createNewProject();
}
setProjectFileName(m_oldFileName);
return;
}
m_oldFileName = m_fileName;
clearProject();
clearErrors();
Engine::audioEngine()->requestChangeInModel();
// get the header information from the DOM
m_tempoModel.loadSettings( dataFile.head(), "bpm" );
m_timeSigModel.loadSettings( dataFile.head(), "timesig" );
m_masterVolumeModel.loadSettings( dataFile.head(), "mastervol" );
m_masterPitchModel.loadSettings( dataFile.head(), "masterpitch" );
getTimeline(PlayMode::Song).setLoopEnabled(false);
if( !dataFile.content().firstChildElement( "track" ).isNull() )
{
m_globalAutomationTrack->restoreState( dataFile.content().
firstChildElement( "track" ) );
}
//Backward compatibility for LMMS <= 0.4.15
PeakController::initGetControllerBySetting();
// Load mixer first to be able to set the correct range for mixer channels
node = dataFile.content().firstChildElement( Engine::mixer()->nodeName() );
if( !node.isNull() )
{
Engine::mixer()->restoreState( node.toElement() );
if( getGUI() != nullptr )
{
// refresh MixerView
getGUI()->mixerView()->refreshDisplay();
}
}
node = dataFile.content().firstChild();
QDomNodeList tclist=dataFile.content().elementsByTagName("trackcontainer");
m_nLoadingTrack=0;
for( int i=0,n=tclist.count(); i<n; ++i )
{
QDomNode nd=tclist.at(i).firstChild();
while(!nd.isNull())
{
if( nd.isElement() && nd.nodeName() == "track" )
{
++m_nLoadingTrack;
if (static_cast<Track::Type>(nd.toElement().attribute("type").toInt()) == Track::Type::Pattern)
{
n += nd.toElement().elementsByTagName("patterntrack").at(0)
.toElement().firstChildElement().childNodes().count();
}
nd=nd.nextSibling();
}
}
}
while( !node.isNull() && !isCancelled() )
{
if( node.isElement() )
{
if( node.nodeName() == "trackcontainer" )
{
( (JournallingObject *)( this ) )->restoreState( node.toElement() );
}
else if( node.nodeName() == "controllers" )
{
restoreControllerStates( node.toElement() );
}
else if (node.nodeName() == "scales")
{
restoreScaleStates(node.toElement());
}
else if (node.nodeName() == "keymaps")
{
restoreKeymapStates(node.toElement());
}
else if( getGUI() != nullptr )
{
if( node.nodeName() == getGUI()->getControllerRackView()->nodeName() )
{
getGUI()->getControllerRackView()->restoreState( node.toElement() );
}
else if( node.nodeName() == getGUI()->pianoRoll()->nodeName() )
{
getGUI()->pianoRoll()->restoreState( node.toElement() );
}
else if( node.nodeName() == getGUI()->automationEditor()->m_editor->nodeName() )
{
getGUI()->automationEditor()->m_editor->restoreState( node.toElement() );
}
else if( node.nodeName() == getGUI()->getProjectNotes()->nodeName() )
{
getGUI()->getProjectNotes()->SerializingObject::restoreState( node.toElement() );
}
else if (node.nodeName() == getTimeline(PlayMode::Song).nodeName())
{
getTimeline(PlayMode::Song).restoreState(node.toElement());
}
}
}
node = node.nextSibling();
}
// quirk for fixing projects with broken positions of Clips inside pattern tracks
Engine::patternStore()->fixIncorrectPositions();
// Connect controller links to their controllers
// now that everything is loaded
ControllerConnection::finalizeConnections();
// Remove dummy controllers that was added for correct connections
m_controllers.erase(std::remove_if(m_controllers.begin(), m_controllers.end(),
[](Controller* c){return c->type() == Controller::ControllerType::Dummy;}),
m_controllers.end());
// resolve all IDs so that autoModels are automated
AutomationClip::resolveAllIDs();
Engine::audioEngine()->doneChangeInModel();
ConfigManager::inst()->addRecentlyOpenedProject( fileName );
Engine::projectJournal()->setJournalling( true );
emit projectLoaded();
if( isCancelled() )
{
m_isCancelled = false;
createNewProject();
return;
}
if ( hasErrors())
{
if ( getGUI() != nullptr )
{
QMessageBox::warning( nullptr, tr("LMMS Error report"), errorSummary(),
QMessageBox::Ok );
}
else
{
#if (QT_VERSION >= QT_VERSION_CHECK(5,15,0))
QTextStream(stderr) << Engine::getSong()->errorSummary() << Qt::endl;
#else
QTextStream(stderr) << Engine::getSong()->errorSummary() << endl;
#endif
}
}
m_loadingProject = false;
updateLength();
setModified(false);
m_loadOnLaunch = false;
}
// only save current song as filename and do nothing else
bool Song::saveProjectFile(const QString & filename, bool withResources)
{
using gui::getGUI;
DataFile dataFile( DataFile::Type::SongProject );
m_savingProject = true;
m_tempoModel.saveSettings( dataFile, dataFile.head(), "bpm" );
m_timeSigModel.saveSettings( dataFile, dataFile.head(), "timesig" );
m_masterVolumeModel.saveSettings( dataFile, dataFile.head(), "mastervol" );
m_masterPitchModel.saveSettings( dataFile, dataFile.head(), "masterpitch" );
saveState( dataFile, dataFile.content() );
m_globalAutomationTrack->saveState( dataFile, dataFile.content() );
Engine::mixer()->saveState( dataFile, dataFile.content() );
if( getGUI() != nullptr )
{
getGUI()->getControllerRackView()->saveState( dataFile, dataFile.content() );
getGUI()->pianoRoll()->saveState( dataFile, dataFile.content() );
getGUI()->automationEditor()->m_editor->saveState( dataFile, dataFile.content() );
getGUI()->getProjectNotes()->SerializingObject::saveState( dataFile, dataFile.content() );
getTimeline(PlayMode::Song).saveState(dataFile, dataFile.content());
}
saveControllerStates( dataFile, dataFile.content() );
saveScaleStates(dataFile, dataFile.content());
saveKeymapStates(dataFile, dataFile.content());
m_savingProject = false;
return dataFile.writeFile(filename, withResources);
}
// Save the current song
bool Song::guiSaveProject()
{
return guiSaveProjectAs(m_fileName);
}
// Save the current song with the given filename
bool Song::guiSaveProjectAs(const QString & filename)
{
DataFile dataFile(DataFile::Type::SongProject);
QString fileNameWithExtension = dataFile.nameWithExtension(filename);
bool withResources = m_saveOptions.saveAsProjectBundle.value();
bool const saveResult = saveProjectFile(fileNameWithExtension, withResources);
// After saving, restore default save options.
m_saveOptions.setDefaultOptions();
// If we saved a bundle, we keep the project on the original
// file and still keep it as modified
if (saveResult && !withResources)
{
setModified(false);
setProjectFileName(fileNameWithExtension);
}
return saveResult;
}
void Song::saveControllerStates( QDomDocument & doc, QDomElement & element )
{
// save settings of controllers
QDomElement controllersNode = doc.createElement( "controllers" );
element.appendChild( controllersNode );
for (const auto& controller : m_controllers)
{
controller->saveState(doc, controllersNode);
}
}
void Song::restoreControllerStates( const QDomElement & element )
{
QDomNode node = element.firstChild();
while( !node.isNull() && !isCancelled() )
{
Controller * c = Controller::create( node.toElement(), this );
if (c) {addController(c);}
else
{
// Fix indices to ensure correct connections
m_controllers.push_back(Controller::create(Controller::ControllerType::Dummy, this));
}
node = node.nextSibling();
}
}
void Song::removeAllControllers()
{
while (m_controllers.size() != 0)
{
removeController(m_controllers.at(0));
}
m_controllers.clear();
}
void Song::saveScaleStates(QDomDocument &doc, QDomElement &element)
{
QDomElement scalesNode = doc.createElement("scales");
element.appendChild(scalesNode);
for (const auto& scale : m_scales)
{
scale->saveState(doc, scalesNode);
}
}
void Song::restoreScaleStates(const QDomElement &element)
{
QDomNode node = element.firstChild();
for (auto i = std::size_t{0}; i < MaxScaleCount && !node.isNull() && !isCancelled(); i++)
{
m_scales[i]->restoreState(node.toElement());
node = node.nextSibling();
}
emit scaleListChanged(-1);
}
void Song::saveKeymapStates(QDomDocument &doc, QDomElement &element)
{
QDomElement keymapsNode = doc.createElement("keymaps");
element.appendChild(keymapsNode);
for (const auto& keymap : m_keymaps)
{
keymap->saveState(doc, keymapsNode);
}
}
void Song::restoreKeymapStates(const QDomElement &element)
{
QDomNode node = element.firstChild();
for (auto i = std::size_t{0}; i < MaxKeymapCount && !node.isNull() && !isCancelled(); i++)
{
m_keymaps[i]->restoreState(node.toElement());
node = node.nextSibling();
}
emit keymapListChanged(-1);
}
void Song::exportProjectMidi(QString const & exportFileName) const
{
// instantiate midi export plugin
TrackContainer::TrackList const & tracks = this->tracks();
TrackContainer::TrackList const & patternStoreTracks = Engine::patternStore()->tracks();
ExportFilter *exf = dynamic_cast<ExportFilter *> (Plugin::instantiate("midiexport", nullptr, nullptr));
if (exf)
{
exf->tryExport(tracks, patternStoreTracks, getTempo(), m_masterPitchModel.value(), exportFileName);
}
else
{
qDebug() << "failed to load midi export filter!";
}
}
void Song::updateFramesPerTick()
{
Engine::updateFramesPerTick();
}
void Song::setModified()
{
setModified(true);
}
void Song::setProjectFileName(QString const & projectFileName)
{
if (m_fileName != projectFileName)
{
m_fileName = projectFileName;
emit projectFileNameChanged();
}
}
void Song::addController( Controller * controller )
{
bool containsController = std::find(m_controllers.begin(), m_controllers.end(), controller) != m_controllers.end();
if (controller && !containsController)
{
m_controllers.push_back(controller);
emit controllerAdded( controller );
this->setModified();
}
}
void Song::removeController( Controller * controller )
{
auto it = std::find(m_controllers.begin(), m_controllers.end(), controller);
if (it != m_controllers.end())
{
m_controllers.erase(it);
emit controllerRemoved( controller );
delete controller;
this->setModified();
}
}
void Song::clearErrors()
{
m_errors.clear();
}
void Song::collectError( const QString error )
{
if (!m_errors.contains(error)) { m_errors[error] = 1; }
else { m_errors[ error ]++; }
}
bool Song::hasErrors()
{
return !(m_errors.isEmpty());
}
QString Song::errorSummary()
{
QString errors;
auto i = m_errors.constBegin();
while (i != m_errors.constEnd())
{
errors.append( i.key() );
if( i.value() > 1 )
{
errors.append( tr(" (repeated %1 times)").arg( i.value() ) );
}
errors.append("\n");
++i;
}
errors.prepend( "\n\n" );
errors.prepend( tr( "The following errors occurred while loading: " ) );
return errors;
}
bool Song::isSavingProject() const {
return m_savingProject;
}
std::shared_ptr<const Scale> Song::getScale(unsigned int index) const
{
if (index >= MaxScaleCount) {index = 0;}
return std::atomic_load(&m_scales[index]);
}
std::shared_ptr<const Keymap> Song::getKeymap(unsigned int index) const
{
if (index >= MaxKeymapCount) {index = 0;}
return std::atomic_load(&m_keymaps[index]);
}
void Song::setScale(unsigned int index, std::shared_ptr<Scale> newScale)
{
if (index >= MaxScaleCount) {index = 0;}
Engine::audioEngine()->requestChangeInModel();
std::atomic_store(&m_scales[index], newScale);
emit scaleListChanged(index);
Engine::audioEngine()->doneChangeInModel();
}
void Song::setKeymap(unsigned int index, std::shared_ptr<Keymap> newMap)
{
if (index >= MaxKeymapCount) {index = 0;}
Engine::audioEngine()->requestChangeInModel();
std::atomic_store(&m_keymaps[index], newMap);
emit keymapListChanged(index);
Engine::audioEngine()->doneChangeInModel();
}
} // namespace lmms
| 36,395
|
C++
|
.cpp
| 1,178
| 28.169779
| 136
| 0.726714
|
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,762
|
TrackContainer.cpp
|
LMMS_lmms/src/core/TrackContainer.cpp
|
/*
* TrackContainer.cpp - implementation of base class for all trackcontainers
* like Song-Editor, Pattern Editor...
*
* 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 <QCoreApplication>
#include <QProgressDialog>
#include <QDomElement>
#include <QWriteLocker>
#include "AutomationClip.h"
#include "embed.h"
#include "TrackContainer.h"
#include "PatternClip.h"
#include "PatternStore.h"
#include "PatternTrack.h"
#include "Song.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "TextFloat.h"
namespace lmms
{
TrackContainer::TrackContainer() :
Model( nullptr ),
JournallingObject(),
m_tracksMutex(),
m_tracks()
{
}
TrackContainer::~TrackContainer()
{
clearAllTracks();
}
void TrackContainer::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
_this.setTagName( classNodeName() );
_this.setAttribute( "type", nodeName() );
// save settings of each track
m_tracksMutex.lockForRead();
for (const auto& track : m_tracks)
{
track->saveState(_doc, _this);
}
m_tracksMutex.unlock();
}
void TrackContainer::loadSettings( const QDomElement & _this )
{
bool journalRestore = _this.parentNode().nodeName() == "journaldata";
if( journalRestore )
{
clearAllTracks();
}
static QProgressDialog * pd = nullptr;
bool was_null = ( pd == nullptr );
if (!journalRestore && gui::getGUI() != nullptr)
{
if( pd == nullptr )
{
pd = new QProgressDialog( tr( "Loading project..." ),
tr( "Cancel" ), 0,
Engine::getSong()->getLoadingTrackCount(),
gui::getGUI()->mainWindow());
pd->setWindowModality( Qt::ApplicationModal );
pd->setWindowTitle( tr( "Please wait..." ) );
pd->show();
}
}
QDomNode node = _this.firstChild();
while( !node.isNull() )
{
if( pd != nullptr )
{
pd->setValue( pd->value() + 1 );
QCoreApplication::instance()->processEvents(
QEventLoop::AllEvents, 100 );
if( pd->wasCanceled() )
{
if (gui::getGUI() != nullptr)
{
gui::TextFloat::displayMessage( tr( "Loading cancelled" ),
tr( "Project loading was cancelled." ),
embed::getIconPixmap( "project_file", 24, 24 ),
2000 );
}
Engine::getSong()->loadingCancelled();
break;
}
}
if( node.isElement() &&
!node.toElement().attribute( "metadata" ).toInt() )
{
QString trackName = node.toElement().hasAttribute( "name" ) ?
node.toElement().attribute( "name" ) :
node.firstChild().toElement().attribute( "name" );
if( pd != nullptr )
{
pd->setLabelText( tr("Loading Track %1 (%2/Total %3)").arg( trackName ).
arg( pd->value() + 1 ).arg( Engine::getSong()->getLoadingTrackCount() ) );
}
Track::create( node.toElement(), this );
}
node = node.nextSibling();
}
if( pd != nullptr )
{
if( was_null )
{
delete pd;
pd = nullptr;
}
}
}
int TrackContainer::countTracks( Track::Type _tt ) const
{
int cnt = 0;
m_tracksMutex.lockForRead();
for (const auto& track : m_tracks)
{
if (track->type() == _tt || _tt == Track::Type::Count)
{
++cnt;
}
}
m_tracksMutex.unlock();
return( cnt );
}
void TrackContainer::addTrack( Track * _track )
{
if( _track->type() != Track::Type::HiddenAutomation )
{
_track->lock();
m_tracksMutex.lockForWrite();
m_tracks.push_back( _track );
m_tracksMutex.unlock();
_track->unlock();
emit trackAdded( _track );
}
}
void TrackContainer::removeTrack( Track * _track )
{
// need a read locker to ensure that m_tracks doesn't change after reading index.
// After checking that index != -1, we need to upgrade the lock to a write locker before changing m_tracks.
// But since Qt offers no function to promote a read lock to a write lock, we must start with the write locker.
QWriteLocker lockTracksAccess(&m_tracksMutex);
auto it = std::find(m_tracks.begin(), m_tracks.end(), _track);
if (it != m_tracks.end())
{
// If the track is solo, all other tracks are muted. Change this before removing the solo track:
if (_track->isSolo()) {
_track->setSolo(false);
}
m_tracks.erase(it);
lockTracksAccess.unlock();
if( Engine::getSong() )
{
Engine::getSong()->setModified();
}
}
}
void TrackContainer::updateAfterTrackAdd()
{
}
void TrackContainer::clearAllTracks()
{
//m_tracksMutex.lockForWrite();
while (!m_tracks.empty())
{
delete m_tracks.front();
}
//m_tracksMutex.unlock();
}
bool TrackContainer::isEmpty() const
{
for (const auto& track : m_tracks)
{
if (!track->getClips().empty())
{
return false;
}
}
return true;
}
AutomatedValueMap TrackContainer::automatedValuesAt(TimePos time, int clipNum) const
{
return automatedValuesFromTracks(tracks(), time, clipNum);
}
AutomatedValueMap TrackContainer::automatedValuesFromTracks(const TrackList &tracks, TimePos time, int clipNum)
{
Track::clipVector clips;
for (Track* track: tracks)
{
if (track->isMuted()) {
continue;
}
switch(track->type())
{
case Track::Type::Automation:
case Track::Type::HiddenAutomation:
case Track::Type::Pattern:
if (clipNum < 0) {
track->getClipsInRange(clips, 0, time);
} else {
Q_ASSERT(track->numOfClips() > clipNum);
clips.push_back(track->getClip(clipNum));
}
default:
break;
}
}
AutomatedValueMap valueMap;
Q_ASSERT(std::is_sorted(clips.begin(), clips.end(), Clip::comparePosition));
for(Clip* clip : clips)
{
if (clip->isMuted() || clip->startPosition() > time) {
continue;
}
if (auto* p = dynamic_cast<AutomationClip *>(clip))
{
if (! p->hasAutomation()) {
continue;
}
TimePos relTime = time - p->startPosition();
if (! p->getAutoResize()) {
relTime = std::min(relTime, p->length());
}
float value = p->valueAt(relTime);
for (AutomatableModel* model : p->objects())
{
valueMap[model] = value;
}
}
else if (auto* pattern = dynamic_cast<PatternClip*>(clip))
{
auto patIndex = dynamic_cast<class PatternTrack*>(pattern->getTrack())->patternIndex();
auto patStore = Engine::patternStore();
TimePos patTime = time - clip->startPosition();
patTime = std::min(patTime, clip->length());
patTime = patTime % (patStore->lengthOfPattern(patIndex) * TimePos::ticksPerBar());
auto patValues = patStore->automatedValuesAt(patTime, patIndex);
for (auto it=patValues.begin(); it != patValues.end(); it++)
{
// override old values, pattern track with the highest index takes precedence
valueMap[it.key()] = it.value();
}
}
else
{
continue;
}
}
return valueMap;
};
} // namespace lmms
| 7,376
|
C++
|
.cpp
| 271
| 24.276753
| 114
| 0.685467
|
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,763
|
AudioResampler.cpp
|
LMMS_lmms/src/core/AudioResampler.cpp
|
/*
* AudioResampler.cpp - wrapper for libsamplerate
*
* Copyright (c) 2023 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 "AudioResampler.h"
#include <samplerate.h>
#include <stdexcept>
#include <string>
namespace lmms {
AudioResampler::AudioResampler(int interpolationMode, int channels)
: m_interpolationMode(interpolationMode)
, m_channels(channels)
, m_state(src_new(interpolationMode, channels, &m_error))
{
if (!m_state)
{
const auto errorMessage = std::string{src_strerror(m_error)};
const auto fullMessage = std::string{"Failed to create an AudioResampler: "} + errorMessage;
throw std::runtime_error{fullMessage};
}
}
AudioResampler::~AudioResampler()
{
src_delete(m_state);
}
auto AudioResampler::resample(const float* in, long inputFrames, float* out, long outputFrames, double ratio)
-> ProcessResult
{
auto data = SRC_DATA{};
data.data_in = in;
data.input_frames = inputFrames;
data.data_out = out;
data.output_frames = outputFrames;
data.src_ratio = ratio;
data.end_of_input = 0;
return {src_process(m_state, &data), data.input_frames_used, data.output_frames_gen};
}
void AudioResampler::setRatio(double ratio)
{
src_set_ratio(m_state, ratio);
}
} // namespace lmms
| 2,000
|
C++
|
.cpp
| 61
| 30.918033
| 109
| 0.756603
|
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,764
|
LocklessAllocator.cpp
|
LMMS_lmms/src/core/LocklessAllocator.cpp
|
/*
* LocklessAllocator.cpp - allocator with lockless alloc and free
*
* Copyright (c) 2016 Javier Serrano Polo <javier@jasp.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 "LocklessAllocator.h"
#include <algorithm>
#include <cstdio>
#include "lmmsconfig.h"
#ifndef LMMS_BUILD_WIN32
#include <strings.h>
#endif
namespace lmms
{
static const size_t SIZEOF_SET = sizeof( int ) * 8;
static size_t align( size_t size, size_t alignment )
{
size_t misalignment = size % alignment;
if( misalignment )
{
size += alignment - misalignment;
}
return size;
}
LocklessAllocator::LocklessAllocator( size_t nmemb, size_t size )
{
m_capacity = align( nmemb, SIZEOF_SET );
m_elementSize = align( size, sizeof( void * ) );
m_pool = new char[m_capacity * m_elementSize];
m_freeStateSets = m_capacity / SIZEOF_SET;
m_freeState = new std::atomic_int[m_freeStateSets];
std::fill(m_freeState, m_freeState + m_freeStateSets, 0);
m_available = m_capacity;
m_startIndex = 0;
}
LocklessAllocator::~LocklessAllocator()
{
if (m_available != m_capacity)
{
fprintf( stderr, "LocklessAllocator: "
"Destroying with elements still allocated\n" );
}
delete[] m_pool;
delete[] m_freeState;
}
#ifdef LMMS_BUILD_WIN32
static int ffs( int i )
{
if( !i )
{
return 0;
}
for( int j = 0;; )
{
if( i & 1 << j++ )
{
return j;
}
}
}
#endif
void * LocklessAllocator::alloc()
{
// Some of these CAS loops could probably use relaxed atomics, as discussed
// in http://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange.
// Let's use sequentially-consistent ops to be safe for now.
auto available = m_available.load();
do
{
if( !available )
{
fprintf( stderr, "LocklessAllocator: No free space\n" );
return nullptr;
}
}
while (!m_available.compare_exchange_weak(available, available - 1));
const size_t startIndex = m_startIndex++ % m_freeStateSets;
for (size_t set = startIndex;; set = ( set + 1 ) % m_freeStateSets)
{
for (int freeState = m_freeState[set]; freeState != -1;)
{
int bit = ffs( ~freeState ) - 1;
if (m_freeState[set].compare_exchange_weak(freeState,
freeState | 1 << bit ) )
{
return m_pool + ( SIZEOF_SET * set + bit )
* m_elementSize;
}
}
}
}
void LocklessAllocator::free( void * ptr )
{
ptrdiff_t diff = (char *)ptr - m_pool;
if( diff < 0 || diff % m_elementSize )
{
invalid:
fprintf( stderr, "LocklessAllocator: Invalid pointer\n" );
return;
}
size_t offset = diff / m_elementSize;
if( offset >= m_capacity )
{
goto invalid;
}
size_t set = offset / SIZEOF_SET;
int bit = offset % SIZEOF_SET;
int mask = 1 << bit;
int prevState = m_freeState[set].fetch_and(~mask);
if ( !( prevState & mask ) )
{
fprintf( stderr, "LocklessAllocator: Block not in use\n" );
return;
}
++m_available;
}
} // namespace lmms
| 3,603
|
C++
|
.cpp
| 135
| 24.318519
| 76
| 0.701892
|
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,765
|
Clip.cpp
|
LMMS_lmms/src/core/Clip.cpp
|
/*
* Clip.cpp - implementation of Clip class
*
* 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 "Clip.h"
#include <QDomDocument>
#include "AutomationEditor.h"
#include "AutomationClip.h"
#include "Engine.h"
#include "GuiApplication.h"
#include "Song.h"
namespace lmms
{
/*! \brief Create a new Clip
*
* Creates a new clip for the given track.
*
* \param _track The track that will contain the new object
*/
Clip::Clip( Track * track ) :
Model( track ),
m_track( track ),
m_startPosition(),
m_length(),
m_mutedModel( false, this, tr( "Mute" ) ),
m_selectViewOnCreate{false}
{
if( getTrack() )
{
getTrack()->addClip( this );
}
setJournalling( false );
movePosition( 0 );
changeLength( 0 );
setJournalling( true );
}
/*! \brief Destroy a Clip
*
* Destroys the given clip.
*
*/
Clip::~Clip()
{
emit destroyedClip();
if( getTrack() )
{
getTrack()->removeClip( this );
}
}
/*! \brief Move this Clip's position in time
*
* If the clip has moved, update its position. We
* also add a journal entry for undo and update the display.
*
* \param _pos The new position of the clip.
*/
void Clip::movePosition( const TimePos & pos )
{
TimePos newPos = std::max(0, pos.getTicks());
if (m_startPosition != newPos)
{
Engine::audioEngine()->requestChangeInModel();
m_startPosition = newPos;
Engine::audioEngine()->doneChangeInModel();
Engine::getSong()->updateLength();
emit positionChanged();
}
}
/*! \brief Change the length of this Clip
*
* If the clip's length has changed, update it. We
* also add a journal entry for undo and update the display.
*
* \param _length The new length of the clip.
*/
void Clip::changeLength( const TimePos & length )
{
m_length = length;
Engine::getSong()->updateLength();
emit lengthChanged();
}
bool Clip::comparePosition(const Clip *a, const Clip *b)
{
return a->startPosition() < b->startPosition();
}
/*! \brief Copies the state of a Clip to another Clip
*
* This method copies the state of a Clip to another Clip
*/
void Clip::copyStateTo( Clip *src, Clip *dst )
{
// If the node names match we copy the state
if( src->nodeName() == dst->nodeName() ){
QDomDocument doc;
QDomElement parent = doc.createElement( "StateCopy" );
src->saveState( doc, parent );
const TimePos pos = dst->startPosition();
dst->restoreState( parent.firstChild().toElement() );
dst->movePosition( pos );
AutomationClip::resolveAllIDs();
gui::getGUI()->automationEditor()->m_editor->updateAfterClipChange();
}
}
/*! \brief Mutes this Clip
*
* Restore the previous state of this clip. This will
* restore the position or the length of the clip
* depending on what was changed.
*
* \param _je The journal entry to undo
*/
void Clip::toggleMute()
{
m_mutedModel.setValue( !m_mutedModel.value() );
emit dataChanged();
}
TimePos Clip::startTimeOffset() const
{
return m_startTimeOffset;
}
void Clip::setStartTimeOffset( const TimePos &startTimeOffset )
{
m_startTimeOffset = startTimeOffset;
}
void Clip::setColor(const std::optional<QColor>& color)
{
m_color = color;
emit colorChanged();
}
} // namespace lmms
| 3,987
|
C++
|
.cpp
| 149
| 24.684564
| 77
| 0.72332
|
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,766
|
LinkedModelGroups.cpp
|
LMMS_lmms/src/core/LinkedModelGroups.cpp
|
/*
* LinkedModelGroups.cpp - base classes for groups of linked models
*
* Copyright (c) 2019-2019 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 <QDomDocument>
#include <QDomElement>
#include "LinkedModelGroups.h"
#include "AutomatableModel.h"
namespace lmms
{
/*
LinkedModelGroup
*/
void LinkedModelGroup::linkControls(LinkedModelGroup *other)
{
foreach_model([&other](const std::string& id, ModelInfo& inf)
{
auto itr2 = other->m_models.find(id);
Q_ASSERT(itr2 != other->m_models.end());
AutomatableModel::linkModels(inf.m_model, itr2->second.m_model);
});
}
void LinkedModelGroup::saveValues(QDomDocument &doc, QDomElement &that)
{
foreach_model([&doc, &that](const std::string& , ModelInfo& inf)
{
inf.m_model->saveSettings(doc, that, /*m_models[idx].m_name*/ inf.m_name); /* TODO: m_name useful */
});
}
void LinkedModelGroup::loadValues(const QDomElement &that)
{
foreach_model([&that](const std::string& , ModelInfo& inf)
{
// try to load, if it fails, this will load a sane initial value
inf.m_model->loadSettings(that, /*m_models()[idx].m_name*/ inf.m_name); /* TODO: m_name useful */
});
}
void LinkedModelGroup::addModel(AutomatableModel *model, const QString &name)
{
model->setObjectName(name);
m_models.emplace(std::string(name.toUtf8().data()), ModelInfo(name, model));
connect(model, &AutomatableModel::destroyed,
this, [this, model](jo_id_t){
if(containsModel(model->objectName()))
{
emit modelRemoved(model);
eraseModel(model->objectName());
}
},
Qt::DirectConnection);
// View needs to create another child view, e.g. a new knob:
emit modelAdded(model);
emit dataChanged();
}
void LinkedModelGroup::removeControl(AutomatableModel* mdl)
{
if(containsModel(mdl->objectName()))
{
emit modelRemoved(mdl);
eraseModel(mdl->objectName());
}
}
bool LinkedModelGroup::eraseModel(const QString& name)
{
return m_models.erase(name.toStdString()) > 0;
}
void LinkedModelGroup::clearModels()
{
m_models.clear();
}
bool LinkedModelGroup::containsModel(const QString &name) const
{
return m_models.find(name.toStdString()) != m_models.end();
}
/*
LinkedModelGroups
*/
void LinkedModelGroups::linkAllModels()
{
LinkedModelGroup* first = getGroup(0);
for (size_t i = 1; auto cur = getGroup(i); ++i)
{
first->linkControls(cur);
}
}
void LinkedModelGroups::saveSettings(QDomDocument& doc, QDomElement& that)
{
LinkedModelGroup* grp0 = getGroup(0);
if (grp0)
{
QDomElement models = doc.createElement("models");
that.appendChild(models);
grp0->saveValues(doc, models);
}
else { /* don't even add a "models" node */ }
}
void LinkedModelGroups::loadSettings(const QDomElement& that)
{
QDomElement models = that.firstChildElement("models");
if (auto grp0 = getGroup(0); !models.isNull() && grp0)
{
// only load the first group, the others are linked to the first
grp0->loadValues(models);
}
}
} // namespace lmms
| 3,772
|
C++
|
.cpp
| 125
| 27.728
| 102
| 0.732665
|
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,767
|
Metronome.cpp
|
LMMS_lmms/src/core/Metronome.cpp
|
/*
* Metronome.cpp
*
* 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 "Metronome.h"
#include "Engine.h"
#include "SamplePlayHandle.h"
namespace lmms {
void Metronome::processTick(int currentTick, int ticksPerBar, int beatsPerBar, size_t bufferOffset)
{
const auto ticksPerBeat = ticksPerBar / beatsPerBar;
if (currentTick % ticksPerBeat != 0 || !m_active) { return; }
const auto handle = currentTick % ticksPerBar == 0 ? new SamplePlayHandle("misc/metronome02.ogg")
: new SamplePlayHandle("misc/metronome01.ogg");
handle->setOffset(bufferOffset);
Engine::audioEngine()->addPlayHandle(handle);
}
} // namespace lmms
| 1,424
|
C++
|
.cpp
| 37
| 36.216216
| 99
| 0.749096
|
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,768
|
VstSyncController.cpp
|
LMMS_lmms/src/core/VstSyncController.cpp
|
/*
* VstSyncController.cpp - manage synchronization between LMMS and VST plugins
*
* Copyright (c) 2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2013 Mike Choi <rdavidian71/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 "VstSyncController.h"
#include <stdexcept>
#include <QDebug>
#include <QUuid>
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "RemotePlugin.h"
namespace lmms
{
VstSyncController::VstSyncController()
{
try
{
m_syncData.create(QUuid::createUuid().toString().toStdString());
}
catch (const std::runtime_error& error)
{
qCritical() << "Failed to allocate shared memory for VST sync:" << error.what();
return;
}
m_syncData->isPlaying = false;
m_syncData->m_bufferSize = Engine::audioEngine()->framesPerPeriod();
m_syncData->timeSigNumer = 4;
m_syncData->timeSigDenom = 4;
connect(Engine::audioEngine(), &AudioEngine::sampleRateChanged, this, &VstSyncController::updateSampleRate);
updateSampleRate();
}
void VstSyncController::setAbsolutePosition(double ticks)
{
if (!m_syncData) { return; }
#ifdef VST_SNC_LATENCY
m_syncData->ppqPos = ( ( ticks + 0 ) / 48.0 ) - m_syncData->m_latency;
#else
m_syncData->ppqPos = ( ( ticks + 0 ) / 48.0 );
#endif
}
void VstSyncController::setPlaybackState(bool enabled)
{
if (!m_syncData) { return; }
m_syncData->isPlaying = enabled;
}
void VstSyncController::setTempo(int newTempo)
{
if (!m_syncData) { return; }
m_syncData->m_bpm = newTempo;
#ifdef VST_SNC_LATENCY
m_syncData->m_latency = m_syncData->m_bufferSize * newTempo / ( (float) m_syncData->m_sampleRate * 60 );
#endif
}
void VstSyncController::setTimeSignature(int num, int denom)
{
if (!m_syncData) { return; }
m_syncData->timeSigNumer = num;
m_syncData->timeSigDenom = denom;
}
void VstSyncController::startCycle(int startTick, int endTick)
{
if (!m_syncData) { return; }
m_syncData->isCycle = true;
m_syncData->cycleStart = startTick / (float)48;
m_syncData->cycleEnd = endTick / (float)48;
}
void VstSyncController::stopCycle()
{
if (!m_syncData) { return; }
m_syncData->isCycle = false;
}
void VstSyncController::setPlaybackJumped(bool jumped)
{
if (!m_syncData) { return; }
m_syncData->m_playbackJumped = jumped;
}
void VstSyncController::update()
{
if (!m_syncData) { return; }
m_syncData->m_bufferSize = Engine::audioEngine()->framesPerPeriod();
#ifdef VST_SNC_LATENCY
m_syncData->m_latency = m_syncData->m_bufferSize * m_syncData->m_bpm / ( (float) m_syncData->m_sampleRate * 60 );
#endif
}
void VstSyncController::updateSampleRate()
{
if (!m_syncData) { return; }
m_syncData->m_sampleRate = Engine::audioEngine()->outputSampleRate();
#ifdef VST_SNC_LATENCY
m_syncData->m_latency = m_syncData->m_bufferSize * m_syncData->m_bpm / ( (float) m_syncData->m_sampleRate * 60 );
#endif
}
} // namespace lmms
| 3,651
|
C++
|
.cpp
| 114
| 29.991228
| 114
| 0.74089
|
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,769
|
Track.cpp
|
LMMS_lmms/src/core/Track.cpp
|
/*
* Track.cpp - implementation of Track class
*
* 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.
*
*/
/** \file Track.cpp
* \brief Implementation of Track class
*/
#include "Track.h"
#include <QDomElement>
#include <QVariant>
#include "AutomationClip.h"
#include "AutomationTrack.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "PatternStore.h"
#include "PatternTrack.h"
#include "SampleTrack.h"
#include "Song.h"
namespace lmms
{
/*! \brief Create a new (empty) track object
*
* The track object is the whole track, linking its contents, its
* automation, name, type, and so forth.
*
* \param type The type of track (Song Editor or Pattern Editor)
* \param tc The track Container object to encapsulate in this track.
*
* \todo check the definitions of all the properties - are they OK?
*/
Track::Track( Type type, TrackContainer * tc ) :
Model( tc ), /*!< The track Model */
m_trackContainer( tc ), /*!< The track container object */
m_type( type ), /*!< The track type */
m_name(), /*!< The track's name */
m_mutedModel( false, this, tr( "Mute" ) ), /*!< For controlling track muting */
m_soloModel( false, this, tr( "Solo" ) ), /*!< For controlling track soloing */
m_clips() /*!< The clips (segments) */
{
m_trackContainer->addTrack( this );
m_height = -1;
}
/*! \brief Destroy this track
*
* Delete the clips and remove this track from the track container.
*/
Track::~Track()
{
lock();
emit destroyedTrack();
while (!m_clips.empty())
{
delete m_clips.back();
}
m_trackContainer->removeTrack( this );
unlock();
}
/*! \brief Create a track based on the given track type and container.
*
* \param tt The type of track to create
* \param tc The track container to attach to
*/
Track * Track::create( Type tt, TrackContainer * tc )
{
Engine::audioEngine()->requestChangeInModel();
Track * t = nullptr;
switch( tt )
{
case Type::Instrument: t = new class InstrumentTrack( tc ); break;
case Type::Pattern: t = new class PatternTrack( tc ); break;
case Type::Sample: t = new class SampleTrack( tc ); break;
// case Type::Event:
// case Type::Video:
case Type::Automation: t = new class AutomationTrack( tc ); break;
case Type::HiddenAutomation:
t = new class AutomationTrack( tc, true ); break;
default: break;
}
if (tc == Engine::patternStore() && t)
{
t->createClipsForPattern(Engine::patternStore()->numOfPatterns() - 1);
}
tc->updateAfterTrackAdd();
Engine::audioEngine()->doneChangeInModel();
return t;
}
/*! \brief Create a track inside TrackContainer from track type in a QDomElement and restore state from XML
*
* \param element The QDomElement containing the type of track to create
* \param tc The track container to attach to
*/
Track * Track::create( const QDomElement & element, TrackContainer * tc )
{
Engine::audioEngine()->requestChangeInModel();
Track * t = create(
static_cast<Type>( element.attribute( "type" ).toInt() ),
tc );
if( t != nullptr )
{
t->restoreState( element );
}
Engine::audioEngine()->doneChangeInModel();
return t;
}
/*! \brief Clone a track from this track
*
*/
Track* Track::clone()
{
// Save track to temporary XML and load it to create a new identical track
QDomDocument doc;
QDomElement parent = doc.createElement("clonedtrack");
saveState(doc, parent);
Track* t = create(parent.firstChild().toElement(), m_trackContainer);
AutomationClip::resolveAllIDs();
return t;
}
/*! \brief Save this track's settings to file
*
* We save the track type and its muted state and solo state, then append the track-
* specific settings. Then we iterate through the clips
* and save all their states in turn.
*
* \param doc The QDomDocument to use to save
* \param element The The QDomElement to save into
* \param presetMode Describes whether to save the track as a preset or not.
* \todo Does this accurately describe the parameters? I think not!?
* \todo Save the track height
*/
void Track::saveTrack(QDomDocument& doc, QDomElement& element, bool presetMode)
{
if (!presetMode)
{
element.setTagName( "track" );
}
element.setAttribute( "type", static_cast<int>(type()) );
element.setAttribute( "name", name() );
m_mutedModel.saveSettings( doc, element, "muted" );
m_soloModel.saveSettings( doc, element, "solo" );
// Save the mutedBeforeSolo value so we can recover the muted state if any solo was active (issue 5562)
element.setAttribute( "mutedBeforeSolo", int(m_mutedBeforeSolo) );
if( m_height >= MINIMAL_TRACK_HEIGHT )
{
element.setAttribute( "trackheight", m_height );
}
if (m_color.has_value())
{
element.setAttribute("color", m_color->name());
}
QDomElement tsDe = doc.createElement( nodeName() );
// let actual track (InstrumentTrack, PatternTrack, SampleTrack etc.) save its settings
element.appendChild( tsDe );
saveTrackSpecificSettings(doc, tsDe, presetMode);
if (presetMode)
{
return;
}
// now save settings of all Clip's
for (const auto& clip : m_clips)
{
clip->saveState(doc, element);
}
}
/*! \brief Load the settings from a file
*
* We load the track's type and muted state and solo state, then clear out our
* current Clip.
*
* Then we step through the QDomElement's children and load the
* track-specific settings and clip states from it
* one at a time.
*
* \param element the QDomElement to load track settings from
* \param presetMode Indicates if a preset or a full track is loaded
* \todo Load the track height.
*/
void Track::loadTrack(const QDomElement& element, bool presetMode)
{
if( static_cast<Type>(element.attribute( "type" ).toInt()) != type() )
{
qWarning( "Current track-type does not match track-type of "
"settings-node!\n" );
}
setName( element.hasAttribute( "name" ) ? element.attribute( "name" ) :
element.firstChild().toElement().attribute( "name" ) );
m_mutedModel.loadSettings( element, "muted" );
m_soloModel.loadSettings( element, "solo" );
// Get the mutedBeforeSolo value so we can recover the muted state if any solo was active.
// Older project files that didn't have this attribute will set the value to false (issue 5562)
m_mutedBeforeSolo = QVariant( element.attribute( "mutedBeforeSolo", "0" ) ).toBool();
if (element.hasAttribute("color"))
{
setColor(QColor{element.attribute("color")});
}
if (presetMode)
{
QDomNode node = element.firstChild();
while( !node.isNull() )
{
if( node.isElement() && node.nodeName() == nodeName() )
{
loadTrackSpecificSettings( node.toElement() );
break;
}
node = node.nextSibling();
}
return;
}
{
auto guard = Engine::audioEngine()->requestChangesGuard();
deleteClips();
}
QDomNode node = element.firstChild();
while( !node.isNull() )
{
if( node.isElement() )
{
if( node.nodeName() == nodeName() )
{
loadTrackSpecificSettings( node.toElement() );
}
else if( node.nodeName() != "muted"
&& node.nodeName() != "solo"
&& !node.toElement().attribute( "metadata" ).toInt() )
{
Clip * clip = createClip(
TimePos( 0 ) );
clip->restoreState( node.toElement() );
}
}
node = node.nextSibling();
}
int storedHeight = element.attribute( "trackheight" ).toInt();
if( storedHeight >= MINIMAL_TRACK_HEIGHT )
{
m_height = storedHeight;
}
}
void Track::savePreset(QDomDocument & doc, QDomElement & element)
{
saveTrack(doc, element, true);
}
void Track::loadPreset(const QDomElement & element)
{
loadTrack(element, true);
}
void Track::saveSettings(QDomDocument& doc, QDomElement& element)
{
// Assume that everything should be saved if we are called through SerializingObject::saveSettings
saveTrack(doc, element, false);
}
void Track::loadSettings(const QDomElement& element)
{
// Assume that everything should be loaded if we are called through SerializingObject::loadSettings
loadTrack(element, false);
}
/*! \brief Add another Clip into this track
*
* \param clip The Clip to attach to this track.
*/
Clip * Track::addClip( Clip * clip )
{
m_clips.push_back( clip );
emit clipAdded( clip );
return clip; // just for convenience
}
/*! \brief Remove a given Clip from this track
*
* \param clip The Clip to remove from this track.
*/
void Track::removeClip( Clip * clip )
{
clipVector::iterator it = std::find( m_clips.begin(), m_clips.end(), clip );
if( it != m_clips.end() )
{
m_clips.erase( it );
if( Engine::getSong() )
{
Engine::getSong()->updateLength();
Engine::getSong()->setModified();
}
}
}
/*! \brief Remove all Clips from this track */
void Track::deleteClips()
{
while (!m_clips.empty())
{
delete m_clips.front();
}
}
/*! \brief Return the number of clips we contain
*
* \return the number of clips we currently contain.
*/
int Track::numOfClips()
{
return m_clips.size();
}
/*! \brief Get a Clip by number
*
* If the Clip number is less than our Clip array size then fetch that
* numbered object from the array. Otherwise we warn the user that
* we've somehow requested a Clip that is too large, and create a new
* Clip for them.
* \param clipNum The number of the Clip to fetch.
* \return the given Clip or a new one if out of range.
* \todo reject Clip numbers less than zero.
* \todo if we create a Clip here, should we somehow attach it to the
* track?
*/
auto Track::getClip(std::size_t clipNum) -> Clip*
{
if( clipNum < m_clips.size() )
{
return m_clips[clipNum];
}
printf( "called Track::getClip( %zu ), "
"but Clip %zu doesn't exist\n", clipNum, clipNum );
return createClip( clipNum * TimePos::ticksPerBar() );
}
/*! \brief Determine the given Clip's number in our array.
*
* \param clip The Clip to search for.
* \return its number in our array.
*/
int Track::getClipNum( const Clip * clip )
{
// for( int i = 0; i < getTrackContentWidget()->numOfClips(); ++i )
clipVector::iterator it = std::find( m_clips.begin(), m_clips.end(), clip );
if( it != m_clips.end() )
{
/* if( getClip( i ) == _clip )
{
return i;
}*/
return it - m_clips.begin();
}
qWarning( "Track::getClipNum(...) -> _clip not found!\n" );
return 0;
}
/*! \brief Retrieve a list of clips that fall within a period.
*
* Here we're interested in a range of clips that intersect
* the given time period.
*
* We return the Clips we find in order by time, earliest Clips first.
*
* \param clipV The list to contain the found clips.
* \param start The MIDI start time of the range.
* \param end The MIDI endi time of the range.
*/
void Track::getClipsInRange( clipVector & clipV, const TimePos & start,
const TimePos & end )
{
for( Clip* clip : m_clips )
{
int s = clip->startPosition();
int e = clip->endPosition();
if( ( s <= end ) && ( e >= start ) )
{
// Clip is within given range
// Insert sorted by Clip's position
clipV.insert(std::upper_bound(clipV.begin(), clipV.end(), clip, Clip::comparePosition),
clip);
}
}
}
/*! \brief Swap the position of two clips.
*
* First, we arrange to swap the positions of the two Clips in the
* clips list. Then we swap their start times as well.
*
* \param clipNum1 The first Clip to swap.
* \param clipNum2 The second Clip to swap.
*/
void Track::swapPositionOfClips( int clipNum1, int clipNum2 )
{
qSwap( m_clips[clipNum1], m_clips[clipNum2] );
const TimePos pos = m_clips[clipNum1]->startPosition();
m_clips[clipNum1]->movePosition( m_clips[clipNum2]->startPosition() );
m_clips[clipNum2]->movePosition( pos );
}
void Track::createClipsForPattern(int pattern)
{
while( numOfClips() < pattern + 1 )
{
TimePos position = TimePos( numOfClips(), 0 );
Clip * clip = createClip( position );
clip->changeLength( TimePos( 1, 0 ) );
}
}
/*! \brief Move all the clips after a certain time later by one bar.
*
* \param pos The time at which we want to insert the bar.
* \todo if we stepped through this list last to first, and the list was
* in ascending order by Clip time, once we hit a Clip that was earlier
* than the insert time, we could fall out of the loop early.
*/
void Track::insertBar( const TimePos & pos )
{
// we'll increase the position of every Clip, positioned behind pos, by
// one bar
for (const auto& clip : m_clips)
{
if (clip->startPosition() >= pos)
{
clip->movePosition(clip->startPosition() + TimePos::ticksPerBar());
}
}
}
/*! \brief Move all the clips after a certain time earlier by one bar.
*
* \param pos The time at which we want to remove the bar.
*/
void Track::removeBar( const TimePos & pos )
{
// we'll decrease the position of every Clip, positioned behind pos, by
// one bar
for (const auto& clip : m_clips)
{
if (clip->startPosition() >= pos)
{
clip->movePosition(clip->startPosition() - TimePos::ticksPerBar());
}
}
}
/*! \brief Return the length of the entire track in bars
*
* We step through our list of Clips and determine their end position,
* keeping track of the latest time found in ticks. Then we return
* that in bars by dividing by the number of ticks per bar.
*/
bar_t Track::length() const
{
// find last end-position
tick_t last = 0;
for (const auto& clip : m_clips)
{
if (Engine::getSong()->isExporting() && clip->isMuted())
{
continue;
}
const tick_t cur = clip->endPosition();
if( cur > last )
{
last = cur;
}
}
return last / TimePos::ticksPerBar();
}
/*! \brief Invert the track's solo state.
*
* We have to go through all the tracks determining if any other track
* is already soloed. Then we have to save the mute state of all tracks,
* and set our mute state to on and all the others to off.
*/
void Track::toggleSolo()
{
const TrackContainer::TrackList & tl = m_trackContainer->tracks();
bool soloBefore = false;
for (const auto& track : tl)
{
if (track != this)
{
if (track->m_soloModel.value())
{
soloBefore = true;
break;
}
}
}
const bool solo = m_soloModel.value();
// Should we use the new behavior of solo or the older/legacy one?
const bool soloLegacyBehavior = ConfigManager::inst()->value("app", "sololegacybehavior", "0").toInt();
for (const auto& track : tl)
{
if (solo)
{
// save mute-state in case no track was solo before
if (!soloBefore)
{
track->m_mutedBeforeSolo = track->isMuted();
}
// Don't mute AutomationTracks (keep their original state) unless we are on the sololegacybehavior mode
if (track == this)
{
track->setMuted(false);
}
else if (soloLegacyBehavior || track->type() != Type::Automation)
{
track->setMuted(true);
}
if (track != this)
{
track->m_soloModel.setValue(false);
}
}
else if (!soloBefore)
{
// Unless we are on the sololegacybehavior mode, only restores the
// mute state if the track isn't an Automation Track
if (soloLegacyBehavior || track->type() != Type::Automation)
{
track->setMuted(track->m_mutedBeforeSolo);
}
}
}
}
void Track::setColor(const std::optional<QColor>& color)
{
m_color = color;
emit colorChanged();
}
BoolModel *Track::getMutedModel()
{
return &m_mutedModel;
}
void Track::setName(const QString& newName)
{
if (m_name != newName)
{
m_name = newName;
if (auto song = Engine::getSong())
{
song->setModified();
}
emit nameChanged();
}
}
} // namespace lmms
| 16,273
|
C++
|
.cpp
| 551
| 27.090744
| 107
| 0.696711
|
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,770
|
LadspaManager.cpp
|
LMMS_lmms/src/core/LadspaManager.cpp
|
/*
* LadspaManager.cpp - a class to manage loading and instantiation
* of ladspa plugins
*
* Copyright (c) 2005-2008 Danny McRae <khjklujn@netscape.net>
* Copyright (c) 2011-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 <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QLibrary>
#include <cmath>
#include "ConfigManager.h"
#include "LadspaManager.h"
#include "PluginFactory.h"
namespace lmms
{
LadspaManager::LadspaManager()
{
// Make sure plugin search paths are set up
PluginFactory::setupSearchPaths();
QStringList ladspaDirectories = QString( getenv( "LADSPA_PATH" ) ).
split( LADSPA_PATH_SEPERATOR );
ladspaDirectories += ConfigManager::inst()->ladspaDir().split( ',' );
ladspaDirectories.push_back( "plugins:ladspa" );
#ifndef LMMS_BUILD_WIN32
ladspaDirectories.push_back( qApp->applicationDirPath() + '/' + LIB_DIR + "ladspa" );
ladspaDirectories.push_back( "/usr/lib/ladspa" );
ladspaDirectories.push_back( "/usr/lib64/ladspa" );
ladspaDirectories.push_back( "/usr/local/lib/ladspa" );
ladspaDirectories.push_back( "/usr/local/lib64/ladspa" );
ladspaDirectories.push_back( "/Library/Audio/Plug-Ins/LADSPA" );
#endif
for (const auto& ladspaDirectory : ladspaDirectories)
{
// Skip empty entries as QDir will interpret it as the working directory
if (ladspaDirectory.isEmpty()) { continue; }
QDir directory(ladspaDirectory);
QFileInfoList list = directory.entryInfoList();
for (const auto& f : list)
{
if(!f.isFile() || f.fileName().right( 3 ).toLower() !=
#ifdef LMMS_BUILD_WIN32
"dll"
#else
".so"
#endif
)
{
continue;
}
QLibrary plugin_lib( f.absoluteFilePath() );
if( plugin_lib.load() == true )
{
auto descriptorFunction = (LADSPA_Descriptor_Function)plugin_lib.resolve("ladspa_descriptor");
if( descriptorFunction != nullptr )
{
addPlugins( descriptorFunction,
f.fileName() );
}
}
else
{
qWarning() << plugin_lib.errorString();
}
}
}
l_ladspa_key_t keys = m_ladspaManagerMap.keys();
for (const auto& key : keys)
{
m_sortedPlugins.append(qMakePair(getName(key), key));
}
std::sort( m_sortedPlugins.begin(), m_sortedPlugins.end() );
}
LadspaManager::~LadspaManager()
{
for( LadspaManagerMapType::iterator it = m_ladspaManagerMap.begin();
it != m_ladspaManagerMap.end(); ++it )
{
delete it.value();
}
}
LadspaManagerDescription * LadspaManager::getDescription(
const ladspa_key_t & _plugin )
{
auto const it = m_ladspaManagerMap.find(_plugin);
return it != m_ladspaManagerMap.end() ? *it : nullptr;
}
void LadspaManager::addPlugins(
LADSPA_Descriptor_Function _descriptor_func,
const QString & _file )
{
for (long pluginIndex = 0; const auto descriptor = _descriptor_func(pluginIndex); ++pluginIndex)
{
ladspa_key_t key( _file, QString( descriptor->Label ) );
if( m_ladspaManagerMap.contains( key ) )
{
continue;
}
auto plugIn = new LadspaManagerDescription;
plugIn->descriptorFunction = _descriptor_func;
plugIn->index = pluginIndex;
plugIn->inputChannels = getPluginInputs( descriptor );
plugIn->outputChannels = getPluginOutputs( descriptor );
if( plugIn->inputChannels == 0 && plugIn->outputChannels > 0 )
{
plugIn->type = LadspaPluginType::Source;
}
else if( plugIn->inputChannels > 0 &&
plugIn->outputChannels > 0 )
{
plugIn->type = LadspaPluginType::Transfer;
}
else if( plugIn->inputChannels > 0 &&
plugIn->outputChannels == 0 )
{
plugIn->type = LadspaPluginType::Sink;
}
else
{
plugIn->type = LadspaPluginType::Other;
}
m_ladspaManagerMap[key] = plugIn;
}
}
uint16_t LadspaManager::getPluginInputs(
const LADSPA_Descriptor * _descriptor )
{
uint16_t inputs = 0;
for( uint16_t port = 0; port < _descriptor->PortCount; port++ )
{
if( LADSPA_IS_PORT_INPUT(
_descriptor->PortDescriptors[port] ) &&
LADSPA_IS_PORT_AUDIO(
_descriptor->PortDescriptors[port] ) )
{
QString name = QString(
_descriptor->PortNames[port] );
if( name.toUpper().contains( "IN" ) )
{
inputs++;
}
}
}
return inputs;
}
uint16_t LadspaManager::getPluginOutputs(
const LADSPA_Descriptor * _descriptor )
{
uint16_t outputs = 0;
for( uint16_t port = 0; port < _descriptor->PortCount; port++ )
{
if( LADSPA_IS_PORT_OUTPUT(
_descriptor->PortDescriptors[port] ) &&
LADSPA_IS_PORT_AUDIO(
_descriptor->PortDescriptors[port] ) )
{
QString name = QString(
_descriptor->PortNames[port] );
if( name.toUpper().contains( "OUT" ) )
{
outputs++;
}
}
}
return outputs;
}
const LADSPA_PortDescriptor* LadspaManager::getPortDescriptor(const ladspa_key_t &_plugin, uint32_t _port)
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && _port < getPortCount( _plugin ) )
{
return( & descriptor->PortDescriptors[_port] );
}
return( nullptr );
}
const LADSPA_PortRangeHint *LadspaManager::getPortRangeHint(const ladspa_key_t &_plugin, uint32_t _port)
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && _port < getPortCount( _plugin ) )
{
return( & descriptor->PortRangeHints[_port] );
}
return( nullptr );
}
l_sortable_plugin_t LadspaManager::getSortedPlugins()
{
return( m_sortedPlugins );
}
QString LadspaManager::getLabel( const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? descriptor->Label : "" );
}
bool LadspaManager::hasRealTimeDependency(
const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? LADSPA_IS_REALTIME( descriptor->Properties )
: false );
}
bool LadspaManager::isInplaceBroken( const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? LADSPA_IS_INPLACE_BROKEN( descriptor->Properties )
: false );
}
bool LadspaManager::isRealTimeCapable(
const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? LADSPA_IS_HARD_RT_CAPABLE( descriptor->Properties )
: false );
}
QString LadspaManager::getName( const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? descriptor->Name : "" );
}
QString LadspaManager::getMaker( const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? descriptor->Maker : "" );
}
QString LadspaManager::getCopyright( const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? descriptor->Copyright : "" );
}
uint32_t LadspaManager::getPortCount( const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? descriptor->PortCount : 0 );
}
bool LadspaManager::isPortInput( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto * descriptor = getPortDescriptor( _plugin, _port );
return( descriptor && LADSPA_IS_PORT_INPUT( * descriptor ) );
}
bool LadspaManager::isPortOutput( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto * descriptor = getPortDescriptor( _plugin, _port );
return( descriptor && LADSPA_IS_PORT_OUTPUT( * descriptor ) );
}
bool LadspaManager::isPortAudio( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto * descriptor = getPortDescriptor( _plugin, _port );
return( descriptor && LADSPA_IS_PORT_AUDIO( * descriptor ) );
}
bool LadspaManager::isPortControl( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto * descriptor = getPortDescriptor( _plugin, _port );
return( descriptor && LADSPA_IS_PORT_CONTROL( * descriptor ) );
}
bool LadspaManager::areHintsSampleRateDependent(
const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto* portRangeHint = getPortRangeHint( _plugin, _port );
return portRangeHint && LADSPA_IS_HINT_SAMPLE_RATE( portRangeHint->HintDescriptor );
}
float LadspaManager::getLowerBound( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto* portRangeHint = getPortRangeHint( _plugin, _port );
if( portRangeHint && LADSPA_IS_HINT_BOUNDED_BELOW( portRangeHint->HintDescriptor ) )
{
return( portRangeHint->LowerBound );
}
return( NOHINT );
}
float LadspaManager::getUpperBound( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto* portRangeHint = getPortRangeHint( _plugin, _port );
if( portRangeHint && LADSPA_IS_HINT_BOUNDED_ABOVE( portRangeHint->HintDescriptor ) )
{
return( portRangeHint->UpperBound );
}
return( NOHINT );
}
bool LadspaManager::isPortToggled( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto* portRangeHint = getPortRangeHint( _plugin, _port );
return( portRangeHint && LADSPA_IS_HINT_TOGGLED( portRangeHint->HintDescriptor ) );
}
float LadspaManager::getDefaultSetting( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto* portRangeHint = getPortRangeHint( _plugin, _port );
if( portRangeHint )
{
LADSPA_PortRangeHintDescriptor hintDescriptor = portRangeHint->HintDescriptor;
switch( hintDescriptor & LADSPA_HINT_DEFAULT_MASK )
{
case LADSPA_HINT_DEFAULT_NONE:
return( NOHINT );
case LADSPA_HINT_DEFAULT_MINIMUM:
return( portRangeHint->LowerBound );
case LADSPA_HINT_DEFAULT_LOW:
if( LADSPA_IS_HINT_LOGARITHMIC
( hintDescriptor ) )
{
return( exp( log( portRangeHint->LowerBound ) * 0.75 +
log( portRangeHint->UpperBound ) * 0.25 ) );
}
else
{
return( portRangeHint->LowerBound * 0.75 +
portRangeHint->UpperBound * 0.25 );
}
case LADSPA_HINT_DEFAULT_MIDDLE:
if( LADSPA_IS_HINT_LOGARITHMIC
( hintDescriptor ) )
{
return( sqrt( portRangeHint->LowerBound
* portRangeHint->UpperBound ) );
}
else
{
return( 0.5 * ( portRangeHint->LowerBound
+ portRangeHint->UpperBound ) );
}
case LADSPA_HINT_DEFAULT_HIGH:
if( LADSPA_IS_HINT_LOGARITHMIC
( hintDescriptor ) )
{
return( exp( log( portRangeHint->LowerBound ) * 0.25 +
log( portRangeHint->UpperBound ) * 0.75 ) );
}
else
{
return( portRangeHint->LowerBound * 0.25 +
portRangeHint->UpperBound * 0.75 );
}
case LADSPA_HINT_DEFAULT_MAXIMUM:
return( portRangeHint->UpperBound );
case LADSPA_HINT_DEFAULT_0:
return( 0.0 );
case LADSPA_HINT_DEFAULT_1:
return( 1.0 );
case LADSPA_HINT_DEFAULT_100:
return( 100.0 );
case LADSPA_HINT_DEFAULT_440:
return( 440.0 );
default:
return( NOHINT );
}
}
else
{
return( NOHINT );
}
}
bool LadspaManager::isLogarithmic( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto* portRangeHint = getPortRangeHint( _plugin, _port );
return( portRangeHint && LADSPA_IS_HINT_LOGARITHMIC( portRangeHint->HintDescriptor ) );
}
bool LadspaManager::isInteger( const ladspa_key_t & _plugin,
uint32_t _port )
{
const auto* portRangeHint = getPortRangeHint( _plugin, _port );
return( portRangeHint && LADSPA_IS_HINT_INTEGER( portRangeHint->HintDescriptor ) );
}
bool LadspaManager::isEnum( const ladspa_key_t & _plugin, uint32_t _port )
{
auto const * desc = getDescriptor(_plugin);
if (desc && _port < desc->PortCount)
{
LADSPA_PortRangeHintDescriptor hintDescriptor =
desc->PortRangeHints[_port].HintDescriptor;
// This is an LMMS extension to ladspa
return LADSPA_IS_HINT_INTEGER(hintDescriptor) && LADSPA_IS_HINT_TOGGLED(hintDescriptor);
}
return false;
}
QString LadspaManager::getPortName( const ladspa_key_t & _plugin,
uint32_t _port )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? descriptor->PortNames[_port] : QString( "" ) );
}
const void * LadspaManager::getImplementationData(
const ladspa_key_t & _plugin )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ? descriptor->ImplementationData : nullptr );
}
const LADSPA_Descriptor * LadspaManager::getDescriptor(const ladspa_key_t & _plugin)
{
auto const it = m_ladspaManagerMap.find(_plugin);
if (it != m_ladspaManagerMap.end())
{
auto const plugin = *it;
LADSPA_Descriptor_Function descriptorFunction = plugin->descriptorFunction;
const LADSPA_Descriptor* descriptor = descriptorFunction(plugin->index);
return descriptor;
}
return nullptr;
}
LADSPA_Handle LadspaManager::instantiate(
const ladspa_key_t & _plugin,
uint32_t _sample_rate )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
return( descriptor ?
( descriptor->instantiate )( descriptor, _sample_rate ) :
nullptr );
}
bool LadspaManager::connectPort( const ladspa_key_t & _plugin,
LADSPA_Handle _instance,
uint32_t _port,
LADSPA_Data * _data_location )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && descriptor->connect_port != nullptr &&
_port < getPortCount( _plugin ) )
{
( descriptor->connect_port )
( _instance, _port, _data_location );
return( true );
}
return( false );
}
bool LadspaManager::activate( const ladspa_key_t & _plugin,
LADSPA_Handle _instance )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && descriptor->activate != nullptr )
{
( descriptor->activate ) ( _instance );
return( true );
}
return( false );
}
bool LadspaManager::run( const ladspa_key_t & _plugin,
LADSPA_Handle _instance,
uint32_t _sample_count )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && descriptor->run!= nullptr )
{
( descriptor->run ) ( _instance, _sample_count );
return( true );
}
return( false );
}
bool LadspaManager::runAdding( const ladspa_key_t & _plugin,
LADSPA_Handle _instance,
uint32_t _sample_count )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && descriptor->run_adding!= nullptr
&& descriptor->set_run_adding_gain != nullptr )
{
( descriptor->run_adding ) ( _instance, _sample_count );
return( true );
}
return( false );
}
bool LadspaManager::setRunAddingGain( const ladspa_key_t & _plugin,
LADSPA_Handle _instance,
LADSPA_Data _gain )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && descriptor->run_adding!= nullptr
&& descriptor->set_run_adding_gain != nullptr )
{
( descriptor->set_run_adding_gain ) ( _instance, _gain );
return( true );
}
return( false );
}
bool LadspaManager::deactivate( const ladspa_key_t & _plugin,
LADSPA_Handle _instance )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && descriptor->deactivate!= nullptr )
{
( descriptor->deactivate ) ( _instance );
return( true );
}
return( false );
}
bool LadspaManager::cleanup( const ladspa_key_t & _plugin,
LADSPA_Handle _instance )
{
const LADSPA_Descriptor * descriptor = getDescriptor( _plugin );
if( descriptor && descriptor->cleanup!= nullptr )
{
( descriptor->cleanup ) ( _instance );
return( true );
}
return( false );
}
} // namespace lmms
| 16,267
|
C++
|
.cpp
| 521
| 27.884837
| 106
| 0.705697
|
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,771
|
PathUtil.cpp
|
LMMS_lmms/src/core/PathUtil.cpp
|
#include "PathUtil.h"
#include <QDir>
#include <QFileInfo>
#include "ConfigManager.h"
#include "Engine.h"
#include "Song.h"
namespace lmms::PathUtil
{
auto relativeBases = std::array{ Base::ProjectDir, Base::FactorySample, Base::UserSample, Base::UserVST, Base::Preset,
Base::UserLADSPA, Base::DefaultLADSPA, Base::UserSoundfont, Base::DefaultSoundfont, Base::UserGIG, Base::DefaultGIG,
Base::LocalDir };
QString baseLocation(const Base base, bool* error /* = nullptr*/)
{
// error is false unless something goes wrong
if (error) { *error = false; }
QString loc = "";
switch (base)
{
case Base::ProjectDir : loc = ConfigManager::inst()->userProjectsDir(); break;
case Base::FactorySample :
{
QDir fsd = QDir(ConfigManager::inst()->factorySamplesDir());
loc = fsd.absolutePath(); break;
}
case Base::UserSample : loc = ConfigManager::inst()->userSamplesDir(); break;
case Base::UserVST : loc = ConfigManager::inst()->userVstDir(); break;
case Base::Preset : loc = ConfigManager::inst()->userPresetsDir(); break;
case Base::UserLADSPA : loc = ConfigManager::inst()->ladspaDir(); break;
case Base::DefaultLADSPA : loc = ConfigManager::inst()->userLadspaDir(); break;
case Base::UserSoundfont : loc = ConfigManager::inst()->sf2Dir(); break;
case Base::DefaultSoundfont : loc = ConfigManager::inst()->userSf2Dir(); break;
case Base::UserGIG : loc = ConfigManager::inst()->gigDir(); break;
case Base::DefaultGIG : loc = ConfigManager::inst()->userGigDir(); break;
case Base::LocalDir:
{
const Song* s = Engine::getSong();
QString projectPath;
if (s)
{
projectPath = s->projectFileName();
loc = QFileInfo(projectPath).path();
}
// We resolved it properly if we had an open Song and the project
// filename wasn't empty
if (error) { *error = (!s || projectPath.isEmpty()); }
break;
}
default : return QString("");
}
return QDir::cleanPath(loc) + "/";
}
QDir baseQDir (const Base base, bool* error /* = nullptr*/)
{
if (base == Base::Absolute)
{
if (error) { *error = false; }
return QDir::root();
}
return QDir(baseLocation(base, error));
}
QString basePrefix(const Base base)
{
switch (base)
{
case Base::ProjectDir : return QStringLiteral("userprojects:");
case Base::FactorySample : return QStringLiteral("factorysample:");
case Base::UserSample : return QStringLiteral("usersample:");
case Base::UserVST : return QStringLiteral("uservst:");
case Base::Preset : return QStringLiteral("preset:");
case Base::UserLADSPA : return QStringLiteral("userladspa:");
case Base::DefaultLADSPA : return QStringLiteral("defaultladspa:");
case Base::UserSoundfont : return QStringLiteral("usersoundfont:");
case Base::DefaultSoundfont : return QStringLiteral("defaultsoundfont:");
case Base::UserGIG : return QStringLiteral("usergig:");
case Base::DefaultGIG : return QStringLiteral("defaultgig:");
case Base::LocalDir : return QStringLiteral("local:");
default : return QStringLiteral("");
}
}
Base baseLookup(const QString & path)
{
for (auto base: relativeBases)
{
QString prefix = basePrefix(base);
if ( path.startsWith(prefix) ) { return base; }
}
return Base::Absolute;
}
QString stripPrefix(const QString & path)
{
return path.mid( basePrefix(baseLookup(path)).length() );
}
QString cleanName(const QString & path)
{
return stripPrefix(QFileInfo(path).baseName());
}
QString oldRelativeUpgrade(const QString & input)
{
if (input.isEmpty()) { return input; }
//Start by assuming that the file is a user sample
Base assumedBase = Base::UserSample;
//Check if it's a factory sample
QString factoryPath = baseLocation(Base::FactorySample) + input;
QFileInfo factoryInfo(factoryPath);
if (factoryInfo.exists()) { assumedBase = Base::FactorySample; }
//Check if it's a VST
QString vstPath = baseLocation(Base::UserVST) + input;
QFileInfo vstInfo(vstPath);
if (vstInfo.exists()) { assumedBase = Base::UserVST; }
//Assume we've found the correct base location, return the full path
return basePrefix(assumedBase) + input;
}
QString toAbsolute(const QString & input, bool* error /* = nullptr*/)
{
//First, do no harm to absolute paths
QFileInfo inputFileInfo = QFileInfo(input);
if (inputFileInfo.isAbsolute())
{
if (error) { *error = false; }
return input;
}
//Next, handle old relative paths with no prefix
QString upgraded = input.contains(":") ? input : oldRelativeUpgrade(input);
Base base = baseLookup(upgraded);
return baseLocation(base, error) + upgraded.remove(0, basePrefix(base).length());
}
QString relativeOrAbsolute(const QString & input, const Base base)
{
if (input.isEmpty()) { return input; }
QString absolutePath = toAbsolute(input);
if (base == Base::Absolute) { return absolutePath; }
bool error;
QString relativePath = baseQDir(base, &error).relativeFilePath(absolutePath);
// Return the relative path if it didn't result in a path starting with ..
// and the baseQDir was resolved properly
return (relativePath.startsWith("..") || error)
? absolutePath
: relativePath;
}
QString toShortestRelative(const QString & input, bool allowLocal /* = false*/)
{
QFileInfo inputFileInfo = QFileInfo(input);
QString absolutePath = inputFileInfo.isAbsolute() ? input : toAbsolute(input);
Base shortestBase = Base::Absolute;
QString shortestPath = relativeOrAbsolute(absolutePath, shortestBase);
for (auto base: relativeBases)
{
// Skip local paths when searching for the shortest relative if those
// are not allowed for that resource
if (base == Base::LocalDir && !allowLocal) { continue; }
QString otherPath = relativeOrAbsolute(absolutePath, base);
if (otherPath.length() < shortestPath.length())
{
shortestBase = base;
shortestPath = otherPath;
}
}
return basePrefix(shortestBase) + relativeOrAbsolute(absolutePath, shortestBase);
}
} // namespace lmms::PathUtil
| 6,205
|
C++
|
.cpp
| 160
| 35.4125
| 119
| 0.69438
|
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,772
|
InstrumentFunctions.cpp
|
LMMS_lmms/src/core/InstrumentFunctions.cpp
|
/*
* InstrumentFunctions.cpp - models for instrument-function-tab
*
* 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 "InstrumentFunctions.h"
#include "AudioEngine.h"
#include "embed.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "PresetPreviewPlayHandle.h"
#include <vector>
#include <algorithm>
namespace lmms
{
std::array<InstrumentFunctionNoteStacking::ChordTable::Init, InstrumentFunctionNoteStacking::NUM_CHORD_TABLES>
InstrumentFunctionNoteStacking::ChordTable::s_initTable =
std::array<InstrumentFunctionNoteStacking::ChordTable::Init, NUM_CHORD_TABLES>
{{
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "octave" ), { 0, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Major" ), { 0, 4, 7, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Majb5" ), { 0, 4, 6, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "minor" ), { 0, 3, 7, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "minb5" ), { 0, 3, 6, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "sus2" ), { 0, 2, 7, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "sus4" ), { 0, 5, 7, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "aug" ), { 0, 4, 8, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "augsus4" ), { 0, 5, 8, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "tri" ), { 0, 3, 6, 9, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "6" ), { 0, 4, 7, 9, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "6sus4" ), { 0, 5, 7, 9, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "6add9" ), { 0, 4, 7, 9, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m6" ), { 0, 3, 7, 9, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m6add9" ), { 0, 3, 7, 9, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7" ), { 0, 4, 7, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7sus4" ), { 0, 5, 7, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7#5" ), { 0, 4, 8, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7b5" ), { 0, 4, 6, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7#9" ), { 0, 4, 7, 10, 15, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7b9" ), { 0, 4, 7, 10, 13, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7#5#9" ), { 0, 4, 8, 10, 15, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7#5b9" ), { 0, 4, 8, 10, 13, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7b5b9" ), { 0, 4, 6, 10, 13, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7add11" ), { 0, 4, 7, 10, 17, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7add13" ), { 0, 4, 7, 10, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "7#11" ), { 0, 4, 7, 10, 18, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj7" ), { 0, 4, 7, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj7b5" ), { 0, 4, 6, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj7#5" ), { 0, 4, 8, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj7#11" ), { 0, 4, 7, 11, 18, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj7add13" ), { 0, 4, 7, 11, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m7" ), { 0, 3, 7, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m7b5" ), { 0, 3, 6, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m7b9" ), { 0, 3, 7, 10, 13, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m7add11" ), { 0, 3, 7, 10, 17, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m7add13" ), { 0, 3, 7, 10, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m-Maj7" ), { 0, 3, 7, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m-Maj7add11" ), { 0, 3, 7, 11, 17, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m-Maj7add13" ), { 0, 3, 7, 11, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "9" ), { 0, 4, 7, 10, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "9sus4" ), { 0, 5, 7, 10, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "add9" ), { 0, 4, 7, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "9#5" ), { 0, 4, 8, 10, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "9b5" ), { 0, 4, 6, 10, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "9#11" ), { 0, 4, 7, 10, 14, 18, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "9b13" ), { 0, 4, 7, 10, 14, 20, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj9" ), { 0, 4, 7, 11, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj9sus4" ), { 0, 5, 7, 11, 15, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj9#5" ), { 0, 4, 8, 11, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj9#11" ), { 0, 4, 7, 11, 14, 18, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m9" ), { 0, 3, 7, 10, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "madd9" ), { 0, 3, 7, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m9b5" ), { 0, 3, 6, 10, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m9-Maj7" ), { 0, 3, 7, 11, 14, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "11" ), { 0, 4, 7, 10, 14, 17, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "11b9" ), { 0, 4, 7, 10, 13, 17, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj11" ), { 0, 4, 7, 11, 14, 17, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m11" ), { 0, 3, 7, 10, 14, 17, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m-Maj11" ), { 0, 3, 7, 11, 14, 17, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "13" ), { 0, 4, 7, 10, 14, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "13#9" ), { 0, 4, 7, 10, 15, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "13b9" ), { 0, 4, 7, 10, 13, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "13b5b9" ), { 0, 4, 6, 10, 13, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Maj13" ), { 0, 4, 7, 11, 14, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m13" ), { 0, 3, 7, 10, 14, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "m-Maj13" ), { 0, 3, 7, 11, 14, 21, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Major" ), { 0, 2, 4, 5, 7, 9, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Harmonic minor" ), { 0, 2, 3, 5, 7, 8, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Melodic minor" ), { 0, 2, 3, 5, 7, 9, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Whole tone" ), { 0, 2, 4, 6, 8, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Diminished" ), { 0, 2, 3, 5, 6, 8, 9, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Major pentatonic" ), { 0, 2, 4, 7, 9, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Minor pentatonic" ), { 0, 3, 5, 7, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Jap in sen" ), { 0, 1, 5, 7, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Major bebop" ), { 0, 2, 4, 5, 7, 8, 9, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Dominant bebop" ), { 0, 2, 4, 5, 7, 9, 10, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Blues" ), { 0, 3, 5, 6, 7, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Arabic" ), { 0, 1, 4, 5, 7, 8, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Enigmatic" ), { 0, 1, 4, 6, 8, 10, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Neopolitan" ), { 0, 1, 3, 5, 7, 9, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Neopolitan minor" ), { 0, 1, 3, 5, 7, 8, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Hungarian minor" ), { 0, 2, 3, 6, 7, 8, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Dorian" ), { 0, 2, 3, 5, 7, 9, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Phrygian" ), { 0, 1, 3, 5, 7, 8, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Lydian" ), { 0, 2, 4, 6, 7, 9, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Mixolydian" ), { 0, 2, 4, 5, 7, 9, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Aeolian" ), { 0, 2, 3, 5, 7, 8, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Locrian" ), { 0, 1, 3, 5, 6, 8, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Minor" ), { 0, 2, 3, 5, 7, 8, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Chromatic" ), { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Half-Whole Diminished" ), { 0, 1, 3, 4, 6, 7, 9, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "5" ), { 0, 7, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Phrygian dominant" ), { 0, 1, 4, 5, 7, 8, 10, -1 } },
{ QT_TRANSLATE_NOOP( "InstrumentFunctionNoteStacking", "Persian" ), { 0, 1, 4, 5, 6, 8, 11, -1 } }
}};
InstrumentFunctionNoteStacking::Chord::Chord( const char * n, const ChordSemiTones & semi_tones ) :
m_name( InstrumentFunctionNoteStacking::tr( n ) )
{
for( m_size = 0; m_size < MAX_CHORD_POLYPHONY; m_size++ )
{
if( semi_tones[m_size] == -1 )
{
break;
}
m_semiTones[m_size] = semi_tones[m_size];
}
}
bool InstrumentFunctionNoteStacking::Chord::hasSemiTone( int8_t semi_tone ) const
{
for( int i = 0; i < size(); ++i )
{
if( semi_tone == m_semiTones[i] )
{
return true;
}
}
return false;
}
InstrumentFunctionNoteStacking::ChordTable::ChordTable()
{
for (const auto& chord : s_initTable)
{
m_chords.emplace_back(chord.m_name, chord.m_semiTones);
}
}
const InstrumentFunctionNoteStacking::Chord & InstrumentFunctionNoteStacking::ChordTable::getByName( const QString & name, bool is_scale ) const
{
for (const auto& chord : m_chords)
{
if (chord.getName() == name && is_scale == chord.isScale())
{
return chord;
}
}
static Chord empty;
return empty;
}
InstrumentFunctionNoteStacking::InstrumentFunctionNoteStacking( Model * _parent ) :
Model( _parent, tr( "Chords" ) ),
m_chordsEnabledModel( false, this ),
m_chordsModel( this, tr( "Chord type" ) ),
m_chordRangeModel( 1.0f, 1.0f, 9.0f, 1.0f, this, tr( "Chord range" ) )
{
const ChordTable & chord_table = ChordTable::getInstance();
for (const auto& chord : chord_table.chords())
{
m_chordsModel.addItem(chord.getName());
}
}
void InstrumentFunctionNoteStacking::processNote( NotePlayHandle * _n )
{
const int base_note_key = _n->key();
const ChordTable & chord_table = ChordTable::getInstance();
// we add chord-subnotes to note if either note is a base-note and
// arpeggio is not used or note is part of an arpeggio
// at the same time we only add sub-notes if nothing of the note was
// played yet, because otherwise we would add chord-subnotes every
// time an audio-buffer is rendered...
if( ( _n->origin() == NotePlayHandle::Origin::Arpeggio || ( _n->hasParent() == false && _n->instrumentTrack()->isArpeggioEnabled() == false ) ) &&
_n->totalFramesPlayed() == 0 &&
m_chordsEnabledModel.value() == true && ! _n->isReleased() )
{
// then insert sub-notes for chord
const int selected_chord = m_chordsModel.value();
for( int octave_cnt = 0; octave_cnt < m_chordRangeModel.value(); ++octave_cnt )
{
const int sub_note_key_base = base_note_key + octave_cnt * KeysPerOctave;
// process all notes in the chord
for( int i = 0; i < chord_table.chords()[selected_chord].size(); ++i )
{
// add interval to sub-note-key
const int sub_note_key = sub_note_key_base + (int) chord_table.chords()[selected_chord][i];
// maybe we're out of range -> let's get outta
// here!
if( sub_note_key > NumKeys )
{
break;
}
// create copy of base-note
Note note_copy( _n->length(), 0, sub_note_key, _n->getVolume(), _n->getPanning(), _n->detuning() );
// create sub-note-play-handle, only note is
// different
Engine::audioEngine()->addPlayHandle(
NotePlayHandleManager::acquire( _n->instrumentTrack(), _n->offset(), _n->frames(), note_copy,
_n, -1, NotePlayHandle::Origin::NoteStacking )
);
}
}
}
}
void InstrumentFunctionNoteStacking::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
m_chordsEnabledModel.saveSettings( _doc, _this, "chord-enabled" );
m_chordsModel.saveSettings( _doc, _this, "chord" );
m_chordRangeModel.saveSettings( _doc, _this, "chordrange" );
}
void InstrumentFunctionNoteStacking::loadSettings( const QDomElement & _this )
{
m_chordsEnabledModel.loadSettings( _this, "chord-enabled" );
m_chordsModel.loadSettings( _this, "chord" );
m_chordRangeModel.loadSettings( _this, "chordrange" );
}
InstrumentFunctionArpeggio::InstrumentFunctionArpeggio( Model * _parent ) :
Model( _parent, tr( "Arpeggio" ) ),
m_arpEnabledModel( false ),
m_arpModel( this, tr( "Arpeggio type" ) ),
m_arpRangeModel( 1.0f, 1.0f, 9.0f, 1.0f, this, tr( "Arpeggio range" ) ),
m_arpRepeatsModel( 1.0f, 1.0f, 8.0f, 1.0f, this, tr( "Note repeats" ) ),
m_arpCycleModel( 0.0f, 0.0f, 6.0f, 1.0f, this, tr( "Cycle steps" ) ),
m_arpSkipModel( 0.0f, 0.0f, 100.0f, 1.0f, this, tr( "Skip rate" ) ),
m_arpMissModel( 0.0f, 0.0f, 100.0f, 1.0f, this, tr( "Miss rate" ) ),
m_arpTimeModel( 200.0f, 25.0f, 2000.0f, 1.0f, 2000, this, tr( "Arpeggio time" ) ),
m_arpGateModel( 100.0f, 1.0f, 200.0f, 1.0f, this, tr( "Arpeggio gate" ) ),
m_arpDirectionModel( this, tr( "Arpeggio direction" ) ),
m_arpModeModel( this, tr( "Arpeggio mode" ) )
{
const InstrumentFunctionNoteStacking::ChordTable & chord_table = InstrumentFunctionNoteStacking::ChordTable::getInstance();
for (auto& chord : chord_table.chords())
{
m_arpModel.addItem(chord.getName());
}
m_arpDirectionModel.addItem( tr( "Up" ), std::make_unique<PixmapLoader>( "arp_up" ) );
m_arpDirectionModel.addItem( tr( "Down" ), std::make_unique<PixmapLoader>( "arp_down" ) );
m_arpDirectionModel.addItem( tr( "Up and down" ), std::make_unique<PixmapLoader>( "arp_up_and_down" ) );
m_arpDirectionModel.addItem( tr( "Down and up" ), std::make_unique<PixmapLoader>( "arp_up_and_down" ) );
m_arpDirectionModel.addItem( tr( "Random" ), std::make_unique<PixmapLoader>( "arp_random" ) );
m_arpDirectionModel.setInitValue( static_cast<float>(ArpDirection::Up) );
m_arpModeModel.addItem( tr( "Free" ), std::make_unique<PixmapLoader>( "arp_free" ) );
m_arpModeModel.addItem( tr( "Sort" ), std::make_unique<PixmapLoader>( "arp_sort" ) );
m_arpModeModel.addItem( tr( "Sync" ), std::make_unique<PixmapLoader>( "arp_sync" ) );
}
void InstrumentFunctionArpeggio::processNote( NotePlayHandle * _n )
{
const int base_note_key = _n->key();
if( _n->origin() == NotePlayHandle::Origin::Arpeggio ||
_n->origin() == NotePlayHandle::Origin::NoteStacking ||
!m_arpEnabledModel.value() ||
_n->isReleased() )
{
return;
}
// Set master note if not playing arp note or it will play as an ordinary note
_n->setMasterNote();
const int selected_arp = m_arpModel.value();
const auto arpMode = static_cast<ArpMode>(m_arpModeModel.value());
ConstNotePlayHandleList cnphv = NotePlayHandle::nphsOfInstrumentTrack(_n->instrumentTrack());
if(arpMode != ArpMode::Free && cnphv.size() == 0 )
{
// maybe we're playing only a preset-preview-note?
cnphv = PresetPreviewPlayHandle::nphsOfInstrumentTrack( _n->instrumentTrack() );
if( cnphv.size() == 0 )
{
// still nothing found here, so lets return
//return;
cnphv.push_back( _n );
}
}
// avoid playing same key for all
// currently playing notes if sort mode is enabled
if (arpMode == ArpMode::Sort && _n != cnphv.first()) { return; }
const InstrumentFunctionNoteStacking::ChordTable & chord_table = InstrumentFunctionNoteStacking::ChordTable::getInstance();
const int cur_chord_size = chord_table.chords()[selected_arp].size();
const int total_chord_size = cur_chord_size * cnphv.size();
// how many notes are in a single chord (multiplied by range)
const int singleNoteRange = static_cast<int>(cur_chord_size * m_arpRangeModel.value() * m_arpRepeatsModel.value());
// how many notes are in the final chord
const int range = arpMode == ArpMode::Sort ? singleNoteRange * cnphv.size() : singleNoteRange;
if (arpMode == ArpMode::Sort)
{
std::sort(cnphv.begin(), cnphv.end(), [](const NotePlayHandle* a, const NotePlayHandle* b)
{
return a->key() < b->key();
});
}
// number of frames that every note should be played
const auto arp_frames = (f_cnt_t)(m_arpTimeModel.value() / 1000.0f * Engine::audioEngine()->outputSampleRate());
const auto gated_frames = (f_cnt_t)(m_arpGateModel.value() * arp_frames / 100.0f);
// used for calculating remaining frames for arp-note, we have to add
// arp_frames-1, otherwise the first arp-note will not be setup
// correctly... -> arp_frames frames silence at the start of every note!
int cur_frame = (arpMode != ArpMode::Free ?
cnphv.first()->totalFramesPlayed() :
_n->totalFramesPlayed()) + arp_frames - 1;
// used for loop
f_cnt_t frames_processed = arpMode != ArpMode::Free ? cnphv.first()->noteOffset() : _n->noteOffset();
while( frames_processed < Engine::audioEngine()->framesPerPeriod() )
{
const f_cnt_t remaining_frames_for_cur_arp = arp_frames - ( cur_frame % arp_frames );
// does current arp-note fill whole audio-buffer or is the remaining time just
// a short bit that we can discard?
if( remaining_frames_for_cur_arp > Engine::audioEngine()->framesPerPeriod() ||
_n->frames() - _n->totalFramesPlayed() < arp_frames / 5 )
{
// then we don't have to do something!
break;
}
frames_processed += remaining_frames_for_cur_arp;
// Skip notes randomly
if( m_arpSkipModel.value() )
{
if (100 * static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) + 1.0f) < m_arpSkipModel.value())
{
// update counters
frames_processed += arp_frames;
cur_frame += arp_frames;
continue;
}
}
auto dir = static_cast<ArpDirection>(m_arpDirectionModel.value());
// Miss notes randomly. We intercept int dir and abuse it
// after need. :)
if( m_arpMissModel.value() )
{
if (100 * static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) + 1.0f) < m_arpMissModel.value())
{
dir = ArpDirection::Random;
}
}
int cur_arp_idx = 0;
// process according to arpeggio-direction...
if (dir == ArpDirection::Up || dir == ArpDirection::Down)
{
cur_arp_idx = (cur_frame / arp_frames) % range;
}
else if ((dir == ArpDirection::UpAndDown || dir == ArpDirection::DownAndUp) && range > 1)
{
// imagine, we had to play the arp once up and then
// once down -> makes 2 * range possible notes...
// because we don't play the lower and upper notes
// twice, we have to subtract 2
cur_arp_idx = (cur_frame / arp_frames) % (range * 2 - (2 * static_cast<int>(m_arpRepeatsModel.value())));
// if greater than range, we have to play down...
// looks like the code for arp_dir==DOWN... :)
if (cur_arp_idx >= range)
{
cur_arp_idx = range - cur_arp_idx % (range - 1) - static_cast<int>(m_arpRepeatsModel.value());
}
}
else if( dir == ArpDirection::Random )
{
// just pick a random chord-index
cur_arp_idx = static_cast<int>(range * static_cast<float>(rand()) / static_cast<float>(RAND_MAX));
}
// Divide cur_arp_idx with wanted repeats. The repeat feature will not affect random notes.
cur_arp_idx = static_cast<int>(cur_arp_idx / m_arpRepeatsModel.value());
// Cycle notes
if( m_arpCycleModel.value() && dir != ArpDirection::Random )
{
cur_arp_idx *= m_arpCycleModel.value() + 1;
cur_arp_idx %= static_cast<int>(range / m_arpRepeatsModel.value());
}
// If ArpDirection::Down or ArpDirection::DownAndUp, invert the final range.
if (dir == ArpDirection::Down || dir == ArpDirection::DownAndUp)
{
cur_arp_idx = static_cast<int>(range / m_arpRepeatsModel.value()) - cur_arp_idx - 1;
}
// now calculate final key for our arp-note
int sub_note_key = 0;
if (arpMode != ArpMode::Sort)
{
sub_note_key = base_note_key + (cur_arp_idx / cur_chord_size) *
KeysPerOctave + chord_table.chords()[selected_arp][cur_arp_idx % cur_chord_size];
}
else
{
const auto octaveDiv = std::div(cur_arp_idx, total_chord_size);
const int octave = octaveDiv.quot;
const auto arpDiv = std::div(octaveDiv.rem, cnphv.size());
const int arpIndex = arpDiv.rem;
const int chordIndex = arpDiv.quot;
sub_note_key = cnphv[arpIndex]->key()
+ chord_table.chords()[selected_arp][chordIndex]
+ octave * KeysPerOctave;
}
// range-checking
if( sub_note_key >= NumKeys ||
sub_note_key < 0 ||
Engine::audioEngine()->criticalXRuns() )
{
continue;
}
// create new arp-note
// create sub-note-play-handle, only ptr to note is different
// and is_arp_note=true
Engine::audioEngine()->addPlayHandle(
NotePlayHandleManager::acquire( _n->instrumentTrack(),
frames_processed,
gated_frames,
Note( TimePos( 0 ), TimePos( 0 ), sub_note_key, _n->getVolume(),
_n->getPanning(), _n->detuning() ),
_n, -1, NotePlayHandle::Origin::Arpeggio )
);
// update counters
frames_processed += arp_frames;
cur_frame += arp_frames;
}
}
void InstrumentFunctionArpeggio::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
m_arpEnabledModel.saveSettings( _doc, _this, "arp-enabled" );
m_arpModel.saveSettings( _doc, _this, "arp" );
m_arpRangeModel.saveSettings( _doc, _this, "arprange" );
m_arpRepeatsModel.saveSettings( _doc, _this, "arprepeats" );
m_arpCycleModel.saveSettings( _doc, _this, "arpcycle" );
m_arpSkipModel.saveSettings( _doc, _this, "arpskip" );
m_arpMissModel.saveSettings( _doc, _this, "arpmiss" );
m_arpTimeModel.saveSettings( _doc, _this, "arptime" );
m_arpGateModel.saveSettings( _doc, _this, "arpgate" );
m_arpDirectionModel.saveSettings( _doc, _this, "arpdir" );
m_arpModeModel.saveSettings( _doc, _this, "arpmode" );
}
void InstrumentFunctionArpeggio::loadSettings( const QDomElement & _this )
{
m_arpEnabledModel.loadSettings( _this, "arp-enabled" );
m_arpModel.loadSettings( _this, "arp" );
m_arpRangeModel.loadSettings( _this, "arprange" );
m_arpRepeatsModel.loadSettings( _this, "arprepeats" );
m_arpCycleModel.loadSettings( _this, "arpcycle" );
m_arpSkipModel.loadSettings( _this, "arpskip" );
m_arpMissModel.loadSettings( _this, "arpmiss" );
m_arpTimeModel.loadSettings( _this, "arptime" );
m_arpGateModel.loadSettings( _this, "arpgate" );
m_arpDirectionModel.loadSettings( _this, "arpdir" );
m_arpModeModel.loadSettings( _this, "arpmode" );
}
} // namespace lmms
| 24,242
|
C++
|
.cpp
| 465
| 49.335484
| 147
| 0.667624
|
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,773
|
ModelVisitor.cpp
|
LMMS_lmms/src/core/ModelVisitor.cpp
|
/*
* ModelVisitor.cpp - visitors for automatable models
*
* Copyright (c) 2019-2019 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 "ModelVisitor.h"
#include "AutomatableModel.h"
#include "ComboBoxModel.h"
#include "TempoSyncKnobModel.h"
namespace lmms
{
void ModelVisitor::visit(BoolModel &m) { up(m); }
void ModelVisitor::visit(IntModel &m) { up(m); }
void ModelVisitor::visit(FloatModel &m) { up(m); }
void ModelVisitor::visit(ComboBoxModel &m) { up<IntModel>(m); }
void ModelVisitor::visit(TempoSyncKnobModel &m) { up<FloatModel>(m); }
void ConstModelVisitor::visit(const BoolModel &m) { up(m); }
void ConstModelVisitor::visit(const IntModel &m) { up(m); }
void ConstModelVisitor::visit(const FloatModel &m) { up(m); }
void ConstModelVisitor::visit(const ComboBoxModel &m) { up<IntModel>(m); }
void ConstModelVisitor::visit(const TempoSyncKnobModel &m) { up<FloatModel>(m); }
} // namespace lmms
| 1,710
|
C++
|
.cpp
| 40
| 41.05
| 81
| 0.746394
|
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,774
|
ThreadPool.cpp
|
LMMS_lmms/src/core/ThreadPool.cpp
|
/*
* ThreadPool.cpp
*
* 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 "ThreadPool.h"
#include <cassert>
#include <cstddef>
#include <memory>
namespace lmms {
ThreadPool::ThreadPool(size_t numWorkers)
{
assert(numWorkers > 0);
m_workers.reserve(numWorkers);
for (size_t i = 0; i < numWorkers; ++i)
{
m_workers.emplace_back([this] { run(); });
}
}
ThreadPool::~ThreadPool()
{
{
const auto lock = std::unique_lock{m_runMutex};
m_done = true;
}
m_runCond.notify_all();
for (auto& worker : m_workers)
{
if (worker.joinable()) { worker.join(); }
}
}
auto ThreadPool::numWorkers() const -> size_t
{
return m_workers.size();
}
void ThreadPool::run()
{
while (!m_done)
{
std::function<void()> task;
{
auto lock = std::unique_lock{m_runMutex};
m_runCond.wait(lock, [this] { return !m_queue.empty() || m_done; });
if (m_done) { break; }
task = m_queue.front();
m_queue.pop();
}
task();
}
}
auto ThreadPool::instance() -> ThreadPool&
{
static auto s_pool = ThreadPool{s_numWorkers};
return s_pool;
}
} // namespace lmms
| 1,852
|
C++
|
.cpp
| 74
| 22.932432
| 71
| 0.703452
|
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,775
|
base64.cpp
|
LMMS_lmms/src/core/base64.cpp
|
/*
* base64.cpp - namespace base64 with methods for encoding/decoding binary data
* to/from base64
*
* 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 "base64.h"
#include <QBuffer>
#include <QDataStream>
namespace lmms::base64
{
QVariant decode( const QString & _b64, QVariant::Type _force_type )
{
char * dst = nullptr;
int dsize = 0;
base64::decode( _b64, &dst, &dsize );
QByteArray ba( dst, dsize );
QBuffer buf( &ba );
buf.open( QBuffer::ReadOnly );
QDataStream in( &buf );
QVariant ret;
in >> ret;
if( _force_type != QVariant::Invalid && ret.type() != _force_type )
{
buf.reset();
in.setVersion( QDataStream::Qt_3_3 );
in >> ret;
}
delete[] dst;
return( ret );
}
} // namespace lmms::base64
| 1,570
|
C++
|
.cpp
| 50
| 29.4
| 79
| 0.717779
|
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,776
|
MixHelpers.cpp
|
LMMS_lmms/src/core/MixHelpers.cpp
|
/*
* MixHelpers.cpp - helper functions for mixing buffers
*
* Copyright (c) 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 "MixHelpers.h"
#ifdef LMMS_DEBUG
#include <cstdio>
#endif
#include <cmath>
#include <QtGlobal>
#include "ValueBuffer.h"
#include "SampleFrame.h"
static bool s_NaNHandler;
namespace lmms::MixHelpers
{
/*! \brief Function for applying MIXOP on all sample frames */
template<typename MIXOP>
static inline void run( SampleFrame* dst, const SampleFrame* src, int frames, const MIXOP& OP )
{
for( int i = 0; i < frames; ++i )
{
OP( dst[i], src[i] );
}
}
/*! \brief Function for applying MIXOP on all sample frames - split source */
template<typename MIXOP>
static inline void run( SampleFrame* dst, const sample_t* srcLeft, const sample_t* srcRight, int frames, const MIXOP& OP )
{
for( int i = 0; i < frames; ++i )
{
const SampleFrame src = { srcLeft[i], srcRight[i] };
OP( dst[i], src );
}
}
bool isSilent( const SampleFrame* src, int frames )
{
const float silenceThreshold = 0.0000001f;
for( int i = 0; i < frames; ++i )
{
if( fabsf( src[i][0] ) >= silenceThreshold || fabsf( src[i][1] ) >= silenceThreshold )
{
return false;
}
}
return true;
}
bool useNaNHandler()
{
return s_NaNHandler;
}
void setNaNHandler( bool use )
{
s_NaNHandler = use;
}
/*! \brief Function for sanitizing a buffer of infs/nans - returns true if those are found */
bool sanitize( SampleFrame* src, int frames )
{
if( !useNaNHandler() )
{
return false;
}
for (int f = 0; f < frames; ++f)
{
auto& currentFrame = src[f];
if (currentFrame.containsInf() || currentFrame.containsNaN())
{
#ifdef LMMS_DEBUG
// TODO don't use printf here
printf("Bad data, clearing buffer. frame: ");
printf("%d: value %f, %f\n", f, currentFrame.left(), currentFrame.right());
#endif
// Clear the whole buffer if a problem is found
zeroSampleFrames(src, frames);
return true;
}
else
{
currentFrame.clamp(sample_t(-1000.0), sample_t(1000.0));
}
};
return false;
}
struct AddOp
{
void operator()( SampleFrame& dst, const SampleFrame& src ) const
{
dst += src;
}
} ;
void add( SampleFrame* dst, const SampleFrame* src, int frames )
{
run<>( dst, src, frames, AddOp() );
}
struct AddMultipliedOp
{
AddMultipliedOp( float coeff ) : m_coeff( coeff ) { }
void operator()( SampleFrame& dst, const SampleFrame& src ) const
{
dst += src * m_coeff;
}
const float m_coeff;
} ;
void addMultiplied( SampleFrame* dst, const SampleFrame* src, float coeffSrc, int frames )
{
run<>( dst, src, frames, AddMultipliedOp(coeffSrc) );
}
struct AddSwappedMultipliedOp
{
AddSwappedMultipliedOp( float coeff ) : m_coeff( coeff ) { }
void operator()( SampleFrame& dst, const SampleFrame& src ) const
{
dst[0] += src[1] * m_coeff;
dst[1] += src[0] * m_coeff;
}
const float m_coeff;
};
void multiply(SampleFrame* dst, float coeff, int frames)
{
for (int i = 0; i < frames; ++i)
{
dst[i] *= coeff;
}
}
void addSwappedMultiplied( SampleFrame* dst, const SampleFrame* src, float coeffSrc, int frames )
{
run<>( dst, src, frames, AddSwappedMultipliedOp(coeffSrc) );
}
void addMultipliedByBuffer( SampleFrame* dst, const SampleFrame* src, float coeffSrc, ValueBuffer * coeffSrcBuf, int frames )
{
for( int f = 0; f < frames; ++f )
{
dst[f][0] += src[f][0] * coeffSrc * coeffSrcBuf->values()[f];
dst[f][1] += src[f][1] * coeffSrc * coeffSrcBuf->values()[f];
}
}
void addMultipliedByBuffers( SampleFrame* dst, const SampleFrame* src, ValueBuffer * coeffSrcBuf1, ValueBuffer * coeffSrcBuf2, int frames )
{
for( int f = 0; f < frames; ++f )
{
dst[f][0] += src[f][0] * coeffSrcBuf1->values()[f] * coeffSrcBuf2->values()[f];
dst[f][1] += src[f][1] * coeffSrcBuf1->values()[f] * coeffSrcBuf2->values()[f];
}
}
void addSanitizedMultipliedByBuffer( SampleFrame* dst, const SampleFrame* src, float coeffSrc, ValueBuffer * coeffSrcBuf, int frames )
{
if ( !useNaNHandler() )
{
addMultipliedByBuffer( dst, src, coeffSrc, coeffSrcBuf,
frames );
return;
}
for( int f = 0; f < frames; ++f )
{
dst[f][0] += ( std::isinf( src[f][0] ) || std::isnan( src[f][0] ) ) ? 0.0f : src[f][0] * coeffSrc * coeffSrcBuf->values()[f];
dst[f][1] += ( std::isinf( src[f][1] ) || std::isnan( src[f][1] ) ) ? 0.0f : src[f][1] * coeffSrc * coeffSrcBuf->values()[f];
}
}
void addSanitizedMultipliedByBuffers( SampleFrame* dst, const SampleFrame* src, ValueBuffer * coeffSrcBuf1, ValueBuffer * coeffSrcBuf2, int frames )
{
if ( !useNaNHandler() )
{
addMultipliedByBuffers( dst, src, coeffSrcBuf1, coeffSrcBuf2,
frames );
return;
}
for( int f = 0; f < frames; ++f )
{
dst[f][0] += ( std::isinf( src[f][0] ) || std::isnan( src[f][0] ) )
? 0.0f
: src[f][0] * coeffSrcBuf1->values()[f] * coeffSrcBuf2->values()[f];
dst[f][1] += ( std::isinf( src[f][1] ) || std::isnan( src[f][1] ) )
? 0.0f
: src[f][1] * coeffSrcBuf1->values()[f] * coeffSrcBuf2->values()[f];
}
}
struct AddSanitizedMultipliedOp
{
AddSanitizedMultipliedOp( float coeff ) : m_coeff( coeff ) { }
void operator()( SampleFrame& dst, const SampleFrame& src ) const
{
dst[0] += ( std::isinf( src[0] ) || std::isnan( src[0] ) ) ? 0.0f : src[0] * m_coeff;
dst[1] += ( std::isinf( src[1] ) || std::isnan( src[1] ) ) ? 0.0f : src[1] * m_coeff;
}
const float m_coeff;
};
void addSanitizedMultiplied( SampleFrame* dst, const SampleFrame* src, float coeffSrc, int frames )
{
if ( !useNaNHandler() )
{
addMultiplied( dst, src, coeffSrc, frames );
return;
}
run<>( dst, src, frames, AddSanitizedMultipliedOp(coeffSrc) );
}
struct AddMultipliedStereoOp
{
AddMultipliedStereoOp( float coeffLeft, float coeffRight )
{
m_coeffs[0] = coeffLeft;
m_coeffs[1] = coeffRight;
}
void operator()( SampleFrame& dst, const SampleFrame& src ) const
{
dst[0] += src[0] * m_coeffs[0];
dst[1] += src[1] * m_coeffs[1];
}
std::array<float, 2> m_coeffs;
} ;
void addMultipliedStereo( SampleFrame* dst, const SampleFrame* src, float coeffSrcLeft, float coeffSrcRight, int frames )
{
run<>( dst, src, frames, AddMultipliedStereoOp(coeffSrcLeft, coeffSrcRight) );
}
struct MultiplyAndAddMultipliedOp
{
MultiplyAndAddMultipliedOp( float coeffDst, float coeffSrc )
{
m_coeffs[0] = coeffDst;
m_coeffs[1] = coeffSrc;
}
void operator()( SampleFrame& dst, const SampleFrame& src ) const
{
dst[0] = dst[0]*m_coeffs[0] + src[0]*m_coeffs[1];
dst[1] = dst[1]*m_coeffs[0] + src[1]*m_coeffs[1];
}
std::array<float, 2> m_coeffs;
} ;
void multiplyAndAddMultiplied( SampleFrame* dst, const SampleFrame* src, float coeffDst, float coeffSrc, int frames )
{
run<>( dst, src, frames, MultiplyAndAddMultipliedOp(coeffDst, coeffSrc) );
}
void multiplyAndAddMultipliedJoined( SampleFrame* dst,
const sample_t* srcLeft,
const sample_t* srcRight,
float coeffDst, float coeffSrc, int frames )
{
run<>( dst, srcLeft, srcRight, frames, MultiplyAndAddMultipliedOp(coeffDst, coeffSrc) );
}
} // namespace lmms::MixHelpers
| 7,870
|
C++
|
.cpp
| 257
| 28.214008
| 148
| 0.688694
|
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,777
|
ProjectVersion.cpp
|
LMMS_lmms/src/core/ProjectVersion.cpp
|
/*
* ProjectVersion.cpp - compare versions in import upgrades
*
* Copyright (c) 2007 Javier Serrano Polo <jasp00/at/users.sourceforge.net>
* Copyright (c) 2008 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2015 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 "ProjectVersion.h"
namespace lmms
{
ProjectVersion::ProjectVersion(QString version, CompareType c) :
m_version(version),
m_compareType(c)
{
// Version numbers may have build data, prefixed with a '+',
// but this mustn't affect version precedence in comparisons
QString metadataStripped = version.split("+").first();
// They must have an obligatory initial segement, and may have
// optional identifiers prefaced by a '-'. Both parts affect precedence
QString obligatorySegment = metadataStripped.section('-', 0, 0);
QString prereleaseSegment = metadataStripped.section('-', 1);
// The obligatory segment consists of three identifiers: MAJOR.MINOR.PATCH
QStringList mainVersion = obligatorySegment.split(".");
// HACK: Pad invalid versions in order to prevent crashes
while (mainVersion.size() < 3){ mainVersion.append("0"); }
m_major = mainVersion.at(0).toInt();
m_minor = mainVersion.at(1).toInt();
m_patch = mainVersion.at(2).toInt();
// Any # of optional pre-release identifiers may follow, separated by '.'s
if (!prereleaseSegment.isEmpty()){ m_labels = prereleaseSegment.split("."); }
// HACK: Handle old (1.2.2 and earlier), non-standard versions of the form
// MAJOR.MINOR.PATCH.COMMITS, used for non-release builds from source.
if (mainVersion.size() >= 4 && m_major <= 1 && m_minor <= 2 && m_patch <= 2){
// Drop the standard version identifiers. erase(a, b) removes [a,b)
mainVersion.erase(mainVersion.begin(), mainVersion.begin() + 3);
// Prepend the remaining identifiers as prerelease versions
m_labels = mainVersion + m_labels;
// Bump the patch version. x.y.z-a < x.y.z, but we want x.y.z.a > x.y.z
m_patch += 1;
}
}
ProjectVersion::ProjectVersion(const char* version, CompareType c) : ProjectVersion(QString(version), c)
{
}
//! @param c Determines the number of identifiers to check when comparing
int ProjectVersion::compare(const ProjectVersion & a, const ProjectVersion & b, CompareType c)
{
// How many identifiers to compare before we consider the versions equal
const int limit = static_cast<int>(c);
// Use the value of limit to zero out identifiers we don't care about
int aMaj = 0, bMaj = 0, aMin = 0, bMin = 0, aPat = 0, bPat = 0;
if (limit >= 1){ aMaj = a.getMajor(); bMaj = b.getMajor(); }
if (limit >= 2){ aMin = a.getMinor(); bMin = b.getMinor(); }
if (limit >= 3){ aPat = a.getPatch(); bPat = b.getPatch(); }
// Then we can compare as if we care about every identifier
if(aMaj != bMaj){ return aMaj - bMaj; }
if(aMin != bMin){ return aMin - bMin; }
if(aPat != bPat){ return aPat - bPat; }
// Decide how many optional identifiers we care about
const int maxLabels = std::max(0, limit - 3);
const auto aLabels = a.getLabels().mid(0, maxLabels);
const auto bLabels = b.getLabels().mid(0, maxLabels);
// We can only compare identifiers if both versions have them
const int commonLabels = std::min(aLabels.size(), bLabels.size());
// If one version has optional labels and the other doesn't,
// the one without them is bigger
if (commonLabels == 0){ return bLabels.size() - aLabels.size(); }
// Otherwise, compare as many labels as we can
for (int i = 0; i < commonLabels; i++){
const QString& labelA = aLabels.at(i);
const QString& labelB = bLabels.at(i);
// If both labels are the same, skip
if (labelA == labelB){ continue; }
// Numeric and non-numeric identifiers compare differently
bool aIsNumeric = false, bIsNumeric = false;
const int numA = labelA.toInt(&aIsNumeric);
const int numB = labelB.toInt(&bIsNumeric);
// toInt reads '-x' as a negative number, semver says it's non-numeric
aIsNumeric &= !labelA.startsWith("-");
bIsNumeric &= !labelB.startsWith("-");
// If only one identifier is numeric, that one is smaller
if (aIsNumeric != bIsNumeric){ return aIsNumeric ? -1 : 1; }
// If both are numeric, compare as numbers
if (aIsNumeric && bIsNumeric){ return numA - numB; }
// Otherwise, compare lexically
return labelA.compare(labelB);
}
// If everything else matches, the version with more labels is bigger
return aLabels.size() - bLabels.size();
}
int ProjectVersion::compare(ProjectVersion v1, ProjectVersion v2)
{
return compare(v1, v2, std::min(v1.getCompareType(), v2.getCompareType()));
}
} // namespace lmms
| 5,367
|
C++
|
.cpp
| 113
| 45.20354
| 104
| 0.725029
|
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,778
|
ToolPlugin.cpp
|
LMMS_lmms/src/core/ToolPlugin.cpp
|
/*
* ToolPlugin.cpp - base class for all tool plugins (graphs, extensions, etc)
*
* Copyright (c) 2006-2008 Javier Serrano Polo <jasp00/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 "ToolPlugin.h"
namespace lmms
{
ToolPlugin::ToolPlugin( const Descriptor * _descriptor, Model * _parent ) :
Plugin( _descriptor, _parent )
{
}
ToolPlugin * ToolPlugin::instantiate( const QString & _plugin_name, Model * _parent )
{
Plugin * p = Plugin::instantiate( _plugin_name, _parent, nullptr );
// check whether instantiated plugin is a tool
if( p->type() == Plugin::Type::Tool )
{
// everything ok, so return pointer
return dynamic_cast<ToolPlugin *>( p );
}
// not quite... so delete plugin
delete p;
return nullptr;
}
} // namespace lmms
| 1,610
|
C++
|
.cpp
| 45
| 33.733333
| 85
| 0.738739
|
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,779
|
Note.cpp
|
LMMS_lmms/src/core/Note.cpp
|
/*
* Note.cpp - implementation of class note
*
* 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 <cmath>
#include "Note.h"
#include "DetuningHelper.h"
namespace lmms
{
Note::Note( const TimePos & length, const TimePos & pos,
int key, volume_t volume, panning_t panning,
DetuningHelper * detuning ) :
m_selected( false ),
m_oldKey(std::clamp(key, 0, NumKeys)),
m_oldPos( pos ),
m_oldLength( length ),
m_isPlaying( false ),
m_key(std::clamp(key, 0, NumKeys)),
m_volume(std::clamp(volume, MinVolume, MaxVolume)),
m_panning(std::clamp(panning, PanningLeft, PanningRight)),
m_length( length ),
m_pos( pos ),
m_detuning( nullptr )
{
if( detuning )
{
m_detuning = sharedObject::ref( detuning );
}
else
{
createDetuning();
}
}
Note::Note( const Note & note ) :
SerializingObject( note ),
m_selected( note.m_selected ),
m_oldKey( note.m_oldKey ),
m_oldPos( note.m_oldPos ),
m_oldLength( note.m_oldLength ),
m_isPlaying( note.m_isPlaying ),
m_key( note.m_key),
m_volume( note.m_volume ),
m_panning( note.m_panning ),
m_length( note.m_length ),
m_pos( note.m_pos ),
m_detuning(nullptr),
m_type(note.m_type)
{
if( note.m_detuning )
{
m_detuning = sharedObject::ref( note.m_detuning );
}
}
Note::~Note()
{
if( m_detuning )
{
sharedObject::unref( m_detuning );
}
}
void Note::setLength( const TimePos & length )
{
m_length = length;
}
void Note::setPos( const TimePos & pos )
{
m_pos = pos;
}
void Note::setKey( const int key )
{
const int k = std::clamp(key, 0, NumKeys - 1);
m_key = k;
}
void Note::setVolume( volume_t volume )
{
const volume_t v = std::clamp(volume, MinVolume, MaxVolume);
m_volume = v;
}
void Note::setPanning( panning_t panning )
{
const panning_t p = std::clamp(panning, PanningLeft, PanningRight);
m_panning = p;
}
TimePos Note::quantized( const TimePos & m, const int qGrid )
{
float p = ( (float) m / qGrid );
if( p - floorf( p ) < 0.5f )
{
return static_cast<int>( p ) * qGrid;
}
return static_cast<int>( p + 1 ) * qGrid;
}
void Note::quantizeLength( const int qGrid )
{
setLength( quantized( length(), qGrid ) );
if( length() == 0 )
{
setLength( qGrid );
}
}
void Note::quantizePos( const int qGrid )
{
setPos( quantized( pos(), qGrid ) );
}
void Note::saveSettings( QDomDocument & doc, QDomElement & parent )
{
parent.setAttribute( "key", m_key );
parent.setAttribute( "vol", m_volume );
parent.setAttribute( "pan", m_panning );
parent.setAttribute( "len", m_length );
parent.setAttribute( "pos", m_pos );
parent.setAttribute("type", static_cast<int>(m_type));
if( m_detuning && m_length )
{
m_detuning->saveSettings( doc, parent );
}
}
void Note::loadSettings( const QDomElement & _this )
{
const int oldKey = _this.attribute( "tone" ).toInt() + _this.attribute( "oct" ).toInt() * KeysPerOctave;
m_key = std::max(oldKey, _this.attribute("key").toInt());
m_volume = _this.attribute( "vol" ).toInt();
m_panning = _this.attribute( "pan" ).toInt();
m_length = _this.attribute( "len" ).toInt();
m_pos = _this.attribute( "pos" ).toInt();
// Default m_type value is 0, which corresponds to RegularNote
static_assert(0 == static_cast<int>(Type::Regular));
m_type = static_cast<Type>(_this.attribute("type", "0").toInt());
if( _this.hasChildNodes() )
{
createDetuning();
m_detuning->loadSettings( _this );
}
}
void Note::createDetuning()
{
if( m_detuning == nullptr )
{
m_detuning = new DetuningHelper;
(void) m_detuning->automationClip();
m_detuning->setRange( -MaxDetuning, MaxDetuning, 0.5f );
m_detuning->automationClip()->setProgressionType( AutomationClip::ProgressionType::Linear );
}
}
bool Note::hasDetuningInfo() const
{
return m_detuning && m_detuning->hasAutomation();
}
bool Note::withinRange(int tickStart, int tickEnd) const
{
return pos().getTicks() >= tickStart && pos().getTicks() <= tickEnd
&& length().getTicks() != 0;
}
/*! \brief Get the start/end/bottom/top positions of notes in a vector
*
* Returns no value if there are no notes
*/
std::optional<NoteBounds> boundsForNotes(const NoteVector& notes)
{
if (notes.empty()) { return std::nullopt; }
TimePos start = notes.front()->pos();
TimePos end = start;
int lower = notes.front()->key();
int upper = lower;
for (const Note* note: notes)
{
// TODO should we assume that NoteVector is always sorted correctly,
// so first() always has the lowest time position?
start = std::min(start, note->pos());
end = std::max(end, note->endPos());
lower = std::min(lower, note->key());
upper = std::max(upper, note->key());
}
return NoteBounds{start, end, lower, upper};
}
} // namespace lmms
| 5,537
|
C++
|
.cpp
| 196
| 26.020408
| 105
| 0.697321
|
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,780
|
PluginIssue.cpp
|
LMMS_lmms/src/core/PluginIssue.cpp
|
/*
* PluginIssue.cpp - PluginIssue class implementation
*
* Copyright (c) 2019-2024 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 <QDebug>
#include "PluginIssue.h"
namespace lmms
{
const char *PluginIssue::msgFor(const PluginIssueType &it)
{
switch (it)
{
case PluginIssueType::UnknownPortFlow:
return "unknown port flow for mandatory port";
case PluginIssueType::UnknownPortType:
return "unknown port type for mandatory port";
case PluginIssueType::TooManyInputChannels:
return "too many audio input channels";
case PluginIssueType::TooManyOutputChannels:
return "too many audio output channels";
case PluginIssueType::TooManyMidiInputChannels:
return "too many MIDI input channels";
case PluginIssueType::TooManyMidiOutputChannels:
return "too many MIDI output channels";
case PluginIssueType::NoOutputChannel:
return "no audio output channel";
case PluginIssueType::PortHasNoDef:
return "port is missing default value";
case PluginIssueType::PortHasNoMin:
return "port is missing min value";
case PluginIssueType::PortHasNoMax:
return "port is missing max value";
case PluginIssueType::MinGreaterMax:
return "port minimum is greater than maximum";
case PluginIssueType::DefaultValueNotInRange:
return "default value is not in range [min, max]";
case PluginIssueType::LogScaleMinMissing:
return "logscale requires minimum value";
case PluginIssueType::LogScaleMaxMissing:
return "logscale requires maximum value";
case PluginIssueType::LogScaleMinMaxDifferentSigns:
return "logscale with min < 0 < max";
case PluginIssueType::FeatureNotSupported:
return "required feature not supported";
case PluginIssueType::BadPortType:
return "unsupported port type";
case PluginIssueType::Blocked:
return "blocked plugin";
case PluginIssueType::NoIssue:
return nullptr;
}
return nullptr;
}
bool PluginIssue::operator==(const PluginIssue &other) const
{
return (m_issueType == other.m_issueType) && (m_info == other.m_info);
}
bool PluginIssue::operator<(const PluginIssue &other) const
{
return (m_issueType != other.m_issueType)
? m_issueType < other.m_issueType
: m_info < other.m_info;
}
QDebug operator<<(QDebug stream, const PluginIssue &iss)
{
stream << PluginIssue::msgFor(iss.m_issueType);
if (iss.m_info.length())
{
stream.nospace() << ": " << iss.m_info.c_str();
}
return stream;
}
} // namespace lmms
| 3,249
|
C++
|
.cpp
| 92
| 32.630435
| 80
| 0.765774
|
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,781
|
MeterModel.cpp
|
LMMS_lmms/src/core/MeterModel.cpp
|
/*
* MeterModel.cpp - model for meter specification
*
* Copyright (c) 2008-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 "MeterModel.h"
#include "AutomationClip.h"
namespace lmms
{
MeterModel::MeterModel( Model * _parent ) :
Model( _parent ),
m_numeratorModel( 4, 1, 32, this, tr( "Numerator" ) ),
m_denominatorModel( 4, 1, 32, this, tr( "Denominator" ) )
{
connect( &m_numeratorModel, SIGNAL(dataChanged()),
this, SIGNAL(dataChanged()), Qt::DirectConnection );
connect( &m_denominatorModel, SIGNAL(dataChanged()),
this, SIGNAL(dataChanged()), Qt::DirectConnection );
}
void MeterModel::reset()
{
m_numeratorModel.setValue( 4 );
m_denominatorModel.setValue( 4 );
AutomationClip::globalAutomationClip( &m_numeratorModel )->clear();
AutomationClip::globalAutomationClip( &m_denominatorModel )->clear();
}
void MeterModel::saveSettings( QDomDocument & _doc, QDomElement & _this,
const QString & _name )
{
m_numeratorModel.saveSettings( _doc, _this, _name + "_numerator" );
m_denominatorModel.saveSettings( _doc, _this, _name + "_denominator" );
}
void MeterModel::loadSettings( const QDomElement & _this,
const QString & _name )
{
m_numeratorModel.loadSettings( _this, _name + "_numerator" );
m_denominatorModel.loadSettings( _this, _name + "_denominator" );
}
} // namespace lmms
| 2,149
|
C++
|
.cpp
| 57
| 35.350877
| 77
| 0.734812
|
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,782
|
RingBuffer.cpp
|
LMMS_lmms/src/core/RingBuffer.cpp
|
/*
* RingBuffer.cpp - an effective and flexible implementation of a ringbuffer for LMMS
*
* Copyright (c) 2014 Vesa Kivim√§ki
* 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 "RingBuffer.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "MixHelpers.h"
namespace lmms
{
RingBuffer::RingBuffer( f_cnt_t size ) :
m_fpp( Engine::audioEngine()->framesPerPeriod() ),
m_samplerate( Engine::audioEngine()->outputSampleRate() ),
m_size( size + m_fpp )
{
m_buffer = new SampleFrame[ m_size ];
zeroSampleFrames(m_buffer, m_size);
m_position = 0;
}
RingBuffer::RingBuffer( float size ) :
m_fpp( Engine::audioEngine()->framesPerPeriod() ),
m_samplerate( Engine::audioEngine()->outputSampleRate() )
{
m_size = msToFrames( size ) + m_fpp;
m_buffer = new SampleFrame[ m_size ];
zeroSampleFrames(m_buffer, m_size);
m_position = 0;
setSamplerateAware( true );
//qDebug( "m_size %d, m_position %d", m_size, m_position );
}
RingBuffer::~RingBuffer()
{
delete[] m_buffer;
}
void RingBuffer::reset()
{
zeroSampleFrames(m_buffer, m_size);
m_position = 0;
}
void RingBuffer::changeSize( f_cnt_t size )
{
size += m_fpp;
SampleFrame* tmp = m_buffer;
m_size = size;
m_buffer = new SampleFrame[ m_size ];
zeroSampleFrames(m_buffer, m_size);
m_position = 0;
delete[] tmp;
}
void RingBuffer::changeSize( float size )
{
changeSize( msToFrames( size ) );
}
void RingBuffer::setSamplerateAware( bool b )
{
if( b )
{
connect( Engine::audioEngine(), SIGNAL(sampleRateChanged()), this, SLOT(updateSamplerate()), Qt::UniqueConnection );
}
else
{
disconnect( Engine::audioEngine(), SIGNAL(sampleRateChanged()), this, SLOT(updateSamplerate()));
}
}
void RingBuffer::advance()
{
m_position = ( m_position + m_fpp ) % m_size;
}
void RingBuffer::movePosition( f_cnt_t amount )
{
m_position = ( m_position + amount ) % m_size;
}
void RingBuffer::movePosition( float amount )
{
movePosition( msToFrames( amount ) );
}
void RingBuffer::pop( SampleFrame* dst )
{
if( m_position + m_fpp <= m_size ) // we won't go over the edge so we can just memcpy here
{
memcpy( dst, & m_buffer [ m_position ], m_fpp * sizeof( SampleFrame ) );
zeroSampleFrames(&m_buffer[m_position], m_fpp);
}
else
{
f_cnt_t first = m_size - m_position;
f_cnt_t second = m_fpp - first;
memcpy( dst, & m_buffer [ m_position ], first * sizeof( SampleFrame ) );
zeroSampleFrames(&m_buffer[m_position], first);
memcpy( & dst [first], m_buffer, second * sizeof( SampleFrame ) );
zeroSampleFrames(m_buffer, second);
}
m_position = ( m_position + m_fpp ) % m_size;
}
void RingBuffer::read( SampleFrame* dst, f_cnt_t offset )
{
f_cnt_t pos = ( m_position + offset ) % m_size;
if( pos + m_fpp <= m_size ) // we won't go over the edge so we can just memcpy here
{
memcpy( dst, & m_buffer [pos], m_fpp * sizeof( SampleFrame ) );
}
else
{
f_cnt_t first = m_size - pos;
f_cnt_t second = m_fpp - first;
memcpy( dst, & m_buffer [pos], first * sizeof( SampleFrame ) );
memcpy( & dst [first], m_buffer, second * sizeof( SampleFrame ) );
}
}
void RingBuffer::read( SampleFrame* dst, float offset )
{
read( dst, msToFrames( offset ) );
}
void RingBuffer::read( SampleFrame* dst, f_cnt_t offset, f_cnt_t length )
{
f_cnt_t pos = ( m_position + offset ) % m_size;
if( pos + length <= m_size ) // we won't go over the edge so we can just memcpy here
{
memcpy( dst, & m_buffer [pos], length * sizeof( SampleFrame ) );
}
else
{
f_cnt_t first = m_size - pos;
f_cnt_t second = length - first;
memcpy( dst, & m_buffer [pos], first * sizeof( SampleFrame ) );
memcpy( & dst [first], m_buffer, second * sizeof( SampleFrame ) );
}
}
void RingBuffer::read( SampleFrame* dst, float offset, f_cnt_t length )
{
read( dst, msToFrames( offset ), length );
}
void RingBuffer::write( SampleFrame* src, f_cnt_t offset, f_cnt_t length )
{
const f_cnt_t pos = ( m_position + offset ) % m_size;
if( length == 0 ) { length = m_fpp; }
if( pos + length <= m_size ) // we won't go over the edge so we can just memcpy here
{
memcpy( & m_buffer [pos], src, length * sizeof( SampleFrame ) );
}
else
{
f_cnt_t first = m_size - pos;
f_cnt_t second = length - first;
memcpy( & m_buffer [pos], src, first * sizeof( SampleFrame ) );
memcpy( m_buffer, & src [first], second * sizeof( SampleFrame ) );
}
}
void RingBuffer::write( SampleFrame* src, float offset, f_cnt_t length )
{
write( src, msToFrames( offset ), length );
}
void RingBuffer::writeAdding( SampleFrame* src, f_cnt_t offset, f_cnt_t length )
{
const f_cnt_t pos = ( m_position + offset ) % m_size;
if( length == 0 ) { length = m_fpp; }
if( pos + length <= m_size ) // we won't go over the edge so we can just memcpy here
{
MixHelpers::add( & m_buffer [pos], src, length );
}
else
{
f_cnt_t first = m_size - pos;
f_cnt_t second = length - first;
MixHelpers::add( & m_buffer[pos], src, first );
MixHelpers::add( m_buffer, & src[first], second );
}
}
void RingBuffer::writeAdding( SampleFrame* src, float offset, f_cnt_t length )
{
writeAdding( src, msToFrames( offset ), length );
}
void RingBuffer::writeAddingMultiplied( SampleFrame* src, f_cnt_t offset, f_cnt_t length, float level )
{
const f_cnt_t pos = ( m_position + offset ) % m_size;
//qDebug( "pos %d m_pos %d ofs %d siz %d", pos, m_position, offset, m_size );
if( length == 0 ) { length = m_fpp; }
if( pos + length <= m_size ) // we won't go over the edge so we can just memcpy here
{
MixHelpers::addMultiplied( & m_buffer[pos], src, level, length );
}
else
{
f_cnt_t first = m_size - pos;
f_cnt_t second = length - first;
MixHelpers::addMultiplied( & m_buffer[pos], src, level, first );
MixHelpers::addMultiplied( m_buffer, & src [first], level, second );
}
}
void RingBuffer::writeAddingMultiplied( SampleFrame* src, float offset, f_cnt_t length, float level )
{
f_cnt_t ofs = msToFrames( offset );
writeAddingMultiplied( src, ofs, length, level );
}
void RingBuffer::writeSwappedAddingMultiplied( SampleFrame* src, f_cnt_t offset, f_cnt_t length, float level )
{
const f_cnt_t pos = ( m_position + offset ) % m_size;
if( length == 0 ) { length = m_fpp; }
if( pos + length <= m_size ) // we won't go over the edge so we can just memcpy here
{
MixHelpers::addSwappedMultiplied( & m_buffer [pos], src, level, length );
}
else
{
f_cnt_t first = m_size - pos;
f_cnt_t second = length - first;
MixHelpers::addSwappedMultiplied( & m_buffer [pos], src, level, first );
MixHelpers::addSwappedMultiplied( m_buffer, & src [first], level, second );
}
}
void RingBuffer::writeSwappedAddingMultiplied( SampleFrame* src, float offset, f_cnt_t length, float level )
{
writeSwappedAddingMultiplied( src, msToFrames( offset ), length, level );
}
void RingBuffer::updateSamplerate()
{
float newsize = static_cast<float>( ( m_size - m_fpp ) * Engine::audioEngine()->outputSampleRate() ) / m_samplerate;
m_size = static_cast<f_cnt_t>( ceilf( newsize ) ) + m_fpp;
m_samplerate = Engine::audioEngine()->outputSampleRate();
delete[] m_buffer;
m_buffer = new SampleFrame[ m_size ];
zeroSampleFrames(m_buffer, m_size);
m_position = 0;
}
} // namespace lmms
| 8,052
|
C++
|
.cpp
| 245
| 30.608163
| 118
| 0.689203
|
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,783
|
ValueBuffer.cpp
|
LMMS_lmms/src/core/ValueBuffer.cpp
|
#include "ValueBuffer.h"
#include "interpolation.h"
namespace lmms
{
ValueBuffer::ValueBuffer(int length)
: std::vector<float>(length)
{}
void ValueBuffer::fill(float value)
{
std::fill(begin(), end(), value);
}
float ValueBuffer::value(int offset) const
{
return at(offset % length());
}
const float *ValueBuffer::values() const
{
return data();
}
float *ValueBuffer::values()
{
return data();
}
int ValueBuffer::length() const
{
return size();
}
void ValueBuffer::interpolate(float start, float end_)
{
float i = 0;
std::generate(begin(), end(), [&]() {
return linearInterpolate( start, end_, i++ / length());
});
}
} // namespace lmms
| 661
|
C++
|
.cpp
| 35
| 17.228571
| 57
| 0.713355
|
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,784
|
PerfLog.cpp
|
LMMS_lmms/src/core/PerfLog.cpp
|
/*
* PerfLog.cpp - Small performance logger
*
* Copyright (c) 2017-2018 LMMS Developers
*
* 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 "PerfLog.h"
#include "lmmsconfig.h"
#if defined(LMMS_HAVE_SYS_TIMES_H) && defined(LMMS_HAVE_UNISTD_H)
# define USE_POSIX_TIME
#endif
#ifdef USE_POSIX_TIME
# include <unistd.h>
# include <sys/times.h>
#endif
namespace lmms
{
PerfTime::PerfTime()
: m_real(-1)
{
}
clock_t PerfTime::real() const
{
return m_real;
}
clock_t PerfTime::user() const
{
return m_user;
}
clock_t PerfTime::system() const
{
return m_system;
}
bool PerfTime::valid() const
{
return m_real != -1;
}
PerfTime PerfTime::now()
{
PerfTime time;
#ifdef USE_POSIX_TIME
tms t;
time.m_real = times(&t);
time.m_user = t.tms_utime;
time.m_system = t.tms_stime;
if (time.m_real == -1) { qWarning("PerfTime: now failed"); }
#endif
return time;
}
clock_t PerfTime::ticksPerSecond()
{
static long clktck = 0;
#ifdef USE_POSIX_TIME
if (!clktck) {
if ((clktck = sysconf(_SC_CLK_TCK)) < 0) {
qWarning("PerfLog::end sysconf()");
}
}
#endif
return clktck;
}
PerfTime operator-(const PerfTime& lhs, const PerfTime& rhs)
{
PerfTime diff;
diff.m_real = lhs.m_real - rhs.m_real;
diff.m_user = lhs.m_user - rhs.m_user;
diff.m_system = lhs.m_system - rhs.m_system;
return diff;
}
PerfLogTimer::PerfLogTimer(const QString& what)
: name(what)
{
begin();
}
PerfLogTimer::~PerfLogTimer()
{
end();
}
void PerfLogTimer::begin()
{
begin_time = PerfTime::now();
}
void PerfLogTimer::end()
{
if (! begin_time.valid()) {
return;
}
long clktck = PerfTime::ticksPerSecond();
PerfTime d = PerfTime::now() - begin_time;
qWarning("PERFLOG | %20s | %.2fuser, %.2fsystem %.2felapsed",
qPrintable(name),
d.user() / (double)clktck,
d.system() / (double)clktck,
d.real() / (double)clktck);
// Invalidate so destructor won't call print another log entry
begin_time = PerfTime();
}
} // namespace lmms
| 2,700
|
C++
|
.cpp
| 115
| 21.591304
| 70
| 0.715847
|
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,785
|
SamplePlayHandle.cpp
|
LMMS_lmms/src/core/SamplePlayHandle.cpp
|
/*
* SamplePlayHandle.cpp - implementation of class SamplePlayHandle
*
* 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 "SamplePlayHandle.h"
#include "AudioEngine.h"
#include "AudioPort.h"
#include "Engine.h"
#include "Note.h"
#include "PatternTrack.h"
#include "SampleClip.h"
#include "SampleTrack.h"
namespace lmms
{
SamplePlayHandle::SamplePlayHandle(Sample* sample, bool ownAudioPort) :
PlayHandle( Type::SamplePlayHandle ),
m_sample(sample),
m_doneMayReturnTrue( true ),
m_frame( 0 ),
m_ownAudioPort( ownAudioPort ),
m_defaultVolumeModel( DefaultVolume, MinVolume, MaxVolume, 1 ),
m_volumeModel( &m_defaultVolumeModel ),
m_track( nullptr ),
m_patternTrack( nullptr )
{
if (ownAudioPort)
{
setAudioPort( new AudioPort( "SamplePlayHandle", false ) );
}
}
SamplePlayHandle::SamplePlayHandle( const QString& sampleFile ) :
SamplePlayHandle(new Sample(sampleFile), true)
{
}
SamplePlayHandle::SamplePlayHandle( SampleClip* clip ) :
SamplePlayHandle(&clip->sample(), false)
{
m_track = clip->getTrack();
setAudioPort( ( (SampleTrack *)clip->getTrack() )->audioPort() );
}
SamplePlayHandle::~SamplePlayHandle()
{
if( m_ownAudioPort )
{
delete audioPort();
delete m_sample;
}
}
void SamplePlayHandle::play( SampleFrame* buffer )
{
const fpp_t fpp = Engine::audioEngine()->framesPerPeriod();
//play( 0, _try_parallelizing );
if( framesDone() >= totalFrames() )
{
zeroSampleFrames(buffer, fpp);
return;
}
SampleFrame* workingBuffer = buffer;
f_cnt_t frames = fpp;
// apply offset for the first period
if( framesDone() == 0 )
{
zeroSampleFrames(buffer, offset());
workingBuffer += offset();
frames -= offset();
}
if( !( m_track && m_track->isMuted() )
&& !(m_patternTrack && m_patternTrack->isMuted()))
{
/* StereoVolumeVector v =
{ { m_volumeModel->value() / DefaultVolume,
m_volumeModel->value() / DefaultVolume } };*/
// SamplePlayHandle always plays the sample at its original pitch;
// it is used only for previews, SampleTracks and the metronome.
if (!m_sample->play(workingBuffer, &m_state, frames, DefaultBaseFreq))
{
zeroSampleFrames(workingBuffer, frames);
}
}
m_frame += frames;
}
bool SamplePlayHandle::isFinished() const
{
return framesDone() >= totalFrames() && m_doneMayReturnTrue == true;
}
bool SamplePlayHandle::isFromTrack( const Track * _track ) const
{
return m_track == _track || m_patternTrack == _track;
}
f_cnt_t SamplePlayHandle::totalFrames() const
{
return (m_sample->endFrame() - m_sample->startFrame()) *
(static_cast<float>(Engine::audioEngine()->outputSampleRate()) / m_sample->sampleRate());
}
} // namespace lmms
| 3,494
|
C++
|
.cpp
| 114
| 28.421053
| 92
| 0.735488
|
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,786
|
Keymap.cpp
|
LMMS_lmms/src/core/Keymap.cpp
|
/*
* Keymap.cpp - implementation of keymap class
*
* Copyright (c) 2020 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 "Keymap.h"
#include <QDomElement>
#include "Note.h"
namespace lmms
{
Keymap::Keymap() :
m_description(tr("empty")),
m_firstKey(0),
m_lastKey(NumKeys - 1),
m_middleKey(DefaultMiddleKey),
m_baseKey(DefaultBaseKey),
m_baseFreq(DefaultBaseFreq)
{
}
Keymap::Keymap(
QString description,
std::vector<int> newMap,
int newFirst,
int newLast,
int newMiddle,
int newBaseKey,
float newBaseFreq
) :
m_description(description),
m_map(std::move(newMap)),
m_firstKey(newFirst),
m_lastKey(newLast),
m_middleKey(newMiddle),
m_baseKey(newBaseKey),
m_baseFreq(newBaseFreq)
{
}
/**
* \brief Return scale degree for a given key, based on current map and first/middle/last notes
* \param MIDI key to be mapped
* \return Scale degree defined by the mapping on success, -1 if key isn't mapped
*/
int Keymap::getDegree(int key) const
{
if (key < m_firstKey || key > m_lastKey) {return -1;}
if (m_map.empty()) {return key;} // exception: empty mapping table means linear (1:1) mapping
const int keyOffset = key - m_middleKey; // -127..127
const int key_rem = keyOffset % static_cast<int>(m_map.size()); // remainder
const int key_mod = key_rem >= 0 ? key_rem : key_rem + m_map.size(); // true modulo
return m_map[key_mod];
}
/**
* \brief Return octave offset for a given key, based on current map and the middle note
* \param MIDI key to be mapped
* \return Octave offset defined by the mapping on success, 0 if key isn't mapped
*/
int Keymap::getOctave(int key) const
{
// The keymap wraparound cannot cause an octave transition if a key isn't mapped or the map is empty → return 0
if (m_map.empty() || getDegree(key) == -1) {return 0;}
const int keyOffset = key - m_middleKey;
if (keyOffset >= 0)
{
return keyOffset / static_cast<int>(m_map.size());
}
else
{
return (keyOffset + 1) / static_cast<int>(m_map.size()) - 1;
}
}
QString Keymap::getDescription() const
{
return m_description;
}
void Keymap::setDescription(QString description)
{
m_description = description;
}
void Keymap::saveSettings(QDomDocument &document, QDomElement &element)
{
element.setAttribute("description", m_description);
element.setAttribute("first_key", m_firstKey);
element.setAttribute("last_key", m_lastKey);
element.setAttribute("middle_key", m_middleKey);
element.setAttribute("base_key", m_baseKey);
element.setAttribute("base_freq", m_baseFreq);
for (int value : m_map)
{
QDomElement degree = document.createElement("degree");
element.appendChild(degree);
degree.setAttribute("value", value);
}
}
void Keymap::loadSettings(const QDomElement &element)
{
m_description = element.attribute("description");
m_firstKey = element.attribute("first_key").toInt();
m_lastKey = element.attribute("last_key").toInt();
m_middleKey = element.attribute("middle_key").toInt();
m_baseKey = element.attribute("base_key").toInt();
m_baseFreq = element.attribute("base_freq").toDouble();
QDomNode node = element.firstChild();
m_map.clear();
while (!node.isNull())
{
m_map.push_back(node.toElement().attribute("value").toInt());
node = node.nextSibling();
}
}
} // namespace lmms
| 4,056
|
C++
|
.cpp
| 128
| 29.664063
| 114
| 0.73294
|
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,787
|
Piano.cpp
|
LMMS_lmms/src/core/Piano.cpp
|
/*
* Piano.cpp - implementation of piano-widget used in instrument-track-window
* for testing + according model class
*
* 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.
*
*/
/** \file Piano.cpp
* \brief A piano keyboard to play notes on in the instrument plugin window.
*/
/*
* \mainpage Instrument plugin keyboard display classes
*
* \section introduction Introduction
*
* \todo fill this out
* \todo write isWhite inline function and replace throughout
*/
#include "Piano.h"
#include "InstrumentTrack.h"
namespace lmms
{
/*! The black / white order of keys as they appear on the keyboard.
*/
static const auto KEY_ORDER = std::array
{
// C CIS D DIS
Piano::KeyType::White, Piano::KeyType::Black, Piano::KeyType::White, Piano::KeyType::Black,
// E F FIS G
Piano::KeyType::White, Piano::KeyType::White, Piano::KeyType::Black, Piano::KeyType::White,
// GIS A AIS B
Piano::KeyType::Black, Piano::KeyType::White, Piano::KeyType::Black, Piano::KeyType::White
} ;
/*! \brief Create a new keyboard display
*
* \param _it the InstrumentTrack window to attach to
*/
Piano::Piano(InstrumentTrack* track) :
Model(nullptr), /*!< base class ctor */
m_instrumentTrack(track),
m_midiEvProc(track) /*!< the InstrumentTrack Model */
{
}
/*! \brief Turn a key on or off
*
* \param key the key number to change
* \param state the state to set the key to
*/
void Piano::setKeyState(int key, bool state)
{
if (isValidKey(key))
{
m_pressedKeys[key] = state;
emit dataChanged();
}
}
/*! \brief Handle a note being pressed on our keyboard display
*
* \param key the key being pressed
*/
void Piano::handleKeyPress(int key, int midiVelocity)
{
if (midiVelocity == -1)
{
midiVelocity = m_instrumentTrack->midiPort()->baseVelocity();
}
if (isValidKey(key))
{
m_midiEvProc->processInEvent(MidiEvent(MidiNoteOn, -1, key, midiVelocity));
m_pressedKeys[key] = true;
}
}
/*! \brief Handle a note being released on our keyboard display
*
* \param key the key being releassed
*/
void Piano::handleKeyRelease(int key)
{
if (isValidKey(key))
{
m_midiEvProc->processInEvent(MidiEvent(MidiNoteOff, -1, key, 0));
m_pressedKeys[key] = false;
}
}
bool Piano::isBlackKey(int key)
{
int keyCode = key % KeysPerOctave;
return KEY_ORDER[keyCode] == Piano::KeyType::Black;
}
bool Piano::isWhiteKey(int key)
{
return !isBlackKey(key);
}
} // namespace lmms
| 3,437
|
C++
|
.cpp
| 111
| 28.981982
| 92
| 0.687386
|
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,788
|
AudioEngineProfiler.cpp
|
LMMS_lmms/src/core/AudioEngineProfiler.cpp
|
/*
* AudioEngineProfiler.cpp - class for profiling performance of AudioEngine
*
* Copyright (c) 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 "AudioEngineProfiler.h"
#include <cstdint>
namespace lmms
{
AudioEngineProfiler::AudioEngineProfiler() :
m_periodTimer(),
m_cpuLoad( 0 ),
m_outputFile()
{
}
void AudioEngineProfiler::finishPeriod( sample_rate_t sampleRate, fpp_t framesPerPeriod )
{
// Time taken to process all data and fill the audio buffer.
const unsigned int periodElapsed = m_periodTimer.elapsed();
// Maximum time the processing can take before causing buffer underflow. Convert to us.
const uint64_t timeLimit = static_cast<uint64_t>(1000000) * framesPerPeriod / sampleRate;
// Compute new overall CPU load and apply exponential averaging.
// The result is used for overload detection in AudioEngine::criticalXRuns()
// → the weight of a new sample must be high enough to allow relatively fast changes!
const auto newCpuLoad = 100.f * periodElapsed / timeLimit;
m_cpuLoad = newCpuLoad * 0.1f + m_cpuLoad * 0.9f;
// Compute detailed load analysis. Can use stronger averaging to get more stable readout.
for (std::size_t i = 0; i < DetailCount; i++)
{
const auto newLoad = 100.f * m_detailTime[i] / timeLimit;
const auto oldLoad = m_detailLoad[i].load(std::memory_order_relaxed);
m_detailLoad[i].store(newLoad * 0.05f + oldLoad * 0.95f, std::memory_order_relaxed);
}
if( m_outputFile.isOpen() )
{
m_outputFile.write( QString( "%1\n" ).arg( periodElapsed ).toLatin1() );
}
}
void AudioEngineProfiler::setOutputFile( const QString& outputFile )
{
m_outputFile.close();
m_outputFile.setFileName( outputFile );
m_outputFile.open( QFile::WriteOnly | QFile::Truncate );
}
} // namespace lmms
| 2,561
|
C++
|
.cpp
| 63
| 38.603175
| 90
| 0.754026
|
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,789
|
DrumSynth.cpp
|
LMMS_lmms/src/core/DrumSynth.cpp
|
/*
* DrumSynth.cpp - DrumSynth DS file renderer
*
* Copyright (c) 1998-2000 Paul Kellett (mda-vst.com)
* Copyright (c) 2007 Paul Giblock <drfaygo/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 "DrumSynth.h"
#include <QFile>
#include <cmath>
#include <cstring>
#include <sstream>
#ifdef _MSC_VER
// not #if LMMS_BUILD_WIN32 because we have strncasecmp in mingw
#define strcasecmp _stricmp
#endif // _MSC_VER
namespace lmms {
using namespace std;
// const int Fs = 44100;
const float TwoPi = 6.2831853f;
const int MAX = 0;
const int ENV = 1;
const int PNT = 2;
const int dENV = 3;
const int NEXTT = 4;
// Bah, I'll move these into the class once I sepearate DrumsynthFile from DrumSynth
// llama
float envpts[8][3][32]; // envelope/time-level/point
float envData[8][6]; // envelope running status
int chkOn[8], sliLev[8]; // section on/off and level
float timestretch; // overall time scaling
short DD[1200], clippoint;
float DF[1200];
float phi[1200];
long wavewords, wavemode = 0;
float mem_t = 1.0f, mem_o = 1.0f, mem_n = 1.0f, mem_b = 1.0f, mem_tune = 1.0f, mem_time = 1.0f;
int DrumSynth::LongestEnv()
{
float l = 0.f;
for (long e = 1; e < 7; e++) // 3
{
long eon = e - 1;
if (eon > 2)
{
eon = eon - 1;
}
long p = 0;
while (envpts[e][0][p + 1] >= 0.f)
{
p++;
}
envData[e][MAX] = envpts[e][0][p] * timestretch;
if (chkOn[eon] == 1 && envData[e][MAX] > l)
{
l = envData[e][MAX];
}
}
// l *= timestretch;
return 2400 + (1200 * static_cast<int>(l / 1200));
}
float DrumSynth::LoudestEnv()
{
float loudest = 0.f;
int i = 0;
while (i < 5) // 2
{
if ((chkOn[i] == 1) && (sliLev[i] > loudest))
{
loudest = static_cast<float>(sliLev[i]);
}
i++;
}
return loudest * loudest;
}
void DrumSynth::UpdateEnv(int e, long t)
{
// 0.2's added
envData[e][NEXTT] = envpts[e][0][static_cast<long>(envData[e][PNT] + 1.f)] * timestretch; // get next point
if (envData[e][NEXTT] < 0)
{
envData[e][NEXTT] = 442000 * timestretch; // if end point, hold
}
envData[e][ENV] = envpts[e][1][static_cast<long>(envData[e][PNT] + 0.f)] * 0.01f; // this level
float endEnv = envpts[e][1][static_cast<long>(envData[e][PNT] + 1.f)] * 0.01f; // next level
float dT = envData[e][NEXTT] - static_cast<float>(t);
if (dT < 1.0)
{
dT = 1.0;
}
envData[e][dENV] = (endEnv - envData[e][ENV]) / dT;
envData[e][PNT] = envData[e][PNT] + 1.0f;
}
void DrumSynth::GetEnv(int env, const char* sec, const char* key, QString ini)
{
char en[256], s[8];
int i = 0, o = 0, ep = 0;
GetPrivateProfileString(sec, key, "0,0 100,0", en, sizeof(en), ini);
// be safe!
en[255] = 0;
s[0] = 0;
while (en[i] != 0)
{
if (en[i] == ',')
{
if (sscanf(s, "%f", &envpts[env][0][ep]) == 0)
{
envpts[env][0][ep] = 0.f;
}
o = 0;
}
else if (en[i] == ' ')
{
if (sscanf(s, "%f", &envpts[env][1][ep]) == 0)
{
envpts[env][1][ep] = 0.f;
}
o = 0;
ep++;
}
else
{
s[o] = en[i];
o++;
s[o] = 0;
}
i++;
}
if (sscanf(s, "%f", &envpts[env][1][ep]) == 0)
{
envpts[env][1][ep] = 0.f;
}
envpts[env][0][ep + 1] = -1;
envData[env][MAX] = envpts[env][0][ep];
}
float DrumSynth::waveform(float ph, int form)
{
float w;
switch (form)
{
case 0:
w = static_cast<float>(sin(fmod(ph, TwoPi)));
break; // sine
case 1:
w = static_cast<float>(fabs(2.0f * static_cast<float>(sin(fmod(0.5f * ph, TwoPi))) - 1.f));
break; // sine^2
case 2:
while (ph < TwoPi)
{
ph += TwoPi;
}
w = 0.6366197f * static_cast<float>(fmod(ph, TwoPi) - 1.f); // tri
if (w > 1.f)
{
w = 2.f - w;
}
break;
case 3:
w = ph - TwoPi * static_cast<float>(static_cast<int>(ph / TwoPi)); // saw
w = (0.3183098f * w) - 1.f;
break;
default:
w = (sin(fmod(ph, TwoPi)) > 0.0) ? 1.f : -1.f;
break; // square
}
return w;
}
int DrumSynth::GetPrivateProfileString(
const char* sec, const char* key, const char* def, char* buffer, int size, QString file)
{
stringstream is;
bool inSection = false;
int len = 0;
char* line = static_cast<char*>(malloc(200));
// Use QFile to handle unicode file name on Windows
// Previously we used ifstream directly
QFile f(file);
f.open(QIODevice::ReadOnly);
QByteArray dat = f.readAll().constData();
is.str(string(dat.constData(), dat.size()));
while (is.good())
{
if (!inSection)
{
is.ignore(numeric_limits<streamsize>::max(), '[');
if (!is.eof())
{
is.getline(line, 200, ']');
if (strcasecmp(line, sec) == 0)
{
inSection = true;
}
}
}
else if (!is.eof())
{
is.getline(line, 200);
if (line[0] == '[')
{
break;
}
char* k = strtok(line, " \t=");
char* b = strtok(nullptr, "\n\r\0");
if (k != 0 && strcasecmp(k, key) == 0)
{
if (b == 0)
{
len = 0;
buffer[0] = 0;
}
else
{
k = static_cast<char*>(b + strlen(b) - 1);
while ((k >= b) && (*k == ' ' || *k == '\t'))
{
--k;
}
*(k + 1) = '\0';
len = strlen(b);
if (len > size - 1)
{
len = size - 1;
}
strncpy(buffer, b, len + 1);
}
break;
}
}
}
if (len == 0)
{
len = strlen(def);
strncpy(buffer, def, size);
}
free(line);
return len;
}
int DrumSynth::GetPrivateProfileInt(const char* sec, const char* key, int def, QString file)
{
char tmp[16];
int i = 0;
GetPrivateProfileString(sec, key, "", tmp, sizeof(tmp), file);
sscanf(tmp, "%d", &i);
if (tmp[0] == 0)
{
i = def;
}
return i;
}
float DrumSynth::GetPrivateProfileFloat(const char* sec, const char* key, float def, QString file)
{
char tmp[16];
float f = 0.f;
GetPrivateProfileString(sec, key, "", tmp, sizeof(tmp), file);
sscanf(tmp, "%f", &f);
if (tmp[0] == 0)
{
f = def;
}
return f;
}
// Constantly opening and scanning each file for the setting really sucks.
// But, the original did this, and we know it works. Will store file into
// an associative array or something once we have a datastructure to load in to.
// llama
int DrumSynth::GetDSFileSamples(QString dsfile, int16_t*& wave, int channels, sample_rate_t Fs)
{
// input file
char sec[32];
char ver[32];
char comment[256];
int commentLen = 0;
// generation
long Length, tpos = 0, tplus, totmp, t, i, j;
float x[3] = {0.f, 0.f, 0.f};
float MasterTune;
constexpr float randmax = 1.f / static_cast<float>(RAND_MAX);
constexpr float randmax2 = 2.f / static_cast<float>(RAND_MAX);
int MainFilter, HighPass;
long NON, NT, TON, DiON, TDroop = 0, DStep;
float a, b = 0.f, c = 0.f, d = 0.f, g, TT = 0.f, TL, NL, F1, F2;
float TphiStart = 0.f, Tphi, TDroopRate, ddF, DAtten, DGain;
long BON, BON2, BFStep, BFStep2, botmp;
float BdF = 0.f, BdF2 = 0.f, BPhi, BPhi2, BF, BF2, BQ, BQ2, BL, BL2;
long OON, OF1Sync = 0, OF2Sync = 0, OMode, OW1, OW2;
float Ophi1, Ophi2, OF1, OF2, OL, Ot = 0 /*PG: init */, OBal1, OBal2, ODrive;
float Ocf1, Ocf2, OcF, OcQ, OcA, Oc[6][2]; // overtone cymbal mode
float Oc0 = 0.0f, Oc1 = 0.0f, Oc2 = 0.0f;
float MFfb, MFtmp, MFres, MFin = 0.f, MFout = 0.f;
float DownAve;
long DownStart, DownEnd, jj;
if (wavemode == 0) // semi-real-time adjustments if working in memory!!
{
mem_t = 1.0f;
mem_o = 1.0f;
mem_n = 1.0f;
mem_b = 1.0f;
mem_tune = 0.0f;
mem_time = 1.0f;
}
// try to read version from input file
strcpy(sec, "General");
GetPrivateProfileString(sec, "Version", "", ver, sizeof(ver), dsfile);
ver[9] = 0;
if ((strcasecmp(ver, "DrumSynth") != 0) // input fail
|| (ver[11] != '1' && ver[11] != '2')) // version fail
{
return 0;
}
// read master parameters
GetPrivateProfileString(sec, "Comment", "", comment, sizeof(comment), dsfile);
while ((comment[commentLen] != 0) && (commentLen < 254))
{
commentLen++;
}
if (commentLen == 0)
{
comment[0] = 32;
comment[1] = 0;
commentLen = 1;
}
comment[commentLen + 1] = 0;
commentLen++;
if ((commentLen % 2) == 1)
{
commentLen++;
}
timestretch = .01f * mem_time * GetPrivateProfileFloat(sec, "Stretch", 100.0, dsfile);
if (timestretch < 0.2f)
{
timestretch = 0.2f;
}
if (timestretch > 10.f)
{
timestretch = 10.f;
}
// the unit of envelope lengths is a sample in 44100Hz sample rate, so correct it
timestretch *= Fs / 44100.f;
DGain = 1.0f; // leave this here!
DGain = static_cast<float>(std::pow(10.0, 0.05 * GetPrivateProfileFloat(sec, "Level", 0, dsfile)));
MasterTune = GetPrivateProfileFloat(sec, "Tuning", 0.0, dsfile);
MasterTune = static_cast<float>(std::pow(1.0594631f, MasterTune + mem_tune));
MainFilter = 2 * GetPrivateProfileInt(sec, "Filter", 0, dsfile);
MFres = 0.0101f * GetPrivateProfileFloat(sec, "Resonance", 0.0, dsfile);
MFres = static_cast<float>(std::pow(MFres, 0.5f));
HighPass = GetPrivateProfileInt(sec, "HighPass", 0, dsfile);
GetEnv(7, sec, "FilterEnv", dsfile);
// read noise parameters
strcpy(sec, "Noise");
chkOn[1] = GetPrivateProfileInt(sec, "On", 0, dsfile);
sliLev[1] = GetPrivateProfileInt(sec, "Level", 0, dsfile);
NT = GetPrivateProfileInt(sec, "Slope", 0, dsfile);
GetEnv(2, sec, "Envelope", dsfile);
NON = chkOn[1];
NL = static_cast<float>(sliLev[1] * sliLev[1]) * mem_n;
if (NT < 0)
{
a = 1.f + (NT / 105.f);
d = -NT / 105.f;
g = (1.f + 0.0005f * NT * NT) * NL;
}
else
{
a = 1.f;
b = -NT / 50.f;
c = static_cast<float>(fabs(static_cast<float>(NT))) / 100.f;
g = NL;
}
// if(GetPrivateProfileInt(sec,"FixedSeq",0,dsfile)!=0)
// srand(1); //fixed random sequence
// read tone parameters
strcpy(sec, "Tone");
chkOn[0] = GetPrivateProfileInt(sec, "On", 0, dsfile);
TON = chkOn[0];
sliLev[0] = GetPrivateProfileInt(sec, "Level", 128, dsfile);
TL = static_cast<float>(sliLev[0] * sliLev[0]) * mem_t;
GetEnv(1, sec, "Envelope", dsfile);
F1 = MasterTune * TwoPi * GetPrivateProfileFloat(sec, "F1", 200.0, dsfile) / Fs;
if (fabs(F1) < 0.001f)
{
F1 = 0.001f; // to prevent overtone ratio div0
}
F2 = MasterTune * TwoPi * GetPrivateProfileFloat(sec, "F2", 120.0, dsfile) / Fs;
TDroopRate = GetPrivateProfileFloat(sec, "Droop", 0.f, dsfile);
if (TDroopRate > 0.f)
{
TDroopRate = static_cast<float>(std::pow(10.0f, (TDroopRate - 20.0f) / 30.0f));
TDroopRate = TDroopRate * -4.f / envData[1][MAX];
TDroop = 1;
F2 = F1 + ((F2 - F1) / (1.f - static_cast<float>(exp(TDroopRate * envData[1][MAX]))));
ddF = F1 - F2;
}
else
{
ddF = F2 - F1;
}
Tphi = GetPrivateProfileFloat(sec, "Phase", 90.f, dsfile) / 57.29578f; // degrees>radians
// read overtone parameters
strcpy(sec, "Overtones");
chkOn[2] = GetPrivateProfileInt(sec, "On", 0, dsfile);
OON = chkOn[2];
sliLev[2] = GetPrivateProfileInt(sec, "Level", 128, dsfile);
OL = static_cast<float>(sliLev[2] * sliLev[2]) * mem_o;
GetEnv(3, sec, "Envelope1", dsfile);
GetEnv(4, sec, "Envelope2", dsfile);
OMode = GetPrivateProfileInt(sec, "Method", 2, dsfile);
OF1 = MasterTune * TwoPi * GetPrivateProfileFloat(sec, "F1", 200.0, dsfile) / Fs;
OF2 = MasterTune * TwoPi * GetPrivateProfileFloat(sec, "F2", 120.0, dsfile) / Fs;
OW1 = GetPrivateProfileInt(sec, "Wave1", 0, dsfile);
OW2 = GetPrivateProfileInt(sec, "Wave2", 0, dsfile);
OBal2 = static_cast<float>(GetPrivateProfileInt(sec, "Param", 50, dsfile));
ODrive = static_cast<float>(std::pow(OBal2, 3.0f)) / std::pow(50.0f, 3.0f);
OBal2 *= 0.01f;
OBal1 = 1.f - OBal2;
Ophi1 = Tphi;
Ophi2 = Tphi;
if (MainFilter == 0)
{
MainFilter = GetPrivateProfileInt(sec, "Filter", 0, dsfile);
}
if ((GetPrivateProfileInt(sec, "Track1", 0, dsfile) == 1) && (TON == 1))
{
OF1Sync = 1;
OF1 = OF1 / F1;
}
if ((GetPrivateProfileInt(sec, "Track2", 0, dsfile) == 1) && (TON == 1))
{
OF2Sync = 1;
OF2 = OF2 / F1;
}
OcA = 0.28f + OBal1 * OBal1; // overtone cymbal mode
OcQ = OcA * OcA;
OcF = (1.8f - 0.7f * OcQ) * 0.92f; // multiply by env 2
OcA *= 1.0f + 4.0f * OBal1; // level is a compromise!
Ocf1 = TwoPi / OF1;
Ocf2 = TwoPi / OF2;
for (i = 0; i < 6; i++)
{
Oc[i][0] = Oc[i][1] = Ocf1 + (Ocf2 - Ocf1) * 0.2f * static_cast<float>(i);
}
// read noise band parameters
strcpy(sec, "NoiseBand");
chkOn[3] = GetPrivateProfileInt(sec, "On", 0, dsfile);
BON = chkOn[3];
sliLev[3] = GetPrivateProfileInt(sec, "Level", 128, dsfile);
BL = static_cast<float>(sliLev[3] * sliLev[3]) * mem_b;
BF = MasterTune * TwoPi * GetPrivateProfileFloat(sec, "F", 1000.0, dsfile) / Fs;
BPhi = TwoPi / 8.f;
GetEnv(5, sec, "Envelope", dsfile);
BFStep = GetPrivateProfileInt(sec, "dF", 50, dsfile);
BQ = static_cast<float>(BFStep);
BQ = BQ * BQ / (10000.f - 6600.f * (static_cast<float>(sqrt(BF)) - 0.19f));
BFStep = 1 + static_cast<int>((40.f - (BFStep / 2.5f)) / (BQ + 1.f + (1.f * BF)));
strcpy(sec, "NoiseBand2");
chkOn[4] = GetPrivateProfileInt(sec, "On", 0, dsfile);
BON2 = chkOn[4];
sliLev[4] = GetPrivateProfileInt(sec, "Level", 128, dsfile);
BL2 = static_cast<float>(sliLev[4] * sliLev[4]) * mem_b;
BF2 = MasterTune * TwoPi * GetPrivateProfileFloat(sec, "F", 1000.0, dsfile) / Fs;
BPhi2 = TwoPi / 8.f;
GetEnv(6, sec, "Envelope", dsfile);
BFStep2 = GetPrivateProfileInt(sec, "dF", 50, dsfile);
BQ2 = static_cast<float>(BFStep2);
BQ2 = BQ2 * BQ2 / (10000.f - 6600.f * (static_cast<float>(sqrt(BF2)) - 0.19f));
BFStep2 = 1 + static_cast<int>((40 - (BFStep2 / 2.5)) / (BQ2 + 1 + (1 * BF2)));
// read distortion parameters
strcpy(sec, "Distortion");
chkOn[5] = GetPrivateProfileInt(sec, "On", 0, dsfile);
DiON = chkOn[5];
DStep = 1 + GetPrivateProfileInt(sec, "Rate", 0, dsfile);
if (DStep == 7) { DStep = 20; }
if (DStep == 6) { DStep = 10; }
if (DStep == 5) { DStep = 8; }
clippoint = 32700;
DAtten = 1.0f;
if (DiON == 1)
{
DAtten = DGain * static_cast<short>(LoudestEnv());
clippoint = DAtten > 32700 ? 32700 : static_cast<short>(DAtten);
DAtten = static_cast<float>(std::pow(2.0, 2.0 * GetPrivateProfileInt(sec, "Bits", 0, dsfile)));
DGain = DAtten * DGain
* static_cast<float>(std::pow(10.0, 0.05 * GetPrivateProfileInt(sec, "Clipping", 0, dsfile)));
}
// prepare envelopes
for (i = 1; i < 8; i++)
{
envData[i][NEXTT] = 0;
envData[i][PNT] = 0;
}
Length = LongestEnv();
// allocate the buffer
// if(wave!=NULL) free(wave);
// wave = new int16_t[channels * (Length + 1280)]; //wave memory buffer
wave = new int16_t[channels * Length]; // wave memory buffer
if (wave == nullptr)
{
return 0;
}
wavewords = 0;
/*
if(wavemode==0)
{
//open output file
fp = fopen(wavfile, "wb");
if(!fp) {return 3;} //output fail
//set up INFO chunk
WI.list = 0x5453494C;
WI.listLength = 36 + commentLen;
WI.info = 0x4F464E49;
WI.isft = 0x54465349;
WI.isftLength = 16;
strcpy(WI.software, "DrumSynth v2.0 "); WI.software[15]=0;
WI.icmt = 0x544D4349;
WI.icmtLength = commentLen;
//write WAV header
WH.riff = 0x46464952;
WH.riffLength = 36 + (2 * Length) + 44 + commentLen;
WH.wave = 0x45564157;
WH.fmt = 0x20746D66;
WH.waveLength = 16;
WH.wFormatTag = WAVE_FORMAT_PCM;
WH.nChannels = 1;
WH.nSamplesPerSec = Fs;
WH.nAvgBytesPerSec = 2 * Fs;
WH.nBlockAlign = 2;
WH.wBitsPerSample = 16;
WH.data = 0x61746164;
WH.dataLength = 2 * Length;
fwrite(&WH, 1, 44, fp);
}
*/
// generate
tpos = 0;
while (tpos < Length)
{
tplus = tpos + 1199;
if (NON == 1) // noise
{
for (t = tpos; t <= tplus; t++)
{
if (t < envData[2][NEXTT])
{
envData[2][ENV] = envData[2][ENV] + envData[2][dENV];
}
else
{
UpdateEnv(2, t);
}
x[2] = x[1];
x[1] = x[0];
x[0] = (randmax2 * static_cast<float>(rand())) - 1.f;
TT = a * x[0] + b * x[1] + c * x[2] + d * TT;
DF[t - tpos] = TT * g * envData[2][ENV];
}
if (t >= envData[2][MAX])
{
NON = 0;
}
}
else
{
for (j = 0; j < 1200; j++)
{
DF[j] = 0.f;
}
}
if (TON == 1) // tone
{
TphiStart = Tphi;
if (TDroop == 1)
{
for (t = tpos; t <= tplus; t++)
{
phi[t - tpos] = F2 + (ddF * static_cast<float>(exp(t * TDroopRate)));
}
}
else
{
for (t = tpos; t <= tplus; t++)
{
phi[t - tpos] = F1 + (t / envData[1][MAX]) * ddF;
}
}
for (t = tpos; t <= tplus; t++)
{
totmp = t - tpos;
if (t < envData[1][NEXTT])
{
envData[1][ENV] = envData[1][ENV] + envData[1][dENV];
}
else
{
UpdateEnv(1, t);
}
Tphi = Tphi + phi[totmp];
DF[totmp] += TL * envData[1][ENV] * static_cast<float>(sin(fmod(Tphi, TwoPi))); // overflow?
}
if (t >= envData[1][MAX])
{
TON = 0;
}
}
else
{
for (j = 0; j < 1200; j++)
{
phi[j] = F2; // for overtone sync
}
}
if (BON == 1) // noise band 1
{
for (t = tpos; t <= tplus; t++)
{
if (t < envData[5][NEXTT])
{
envData[5][ENV] = envData[5][ENV] + envData[5][dENV];
}
else
{
UpdateEnv(5, t);
}
if ((t % BFStep) == 0)
{
BdF = randmax * static_cast<float>(rand()) - 0.5f;
}
BPhi = BPhi + BF + BQ * BdF;
botmp = t - tpos;
DF[botmp] = DF[botmp] + static_cast<float>(cos(fmod(BPhi, TwoPi))) * envData[5][ENV] * BL;
}
if (t >= envData[5][MAX])
{
BON = 0;
}
}
if (BON2 == 1) // noise band 2
{
for (t = tpos; t <= tplus; t++)
{
if (t < envData[6][NEXTT])
{
envData[6][ENV] = envData[6][ENV] + envData[6][dENV];
}
else
{
UpdateEnv(6, t);
}
if ((t % BFStep2) == 0)
{
BdF2 = randmax * static_cast<float>(rand()) - 0.5f;
}
BPhi2 = BPhi2 + BF2 + BQ2 * BdF2;
botmp = t - tpos;
DF[botmp] = DF[botmp] + static_cast<float>(cos(fmod(BPhi2, TwoPi))) * envData[6][ENV] * BL2;
}
if (t >= envData[6][MAX])
{
BON2 = 0;
}
}
for (t = tpos; t <= tplus; t++)
{
if (OON == 1) // overtones
{
if (t < envData[3][NEXTT])
{
envData[3][ENV] = envData[3][ENV] + envData[3][dENV];
}
else
{
if (t >= envData[3][MAX]) // wait for OT2
{
envData[3][ENV] = 0;
envData[3][dENV] = 0;
envData[3][NEXTT] = 999999;
}
else
{
UpdateEnv(3, t);
}
}
//
if (t < envData[4][NEXTT])
{
envData[4][ENV] = envData[4][ENV] + envData[4][dENV];
}
else
{
if (t >= envData[4][MAX]) // wait for OT1
{
envData[4][ENV] = 0;
envData[4][dENV] = 0;
envData[4][NEXTT] = 999999;
}
else
{
UpdateEnv(4, t);
}
}
//
TphiStart = TphiStart + phi[t - tpos];
if (OF1Sync == 1)
{
Ophi1 = TphiStart * OF1;
}
else
{
Ophi1 = Ophi1 + OF1;
}
if (OF2Sync == 1)
{
Ophi2 = TphiStart * OF2;
}
else
{
Ophi2 = Ophi2 + OF2;
}
Ot = 0.0f;
switch (OMode)
{
case 0: // add
Ot = OBal1 * envData[3][ENV] * waveform(Ophi1, OW1);
Ot = OL * (Ot + OBal2 * envData[4][ENV] * waveform(Ophi2, OW2));
break;
case 1: // FM
Ot = ODrive * envData[4][ENV] * waveform(Ophi2, OW2);
Ot = OL * envData[3][ENV] * waveform(Ophi1 + Ot, OW1);
break;
case 2: // RM
Ot = (1 - ODrive / 8) + (((ODrive / 8) * envData[4][ENV]) * waveform(Ophi2, OW2));
Ot = OL * envData[3][ENV] * waveform(Ophi1, OW1) * Ot;
break;
case 3: // 808 Cymbal
for (j = 0; j < 6; j++)
{
Oc[j][0] += 1.0f;
if (Oc[j][0] > Oc[j][1])
{
Oc[j][0] -= Oc[j][1];
Ot = OL * envData[3][ENV];
}
}
Ocf1 = envData[4][ENV] * OcF; // filter freq
Oc0 += Ocf1 * Oc1;
Oc1 += Ocf1 * (Ot + Oc2 - OcQ * Oc1 - Oc0); // bpf
Oc2 = Ot;
Ot = Oc1;
break;
}
}
if (MainFilter == 1) // filter overtones
{
if (t < envData[7][NEXTT])
{
envData[7][ENV] = envData[7][ENV] + envData[7][dENV];
}
else
{
UpdateEnv(7, t);
}
MFtmp = envData[7][ENV];
if (MFtmp > 0.2f)
{
MFfb = 1.001f - static_cast<float>(std::pow(10.0f, MFtmp - 1));
}
else
{
MFfb = 0.999f - 0.7824f * MFtmp;
}
MFtmp = Ot + MFres * (1.f + (1.f / MFfb)) * (MFin - MFout);
MFin = MFfb * (MFin - MFtmp) + MFtmp;
MFout = MFfb * (MFout - MFin) + MFin;
DF[t - tpos] = DF[t - tpos] + (MFout - (HighPass * Ot));
}
else if (MainFilter == 2) // filter all
{
if (t < envData[7][NEXTT])
{
envData[7][ENV] = envData[7][ENV] + envData[7][dENV];
}
else
{
UpdateEnv(7, t);
}
MFtmp = envData[7][ENV];
if (MFtmp > 0.2f)
{
MFfb = 1.001f - static_cast<float>(std::pow(10.0f, MFtmp - 1));
}
else
{
MFfb = 0.999f - 0.7824f * MFtmp;
}
MFtmp = DF[t - tpos] + Ot + MFres * (1.f + (1.f / MFfb)) * (MFin - MFout);
MFin = MFfb * (MFin - MFtmp) + MFtmp;
MFout = MFfb * (MFout - MFin) + MFin;
DF[t - tpos] = MFout - (HighPass * (DF[t - tpos] + Ot));
}
// PG: Ot is uninitialized
else
{
DF[t - tpos] = DF[t - tpos] + Ot; // no filter
}
}
if (DiON == 1) // bit resolution
{
for (j = 0; j < 1200; j++)
{
DF[j] = DGain * static_cast<int>(DF[j] / DAtten);
}
for (j = 0; j < 1200; j += DStep) // downsampling
{
DownAve = 0;
DownStart = j;
DownEnd = j + DStep - 1;
for (jj = DownStart; jj <= DownEnd; jj++)
{
DownAve = DownAve + DF[jj];
}
DownAve = DownAve / DStep;
for (jj = DownStart; jj <= DownEnd; jj++)
{
DF[jj] = DownAve;
}
}
}
else
{
for (j = 0; j < 1200; j++)
{
DF[j] *= DGain;
}
}
for (j = 0; j < 1200; j++) // clipping + output
{
if (DF[j] > clippoint)
{
wave[wavewords++] = clippoint;
}
else if (DF[j] < -clippoint)
{
wave[wavewords++] = -clippoint;
}
else
{
wave[wavewords++] = static_cast<short>(DF[j]);
}
for (int c = 1; c < channels; c++)
{
wave[wavewords] = wave[wavewords - 1];
wavewords++;
}
}
tpos = tpos + 1200;
}
/*
if(wavemode==0)
{
fwrite(wave, 2, Length, fp); //write data
fwrite(&WI, 1, 44, fp); //write INFO chunk
fwrite(&comment, 1, commentLen, fp);
fclose(fp);
}
wavemode = 0; //force compatibility!!
*/
return Length;
}
} // namespace lmms
| 22,812
|
C++
|
.cpp
| 883
| 22.399773
| 108
| 0.584631
|
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,790
|
MicroTimer.cpp
|
LMMS_lmms/src/core/MicroTimer.cpp
|
#include "MicroTimer.h"
namespace lmms
{
using namespace std;
using namespace std::chrono;
static_assert(ratio_less_equal<steady_clock::duration::period, micro>::value,
"MicroTimer: steady_clock doesn't support microsecond resolution");
MicroTimer::MicroTimer()
{
reset();
}
void MicroTimer::reset()
{
begin = steady_clock::now();
}
int MicroTimer::elapsed() const
{
auto now = steady_clock::now();
return std::chrono::duration_cast<std::chrono::duration<int, std::micro>>(now - begin).count();
}
} // namespace lmms
| 530
|
C++
|
.cpp
| 21
| 23.619048
| 96
| 0.750996
|
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,791
|
Effect.cpp
|
LMMS_lmms/src/core/Effect.cpp
|
/*
* Effect.cpp - base-class for effects
*
* 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 <QDomElement>
#include "Effect.h"
#include "EffectChain.h"
#include "EffectControls.h"
#include "EffectView.h"
#include "ConfigManager.h"
#include "SampleFrame.h"
#include "lmms_constants.h"
namespace lmms
{
Effect::Effect( const Plugin::Descriptor * _desc,
Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Plugin( _desc, _parent, _key ),
m_parent( nullptr ),
m_processors( 1 ),
m_okay( true ),
m_noRun( false ),
m_running( false ),
m_bufferCount( 0 ),
m_enabledModel( true, this, tr( "Effect enabled" ) ),
m_wetDryModel( 1.0f, -1.0f, 1.0f, 0.01f, this, tr( "Wet/Dry mix" ) ),
m_gateModel( 0.0f, 0.0f, 1.0f, 0.01f, this, tr( "Gate" ) ),
m_autoQuitModel( 1.0f, 1.0f, 8000.0f, 100.0f, 1.0f, this, tr( "Decay" ) ),
m_autoQuitDisabled( false )
{
m_wetDryModel.setCenterValue(0);
m_srcState[0] = m_srcState[1] = nullptr;
reinitSRC();
if( ConfigManager::inst()->value( "ui", "disableautoquit").toInt() )
{
m_autoQuitDisabled = true;
}
// Call the virtual method onEnabledChanged so that effects can react to changes,
// e.g. by resetting state.
connect(&m_enabledModel, &BoolModel::dataChanged, [this] { onEnabledChanged(); });
}
Effect::~Effect()
{
for (const auto& state : m_srcState)
{
if (state != nullptr)
{
src_delete(state);
}
}
}
void Effect::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
m_enabledModel.saveSettings( _doc, _this, "on" );
m_wetDryModel.saveSettings( _doc, _this, "wet" );
m_autoQuitModel.saveSettings( _doc, _this, "autoquit" );
m_gateModel.saveSettings( _doc, _this, "gate" );
controls()->saveState( _doc, _this );
}
void Effect::loadSettings( const QDomElement & _this )
{
m_enabledModel.loadSettings( _this, "on" );
m_wetDryModel.loadSettings( _this, "wet" );
m_autoQuitModel.loadSettings( _this, "autoquit" );
m_gateModel.loadSettings( _this, "gate" );
QDomNode node = _this.firstChild();
while( !node.isNull() )
{
if( node.isElement() )
{
if( controls()->nodeName() == node.nodeName() )
{
controls()->restoreState( node.toElement() );
}
}
node = node.nextSibling();
}
}
bool Effect::processAudioBuffer(SampleFrame* buf, const fpp_t frames)
{
if (!isOkay() || dontRun() || !isEnabled() || !isRunning())
{
processBypassedImpl();
return false;
}
const auto status = processImpl(buf, frames);
switch (status)
{
case ProcessStatus::Continue:
break;
case ProcessStatus::ContinueIfNotQuiet:
{
double outSum = 0.0;
for (std::size_t idx = 0; idx < frames; ++idx)
{
outSum += buf[idx].sumOfSquaredAmplitudes();
}
checkGate(outSum / frames);
break;
}
case ProcessStatus::Sleep:
return false;
default:
break;
}
return isRunning();
}
Effect * Effect::instantiate( const QString& pluginName,
Model * _parent,
Descriptor::SubPluginFeatures::Key * _key )
{
Plugin * p = Plugin::instantiateWithKey( pluginName, _parent, _key );
// check whether instantiated plugin is an effect
if( dynamic_cast<Effect *>( p ) != nullptr )
{
// everything ok, so return pointer
auto effect = dynamic_cast<Effect*>(p);
effect->m_parent = dynamic_cast<EffectChain *>(_parent);
return effect;
}
// not quite... so delete plugin and leave it up to the caller to instantiate a DummyEffect
delete p;
return nullptr;
}
void Effect::checkGate(double outSum)
{
if( m_autoQuitDisabled )
{
return;
}
// Check whether we need to continue processing input. Restart the
// counter if the threshold has been exceeded.
if (outSum - gate() <= F_EPSILON)
{
incrementBufferCount();
if( bufferCount() > timeout() )
{
stopRunning();
resetBufferCount();
}
}
else
{
resetBufferCount();
}
}
gui::PluginView * Effect::instantiateView( QWidget * _parent )
{
return new gui::EffectView( this, _parent );
}
void Effect::reinitSRC()
{
for (auto& state : m_srcState)
{
if (state != nullptr)
{
src_delete(state);
}
int error;
const int currentInterpolation = Engine::audioEngine()->currentQualitySettings().libsrcInterpolation();
if((state = src_new(currentInterpolation, DEFAULT_CHANNELS, &error)) == nullptr)
{
qFatal( "Error: src_new() failed in effect.cpp!\n" );
}
}
}
void Effect::resample( int _i, const SampleFrame* _src_buf,
sample_rate_t _src_sr,
SampleFrame* _dst_buf, sample_rate_t _dst_sr,
f_cnt_t _frames )
{
if( m_srcState[_i] == nullptr )
{
return;
}
m_srcData[_i].input_frames = _frames;
m_srcData[_i].output_frames = Engine::audioEngine()->framesPerPeriod();
m_srcData[_i].data_in = const_cast<float*>(_src_buf[0].data());
m_srcData[_i].data_out = _dst_buf[0].data ();
m_srcData[_i].src_ratio = (double) _dst_sr / _src_sr;
m_srcData[_i].end_of_input = 0;
if (int error = src_process(m_srcState[_i], &m_srcData[_i]))
{
qFatal( "Effect::resample(): error while resampling: %s\n",
src_strerror( error ) );
}
}
} // namespace lmms
| 5,944
|
C++
|
.cpp
| 208
| 25.995192
| 105
| 0.693188
|
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,792
|
AudioEngineWorkerThread.cpp
|
LMMS_lmms/src/core/AudioEngineWorkerThread.cpp
|
/*
* AudioEngineWorkerThread.cpp - implementation of AudioEngineWorkerThread
*
* 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 "AudioEngineWorkerThread.h"
#include <QDebug>
#include <QMutex>
#include <QWaitCondition>
#include "denormals.h"
#include "AudioEngine.h"
#include "ThreadableJob.h"
#if __SSE__
#include <xmmintrin.h>
#endif
namespace lmms
{
AudioEngineWorkerThread::JobQueue AudioEngineWorkerThread::globalJobQueue;
QWaitCondition * AudioEngineWorkerThread::queueReadyWaitCond = nullptr;
QList<AudioEngineWorkerThread *> AudioEngineWorkerThread::workerThreads;
// implementation of internal JobQueue
void AudioEngineWorkerThread::JobQueue::reset( OperationMode _opMode )
{
m_writeIndex = 0;
m_itemsDone = 0;
m_opMode = _opMode;
}
void AudioEngineWorkerThread::JobQueue::addJob( ThreadableJob * _job )
{
if( _job->requiresProcessing() )
{
// update job state
_job->queue();
// actually queue the job via atomic operations
auto index = m_writeIndex++;
if (index < JOB_QUEUE_SIZE) {
m_items[index] = _job;
} else {
qWarning() << "Job queue is full!";
++m_itemsDone;
}
}
}
void AudioEngineWorkerThread::JobQueue::run()
{
bool processedJob = true;
while (processedJob && m_itemsDone < m_writeIndex)
{
processedJob = false;
for (auto i = std::size_t{0}; i < m_writeIndex && i < JOB_QUEUE_SIZE; ++i)
{
ThreadableJob * job = m_items[i].exchange(nullptr);
if( job )
{
job->process();
processedJob = true;
++m_itemsDone;
}
}
// always exit loop if we're not in dynamic mode
processedJob = processedJob && ( m_opMode == OperationMode::Dynamic );
}
}
void AudioEngineWorkerThread::JobQueue::wait()
{
while (m_itemsDone < m_writeIndex)
{
#ifdef __SSE__
_mm_pause();
#endif
}
}
// implementation of worker threads
AudioEngineWorkerThread::AudioEngineWorkerThread( AudioEngine* audioEngine ) :
QThread( audioEngine ),
m_quit( false )
{
// initialize global static data
if( queueReadyWaitCond == nullptr )
{
queueReadyWaitCond = new QWaitCondition;
}
// keep track of all instantiated worker threads - this is used for
// processing the last worker thread "inline", see comments in
// AudioEngineWorkerThread::startAndWaitForJobs() for details
workerThreads << this;
resetJobQueue();
}
AudioEngineWorkerThread::~AudioEngineWorkerThread()
{
workerThreads.removeAll( this );
}
void AudioEngineWorkerThread::quit()
{
m_quit = true;
resetJobQueue();
}
void AudioEngineWorkerThread::startAndWaitForJobs()
{
queueReadyWaitCond->wakeAll();
// The last worker-thread is never started. Instead it's processed "inline"
// i.e. within the global AudioEngine thread. This way we can reduce latencies
// that otherwise would be caused by synchronizing with another thread.
globalJobQueue.run();
globalJobQueue.wait();
}
void AudioEngineWorkerThread::run()
{
disable_denormals();
QMutex m;
while( m_quit == false )
{
m.lock();
queueReadyWaitCond->wait( &m );
globalJobQueue.run();
m.unlock();
}
}
} // namespace lmms
| 3,885
|
C++
|
.cpp
| 137
| 26.080292
| 79
| 0.74973
|
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,793
|
PluginFactory.cpp
|
LMMS_lmms/src/core/PluginFactory.cpp
|
/*
* PluginFactory.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 "PluginFactory.h"
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QLibrary>
#include <memory>
#include "lmmsconfig.h"
#include "ConfigManager.h"
#include "Plugin.h"
// QT qHash specialization, needs to be in global namespace
qint64 qHash(const QFileInfo& fi)
{
return qHash(fi.absoluteFilePath());
}
namespace lmms
{
#ifdef LMMS_BUILD_WIN32
QStringList nameFilters("*.dll");
#else
QStringList nameFilters("lib*.so");
#endif
std::unique_ptr<PluginFactory> PluginFactory::s_instance;
PluginFactory::PluginFactory()
{
setupSearchPaths();
discoverPlugins();
}
void PluginFactory::setupSearchPaths()
{
// Adds a search path relative to the main executable if the path exists.
auto addRelativeIfExists = [](const QString & path) {
QDir dir(qApp->applicationDirPath());
if (!path.isEmpty() && dir.cd(path)) {
QDir::addSearchPath("plugins", dir.absolutePath());
}
};
// We're either running LMMS installed on an Unixoid or we're running a
// portable version like we do on Windows.
// We want to find our plugins in both cases:
// (a) Installed (Unix):
// e.g. binary at /usr/bin/lmms - plugin dir at /usr/lib/lmms/
// (b) Portable:
// e.g. binary at "C:/Program Files/LMMS/lmms.exe"
// plugins at "C:/Program Files/LMMS/plugins/"
#ifndef LMMS_BUILD_WIN32
addRelativeIfExists("../lib/lmms"); // Installed
#endif
addRelativeIfExists("plugins"); // Portable
#ifdef PLUGIN_DIR // We may also have received a relative directory via a define
addRelativeIfExists(PLUGIN_DIR);
#endif
// Or via an environment variable:
if (const char* env_path = std::getenv("LMMS_PLUGIN_DIR"))
QDir::addSearchPath("plugins", env_path);
QDir::addSearchPath("plugins", ConfigManager::inst()->workingDir() + "plugins");
}
PluginFactory* PluginFactory::instance()
{
if (s_instance == nullptr)
s_instance = std::make_unique<PluginFactory>();
return s_instance.get();
}
PluginFactory* getPluginFactory()
{
return PluginFactory::instance();
}
Plugin::DescriptorList PluginFactory::descriptors() const
{
return m_descriptors.values();
}
Plugin::DescriptorList PluginFactory::descriptors(Plugin::Type type) const
{
return m_descriptors.values(type);
}
const PluginFactory::PluginInfoList& PluginFactory::pluginInfos() const
{
return m_pluginInfos;
}
PluginFactory::PluginInfoAndKey PluginFactory::pluginSupportingExtension(const QString& ext)
{
return m_pluginByExt.value(ext, PluginInfoAndKey());
}
PluginFactory::PluginInfo PluginFactory::pluginInfo(const char* name) const
{
for (const PluginInfo& info : m_pluginInfos)
{
if (qstrcmp(info.descriptor->name, name) == 0)
return info;
}
return PluginInfo();
}
QString PluginFactory::errorString(QString pluginName) const
{
static QString notfound = qApp->translate("PluginFactory", "Plugin not found.");
return m_errors.value(pluginName, notfound);
}
void PluginFactory::discoverPlugins()
{
DescriptorMap descriptors;
PluginInfoList pluginInfos;
m_pluginByExt.clear();
QSet<QFileInfo> files;
for (const QString& searchPath : QDir::searchPaths("plugins"))
{
#if (QT_VERSION >= QT_VERSION_CHECK(5,14,0))
auto discoveredPluginList = QDir(searchPath).entryInfoList(nameFilters);
files.unite(QSet<QFileInfo>(discoveredPluginList.begin(), discoveredPluginList.end()));
#else
files.unite(QDir(searchPath).entryInfoList(nameFilters).toSet());
#endif
}
// Cheap dependency handling: zynaddsubfx needs ZynAddSubFxCore. By loading
// all libraries twice we ensure that libZynAddSubFxCore is found.
for (const QFileInfo& file : files)
{
QLibrary(file.absoluteFilePath()).load();
}
for (const QFileInfo& file : files)
{
auto library = std::make_shared<QLibrary>(file.absoluteFilePath());
if (! library->load()) {
m_errors[file.baseName()] = library->errorString();
qWarning("%s", library->errorString().toLocal8Bit().data());
continue;
}
Plugin::Descriptor* pluginDescriptor = nullptr;
if (library->resolve("lmms_plugin_main"))
{
QString descriptorName = file.baseName() + "_plugin_descriptor";
if( descriptorName.left(3) == "lib" )
{
descriptorName = descriptorName.mid(3);
}
pluginDescriptor = reinterpret_cast<Plugin::Descriptor*>(library->resolve(descriptorName.toUtf8().constData()));
if(pluginDescriptor == nullptr)
{
qWarning() << qApp->translate("PluginFactory", "LMMS plugin %1 does not have a plugin descriptor named %2!").
arg(file.absoluteFilePath()).arg(descriptorName);
continue;
}
}
if(pluginDescriptor)
{
PluginInfo info;
info.file = file;
info.library = library;
info.descriptor = pluginDescriptor;
pluginInfos << info;
auto addSupportedFileTypes =
[this](QString supportedFileTypes,
const PluginInfo& info,
const Plugin::Descriptor::SubPluginFeatures::Key* key = nullptr)
{
if(!supportedFileTypes.isNull())
{
for (const QString& ext : supportedFileTypes.split(','))
{
//qDebug() << "Plugin " << info.name()
// << "supports" << ext;
PluginInfoAndKey infoAndKey;
infoAndKey.info = info;
infoAndKey.key = key
? *key
: Plugin::Descriptor::SubPluginFeatures::Key();
m_pluginByExt.insert(ext, infoAndKey);
}
}
};
if (info.descriptor->supportedFileTypes)
addSupportedFileTypes(QString(info.descriptor->supportedFileTypes), info);
if (info.descriptor->subPluginFeatures)
{
Plugin::Descriptor::SubPluginFeatures::KeyList
subPluginKeys;
info.descriptor->subPluginFeatures->listSubPluginKeys(
info.descriptor,
subPluginKeys);
for(const Plugin::Descriptor::SubPluginFeatures::Key& key
: subPluginKeys)
{
addSupportedFileTypes(key.additionalFileExtensions(), info, &key);
}
}
descriptors.insert(info.descriptor->type, info.descriptor);
}
}
m_pluginInfos = pluginInfos;
m_descriptors = descriptors;
}
QString PluginFactory::PluginInfo::name() const
{
return descriptor ? descriptor->name : QString();
}
} // namespace lmms
| 6,925
|
C++
|
.cpp
| 217
| 29.101382
| 115
| 0.736092
|
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,794
|
SampleDecoder.cpp
|
LMMS_lmms/src/core/SampleDecoder.cpp
|
/*
* SampleDecoder.cpp - Decodes audio files in various formats
*
* Copyright (c) 2023 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 "SampleDecoder.h"
#include <QFile>
#include <QFileInfo>
#include <QString>
#include <memory>
#include <sndfile.h>
#ifdef LMMS_HAVE_OGGVORBIS
#include <vorbis/vorbisfile.h>
#endif
#include "AudioEngine.h"
#include "DrumSynth.h"
#include "Engine.h"
#include "lmms_basics.h"
namespace lmms {
namespace {
using Decoder = std::optional<SampleDecoder::Result> (*)(const QString&);
auto decodeSampleSF(const QString& audioFile) -> std::optional<SampleDecoder::Result>;
auto decodeSampleDS(const QString& audioFile) -> std::optional<SampleDecoder::Result>;
#ifdef LMMS_HAVE_OGGVORBIS
auto decodeSampleOggVorbis(const QString& audioFile) -> std::optional<SampleDecoder::Result>;
#endif
static constexpr std::array<Decoder, 3> decoders = {&decodeSampleSF,
#ifdef LMMS_HAVE_OGGVORBIS
&decodeSampleOggVorbis,
#endif
&decodeSampleDS};
auto decodeSampleSF(const QString& audioFile) -> std::optional<SampleDecoder::Result>
{
SNDFILE* sndFile = nullptr;
auto sfInfo = SF_INFO{};
// TODO: Remove use of QFile
auto file = QFile{audioFile};
if (!file.open(QIODevice::ReadOnly)) { return std::nullopt; }
sndFile = sf_open_fd(file.handle(), SFM_READ, &sfInfo, false);
if (sf_error(sndFile) != 0) { return std::nullopt; }
auto buf = std::vector<sample_t>(sfInfo.channels * sfInfo.frames);
sf_read_float(sndFile, buf.data(), buf.size());
sf_close(sndFile);
file.close();
auto result = std::vector<SampleFrame>(sfInfo.frames);
for (int i = 0; i < static_cast<int>(result.size()); ++i)
{
if (sfInfo.channels == 1)
{
// Upmix from mono to stereo
result[i] = {buf[i], buf[i]};
}
else if (sfInfo.channels > 1)
{
// TODO: Add support for higher number of channels (i.e., 5.1 channel systems)
// The current behavior assumes stereo in all cases excluding mono.
// This may not be the expected behavior, given some audio files with a higher number of channels.
result[i] = {buf[i * sfInfo.channels], buf[i * sfInfo.channels + 1]};
}
}
return SampleDecoder::Result{std::move(result), static_cast<int>(sfInfo.samplerate)};
}
auto decodeSampleDS(const QString& audioFile) -> std::optional<SampleDecoder::Result>
{
// Populated by DrumSynth::GetDSFileSamples
int_sample_t* dataPtr = nullptr;
auto ds = DrumSynth{};
const auto engineRate = Engine::audioEngine()->outputSampleRate();
const auto frames = ds.GetDSFileSamples(audioFile, dataPtr, DEFAULT_CHANNELS, engineRate);
const auto data = std::unique_ptr<int_sample_t[]>{dataPtr}; // NOLINT, we have to use a C-style array here
if (frames <= 0 || !data) { return std::nullopt; }
auto result = std::vector<SampleFrame>(frames);
src_short_to_float_array(data.get(), &result[0][0], frames * DEFAULT_CHANNELS);
return SampleDecoder::Result{std::move(result), static_cast<int>(engineRate)};
}
#ifdef LMMS_HAVE_OGGVORBIS
auto decodeSampleOggVorbis(const QString& audioFile) -> std::optional<SampleDecoder::Result>
{
static auto s_read = [](void* buffer, size_t size, size_t count, void* stream) -> size_t {
auto file = static_cast<QFile*>(stream);
return file->read(static_cast<char*>(buffer), size * count);
};
static auto s_seek = [](void* stream, ogg_int64_t offset, int whence) -> int {
auto file = static_cast<QFile*>(stream);
if (whence == SEEK_SET) { file->seek(offset); }
else if (whence == SEEK_CUR) { file->seek(file->pos() + offset); }
else if (whence == SEEK_END) { file->seek(file->size() + offset); }
else { return -1; }
return 0;
};
static auto s_close = [](void* stream) -> int {
auto file = static_cast<QFile*>(stream);
file->close();
return 0;
};
static auto s_tell = [](void* stream) -> long {
auto file = static_cast<QFile*>(stream);
return file->pos();
};
static ov_callbacks s_callbacks = {s_read, s_seek, s_close, s_tell};
// TODO: Remove use of QFile
auto file = QFile{audioFile};
if (!file.open(QIODevice::ReadOnly)) { return std::nullopt; }
auto vorbisFile = OggVorbis_File{};
if (ov_open_callbacks(&file, &vorbisFile, nullptr, 0, s_callbacks) < 0) { return std::nullopt; }
const auto vorbisInfo = ov_info(&vorbisFile, -1);
if (vorbisInfo == nullptr) { return std::nullopt; }
const auto numChannels = vorbisInfo->channels;
const auto sampleRate = vorbisInfo->rate;
const auto numSamples = ov_pcm_total(&vorbisFile, -1);
if (numSamples < 0) { return std::nullopt; }
auto buffer = std::vector<float>(numSamples);
auto output = static_cast<float**>(nullptr);
auto totalSamplesRead = 0;
while (true)
{
auto samplesRead = ov_read_float(&vorbisFile, &output, numSamples, 0);
if (samplesRead < 0) { return std::nullopt; }
else if (samplesRead == 0) { break; }
std::copy_n(*output, samplesRead, buffer.begin() + totalSamplesRead);
totalSamplesRead += samplesRead;
}
auto result = std::vector<SampleFrame>(totalSamplesRead / numChannels);
for (auto i = std::size_t{0}; i < result.size(); ++i)
{
if (numChannels == 1) { result[i] = {buffer[i], buffer[i]}; }
else if (numChannels > 1) { result[i] = {buffer[i * numChannels], buffer[i * numChannels + 1]}; }
}
ov_clear(&vorbisFile);
return SampleDecoder::Result{std::move(result), static_cast<int>(sampleRate)};
}
#endif // LMMS_HAVE_OGGVORBIS
} // namespace
auto SampleDecoder::supportedAudioTypes() -> const std::vector<AudioType>&
{
static const auto s_audioTypes = [] {
auto types = std::vector<AudioType>();
// Add DrumSynth by default since that support comes from us
types.push_back(AudioType{"DrumSynth", "ds"});
auto sfFormatInfo = SF_FORMAT_INFO{};
auto simpleTypeCount = 0;
sf_command(nullptr, SFC_GET_SIMPLE_FORMAT_COUNT, &simpleTypeCount, sizeof(int));
// TODO: Ideally, this code should be iterating over the major formats, but some important extensions such as
// *.ogg are not included. This is planned for future versions of sndfile.
for (int simple = 0; simple < simpleTypeCount; ++simple)
{
sfFormatInfo.format = simple;
sf_command(nullptr, SFC_GET_SIMPLE_FORMAT, &sfFormatInfo, sizeof(sfFormatInfo));
auto it = std::find_if(types.begin(), types.end(),
[&](const AudioType& type) { return sfFormatInfo.extension == type.extension; });
if (it != types.end()) { continue; }
auto name = std::string{sfFormatInfo.extension};
std::transform(name.begin(), name.end(), name.begin(), [](unsigned char ch) { return std::toupper(ch); });
types.push_back(AudioType{std::move(name), sfFormatInfo.extension});
}
std::sort(types.begin(), types.end(), [&](const AudioType& a, const AudioType& b) { return a.name < b.name; });
return types;
}();
return s_audioTypes;
}
auto SampleDecoder::decode(const QString& audioFile) -> std::optional<Result>
{
auto result = std::optional<Result>{};
for (const auto& decoder : decoders)
{
result = decoder(audioFile);
if (result) { break; }
}
return result;
}
} // namespace lmms
| 7,758
|
C++
|
.cpp
| 189
| 38.661376
| 113
| 0.714172
|
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,795
|
RenderManager.cpp
|
LMMS_lmms/src/core/RenderManager.cpp
|
/*
* RenderManager - exporting logic common between the CLI and GUI.
*
* Copyright (c) 2015 Ryan Roden-Corrent <ryan/at/rcorre.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 <QRegularExpression>
#include "RenderManager.h"
#include "PatternStore.h"
#include "Song.h"
namespace lmms
{
RenderManager::RenderManager(
const AudioEngine::qualitySettings & qualitySettings,
const OutputSettings & outputSettings,
ProjectRenderer::ExportFileFormat fmt,
QString outputPath) :
m_qualitySettings(qualitySettings),
m_oldQualitySettings( Engine::audioEngine()->currentQualitySettings() ),
m_outputSettings(outputSettings),
m_format(fmt),
m_outputPath(outputPath)
{
Engine::audioEngine()->storeAudioDevice();
}
RenderManager::~RenderManager()
{
Engine::audioEngine()->restoreAudioDevice(); // Also deletes audio dev.
Engine::audioEngine()->changeQuality( m_oldQualitySettings );
}
void RenderManager::abortProcessing()
{
if ( m_activeRenderer ) {
disconnect( m_activeRenderer.get(), SIGNAL(finished()),
this, SLOT(renderNextTrack()));
m_activeRenderer->abortProcessing();
}
restoreMutedState();
}
// Called to render each new track when rendering tracks individually.
void RenderManager::renderNextTrack()
{
m_activeRenderer.reset();
if (m_tracksToRender.empty())
{
// nothing left to render
restoreMutedState();
emit finished();
}
else
{
// pop the next track from our rendering queue
Track* renderTrack = m_tracksToRender.back();
m_tracksToRender.pop_back();
// mute everything but the track we are about to render
for (auto track : m_unmuted)
{
track->setMuted(track != renderTrack);
}
// for multi-render, prefix each output file with a different number
int trackNum = m_tracksToRender.size() + 1;
render( pathForTrack(renderTrack, trackNum) );
}
}
// Render the song into individual tracks
void RenderManager::renderTracks()
{
const TrackContainer::TrackList& tl = Engine::getSong()->tracks();
// find all currently unnmuted tracks -- we want to render these.
for (const auto& tk : tl)
{
Track::Type type = tk->type();
// Don't render automation tracks
if ( tk->isMuted() == false &&
( type == Track::Type::Instrument || type == Track::Type::Sample ) )
{
m_unmuted.push_back(tk);
}
}
const TrackContainer::TrackList& t2 = Engine::patternStore()->tracks();
for (const auto& tk : t2)
{
Track::Type type = tk->type();
// Don't render automation tracks
if ( tk->isMuted() == false &&
( type == Track::Type::Instrument || type == Track::Type::Sample ) )
{
m_unmuted.push_back(tk);
}
}
// copy the list of unmuted tracks into our rendering queue.
// we need to remember which tracks were unmuted to restore state at the end.
m_tracksToRender = m_unmuted;
renderNextTrack();
}
// Render the song into a single track
void RenderManager::renderProject()
{
render( m_outputPath );
}
void RenderManager::render(QString outputPath)
{
m_activeRenderer = std::make_unique<ProjectRenderer>(
m_qualitySettings,
m_outputSettings,
m_format,
outputPath);
if( m_activeRenderer->isReady() )
{
// pass progress signals through
connect( m_activeRenderer.get(), SIGNAL(progressChanged(int)),
this, SIGNAL(progressChanged(int)));
// when it is finished, render the next track.
// if we have not queued any tracks, renderNextTrack will just clean up
connect( m_activeRenderer.get(), SIGNAL(finished()),
this, SLOT(renderNextTrack()));
m_activeRenderer->startProcessing();
}
else
{
qDebug( "Renderer failed to acquire a file device!" );
renderNextTrack();
}
}
// Unmute all tracks that were muted while rendering tracks
void RenderManager::restoreMutedState()
{
while (!m_unmuted.empty())
{
Track* restoreTrack = m_unmuted.back();
m_unmuted.pop_back();
restoreTrack->setMuted( false );
}
}
// Determine the output path for a track when rendering tracks individually
QString RenderManager::pathForTrack(const Track *track, int num)
{
QString extension = ProjectRenderer::getFileExtensionFromFormat( m_format );
QString name = track->name();
name = name.remove(QRegularExpression(FILENAME_FILTER));
name = QString( "%1_%2%3" ).arg( num ).arg( name ).arg( extension );
return QDir(m_outputPath).filePath(name);
}
void RenderManager::updateConsoleProgress()
{
if ( m_activeRenderer )
{
m_activeRenderer->updateConsoleProgress();
int totalNum = m_unmuted.size();
if ( totalNum > 0 )
{
// we are rendering multiple tracks, append a track counter to the output
int trackNum = totalNum - m_tracksToRender.size();
fprintf( stderr, "(%d/%d)", trackNum, totalNum );
}
}
}
} // namespace lmms
| 5,447
|
C++
|
.cpp
| 176
| 28.568182
| 78
| 0.736641
|
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,796
|
ImportFilter.cpp
|
LMMS_lmms/src/core/ImportFilter.cpp
|
/*
* ImportFilter.cpp - base-class for all import-filters
*
* 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 <memory>
#include <QMessageBox>
#include "ImportFilter.h"
#include "Engine.h"
#include "TrackContainer.h"
#include "PluginFactory.h"
#include "ProjectJournal.h"
namespace lmms
{
using std::unique_ptr;
ImportFilter::ImportFilter( const QString & _file_name,
const Descriptor * _descriptor ) :
Plugin( _descriptor, nullptr ),
m_file( _file_name )
{
}
void ImportFilter::import( const QString & _file_to_import,
TrackContainer* tc )
{
bool successful = false;
QByteArray s = _file_to_import.toUtf8();
s.detach();
// do not record changes while importing files
const bool j = Engine::projectJournal()->isJournalling();
Engine::projectJournal()->setJournalling( false );
for (const Plugin::Descriptor* desc : getPluginFactory()->descriptors(Plugin::Type::ImportFilter))
{
unique_ptr<Plugin> p(Plugin::instantiate( desc->name, nullptr, s.data() ));
if( dynamic_cast<ImportFilter *>( p.get() ) != nullptr &&
dynamic_cast<ImportFilter *>( p.get() )->tryImport( tc ) )
{
successful = true;
break;
}
}
Engine::projectJournal()->setJournalling( j );
if( successful == false )
{
QMessageBox::information( nullptr,
TrackContainer::tr( "Couldn't import file" ),
TrackContainer::tr( "Couldn't find a filter for "
"importing file %1.\n"
"You should convert this file "
"into a format supported by "
"LMMS using another software."
).arg( _file_to_import ),
QMessageBox::Ok,
QMessageBox::NoButton );
}
}
bool ImportFilter::openFile()
{
if( m_file.open( QFile::ReadOnly ) == false )
{
QMessageBox::critical( nullptr,
TrackContainer::tr( "Couldn't open file" ),
TrackContainer::tr( "Couldn't open file %1 "
"for reading.\nPlease make "
"sure you have read-"
"permission to the file and "
"the directory containing the "
"file and try again!" ).arg(
m_file.fileName() ),
QMessageBox::Ok,
QMessageBox::NoButton );
return false;
}
return true;
}
} // namespace lmms
| 2,964
|
C++
|
.cpp
| 93
| 28.72043
| 99
| 0.707865
|
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,797
|
BandLimitedWave.cpp
|
LMMS_lmms/src/core/BandLimitedWave.cpp
|
/*
* BandLimitedWave.cpp - helper functions for band-limited
* waveform generation
*
* 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 "BandLimitedWave.h"
#include <QDataStream>
namespace lmms
{
std::array<WaveMipMap, BandLimitedWave::NumWaveforms> BandLimitedWave::s_waveforms = { };
bool BandLimitedWave::s_wavesGenerated = false;
QString BandLimitedWave::s_wavetableDir = "";
QDataStream& operator<< ( QDataStream &out, WaveMipMap &waveMipMap )
{
for( int tbl = 0; tbl <= MAXTBL; tbl++ )
{
for( int i = 0; i < TLENS[tbl]; i++ )
{
out << waveMipMap.sampleAt( tbl, i );
}
}
return out;
}
QDataStream& operator>> ( QDataStream &in, WaveMipMap &waveMipMap )
{
for( int tbl = 0; tbl <= MAXTBL; tbl++ )
{
for( int i = 0; i < TLENS[tbl]; i++ )
{
sample_t sample;
in >> sample;
waveMipMap.setSampleAt( tbl, i, sample );
}
}
return in;
}
void BandLimitedWave::generateWaves()
{
// don't generate if they already exist
if( s_wavesGenerated ) return;
// set wavetable directory
s_wavetableDir = "data:wavetables/";
// set wavetable files
QFile saw_file( s_wavetableDir + "saw.bin" );
QFile sqr_file( s_wavetableDir + "sqr.bin" );
QFile tri_file( s_wavetableDir + "tri.bin" );
QFile moog_file( s_wavetableDir + "moog.bin" );
// saw wave - BLSaw
// check for file and use it if exists
if( saw_file.exists() )
{
saw_file.open( QIODevice::ReadOnly );
QDataStream in( &saw_file );
in >> s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSaw)];
saw_file.close();
}
else
{
for (int i = 0; i <= MAXTBL; i++)
{
const int len = TLENS[i];
//const double om = 1.0 / len;
double max = 0.0;
for( int ph = 0; ph < len; ph++ )
{
int harm = 1;
double s = 0.0f;
double hlen;
do
{
hlen = static_cast<double>( len ) / static_cast<double>( harm );
const double amp = -1.0 / static_cast<double>( harm );
//const double a2 = cos( om * harm * F_2PI );
s += amp * /*a2 **/sin( static_cast<double>( ph * harm ) / static_cast<double>( len ) * F_2PI );
harm++;
} while( hlen > 2.0 );
s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSaw)].setSampleAt( i, ph, s );
max = std::max(max, std::abs(s));
}
// normalize
for( int ph = 0; ph < len; ph++ )
{
sample_t s = s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSaw)].sampleAt( i, ph ) / max;
s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSaw)].setSampleAt( i, ph, s );
}
}
}
// square wave - BLSquare
// check for file and use it if exists
if( sqr_file.exists() )
{
sqr_file.open( QIODevice::ReadOnly );
QDataStream in( &sqr_file );
in >> s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSquare)];
sqr_file.close();
}
else
{
for (int i = 0; i <= MAXTBL; i++)
{
const int len = TLENS[i];
//const double om = 1.0 / len;
double max = 0.0;
for( int ph = 0; ph < len; ph++ )
{
int harm = 1;
double s = 0.0f;
double hlen;
do
{
hlen = static_cast<double>( len ) / static_cast<double>( harm );
const double amp = 1.0 / static_cast<double>( harm );
//const double a2 = cos( om * harm * F_2PI );
s += amp * /*a2 **/ sin( static_cast<double>( ph * harm ) / static_cast<double>( len ) * F_2PI );
harm += 2;
} while( hlen > 2.0 );
s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSquare)].setSampleAt( i, ph, s );
max = std::max(max, std::abs(s));
}
// normalize
for( int ph = 0; ph < len; ph++ )
{
sample_t s = s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSquare)].sampleAt( i, ph ) / max;
s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSquare)].setSampleAt( i, ph, s );
}
}
}
// triangle wave - BLTriangle
if( tri_file.exists() )
{
tri_file.open( QIODevice::ReadOnly );
QDataStream in( &tri_file );
in >> s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLTriangle)];
tri_file.close();
}
else
{
for (int i = 0; i <= MAXTBL; i++)
{
const int len = TLENS[i];
//const double om = 1.0 / len;
double max = 0.0;
for( int ph = 0; ph < len; ph++ )
{
int harm = 1;
double s = 0.0f;
double hlen;
do
{
hlen = static_cast<double>( len ) / static_cast<double>( harm );
const double amp = 1.0 / static_cast<double>( harm * harm );
//const double a2 = cos( om * harm * F_2PI );
s += amp * /*a2 **/ sin( ( static_cast<double>( ph * harm ) / static_cast<double>( len ) +
( ( harm + 1 ) % 4 == 0 ? 0.5 : 0.0 ) ) * F_2PI );
harm += 2;
} while( hlen > 2.0 );
s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLTriangle)].setSampleAt( i, ph, s );
max = std::max(max, std::abs(s));
}
// normalize
for( int ph = 0; ph < len; ph++ )
{
sample_t s = s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLTriangle)].sampleAt( i, ph ) / max;
s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLTriangle)].setSampleAt( i, ph, s );
}
}
}
// moog saw wave - BLMoog
// basically, just add in triangle + 270-phase saw
if( moog_file.exists() )
{
moog_file.open( QIODevice::ReadOnly );
QDataStream in( &moog_file );
in >> s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLMoog)];
moog_file.close();
}
else
{
for (int i = 0; i <= MAXTBL; i++)
{
const int len = TLENS[i];
for( int ph = 0; ph < len; ph++ )
{
const int sawph = ( ph + static_cast<int>( len * 0.75 ) ) % len;
const sample_t saw = s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSaw)].sampleAt( i, sawph );
const sample_t tri = s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLTriangle)].sampleAt( i, ph );
s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLMoog)].setSampleAt( i, ph, ( saw + tri ) * 0.5f );
}
}
}
// set the generated flag so we don't load/generate them again needlessly
s_wavesGenerated = true;
// generate files, serialize mipmaps as QDataStreams and save them on disk
//
// normally these are now provided with LMMS as pre-generated so we don't have to do this,
// but I'm leaving the code here in case it's needed in the future
// (maybe we add more waveforms or change the generation code or mipmap format, etc.)
/*
// if you want to generate the files, you need to set the filenames and paths here -
// can't use the usual wavetable directory here as it can require permissions on
// some systems...
QFile sawfile( "path-to-wavetables/saw.bin" );
QFile sqrfile( "path-to-wavetables/sqr.bin" );
QFile trifile( "path-to-wavetables/tri.bin" );
QFile moogfile( "path-to-wavetables/moog.bin" );
sawfile.open( QIODevice::WriteOnly );
QDataStream sawout( &sawfile );
sawout << s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSaw)];
sawfile.close();
sqrfile.open( QIODevice::WriteOnly );
QDataStream sqrout( &sqrfile );
sqrout << s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLSquare)];
sqrfile.close();
trifile.open( QIODevice::WriteOnly );
QDataStream triout( &trifile );
triout << s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLTriangle)];
trifile.close();
moogfile.open( QIODevice::WriteOnly );
QDataStream moogout( &moogfile );
moogout << s_waveforms[static_cast<std::size_t>(BandLimitedWave::Waveform::BLMoog)];
moogfile.close();
*/
}
} // namespace lmms
| 8,354
|
C++
|
.cpp
| 243
| 31.316872
| 120
| 0.658869
|
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,798
|
RemotePlugin.cpp
|
LMMS_lmms/src/core/RemotePlugin.cpp
|
/*
* RemotePlugin.cpp - base class providing RPC like mechanisms
*
* 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 "RemotePlugin.h"
//#define DEBUG_REMOTE_PLUGIN
#ifdef DEBUG_REMOTE_PLUGIN
#include <QDebug>
#endif
#ifdef LMMS_BUILD_WIN32
#include <windows.h>
#endif
#include "BufferManager.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "Song.h"
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QUuid>
#ifndef SYNC_WITH_SHM_FIFO
#include <sys/socket.h>
#include <sys/un.h>
#endif
#ifdef LMMS_BUILD_WIN32
namespace {
HANDLE getRemotePluginJob()
{
static const auto job = []
{
const auto job = CreateJobObject(nullptr, nullptr);
auto limitInfo = JOBOBJECT_EXTENDED_LIMIT_INFORMATION{};
limitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limitInfo, sizeof(limitInfo));
return job;
}();
return job;
}
} // namespace
#endif // LMMS_BUILD_WIN32
namespace lmms
{
// simple helper thread monitoring our RemotePlugin - if process terminates
// unexpectedly invalidate plugin so LMMS doesn't lock up
ProcessWatcher::ProcessWatcher( RemotePlugin * _p ) :
QThread(),
m_plugin( _p ),
m_quit( false )
{
}
void ProcessWatcher::run()
{
auto& process = m_plugin->m_process;
process.start(m_plugin->m_exec, m_plugin->m_args);
#ifdef LMMS_BUILD_WIN32
// Add the process to our job so it is killed if we crash
if (process.waitForStarted(-1))
{
if (const auto processHandle = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, process.processId()))
{
// Ensure the process is still running, otherwise the handle we
// obtained may be for a different process that happened to reuse
// the same process id.
// QProcess::state() alone is insufficient as it only returns a
// cached state variable that is updated asynchronously. To query
// the process itself, we can use QProcess::waitForFinished() with a
// zero timeout, but that too is insufficient as it fails if the
// process has already finished. Therefore, we check both.
if (!process.waitForFinished(0) && process.state() == QProcess::Running)
{
AssignProcessToJobObject(getRemotePluginJob(), processHandle);
}
CloseHandle(processHandle);
}
}
#endif // LMMS_BUILD_WIN32
exec();
process.moveToThread(m_plugin->thread());
while (!m_quit && m_plugin->messagesLeft())
{
msleep(200);
}
if (!m_quit)
{
fprintf(stderr, "remote plugin died! invalidating now.\n");
m_plugin->invalidate();
}
}
RemotePlugin::RemotePlugin() :
QObject(),
#ifdef SYNC_WITH_SHM_FIFO
RemotePluginBase( new shmFifo(), new shmFifo() ),
#else
RemotePluginBase(),
#endif
m_failed( true ),
m_watcher( this ),
#if (QT_VERSION < QT_VERSION_CHECK(5,14,0))
m_commMutex(QMutex::Recursive),
#endif
m_splitChannels( false ),
m_audioBufferSize( 0 ),
m_inputCount( DEFAULT_CHANNELS ),
m_outputCount( DEFAULT_CHANNELS )
{
#ifndef SYNC_WITH_SHM_FIFO
struct sockaddr_un sa;
sa.sun_family = AF_LOCAL;
m_socketFile = QDir::tempPath() + QDir::separator() +
QUuid::createUuid().toString();
auto path = m_socketFile.toUtf8();
size_t length = path.length();
if ( length >= sizeof sa.sun_path )
{
length = sizeof sa.sun_path - 1;
qWarning( "Socket path too long." );
}
memcpy(sa.sun_path, path.constData(), length );
sa.sun_path[length] = '\0';
m_server = socket( PF_LOCAL, SOCK_STREAM, 0 );
if ( m_server == -1 )
{
qWarning( "Unable to start the server." );
}
remove(path.constData());
int ret = bind( m_server, (struct sockaddr *) &sa, sizeof sa );
if ( ret == -1 || listen( m_server, 1 ) == -1 )
{
qWarning( "Unable to start the server." );
}
#endif
connect( &m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
this, SLOT(processFinished(int,QProcess::ExitStatus)),
Qt::DirectConnection );
connect( &m_process, SIGNAL(errorOccurred(QProcess::ProcessError)),
this, SLOT(processErrored(QProcess::ProcessError)),
Qt::DirectConnection );
connect( &m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
&m_watcher, SLOT(quit()), Qt::DirectConnection );
}
RemotePlugin::~RemotePlugin()
{
m_watcher.stop();
m_watcher.wait();
if( m_failed == false )
{
if( isRunning() )
{
lock();
sendMessage( IdQuit );
m_process.waitForFinished( 1000 );
if( m_process.state() != QProcess::NotRunning )
{
m_process.terminate();
m_process.kill();
}
unlock();
}
}
#ifndef SYNC_WITH_SHM_FIFO
if ( close( m_server ) == -1)
{
qWarning( "Error freeing resources." );
}
remove( m_socketFile.toUtf8().constData() );
#endif
}
bool RemotePlugin::init(const QString &pluginExecutable,
bool waitForInitDoneMsg , QStringList extraArgs)
{
lock();
if( m_failed )
{
#ifdef SYNC_WITH_SHM_FIFO
reset( new shmFifo(), new shmFifo() );
#endif
m_failed = false;
}
QString exec = QFileInfo(QDir("plugins:"), pluginExecutable).absoluteFilePath();
#ifdef LMMS_BUILD_APPLE
// search current directory first
QString curDir = QCoreApplication::applicationDirPath() + "/" + pluginExecutable;
if( QFile( curDir ).exists() )
{
exec = curDir;
}
#endif
#ifdef LMMS_BUILD_WIN32
if( ! exec.endsWith( ".exe", Qt::CaseInsensitive ) )
{
exec += ".exe";
}
#endif
if( ! QFile( exec ).exists() )
{
qWarning( "Remote plugin '%s' not found.",
exec.toUtf8().constData() );
m_failed = true;
invalidate();
unlock();
return failed();
}
// ensure the watcher is ready in case we're running again
// (e.g. 32-bit VST plugins on Windows)
m_watcher.wait();
m_watcher.reset();
QStringList args;
#ifdef SYNC_WITH_SHM_FIFO
// swap in and out for bidirectional communication
args << QString::fromStdString(out()->shmKey());
args << QString::fromStdString(in()->shmKey());
#else
args << m_socketFile;
#endif
args << extraArgs;
#ifndef DEBUG_REMOTE_PLUGIN
m_process.setProcessChannelMode( QProcess::ForwardedChannels );
m_process.setWorkingDirectory( QCoreApplication::applicationDirPath() );
m_exec = exec;
m_args = args;
// we start the process on the watcher thread to work around QTBUG-8819
m_process.moveToThread( &m_watcher );
m_watcher.start( QThread::LowestPriority );
#else
qDebug() << exec << args;
#endif
#ifndef SYNC_WITH_SHM_FIFO
struct pollfd pollin;
pollin.fd = m_server;
pollin.events = POLLIN;
switch ( poll( &pollin, 1, 30000 ) )
{
case -1:
qWarning( "Unexpected poll error." );
break;
case 0:
qWarning( "Remote plugin did not connect." );
break;
default:
m_socket = accept( m_server, nullptr, nullptr );
if ( m_socket == -1 )
{
qWarning( "Unexpected socket error." );
}
}
#endif
sendMessage(message(IdSyncKey).addString(Engine::getSong()->syncKey()));
resizeSharedProcessingMemory();
if( waitForInitDoneMsg )
{
waitForInitDone();
}
unlock();
return failed();
}
bool RemotePlugin::process( const SampleFrame* _in_buf, SampleFrame* _out_buf )
{
const fpp_t frames = Engine::audioEngine()->framesPerPeriod();
if( m_failed || !isRunning() )
{
if( _out_buf != nullptr )
{
zeroSampleFrames(_out_buf, frames);
}
return false;
}
if (!m_audioBuffer)
{
// m_audioBuffer being zero means we didn't initialize everything so
// far so process one message each time (and hope we get
// information like SHM-key etc.) until we process messages
// in a later stage of this procedure
if( m_audioBufferSize == 0 )
{
lock();
fetchAndProcessAllMessages();
unlock();
}
if( _out_buf != nullptr )
{
zeroSampleFrames(_out_buf, frames);
}
return false;
}
memset( m_audioBuffer.get(), 0, m_audioBufferSize );
ch_cnt_t inputs = std::min<ch_cnt_t>(m_inputCount, DEFAULT_CHANNELS);
if( _in_buf != nullptr && inputs > 0 )
{
if( m_splitChannels )
{
for( ch_cnt_t ch = 0; ch < inputs; ++ch )
{
for( fpp_t frame = 0; frame < frames; ++frame )
{
m_audioBuffer[ch * frames + frame] =
_in_buf[frame][ch];
}
}
}
else if( inputs == DEFAULT_CHANNELS )
{
auto target = m_audioBuffer.get();
copyFromSampleFrames(target, _in_buf, frames);
}
else
{
auto o = (SampleFrame*)m_audioBuffer.get();
for( ch_cnt_t ch = 0; ch < inputs; ++ch )
{
for( fpp_t frame = 0; frame < frames; ++frame )
{
o[frame][ch] = _in_buf[frame][ch];
}
}
}
}
lock();
sendMessage( IdStartProcessing );
if( m_failed || _out_buf == nullptr || m_outputCount == 0 )
{
unlock();
return false;
}
waitForMessage( IdProcessingDone );
unlock();
const ch_cnt_t outputs = std::min<ch_cnt_t>(m_outputCount,
DEFAULT_CHANNELS);
if( m_splitChannels )
{
for( ch_cnt_t ch = 0; ch < outputs; ++ch )
{
for( fpp_t frame = 0; frame < frames; ++frame )
{
_out_buf[frame][ch] = m_audioBuffer[( m_inputCount+ch )*
frames + frame];
}
}
}
else if( outputs == DEFAULT_CHANNELS )
{
auto source = m_audioBuffer.get() + m_inputCount * frames;
copyToSampleFrames(_out_buf, source, frames);
}
else
{
auto o = (SampleFrame*)(m_audioBuffer.get() + m_inputCount * frames);
// clear buffer, if plugin didn't fill up both channels
zeroSampleFrames(_out_buf, frames);
for (ch_cnt_t ch = 0; ch <
std::min<int>(DEFAULT_CHANNELS, outputs); ++ch)
{
for( fpp_t frame = 0; frame < frames; ++frame )
{
_out_buf[frame][ch] = o[frame][ch];
}
}
}
return true;
}
void RemotePlugin::processMidiEvent( const MidiEvent & _e,
const f_cnt_t _offset )
{
message m( IdMidiEvent );
m.addInt( _e.type() );
m.addInt( _e.channel() );
m.addInt( _e.param( 0 ) );
m.addInt( _e.param( 1 ) );
m.addInt( _offset );
lock();
sendMessage( m );
unlock();
}
void RemotePlugin::showUI()
{
lock();
sendMessage( IdShowUI );
unlock();
}
void RemotePlugin::hideUI()
{
lock();
sendMessage( IdHideUI );
unlock();
}
void RemotePlugin::resizeSharedProcessingMemory()
{
const size_t s = (m_inputCount + m_outputCount) * Engine::audioEngine()->framesPerPeriod();
try
{
m_audioBuffer.create(QUuid::createUuid().toString().toStdString(), s);
}
catch (const std::runtime_error& error)
{
qCritical() << "Failed to allocate shared audio buffer:" << error.what();
m_audioBuffer.detach();
return;
}
m_audioBufferSize = s * sizeof(float);
sendMessage(message(IdChangeSharedMemoryKey).addString(m_audioBuffer.key()));
}
void RemotePlugin::processFinished( int exitCode,
QProcess::ExitStatus exitStatus )
{
if ( exitStatus == QProcess::CrashExit )
{
qCritical() << "Remote plugin crashed";
}
else if ( exitCode )
{
qCritical() << "Remote plugin exit code: " << exitCode;
}
#ifndef SYNC_WITH_SHM_FIFO
invalidate();
#endif
}
void RemotePlugin::processErrored( QProcess::ProcessError err )
{
qCritical() << "Process error: " << err;
}
bool RemotePlugin::processMessage( const message & _m )
{
lock();
message reply_message( _m.id );
bool reply = false;
switch( _m.id )
{
case IdUndefined:
unlock();
return false;
case IdInitDone:
reply = true;
break;
case IdSampleRateInformation:
reply = true;
reply_message.addInt( Engine::audioEngine()->outputSampleRate() );
break;
case IdBufferSizeInformation:
reply = true;
reply_message.addInt( Engine::audioEngine()->framesPerPeriod() );
break;
case IdChangeInputCount:
m_inputCount = _m.getInt( 0 );
resizeSharedProcessingMemory();
break;
case IdChangeOutputCount:
m_outputCount = _m.getInt( 0 );
resizeSharedProcessingMemory();
break;
case IdChangeInputOutputCount:
m_inputCount = _m.getInt( 0 );
m_outputCount = _m.getInt( 1 );
resizeSharedProcessingMemory();
break;
case IdDebugMessage:
fprintf( stderr, "RemotePlugin::DebugMessage: %s",
_m.getString( 0 ).c_str() );
break;
case IdProcessingDone:
case IdQuit:
default:
break;
}
if( reply )
{
sendMessage( reply_message );
}
unlock();
return true;
}
} // namespace lmms
| 12,784
|
C++
|
.cpp
| 489
| 23.476483
| 112
| 0.69773
|
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,799
|
ProjectJournal.cpp
|
LMMS_lmms/src/core/ProjectJournal.cpp
|
/*
* ProjectJournal.cpp - implementation of ProjectJournal
*
* 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 <cstdlib>
#include <QDomElement>
#include "ProjectJournal.h"
#include "Engine.h"
#include "JournallingObject.h"
#include "Song.h"
#include "AutomationClip.h"
namespace lmms
{
//! Avoid clashes between loaded IDs (have the bit cleared)
//! and newly created IDs (have the bit set)
static const int EO_ID_MSB = 1 << 23;
const int ProjectJournal::MAX_UNDO_STATES = 100; // TODO: make this configurable in settings
ProjectJournal::ProjectJournal() :
m_joIDs(),
m_undoCheckPoints(),
m_redoCheckPoints(),
m_journalling( false )
{
}
void ProjectJournal::undo()
{
while( !m_undoCheckPoints.isEmpty() )
{
CheckPoint c = m_undoCheckPoints.pop();
JournallingObject *jo = m_joIDs[c.joID];
if( jo )
{
DataFile curState( DataFile::Type::JournalData );
jo->saveState( curState, curState.content() );
m_redoCheckPoints.push( CheckPoint( c.joID, curState ) );
bool prev = isJournalling();
setJournalling( false );
jo->restoreState( c.data.content().firstChildElement() );
setJournalling( prev );
Engine::getSong()->setModified();
// loading AutomationClip connections correctly
if (!c.data.content().elementsByTagName("automationclip").isEmpty())
{
AutomationClip::resolveAllIDs();
}
break;
}
}
}
void ProjectJournal::redo()
{
while( !m_redoCheckPoints.isEmpty() )
{
CheckPoint c = m_redoCheckPoints.pop();
JournallingObject *jo = m_joIDs[c.joID];
if( jo )
{
DataFile curState( DataFile::Type::JournalData );
jo->saveState( curState, curState.content() );
m_undoCheckPoints.push( CheckPoint( c.joID, curState ) );
bool prev = isJournalling();
setJournalling( false );
jo->restoreState( c.data.content().firstChildElement() );
setJournalling( prev );
Engine::getSong()->setModified();
break;
}
}
}
bool ProjectJournal::canUndo() const
{
return !m_undoCheckPoints.isEmpty();
}
bool ProjectJournal::canRedo() const
{
return !m_redoCheckPoints.isEmpty();
}
void ProjectJournal::addJournalCheckPoint( JournallingObject *jo )
{
if( isJournalling() )
{
m_redoCheckPoints.clear();
DataFile dataFile( DataFile::Type::JournalData );
jo->saveState( dataFile, dataFile.content() );
m_undoCheckPoints.push( CheckPoint( jo->id(), dataFile ) );
if( m_undoCheckPoints.size() > MAX_UNDO_STATES )
{
m_undoCheckPoints.remove( 0, m_undoCheckPoints.size() - MAX_UNDO_STATES );
}
}
}
jo_id_t ProjectJournal::allocID( JournallingObject * _obj )
{
jo_id_t id;
for( jo_id_t tid = rand(); m_joIDs.contains( id = tid % EO_ID_MSB
| EO_ID_MSB ); tid++ )
{
}
m_joIDs[id] = _obj;
//printf("new id: %d\n", id );
return id;
}
void ProjectJournal::reallocID( const jo_id_t _id, JournallingObject * _obj )
{
//printf("realloc %d %d\n", _id, _obj );
// if( m_joIDs.contains( _id ) )
{
m_joIDs[_id] = _obj;
}
}
jo_id_t ProjectJournal::idToSave( jo_id_t id )
{
return id & ~EO_ID_MSB;
}
jo_id_t ProjectJournal::idFromSave( jo_id_t id )
{
return id | EO_ID_MSB;
}
void ProjectJournal::clearJournal()
{
m_undoCheckPoints.clear();
m_redoCheckPoints.clear();
for( JoIdMap::Iterator it = m_joIDs.begin(); it != m_joIDs.end(); )
{
if( it.value() == nullptr )
{
it = m_joIDs.erase( it );
}
else
{
++it;
}
}
}
void ProjectJournal::stopAllJournalling()
{
for( JoIdMap::Iterator it = m_joIDs.begin(); it != m_joIDs.end(); ++it)
{
if( it.value() != nullptr )
{
it.value()->setJournalling(false);
}
}
setJournalling(false);
}
} // namespace lmms
| 4,450
|
C++
|
.cpp
| 165
| 24.460606
| 92
| 0.706868
|
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,800
|
Ladspa2LMMS.cpp
|
LMMS_lmms/src/core/Ladspa2LMMS.cpp
|
/*
* Ladspa2LMMS.cpp - class that identifies and instantiates LADSPA effects
* for use with LMMS
*
* Copyright (c) 2005-2008 Danny McRae <khjklujn@netscape.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 "Ladspa2LMMS.h"
namespace lmms
{
Ladspa2LMMS::Ladspa2LMMS()
{
l_sortable_plugin_t plugins = getSortedPlugins();
for (const auto& plugin : plugins)
{
ladspa_key_t key = plugin.second;
LadspaManagerDescription * desc = getDescription( key );
if( desc->type == LadspaPluginType::Source )
{
m_instruments.append( qMakePair( getName( key ),
key ) );
}
else if( desc->type == LadspaPluginType::Transfer &&
( desc->inputChannels == desc->outputChannels &&
( desc->inputChannels == 1 ||
desc->inputChannels == 2 ||
desc->inputChannels == 4 )/* &&
isRealTimeCapable( key )*/ ) )
{
m_validEffects.append( qMakePair( getName( key ),
key ) );
}
else if( desc->type == LadspaPluginType::Transfer &&
( desc->inputChannels != desc->outputChannels ||
( desc->inputChannels != 1 &&
desc->inputChannels != 2 &&
desc->inputChannels != 4 ) ||
!isRealTimeCapable( key ) ) )
{
m_invalidEffects.append( qMakePair( getName( key ),
key ) );
}
else if( desc->type == LadspaPluginType::Sink )
{
m_analysisTools.append( qMakePair( getName( key ),
key ) );
}
else if( desc->type == LadspaPluginType::Other )
{
m_otherPlugins.append( qMakePair( getName( key ),
key ) );
}
}
}
QString Ladspa2LMMS::getShortName( const ladspa_key_t & _key )
{
QString name = getName( _key );
if( name.indexOf( "(" ) > 0 )
{
name = name.left( name.indexOf( "(" ) );
}
if( name.indexOf( " - " ) > 0 )
{
name = name.left( name.indexOf( " - " ) );
}
if( name.indexOf( " " ) > 0 )
{
name = name.left( name.indexOf( " " ) );
}
Qt::CaseSensitivity cs = Qt::CaseInsensitive;
if( name.indexOf( " with ", 0, cs ) > 0 )
{
name = name.left( name.indexOf( " with ", 0, cs ) );
}
if( name.indexOf( ",", 0, cs ) > 0 )
{
name = name.left( name.indexOf( ",", 0, cs ) );
}
if( name.length() > 40 )
{
int i = 40;
while( name[i] != ' ' && i > 0 )
{
i--;
}
name = name.left( i );
}
if( name.length() == 0 )
{
name = "LADSPA Plugin";
}
return name;
}
} // namespace lmms
| 3,092
|
C++
|
.cpp
| 111
| 24.828829
| 74
| 0.644332
|
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,801
|
PeakController.cpp
|
LMMS_lmms/src/core/PeakController.cpp
|
/*
* PeakController.cpp - implementation of class controller which handles
* remote-control of AutomatableModels
*
* Copyright (c) 2008 Paul Giblock <drfaygo/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 "PeakController.h"
#include <cmath>
#include <QDomElement>
#include <QMessageBox>
#include "AudioEngine.h"
#include "EffectChain.h"
#include "plugins/PeakControllerEffect/PeakControllerEffect.h"
namespace lmms
{
PeakControllerEffectVector PeakController::s_effects;
int PeakController::m_getCount;
int PeakController::m_loadCount;
bool PeakController::m_buggedFile;
PeakController::PeakController( Model * _parent,
PeakControllerEffect * _peak_effect ) :
Controller( ControllerType::Peak, _parent, tr( "Peak Controller" ) ),
m_peakEffect( _peak_effect ),
m_currentSample( 0.0f )
{
setSampleExact( true );
if( m_peakEffect )
{
connect( m_peakEffect, SIGNAL(destroyed()),
this, SLOT(handleDestroyedEffect()));
}
connect( Engine::audioEngine(), SIGNAL(sampleRateChanged()), this, SLOT(updateCoeffs()));
connect( m_peakEffect->attackModel(), SIGNAL(dataChanged()),
this, SLOT(updateCoeffs()), Qt::DirectConnection );
connect( m_peakEffect->decayModel(), SIGNAL(dataChanged()),
this, SLOT(updateCoeffs()), Qt::DirectConnection );
m_coeffNeedsUpdate = true;
}
PeakController::~PeakController()
{
if( m_peakEffect != nullptr && m_peakEffect->effectChain() != nullptr )
{
m_peakEffect->effectChain()->removeEffect( m_peakEffect );
}
}
void PeakController::updateValueBuffer()
{
if( m_coeffNeedsUpdate )
{
m_coeff = 100.0f / Engine::audioEngine()->outputSampleRate();
m_coeffNeedsUpdate = false;
}
if( m_peakEffect )
{
float targetSample = m_peakEffect->lastSample();
if( m_currentSample != targetSample )
{
const f_cnt_t frames = Engine::audioEngine()->framesPerPeriod();
float * values = m_valueBuffer.values();
for( f_cnt_t f = 0; f < frames; ++f )
{
const float diff = ( targetSample - m_currentSample );
m_currentSample += diff * m_coeff;
values[f] = m_currentSample;
}
}
else
{
m_valueBuffer.fill( m_currentSample );
}
}
else
{
m_valueBuffer.fill( 0 );
}
m_bufferLastUpdated = s_periods;
}
void PeakController::updateCoeffs()
{
m_coeffNeedsUpdate = true;
}
void PeakController::handleDestroyedEffect()
{
// possible race condition...
//printf("disconnecting effect\n");
disconnect( m_peakEffect );
m_peakEffect = nullptr;
//deleteLater();
delete this;
}
void PeakController::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
if( m_peakEffect )
{
Controller::saveSettings( _doc, _this );
_this.setAttribute( "effectId", m_peakEffect->m_effectId );
}
}
void PeakController::loadSettings( const QDomElement & _this )
{
Controller::loadSettings( _this );
int effectId = _this.attribute( "effectId" ).toInt();
if( m_buggedFile == true )
{
effectId = m_loadCount++;
}
for (const auto& effect : s_effects)
{
if (effect->m_effectId == effectId)
{
m_peakEffect = effect;
return;
}
}
}
//Backward compatibility function for bug in <= 0.4.15
void PeakController::initGetControllerBySetting()
{
m_loadCount = 0;
m_getCount = 0;
m_buggedFile = false;
}
PeakController * PeakController::getControllerBySetting(const QDomElement & _this )
{
int effectId = _this.attribute( "effectId" ).toInt();
//Backward compatibility for bug in <= 0.4.15 . For >= 1.0.0 ,
//foundCount should always be 1 because m_effectId is initialized with rand()
int foundCount = 0;
if( m_buggedFile == false )
{
for (const auto& effect : s_effects)
{
if (effect->m_effectId == effectId)
{
foundCount++;
}
}
if( foundCount >= 2 )
{
m_buggedFile = true;
int newEffectId = 0;
for (const auto& effect : s_effects)
{
effect->m_effectId = newEffectId++;
}
QMessageBox msgBox;
msgBox.setIcon( QMessageBox::Information );
msgBox.setWindowTitle( tr("Peak Controller Bug") );
msgBox.setText( tr("Due to a bug in older version of LMMS, the peak "
"controllers may not be connect properly. "
"Please ensure that peak controllers are connected "
"properly and re-save this file. "
"Sorry for any inconvenience caused.") );
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.exec();
}
}
if( m_buggedFile == true )
{
effectId = m_getCount;
}
m_getCount++; //NB: m_getCount should be increased even m_buggedFile is false
for (const auto& effect : s_effects)
{
if (effect->m_effectId == effectId)
{
return effect->controller();
}
}
return nullptr;
}
QString PeakController::nodeName() const
{
return( "Peakcontroller" );
}
gui::ControllerDialog * PeakController::createDialog( QWidget * _parent )
{
return new gui::PeakControllerDialog( this, _parent );
}
} // namespace lmms
| 5,632
|
C++
|
.cpp
| 198
| 25.772727
| 90
| 0.717125
|
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,802
|
Scale.cpp
|
LMMS_lmms/src/core/Scale.cpp
|
/*
* Scale.cpp - implementation of scale class
*
* Copyright (c) 2020 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 "Scale.h"
#include <cmath>
#include <QDomElement>
namespace lmms
{
Interval::Interval(float cents) :
m_numerator(0),
m_denominator(0),
m_cents(cents)
{
m_ratio = powf(2.f, m_cents / 1200.f);
}
Interval::Interval(uint32_t numerator, uint32_t denominator) :
m_numerator(numerator),
m_denominator(denominator > 0 ? denominator : 1),
m_cents(0)
{
m_ratio = static_cast<float>(m_numerator) / m_denominator;
}
void Interval::saveSettings(QDomDocument &document, QDomElement &element)
{
if (m_denominator > 0)
{
element.setAttribute("num", QString::number(m_numerator));
element.setAttribute("den", QString::number(m_denominator));
}
else
{
element.setAttribute("cents", QString::number(m_cents));
}
}
void Interval::loadSettings(const QDomElement &element)
{
m_numerator = element.attribute("num", "0").toULong();
m_denominator = element.attribute("den", "0").toULong();
m_cents = element.attribute("cents", "0").toDouble();
if (m_denominator) {m_ratio = static_cast<float>(m_numerator) / m_denominator;}
else {m_ratio = powf(2.f, m_cents / 1200.f);}
}
Scale::Scale() :
m_description(tr("empty"))
{
m_intervals.emplace_back(1, 1);
}
Scale::Scale(QString description, std::vector<Interval> intervals) :
m_description(description),
m_intervals(std::move(intervals))
{
}
QString Scale::getDescription() const
{
return m_description;
}
void Scale::setDescription(QString description)
{
m_description = description;
}
void Scale::saveSettings(QDomDocument &document, QDomElement &element)
{
element.setAttribute("description", m_description);
for (auto& interval : m_intervals)
{
interval.saveState(document, element);
}
}
void Scale::loadSettings(const QDomElement &element)
{
m_description = element.attribute("description");
QDomNode node = element.firstChild();
m_intervals.clear();
while (!node.isNull())
{
Interval temp;
temp.restoreState(node.toElement());
m_intervals.push_back(temp);
node = node.nextSibling();
}
}
} // namespace lmms
| 2,925
|
C++
|
.cpp
| 102
| 26.696078
| 80
| 0.743205
|
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,803
|
TimePos.cpp
|
LMMS_lmms/src/core/TimePos.cpp
|
/*
* TimePos.cpp - Class that encapsulates the position of a note/event in terms of
* its bar, beat and tick.
*
* 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 "TimePos.h"
#include <cassert>
#include "MeterModel.h"
namespace lmms
{
TimeSig::TimeSig( int num, int denom ) :
m_num(num),
m_denom(denom)
{
}
TimeSig::TimeSig( const MeterModel &model ) :
m_num(model.getNumerator()),
m_denom(model.getDenominator())
{
}
TimePos::TimePos( const bar_t bar, const tick_t ticks ) :
m_ticks( bar * s_ticksPerBar + ticks )
{
}
TimePos::TimePos( const tick_t ticks ) :
m_ticks( ticks )
{
}
TimePos TimePos::quantize(float bars) const
{
//The intervals we should snap to, our new position should be a factor of this
int interval = s_ticksPerBar * bars;
//The lower position we could snap to
int lowPos = m_ticks / interval;
//Offset from the lower position
int offset = m_ticks % interval;
//1 if we should snap up, 0 if we shouldn't
// Ternary expression is making sure that the snap happens in the direction to
// the right even if m_ticks is negative and the offset is exactly half-way
// More details on issue #5840 and PR #5847
int snapUp = ((2 * offset) == -interval)
? 0
: (2 * offset) / interval;
return (lowPos + snapUp) * interval;
}
} // namespace lmms
| 2,120
|
C++
|
.cpp
| 65
| 30.769231
| 81
| 0.734963
|
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,804
|
SampleBuffer.cpp
|
LMMS_lmms/src/core/SampleBuffer.cpp
|
/*
* SampleBuffer.cpp - container-class SampleBuffer
*
* 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 "SampleBuffer.h"
#include <cstring>
#include "PathUtil.h"
#include "SampleDecoder.h"
#include "lmms_basics.h"
namespace lmms {
SampleBuffer::SampleBuffer(const SampleFrame* data, size_t numFrames, int sampleRate)
: m_data(data, data + numFrames)
, m_sampleRate(sampleRate)
{
}
SampleBuffer::SampleBuffer(const QString& audioFile)
{
if (audioFile.isEmpty()) { throw std::runtime_error{"Failure loading audio file: Audio file path is empty."}; }
const auto absolutePath = PathUtil::toAbsolute(audioFile);
if (auto decodedResult = SampleDecoder::decode(absolutePath))
{
auto& [data, sampleRate] = *decodedResult;
m_data = std::move(data);
m_sampleRate = sampleRate;
m_audioFile = PathUtil::toShortestRelative(audioFile);
return;
}
throw std::runtime_error{
"Failed to decode audio file: Either the audio codec is unsupported, or the file is corrupted."};
}
SampleBuffer::SampleBuffer(const QString& base64, int sampleRate)
: m_sampleRate(sampleRate)
{
// TODO: Replace with non-Qt equivalent
const auto bytes = QByteArray::fromBase64(base64.toUtf8());
m_data.resize(bytes.size() / sizeof(SampleFrame));
std::memcpy(reinterpret_cast<char*>(m_data.data()), bytes, m_data.size() * sizeof(SampleFrame));
}
SampleBuffer::SampleBuffer(std::vector<SampleFrame> data, int sampleRate)
: m_data(std::move(data))
, m_sampleRate(sampleRate)
{
}
void swap(SampleBuffer& first, SampleBuffer& second) noexcept
{
using std::swap;
swap(first.m_data, second.m_data);
swap(first.m_audioFile, second.m_audioFile);
swap(first.m_sampleRate, second.m_sampleRate);
}
QString SampleBuffer::toBase64() const
{
// TODO: Replace with non-Qt equivalent
const auto data = reinterpret_cast<const char*>(m_data.data());
const auto size = static_cast<int>(m_data.size() * sizeof(SampleFrame));
const auto byteArray = QByteArray{data, size};
return byteArray.toBase64();
}
auto SampleBuffer::emptyBuffer() -> std::shared_ptr<const SampleBuffer>
{
static auto s_buffer = std::make_shared<const SampleBuffer>();
return s_buffer;
}
} // namespace lmms
| 3,001
|
C++
|
.cpp
| 83
| 34.277108
| 112
| 0.758003
|
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,805
|
InlineAutomation.cpp
|
LMMS_lmms/src/core/InlineAutomation.cpp
|
/*
* InlineAutomation.cpp - class for automating something "inline"
*
* Copyright (c) 2008-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 <QDomElement>
#include "InlineAutomation.h"
namespace lmms
{
void InlineAutomation::saveSettings( QDomDocument & _doc,
QDomElement & _parent )
{
if( hasAutomation() )
{
QDomElement ap = _doc.createElement(
AutomationClip::classNodeName() );
QDomElement v = _doc.createElement( nodeName() );
automationClip()->saveSettings( _doc, v );
ap.appendChild( v );
_parent.appendChild( ap );
}
}
void InlineAutomation::loadSettings( const QDomElement & _this )
{
QDomNode node = _this.namedItem( AutomationClip::classNodeName() );
if( node.isElement() )
{
node = node.namedItem( nodeName() );
if( node.isElement() )
{
automationClip()->loadSettings(
node.toElement() );
}
}
}
} // namespace lmms
| 1,696
|
C++
|
.cpp
| 54
| 28.944444
| 77
| 0.732843
|
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,806
|
Model.cpp
|
LMMS_lmms/src/core/Model.cpp
|
/*
* Model.cpp - implementation of Model base class
*
* Copyright (c) 2007-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 "Model.h"
namespace lmms
{
Model::Model(Model* parent, QString displayName, bool defaultConstructed) :
QObject(parent),
m_displayName(displayName),
m_defaultConstructed(defaultConstructed)
{
}
bool Model::isDefaultConstructed() const
{
return m_defaultConstructed;
}
Model* Model::parentModel() const
{
return dynamic_cast<Model*>(parent());
}
QString Model::displayName() const
{
return m_displayName;
}
void Model::setDisplayName(const QString& displayName)
{
m_displayName = displayName;
}
QString Model::fullDisplayName() const
{
const QString n = displayName();
if (parentModel())
{
const QString p = parentModel()->fullDisplayName();
if (!p.isEmpty())
{
return p + ">" + n;
}
}
return n;
}
} // namespace lmms
| 1,691
|
C++
|
.cpp
| 62
| 25.306452
| 77
| 0.753408
|
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,807
|
JournallingObject.cpp
|
LMMS_lmms/src/core/JournallingObject.cpp
|
/*
* JournallingObject.cpp - implementation of journalling-object related stuff
*
* 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 <QDomElement>
#include "JournallingObject.h"
#include "AutomatableModel.h"
#include "ProjectJournal.h"
#include "Engine.h"
namespace lmms
{
JournallingObject::JournallingObject() :
SerializingObject(),
m_id( Engine::projectJournal()->allocID( this ) ),
m_journalling( true ),
m_journallingStateStack()
{
}
JournallingObject::~JournallingObject()
{
if( Engine::projectJournal() )
{
Engine::projectJournal()->freeID( id() );
}
}
void JournallingObject::addJournalCheckPoint()
{
if( isJournalling() )
{
Engine::projectJournal()->addJournalCheckPoint( this );
}
}
QDomElement JournallingObject::saveState( QDomDocument & _doc,
QDomElement & _parent )
{
if( isJournalling() )
{
QDomElement _this = SerializingObject::saveState( _doc, _parent );
QDomElement journalNode = _doc.createElement( "journallingObject" );
journalNode.setAttribute( "id", id() );
journalNode.setAttribute( "metadata", true );
_this.appendChild( journalNode );
return _this;
} else {
return QDomElement();
}
}
void JournallingObject::restoreState( const QDomElement & _this )
{
SerializingObject::restoreState( _this );
saveJournallingState( false );
// search for journal-node
QDomNode node = _this.firstChild();
while( !node.isNull() )
{
if( node.isElement() && node.nodeName() == "journal" )
{
const jo_id_t new_id = node.toElement().attribute( "id" ).toInt();
if( new_id )
{
changeID( new_id );
}
}
node = node.nextSibling();
}
restoreJournallingState();
}
void JournallingObject::changeID( jo_id_t _id )
{
if( id() != _id )
{
JournallingObject * jo = Engine::projectJournal()->
journallingObject( _id );
if( jo != nullptr )
{
QString used_by = jo->nodeName();
if( used_by == "automatablemodel" &&
dynamic_cast<AutomatableModel *>( jo ) )
{
used_by += ":" +
dynamic_cast<AutomatableModel *>( jo )->
displayName();
}
fprintf( stderr, "JO-ID %d already in use by %s!\n",
(int) _id, used_by.toUtf8().constData() );
return;
}
Engine::projectJournal()->freeID( m_id );
Engine::projectJournal()->reallocID( _id, this );
m_id = _id;
}
}
} // namespace lmms
| 3,162
|
C++
|
.cpp
| 112
| 25.473214
| 77
| 0.706994
|
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,808
|
DataFile.cpp
|
LMMS_lmms/src/core/DataFile.cpp
|
/*
* DataFile.cpp - implementation of class DataFile
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2012-2013 Paul Giblock <p/at/pgiblock.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 "DataFile.h"
#include <algorithm>
#include <cmath>
#include <map>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QMessageBox>
#include <QRegularExpression>
#include <QSaveFile>
#include "base64.h"
#include "ConfigManager.h"
#include "Effect.h"
#include "embed.h"
#include "GuiApplication.h"
#include "LocaleHelper.h"
#include "Note.h"
#include "PluginFactory.h"
#include "ProjectVersion.h"
#include "SongEditor.h"
#include "TextFloat.h"
#include "Track.h"
#include "PathUtil.h"
#include "UpgradeExtendedNoteRange.h"
#include "lmmsversion.h"
namespace lmms
{
static void findIds(const QDomElement& elem, QList<jo_id_t>& idList);
// QMap with the DOM elements that access file resources
const DataFile::ResourcesMap DataFile::ELEMENTS_WITH_RESOURCES = {
{ "sampleclip", {"src"} },
{ "audiofileprocessor", {"src"} },
};
// Vector with all the upgrade methods
const std::vector<DataFile::UpgradeMethod> DataFile::UPGRADE_METHODS = {
&DataFile::upgrade_0_2_1_20070501 , &DataFile::upgrade_0_2_1_20070508,
&DataFile::upgrade_0_3_0_rc2 , &DataFile::upgrade_0_3_0,
&DataFile::upgrade_0_4_0_20080104 , &DataFile::upgrade_0_4_0_20080118,
&DataFile::upgrade_0_4_0_20080129 , &DataFile::upgrade_0_4_0_20080409,
&DataFile::upgrade_0_4_0_20080607 , &DataFile::upgrade_0_4_0_20080622,
&DataFile::upgrade_0_4_0_beta1 , &DataFile::upgrade_0_4_0_rc2,
&DataFile::upgrade_1_0_99 , &DataFile::upgrade_1_1_0,
&DataFile::upgrade_1_1_91 , &DataFile::upgrade_1_2_0_rc3,
&DataFile::upgrade_1_3_0 , &DataFile::upgrade_noHiddenClipNames,
&DataFile::upgrade_automationNodes , &DataFile::upgrade_extendedNoteRange,
&DataFile::upgrade_defaultTripleOscillatorHQ,
&DataFile::upgrade_mixerRename , &DataFile::upgrade_bbTcoRename,
&DataFile::upgrade_sampleAndHold , &DataFile::upgrade_midiCCIndexing,
&DataFile::upgrade_loopsRename , &DataFile::upgrade_noteTypes,
&DataFile::upgrade_fixCMTDelays , &DataFile::upgrade_fixBassLoopsTypo,
&DataFile::findProblematicLadspaPlugins
};
// Vector of all versions that have upgrade routines.
const std::vector<ProjectVersion> DataFile::UPGRADE_VERSIONS = {
"0.2.1-20070501" , "0.2.1-20070508" , "0.3.0-rc2",
"0.3.0" , "0.4.0-20080104" , "0.4.0-20080118",
"0.4.0-20080129" , "0.4.0-20080409" , "0.4.0-20080607",
"0.4.0-20080622" , "0.4.0-beta1" , "0.4.0-rc2",
"1.0.99-0" , "1.1.0-0" , "1.1.91-0",
"1.2.0-rc3" , "1.3.0"
};
namespace
{
struct TypeDescStruct
{
DataFile::Type m_type;
QString m_name;
};
const auto s_types = std::array{
TypeDescStruct{ DataFile::Type::Unknown, "unknown" },
TypeDescStruct{ DataFile::Type::SongProject, "song" },
TypeDescStruct{ DataFile::Type::SongProjectTemplate, "songtemplate" },
TypeDescStruct{ DataFile::Type::InstrumentTrackSettings, "instrumenttracksettings" },
TypeDescStruct{ DataFile::Type::DragNDropData, "dnddata" },
TypeDescStruct{ DataFile::Type::ClipboardData, "clipboard-data" },
TypeDescStruct{ DataFile::Type::JournalData, "journaldata" },
TypeDescStruct{ DataFile::Type::EffectSettings, "effectsettings" },
TypeDescStruct{ DataFile::Type::MidiClip, "midiclip" }
};
}
DataFile::DataFile( Type type ) :
QDomDocument( "lmms-project" ),
m_fileName(""),
m_content(),
m_head(),
m_type( type ),
m_fileVersion( UPGRADE_METHODS.size() )
{
appendChild( createProcessingInstruction("xml", "version=\"1.0\""));
QDomElement root = createElement( "lmms-project" );
root.setAttribute( "version", m_fileVersion );
root.setAttribute( "type", typeName( type ) );
root.setAttribute( "creator", "LMMS" );
root.setAttribute( "creatorversion", LMMS_VERSION );
appendChild( root );
m_head = createElement( "head" );
root.appendChild( m_head );
m_content = createElement( typeName( type ) );
root.appendChild( m_content );
}
DataFile::DataFile( const QString & _fileName ) :
QDomDocument(),
m_fileName(_fileName),
m_content(),
m_head(),
m_fileVersion( UPGRADE_METHODS.size() )
{
QFile inFile( _fileName );
if( !inFile.open( QIODevice::ReadOnly ) )
{
if (gui::getGUI() != nullptr)
{
QMessageBox::critical( nullptr,
gui::SongEditor::tr( "Could not open file" ),
gui::SongEditor::tr( "Could not open file %1. You probably "
"have no permissions to read this "
"file.\n Please make sure to have at "
"least read permissions to the file "
"and try again." ).arg( _fileName ) );
}
return;
}
loadData( inFile.readAll(), _fileName );
}
DataFile::DataFile( const QByteArray & _data ) :
QDomDocument(),
m_fileName(""),
m_content(),
m_head(),
m_fileVersion( UPGRADE_METHODS.size() )
{
loadData( _data, "<internal data>" );
}
bool DataFile::validate( QString extension )
{
switch( m_type )
{
case Type::SongProject:
if( extension == "mmp" || extension == "mmpz" )
{
return true;
}
break;
case Type::SongProjectTemplate:
if( extension == "mpt" )
{
return true;
}
break;
case Type::InstrumentTrackSettings:
if ( extension == "xpf" || extension == "xml" )
{
return true;
}
break;
case Type::MidiClip:
if (extension == "xpt" || extension == "xptz")
{
return true;
}
break;
case Type::Unknown:
if (! ( extension == "mmp" || extension == "mpt" || extension == "mmpz" ||
extension == "xpf" || extension == "xml" ||
( extension == "xiz" && ! getPluginFactory()->pluginSupportingExtension(extension).isNull()) ||
extension == "sf2" || extension == "sf3" || extension == "pat" || extension == "mid" ||
extension == "dll"
#ifdef LMMS_BUILD_LINUX
|| extension == "so"
#endif
#ifdef LMMS_HAVE_LV2
|| extension == "lv2"
#endif
) )
{
return true;
}
if( extension == "wav" || extension == "ogg" || extension == "ds"
#ifdef LMMS_HAVE_SNDFILE_MP3
|| extension == "mp3"
#endif
)
{
return true;
}
break;
default:
return false;
}
return false;
}
QString DataFile::nameWithExtension( const QString & _fn ) const
{
const QString extension = _fn.section( '.', -1 );
switch( type() )
{
case Type::SongProject:
if( extension != "mmp" &&
extension != "mpt" &&
extension != "mmpz" )
{
if( ConfigManager::inst()->value( "app",
"nommpz" ).toInt() == 0 )
{
return _fn + ".mmpz";
}
return _fn + ".mmp";
}
break;
case Type::SongProjectTemplate:
if( extension != "mpt" )
{
return _fn + ".mpt";
}
break;
case Type::InstrumentTrackSettings:
if( extension != "xpf" )
{
return _fn + ".xpf";
}
break;
default: ;
}
return _fn;
}
void DataFile::write( QTextStream & _strm )
{
if( type() == Type::SongProject || type() == Type::SongProjectTemplate
|| type() == Type::InstrumentTrackSettings )
{
cleanMetaNodes( documentElement() );
}
save(_strm, 2);
}
bool DataFile::writeFile(const QString& filename, bool withResources)
{
// Small lambda function for displaying errors
auto showError = [](QString title, QString body){
if (gui::getGUI() != nullptr)
{
QMessageBox mb;
mb.setWindowTitle(title);
mb.setText(body);
mb.setIcon(QMessageBox::Warning);
mb.setStandardButtons(QMessageBox::Ok);
mb.exec();
}
else
{
qWarning() << body;
}
};
// If we are saving without resources, filename is just the file we are
// saving to. If we are saving with resources (project bundle), filename
// will be used (discarding extensions) to create a folder where the
// bundle will be saved in
QFileInfo fInfo(filename);
const QString bundleDir = fInfo.path() + "/" + fInfo.fileName().section('.', 0, 0);
const QString resourcesDir = bundleDir + "/resources";
const QString fullName = withResources
? nameWithExtension(bundleDir + "/" + fInfo.fileName())
: nameWithExtension(filename);
const QString fullNameTemp = fullName + ".new";
const QString fullNameBak = fullName + ".bak";
using gui::SongEditor;
// If we are saving with resources, setup the bundle folder first
if (withResources)
{
// First check if there's a bundle folder with the same name in
// the path already. If so, warns user that we can't overwrite a
// project bundle.
if (QDir(bundleDir).exists())
{
showError(SongEditor::tr("Operation denied"),
SongEditor::tr("A bundle folder with that name already eists on the "
"selected path. Can't overwrite a project bundle. Please select a different "
"name."));
return false;
}
// Create bundle folder
if (!QDir().mkdir(bundleDir))
{
showError(SongEditor::tr("Error"),
SongEditor::tr("Couldn't create bundle folder."));
return false;
}
// Create resources folder
if (!QDir().mkdir(resourcesDir))
{
showError(SongEditor::tr("Error"),
SongEditor::tr("Couldn't create resources folder."));
return false;
}
// Copy resources to folder and update paths
if (!copyResources(resourcesDir))
{
showError(SongEditor::tr("Error"),
SongEditor::tr("Failed to copy resources."));
return false;
}
}
QSaveFile outfile(fullNameTemp);
if (!outfile.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
showError(SongEditor::tr("Could not write file"),
SongEditor::tr("Could not open %1 for writing. You probably are not permitted to "
"write to this file. Please make sure you have write-access to "
"the file and try again.").arg(fullName));
return false;
}
const QString extension = fullName.section('.', -1);
if (extension == "mmpz" || extension == "xptz")
{
QString xml;
QTextStream ts( &xml );
write( ts );
outfile.write( qCompress( xml.toUtf8() ) );
}
else
{
QTextStream ts( &outfile );
write( ts );
}
if (!outfile.commit())
{
showError(SongEditor::tr("Could not write file"),
SongEditor::tr("An unknown error has occurred and the file could not be saved."));
return false;
}
if (ConfigManager::inst()->value("app", "disablebackup").toInt())
{
// remove current file
QFile::remove(fullName);
}
else
{
// remove old backup file
QFile::remove(fullNameBak);
// move current file to backup file
QFile::rename(fullName, fullNameBak);
}
// move temporary file to current file
QFile::rename(fullNameTemp, fullName);
return true;
}
bool DataFile::copyResources(const QString& resourcesDir)
{
// List of filenames used so we can append a counter to any
// repeating filenames
std::list<QString> namesList;
auto it = ELEMENTS_WITH_RESOURCES.begin();
// Copy resources and manipulate the DataFile to have local paths to them
while (it != ELEMENTS_WITH_RESOURCES.end())
{
QDomNodeList list = elementsByTagName(it->first);
// Go through all elements with the tagname from our map
for (int i = 0; !list.item(i).isNull(); ++i)
{
QDomElement el = list.item(i).toElement();
auto res = it->second.begin();
// Search for attributes that point to resources
while (res != it->second.end())
{
// If the element has that attribute
if (el.hasAttribute(*res))
{
// Get absolute path to resource
bool error;
QString resPath = PathUtil::toAbsolute(el.attribute(*res), &error);
// If we are running without the project loaded (from CLI), "local:" base
// prefixes aren't converted, so we need to convert it ourselves
if (error)
{
resPath = QFileInfo(m_fileName).path() + "/" + resPath.remove(0,
PathUtil::basePrefix(PathUtil::Base::LocalDir).length());
}
// Check if we need to add a counter to the filename
QString finalFileName = QFileInfo(resPath).fileName();
QString extension = resPath.section('.', -1);
int repeatedNames = 0;
for (QString name : namesList)
{
if (finalFileName == name)
{
++repeatedNames;
}
}
// Add the name to the list before modifying it
namesList.push_back(finalFileName);
if (repeatedNames)
{
// Remove the extension, add the counter and add the
// extension again to get the final file name
finalFileName.truncate(finalFileName.lastIndexOf('.'));
finalFileName = finalFileName + "-" + QString::number(repeatedNames) + "." + extension;
}
// Final path is our resources dir + the new file name
QString finalPath = resourcesDir + "/" + finalFileName;
// Copy resource file to the resources folder
if(!QFile::copy(resPath, finalPath))
{
qWarning("ERROR: Failed to copy resource");
return false;
}
// Update attribute path to point to the bundle file
QString newAtt = PathUtil::basePrefix(PathUtil::Base::LocalDir) + "resources/" + finalFileName;
el.setAttribute(*res, newAtt);
}
++res;
}
}
++it;
}
return true;
}
/**
* @brief This recursive method will go through all XML nodes of the DataFile
* and check whether any of them have local paths. If they are not on
* our list of elements that can have local paths we return true,
* indicating that we potentially have plugins with local paths that
* would be a security issue. The Song class can then abort loading
* this project.
* @param parent The parent node being iterated. When called
* without arguments, this will be an empty element that will be
* ignored (since the second parameter will be true).
* @param firstCall Defaults to true, and indicates to this recursive
* method whether this is the first call. If it is it will use the
* root element as the parent.
*/
bool DataFile::hasLocalPlugins(QDomElement parent /* = QDomElement()*/, bool firstCall /* = true*/) const
{
// If this is the first iteration of the recursion we use the root element
if (firstCall) { parent = documentElement(); }
auto children = parent.childNodes();
for (int i = 0; i < children.size(); ++i)
{
QDomNode child = children.at(i);
QDomElement childElement = child.toElement();
bool skipNode = false;
// Skip the nodes allowed to have "local:" attributes, but
// still check its children
for (const auto& element : ELEMENTS_WITH_RESOURCES)
{
if (childElement.tagName() == element.first)
{
skipNode = true;
break;
}
}
// Check if they have "local:" attribute (unless they are allowed to
// and skipNode is true)
if (!skipNode)
{
auto attributes = childElement.attributes();
for (int i = 0; i < attributes.size(); ++i)
{
QDomNode attribute = attributes.item(i);
QDomAttr attr = attribute.toAttr();
if (attr.value().startsWith(PathUtil::basePrefix(PathUtil::Base::LocalDir),
Qt::CaseInsensitive))
{
return true;
}
}
}
// Now we check the children of this node (recursively)
// and if any return true we return true.
if (hasLocalPlugins(childElement, false))
{
return true;
}
}
// If we got here none of the nodes had the "local:" path.
return false;
}
DataFile::Type DataFile::type( const QString& typeName )
{
const auto it = std::find_if(s_types.begin(), s_types.end(),
[&typeName](const TypeDescStruct& type) { return type.m_name == typeName; });
if (it != s_types.end()) { return it->m_type; }
// compat code
if( typeName == "channelsettings" )
{
return Type::InstrumentTrackSettings;
}
return Type::Unknown;
}
QString DataFile::typeName( Type type )
{
return s_types[static_cast<std::size_t>(type)].m_name;
}
void DataFile::cleanMetaNodes( QDomElement _de )
{
QDomNode node = _de.firstChild();
while( !node.isNull() )
{
if( node.isElement() )
{
if( node.toElement().attribute( "metadata" ).toInt() )
{
QDomNode ns = node.nextSibling();
_de.removeChild( node );
node = ns;
continue;
}
if( node.hasChildNodes() )
{
cleanMetaNodes( node.toElement() );
}
}
node = node.nextSibling();
}
}
void DataFile::mapSrcAttributeInElementsWithResources(const QMap<QString, QString>& map)
{
for (const auto& [elem, srcAttrs] : ELEMENTS_WITH_RESOURCES)
{
auto elements = elementsByTagName(elem);
for (const auto& srcAttr : srcAttrs)
{
for (int i = 0; i < elements.length(); ++i)
{
auto item = elements.item(i).toElement();
if (item.isNull() || !item.hasAttribute(srcAttr)) { continue; }
const QString srcVal = item.attribute(srcAttr);
const auto it = map.constFind(srcVal);
if (it != map.constEnd())
{
item.setAttribute(srcAttr, *it);
}
}
}
}
}
void DataFile::upgrade_0_2_1_20070501()
{
// Upgrade to version 0.2.1-20070501
QDomNodeList list = elementsByTagName( "arpandchords" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
if( el.hasAttribute( "arpdir" ) )
{
int arpdir = el.attribute( "arpdir" ).toInt();
if( arpdir > 0 )
{
el.setAttribute( "arpdir", arpdir - 1 );
}
else
{
el.setAttribute( "arpdisabled", "1" );
}
}
}
list = elementsByTagName( "sampletrack" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
if( el.attribute( "vol" ) != "" )
{
el.setAttribute( "vol", LocaleHelper::toFloat(
el.attribute( "vol" ) ) * 100.0f );
}
else
{
QDomNode node = el.namedItem(
"automation-pattern" );
if( !node.isElement() ||
!node.namedItem( "vol" ).isElement() )
{
el.setAttribute( "vol", 100.0f );
}
}
}
list = elementsByTagName( "ladspacontrols" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
QDomNode anode = el.namedItem( "automation-pattern" );
QDomNode node = anode.firstChild();
while( !node.isNull() )
{
if( node.isElement() )
{
QString name = node.nodeName();
if( name.endsWith( "link" ) )
{
el.setAttribute( name,
node.namedItem( "time" )
.toElement()
.attribute( "value" ) );
QDomNode oldNode = node;
node = node.nextSibling();
anode.removeChild( oldNode );
continue;
}
}
node = node.nextSibling();
}
}
QDomNode node = m_head.firstChild();
while( !node.isNull() )
{
if( node.isElement() )
{
if( node.nodeName() == "bpm" )
{
int value = node.toElement().attribute(
"value" ).toInt();
if( value > 0 )
{
m_head.setAttribute( "bpm",
value );
QDomNode oldNode = node;
node = node.nextSibling();
m_head.removeChild( oldNode );
continue;
}
}
else if( node.nodeName() == "mastervol" )
{
int value = node.toElement().attribute(
"value" ).toInt();
if( value > 0 )
{
m_head.setAttribute(
"mastervol", value );
QDomNode oldNode = node;
node = node.nextSibling();
m_head.removeChild( oldNode );
continue;
}
}
else if( node.nodeName() == "masterpitch" )
{
m_head.setAttribute( "masterpitch",
-node.toElement().attribute(
"value" ).toInt() );
QDomNode oldNode = node;
node = node.nextSibling();
m_head.removeChild( oldNode );
continue;
}
}
node = node.nextSibling();
}
}
void DataFile::upgrade_0_2_1_20070508()
{
// Upgrade to version 0.2.1-20070508 from some version greater than or equal to 0.2.1-20070501
QDomNodeList list = elementsByTagName( "arpandchords" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
if( el.hasAttribute( "chorddisabled" ) )
{
el.setAttribute( "chord-enabled",
!el.attribute( "chorddisabled" )
.toInt() );
el.setAttribute( "arp-enabled",
!el.attribute( "arpdisabled" )
.toInt() );
}
else if( !el.hasAttribute( "chord-enabled" ) )
{
el.setAttribute( "chord-enabled", true );
el.setAttribute( "arp-enabled",
el.attribute( "arpdir" ).toInt() != 0 );
}
}
while( !( list = elementsByTagName( "channeltrack" ) ).isEmpty() )
{
QDomElement el = list.item( 0 ).toElement();
el.setTagName( "instrumenttrack" );
}
list = elementsByTagName( "instrumenttrack" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
if( el.hasAttribute( "vol" ) )
{
float value = LocaleHelper::toFloat( el.attribute( "vol" ) );
value = roundf( value * 0.585786438f );
el.setAttribute( "vol", value );
}
else
{
QDomNodeList vol_list = el.namedItem(
"automation-pattern" )
.namedItem( "vol" ).toElement()
.elementsByTagName( "time" );
for( int j = 0; !vol_list.item( j ).isNull();
++j )
{
QDomElement timeEl = list.item( j )
.toElement();
int value = timeEl.attribute( "value" )
.toInt();
value = (int)roundf( value *
0.585786438f );
timeEl.setAttribute( "value", value );
}
}
}
}
void DataFile::upgrade_0_3_0_rc2()
{
// Upgrade to version 0.3.0-rc2 from some version greater than or equal to 0.2.1-20070508
QDomNodeList list = elementsByTagName( "arpandchords" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
if( el.attribute( "arpdir" ).toInt() > 0 )
{
el.setAttribute( "arpdir",
el.attribute( "arpdir" ).toInt() - 1 );
}
}
}
void DataFile::upgrade_0_3_0()
{
// Upgrade to version 0.3.0 (final) from some version greater than or equal to 0.3.0-rc2
QDomNodeList list;
while( !( list = elementsByTagName(
"pluckedstringsynth" ) ).isEmpty() )
{
QDomElement el = list.item( 0 ).toElement();
el.setTagName( "vibedstrings" );
el.setAttribute( "active0", 1 );
}
while( !( list = elementsByTagName( "lb303" ) ).isEmpty() )
{
QDomElement el = list.item( 0 ).toElement();
el.setTagName( "lb302" );
}
while( !( list = elementsByTagName( "channelsettings" ) ).
isEmpty() )
{
QDomElement el = list.item( 0 ).toElement();
el.setTagName( "instrumenttracksettings" );
}
}
void DataFile::upgrade_0_4_0_20080104()
{
// Upgrade to version 0.4.0-20080104 from some version greater than or equal to 0.3.0 (final)
QDomNodeList list = elementsByTagName( "fx" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
if( el.hasAttribute( "fxdisabled" ) &&
el.attribute( "fxdisabled" ).toInt() == 0 )
{
el.setAttribute( "enabled", 1 );
}
}
}
void DataFile::upgrade_0_4_0_20080118()
{
// Upgrade to version 0.4.0-20080118 from some version greater than or equal to 0.4.0-20080104
QDomNodeList list;
while( !( list = elementsByTagName( "fx" ) ).isEmpty() )
{
QDomElement fxchain = list.item( 0 ).toElement();
fxchain.setTagName( "fxchain" );
QDomNode rack = list.item( 0 ).firstChild();
QDomNodeList effects = rack.childNodes();
// move items one level up
while( effects.count() )
{
fxchain.appendChild( effects.at( 0 ) );
}
fxchain.setAttribute( "numofeffects",
rack.toElement().attribute( "numofeffects" ) );
fxchain.removeChild( rack );
}
}
void DataFile::upgrade_0_4_0_20080129()
{
// Upgrade to version 0.4.0-20080129 from some version greater than or equal to 0.4.0-20080118
QDomNodeList list;
while( !( list =
elementsByTagName( "arpandchords" ) ).isEmpty() )
{
QDomElement aac = list.item( 0 ).toElement();
aac.setTagName( "arpeggiator" );
QDomNode cloned = aac.cloneNode();
cloned.toElement().setTagName( "chordcreator" );
aac.parentNode().appendChild( cloned );
}
}
void DataFile::upgrade_0_4_0_20080409()
{
// Upgrade to version 0.4.0-20080409 from some version greater than or equal to 0.4.0-20080129
QStringList s;
s << "note" << "pattern" << "bbtco" << "sampletco" << "time";
for( QStringList::iterator it = s.begin(); it < s.end(); ++it )
{
QDomNodeList list = elementsByTagName( *it );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
el.setAttribute( "pos",
el.attribute( "pos" ).toInt()*3 );
el.setAttribute( "len",
el.attribute( "len" ).toInt()*3 );
}
}
QDomNodeList list = elementsByTagName( "timeline" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
el.setAttribute( "lp0pos",
el.attribute( "lp0pos" ).toInt()*3 );
el.setAttribute( "lp1pos",
el.attribute( "lp1pos" ).toInt()*3 );
}
}
void DataFile::upgrade_0_4_0_20080607()
{
// Upgrade to version 0.4.0-20080607 from some version greater than or equal to 0.3.0-20080409
QDomNodeList list;
while( !( list = elementsByTagName( "midi" ) ).isEmpty() )
{
QDomElement el = list.item( 0 ).toElement();
el.setTagName( "midiport" );
}
}
void DataFile::upgrade_0_4_0_20080622()
{
// Upgrade to version 0.4.0-20080622 from some version greater than or equal to 0.3.0-20080607
QDomNodeList list;
while( !( list = elementsByTagName(
"automation-pattern" ) ).isEmpty() )
{
QDomElement el = list.item( 0 ).toElement();
el.setTagName( "automationpattern" );
}
list = elementsByTagName( "bbtrack" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
QString s = el.attribute( "name" );
s.replace(QRegularExpression("^Beat/Baseline "), "Beat/Bassline");
el.setAttribute( "name", s );
}
}
void DataFile::upgrade_0_4_0_beta1()
{
// Upgrade to version 0.4.0-beta1 from some version greater than or equal to 0.4.0-20080622
// convert binary effect-key-blobs to XML
QDomNodeList list;
list = elementsByTagName( "effect" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
QString k = el.attribute( "key" );
if( !k.isEmpty() )
{
const QList<QVariant> l =
base64::decode( k, QVariant::List ).toList();
if( !l.isEmpty() )
{
QString name = l[0].toString();
QVariant u = l[1];
EffectKey::AttributeMap m;
// VST-effect?
if( u.type() == QVariant::String )
{
m["file"] = u.toString();
}
// LADSPA-effect?
else if( u.type() == QVariant::StringList )
{
const QStringList sl = u.toStringList();
m["plugin"] = sl.value( 0 );
m["file"] = sl.value( 1 );
}
EffectKey key( nullptr, name, m );
el.appendChild( key.saveXML( *this ) );
}
}
}
}
void DataFile::upgrade_0_4_0_rc2()
{
// Upgrade to version 0.4.0-rc2 from some version greater than or equal to 0.4.0-beta1
QDomNodeList list = elementsByTagName( "audiofileprocessor" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
QString s = el.attribute( "src" );
s.replace( "drumsynth/misc ", "drumsynth/misc_" );
s.replace( "drumsynth/r&b", "drumsynth/r_n_b" );
s.replace( "drumsynth/r_b", "drumsynth/r_n_b" );
el.setAttribute( "src", s );
}
list = elementsByTagName( "lb302" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
int s = el.attribute( "shape" ).toInt();
if( s >= 1 )
{
s--;
}
el.setAttribute( "shape", QString("%1").arg(s) );
}
}
void DataFile::upgrade_1_0_99()
{
jo_id_t last_assigned_id = 0;
QList<jo_id_t> idList;
findIds(documentElement(), idList);
QDomNodeList list = elementsByTagName("ladspacontrols");
for(int i = 0; !list.item(i).isNull(); ++i)
{
for(QDomNode node = list.item(i).firstChild(); !node.isNull();
node = node.nextSibling())
{
QDomElement el = node.toElement();
QDomNode data_child = el.namedItem("data");
if(!data_child.isElement())
{
if (el.attribute("scale_type") == "log")
{
QDomElement me = createElement("data");
me.setAttribute("value", el.attribute("data"));
me.setAttribute("scale_type", "log");
jo_id_t id;
for(id = last_assigned_id + 1;
idList.contains(id); id++)
{
}
last_assigned_id = id;
idList.append(id);
me.setAttribute("id", id);
el.appendChild(me);
}
}
}
}
}
void DataFile::upgrade_1_1_0()
{
QDomNodeList list = elementsByTagName("fxchannel");
for (int i = 1; !list.item(i).isNull(); ++i)
{
QDomElement el = list.item(i).toElement();
QDomElement send = createElement("send");
send.setAttribute("channel", "0");
send.setAttribute("amount", "1");
el.appendChild(send);
}
}
void DataFile::upgrade_1_1_91()
{
// Upgrade to version 1.1.91 from some version less than 1.1.91
QDomNodeList list = elementsByTagName( "audiofileprocessor" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
QString s = el.attribute( "src" );
s.replace(QRegularExpression("/samples/bassloopes/"), "/samples/bassloops/");
el.setAttribute( "src", s );
}
list = elementsByTagName( "attribute" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
if( el.attribute( "name" ) == "plugin" && el.attribute( "value" ) == "vocoder-lmms" ) {
el.setAttribute( "value", "vocoder" );
}
}
list = elementsByTagName( "crossoevereqcontrols" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
// invert the mute LEDs
for( int j = 1; j <= 4; ++j ){
QString a = QString( "mute%1" ).arg( j );
el.setAttribute( a, ( el.attribute( a ) == "0" ) ? "1" : "0" );
}
}
list = elementsByTagName( "arpeggiator" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
// Swap elements ArpDirRandom and ArpDirDownAndUp
if( el.attribute( "arpdir" ) == "3" )
{
el.setAttribute( "arpdir", "4" );
}
else if( el.attribute( "arpdir" ) == "4" )
{
el.setAttribute( "arpdir", "3" );
}
}
}
static void upgradeElement_1_2_0_rc2_42( QDomElement & el )
{
if( el.hasAttribute( "syncmode" ) )
{
int syncmode = el.attribute( "syncmode" ).toInt();
QStringList names;
QDomNamedNodeMap atts = el.attributes();
for (auto i = 0; i < atts.length(); i++)
{
QString name = atts.item( i ).nodeName();
if( name.endsWith( "_numerator" ) )
{
names << name.remove( "_numerator" )
+ "_syncmode";
}
}
for( QStringList::iterator it = names.begin(); it < names.end();
++it )
{
el.setAttribute( *it, syncmode );
}
}
QDomElement child = el.firstChildElement();
while ( !child.isNull() )
{
upgradeElement_1_2_0_rc2_42( child );
child = child.nextSiblingElement();
}
}
void DataFile::upgrade_1_2_0_rc3()
{
// Upgrade from earlier bbtrack beat note behaviour of adding
// steps if a note is placed after the last step.
QDomNodeList bbtracks = elementsByTagName( "bbtrack" );
for( int i = 0; !bbtracks.item( i ).isNull(); ++i )
{
QDomNodeList patterns = bbtracks.item( i
).toElement().elementsByTagName(
"pattern" );
for( int j = 0; !patterns.item( j ).isNull(); ++j )
{
QDomElement el = patterns.item( j ).toElement();
if( el.attribute( "len" ) != "" )
{
int patternLength = el.attribute( "len" ).toInt();
int steps = patternLength / 12;
el.setAttribute( "steps", steps );
}
}
}
// DataFile::upgrade_1_2_0_rc2_42
QDomElement el = firstChildElement();
while ( !el.isNull() )
{
upgradeElement_1_2_0_rc2_42( el );
el = el.nextSiblingElement();
}
}
/**
* Helper function to call a functor for all effect ports' DomElements,
* providing the functor with lists to add and remove DomElements. Helpful for
* patching port values from savefiles.
*/
template<class Ftor>
void iterate_ladspa_ports(QDomElement& effect, Ftor& ftor)
{
// Head back up the DOM to upgrade ports
QDomNodeList ladspacontrols = effect.elementsByTagName( "ladspacontrols" );
for( int m = 0; !ladspacontrols.item( m ).isNull(); ++m )
{
QList<QDomElement> addList, removeList;
QDomElement ladspacontrol = ladspacontrols.item( m ).toElement();
for( QDomElement port = ladspacontrol.firstChild().toElement();
!port.isNull(); port = port.nextSibling().toElement() )
{
QStringList parts = port.tagName().split("port");
// Not a "port"
if ( parts.size() < 2 )
{
continue;
}
int num = parts[1].toInt();
// From Qt's docs of QDomNode:
// * copying a QDomNode is OK, they still have the same
// pointer to the "internal" QDomNodePrivate.
// * Also, they are using linked lists, which means
// deleting or appending QDomNode does not invalidate
// any other pointers.
// => Inside ftor, you can (and should) push back the
// QDomElements by value, not references
// => The loops below for adding and removing don't
// invalidate any other QDomElements
ftor(port, num, addList, removeList);
}
// Add ports marked for adding
for ( QDomElement e : addList )
{
ladspacontrol.appendChild( e );
}
// Remove ports marked for removal
for ( QDomElement e : removeList )
{
ladspacontrol.removeChild( e );
}
}
}
// helper function if you need to print a QDomNode
QDebug operator<<(QDebug dbg, const QDomNode& node)
{
QString s;
QTextStream str(&s, QIODevice::WriteOnly);
node.save(str, 2);
dbg << qPrintable(s);
return dbg;
}
void DataFile::upgrade_1_3_0()
{
QDomNodeList list = elementsByTagName( "instrument" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement el = list.item( i ).toElement();
if( el.attribute( "name" ) == "papu" )
{
el.setAttribute( "name", "freeboy" );
QDomNodeList children = el.elementsByTagName( "papu" );
for( int j = 0; !children.item( j ).isNull(); ++j )
{
QDomElement child = children.item( j ).toElement();
child.setTagName( "freeboy" );
}
}
else if( el.attribute( "name" ) == "OPL2" )
{
el.setAttribute( "name", "opulenz" );
QDomNodeList children = el.elementsByTagName( "OPL2" );
for( int j = 0; !children.item( j ).isNull(); ++j )
{
QDomElement child = children.item( j ).toElement();
child.setTagName( "opulenz" );
}
}
}
list = elementsByTagName( "effect" );
for( int i = 0; !list.item( i ).isNull(); ++i )
{
QDomElement effect = list.item( i ).toElement();
if( effect.attribute( "name" ) == "ladspaeffect" )
{
QDomNodeList keys = effect.elementsByTagName( "key" );
for( int j = 0; !keys.item( j ).isNull(); ++j )
{
QDomElement key = keys.item( j ).toElement();
QDomNodeList attributes = key.elementsByTagName( "attribute" );
for( int k = 0; !attributes.item( k ).isNull(); ++k )
{
// Effect name changes
QDomElement attribute = attributes.item( k ).toElement();
const QString attrName = attribute.attribute("name");
const QString attrVal = attribute.attribute("value");
const QString plugin = attrName == "plugin" ? attrVal : "";
static const std::map<QString, QString> pluginNames = {
{"Sidechaincompressor", "SidechainCompressor"},
{"Sidechaingate", "SidechainGate"},
{"Multibandcompressor", "MultibandCompressor"},
{"Multibandgate", "MultibandGate"},
{"Multibandlimiter", "MultibandLimiter"},
};
if (attrName == "file" && (attrVal == "calf" || attrVal == "calf.so" ))
{
attribute.setAttribute( "value", "veal" );
}
const auto newName = pluginNames.find(plugin);
if (newName != pluginNames.end())
{
attribute.setAttribute("value", newName->second);
}
// Handle port changes
if (plugin == "MultibandLimiter" || plugin == "MultibandCompressor" || plugin == "MultibandGate")
{
auto fn = [&](QDomElement& port, int num, QList<QDomElement>&, QList<QDomElement>& removeList)
{
// Mark ports for removal
if ( num >= 18 && num <= 23 )
{
removeList << port;
}
// Bump higher ports up 6 positions
else if ( num >= 24 )
{
// port01...port010, etc
QString name( "port0" );
name.append( QString::number( num -6 ) );
port.setTagName( name );
}
};
iterate_ladspa_ports(effect, fn);
}
else if (plugin == "Pulsator")
{
auto fn = [&](QDomElement& port, int num, QList<QDomElement>& addList, QList<QDomElement>& removeList)
{
switch(num)
{
case 16:
{
// old freq is now at port 25
QDomElement portCopy = createElement("port025");
portCopy.setAttribute("data", port.attribute("data"));
addList << portCopy;
// remove old freq port
removeList << port;
// set the "timing" port to choose port23+2=port25 (timing in Hz)
QDomElement timing = createElement("port022");
timing.setAttribute("data", 2);
addList << timing;
break;
}
// port 18 (modulation) => 17
case 17:
port.setTagName("port016");
break;
case 18:
{
// leave port 18 (offsetr), but add port 17 (offsetl)
QDomElement offsetl = createElement("port017");
offsetl.setAttribute("data", 0.0f);
addList << offsetl;
// additional: bash port 21 to 1
QDomElement pulsewidth = createElement("port021");
pulsewidth.setAttribute("data", 1.0f);
addList << pulsewidth;
break;
}
}
};
iterate_ladspa_ports(effect, fn);
}
else if (plugin == "VintageDelay")
{
auto fn = [&](QDomElement& port, int num, QList<QDomElement>& addList, QList<QDomElement>& )
{
switch(num)
{
case 4:
{
// BPM is now port028
port.setTagName("port028");
// bash timing to BPM
QDomElement timing = createElement("port027");
timing.setAttribute("data", 0);
addList << timing;
// port 5 and 6 (in, out gain) need to be bashed to 1:
QDomElement input = createElement("port05");
input.setAttribute("data", 1.0f);
addList << input;
QDomElement output = createElement("port06");
output.setAttribute("data", 1.0f);
addList << output;
break;
}
default:
// all other ports increase by 10
QString name( "port0" );
name.append( QString::number( num + 10 ) );
port.setTagName( name );
}
};
iterate_ladspa_ports(effect, fn);
}
else if (plugin == "Equalizer5Band" || plugin == "Equalizer8Band" || plugin == "Equalizer12Band")
{
// NBand equalizers got 4 q nobs inserted. We need to shift everything else...
// HOWEVER: 5 band eq has only 2 q nobs inserted (no LS/HS filters)
bool band5 = plugin == "Equalizer5Band";
auto fn = [&](QDomElement& port, int num, QList<QDomElement>& addList, QList<QDomElement>& )
{
if(num == 4)
{
// don't modify port 4, but some other ones:
int zoom_port = 0;
if (plugin == "Equalizer5Band")
zoom_port = 36;
else if (plugin == "Equalizer8Band")
zoom_port = 48;
else // 12 band
zoom_port = 64;
// bash zoom to 0.25
QString name( "port0" );
name.append( QString::number( zoom_port ) );
QDomElement timing = createElement(name);
timing.setAttribute("data", 0.25f);
addList << timing;
}
// the following code could be refactored, but I did careful code-reading
// to prevent copy-paste-errors
if(num == 18)
{
// 18 => 19
port.setTagName("port019");
// insert port 18 (q)
QDomElement q = createElement("port018");
q.setAttribute("data", 0.707f);
addList << q;
}
else if(num >= 19 && num <= 20)
{
// num += 1
QString name( "port0" );
name.append( QString::number( num + 1 ) );
port.setTagName( name );
}
else if(num == 21)
{
// 21 => 23
port.setTagName("port023");
// insert port 22 (q)
QDomElement q = createElement("port022");
q.setAttribute("data", 0.707f);
addList << q;
}
else if(num >= 22 && (num <= 23 || band5))
{
// num += 2
QString name( "port0" );
name.append( QString::number( num + 2 ) );
port.setTagName( name );
}
else if(num == 24 && !band5)
{
// 24 => 27
port.setTagName("port027");
// insert port 26 (q)
QDomElement q = createElement("port026");
q.setAttribute("data", 0.707f);
addList << q;
}
else if(num >= 25 && num <= 26 && !band5)
{
// num += 3
QString name( "port0" );
name.append( QString::number( num + 3 ) );
port.setTagName( name );
}
else if(num == 27 && !band5)
{
// 27 => 31
port.setTagName("port031");
// insert port 30 (q)
QDomElement q = createElement("port030");
q.setAttribute("data", 0.707f);
addList << q;
}
else if(num >= 28 && !band5)
{
// num += 4
QString name( "port0" );
name.append( QString::number( num + 4 ) );
port.setTagName( name );
}
};
iterate_ladspa_ports(effect, fn);
}
else if (plugin == "Saturator")
{
auto fn = [&](QDomElement& port, int num, QList<QDomElement>&, QList<QDomElement>& )
{
// These ports have been shifted a bit weird...
if( num == 7 )
{
port.setTagName("port015");
}
else if(num == 12)
{
port.setTagName("port016");
}
else if(num == 13)
{
port.setTagName("port017");
}
else if ( num >= 15 )
{
QString name( "port0" );
name.append( QString::number( num + 3 ) );
port.setTagName( name );
}
};
iterate_ladspa_ports(effect, fn);
}
else if (plugin == "StereoTools")
{
auto fn = [&](QDomElement& port, int num, QList<QDomElement>&, QList<QDomElement>& )
{
// This effect can not be back-ported due to bugs in the old version,
// or due to different behaviour. We thus port all parameters we can,
// and bash all new parameters (in this case, s.level and m.level) to
// their new defaults (both 1.0f in this case)
if( num == 23 || num == 25 )
{
port.setAttribute("data", 1.0f);
}
};
iterate_ladspa_ports(effect, fn);
}
else if (plugin == "amPitchshift")
{
auto fn = [&](QDomElement& port, int num, QList<QDomElement>&, QList<QDomElement>& removeList)
{
switch (num)
{
case 0:
port.setTagName("port01");
break;
case 1:
port.setTagName("port03");
break;
case 10:
port.setTagName("port11");
break;
case 11:
port.setTagName("port13");
break;
}
};
iterate_ladspa_ports(effect, fn);
}
}
}
}
}
}
void DataFile::upgrade_noHiddenClipNames()
{
QDomNodeList tracks = elementsByTagName("track");
auto clearDefaultNames = [](QDomNodeList clips, QString trackName)
{
for (int j = 0; j < clips.size(); ++j)
{
QDomElement clip = clips.item(j).toElement();
QString clipName = clip.attribute("name", "");
if (clipName == trackName) { clip.setAttribute("name", ""); }
}
};
for (int i = 0; i < tracks.size(); ++i)
{
QDomElement track = tracks.item(i).toElement();
QString trackName = track.attribute("name", "");
QDomNodeList instClips = track.elementsByTagName("pattern");
QDomNodeList autoClips = track.elementsByTagName("automationpattern");
QDomNodeList bbClips = track.elementsByTagName("bbtco");
clearDefaultNames(instClips, trackName);
clearDefaultNames(autoClips, trackName);
clearDefaultNames(bbClips, trackName);
}
}
void DataFile::upgrade_automationNodes()
{
QDomNodeList autoPatterns = elementsByTagName("automationpattern");
// Go through all automation patterns
for (int i = 0; i < autoPatterns.size(); ++i)
{
QDomElement autoPattern = autoPatterns.item(i).toElement();
// On each automation pattern, get all <time> elements
QDomNodeList times = autoPattern.elementsByTagName("time");
// Loop through all <time> elements and change what we need
for (int j=0; j < times.size(); ++j)
{
QDomElement el = times.item(j).toElement();
float value = LocaleHelper::toFloat(el.attribute("value"));
// inValue will be equal to "value" and outValue will
// be set to the same
el.setAttribute("outValue", value);
}
}
}
// Convert the negative length notes to StepNotes
void DataFile::upgrade_noteTypes()
{
const auto notes = elementsByTagName("note");
for (int i = 0; i < notes.size(); ++i)
{
auto note = notes.item(i).toElement();
const auto noteSize = note.attribute("len").toInt();
if (noteSize < 0)
{
note.setAttribute("len", DefaultTicksPerBar / 16);
note.setAttribute("type", static_cast<int>(Note::Type::Step));
}
}
}
void DataFile::upgrade_fixCMTDelays()
{
static const QMap<QString, QString> nameMap {
{ "delay_0,01s", "delay_0.01s" },
{ "delay_0,1s", "delay_0.1s" },
{ "fbdelay_0,01s", "fbdelay_0.01s" },
{ "fbdelay_0,1s", "fbdelay_0.1s" }
};
const auto effects = elementsByTagName("effect");
for (int i = 0; i < effects.size(); ++i)
{
auto effect = effects.item(i).toElement();
// We are only interested in LADSPA plugins
if (effect.attribute("name") != "ladspaeffect") { continue; }
// Fetch all attributes (LMMS) beneath the LADSPA effect so that we can check the value of the plugin attribute (XML)
auto attributes = effect.elementsByTagName("attribute");
for (int j = 0; j < attributes.size(); ++j)
{
auto attribute = attributes.item(j).toElement();
if (attribute.attribute("name") == "plugin")
{
const auto attributeValue = attribute.attribute("value");
const auto it = nameMap.constFind(attributeValue);
if (it != nameMap.constEnd())
{
attribute.setAttribute("value", *it);
}
}
}
}
}
/** \brief Note range has been extended to match MIDI specification
*
* The non-standard note range previously affected all MIDI-based instruments
* except OpulenZ, and made them sound an octave lower than they should (#1857).
*/
void DataFile::upgrade_extendedNoteRange()
{
auto root = documentElement();
UpgradeExtendedNoteRange upgradeExtendedNoteRange(root);
upgradeExtendedNoteRange.upgrade();
}
/** \brief TripleOscillator switched to using high-quality, alias-free oscillators by default
*
* Older projects were made without this feature and would sound differently if loaded
* with the new default setting. This upgrade routine preserves their old behavior.
*/
void DataFile::upgrade_defaultTripleOscillatorHQ()
{
QDomNodeList tripleoscillators = elementsByTagName("tripleoscillator");
for (int i = 0; !tripleoscillators.item(i).isNull(); i++)
{
for (int j = 1; j <= 3; j++)
{
// Only set the attribute if it does not exist (default template has it but reports as 1.2.0)
if (tripleoscillators.item(i).toElement().attribute("useWaveTable" + QString::number(j)) == "")
{
tripleoscillators.item(i).toElement().setAttribute("useWaveTable" + QString::number(j), 0);
}
}
}
}
// Remove FX prefix from mixer and related nodes
void DataFile::upgrade_mixerRename()
{
// Change nodename <fxmixer> to <mixer>
QDomNodeList fxmixer = elementsByTagName("fxmixer");
for (int i = 0; i < fxmixer.length(); ++i)
{
auto item = fxmixer.item(i).toElement();
if (item.isNull())
{
continue;
}
item.setTagName("mixer");
}
// Change nodename <fxchannel> to <mixerchannel>
QDomNodeList fxchannel = elementsByTagName("fxchannel");
for (int i = 0; i < fxchannel.length(); ++i)
{
auto item = fxchannel.item(i).toElement();
if (item.isNull())
{
continue;
}
item.setTagName("mixerchannel");
}
// Change the attribute fxch of element <instrumenttrack> to mixch
QDomNodeList fxch = elementsByTagName("instrumenttrack");
for (int i = 0; i < fxch.length(); ++i)
{
auto item = fxch.item(i).toElement();
if (item.isNull())
{
continue;
}
if (item.hasAttribute("fxch"))
{
item.setAttribute("mixch", item.attribute("fxch"));
item.removeAttribute("fxch");
}
}
// Change the attribute fxch of element <sampletrack> to mixch
fxch = elementsByTagName("sampletrack");
for (int i = 0; i < fxch.length(); ++i)
{
auto item = fxch.item(i).toElement();
if (item.isNull())
{
continue;
}
if (item.hasAttribute("fxch"))
{
item.setAttribute("mixch", item.attribute("fxch"));
item.removeAttribute("fxch");
}
}
}
// Rename BB to pattern and TCO to clip
void DataFile::upgrade_bbTcoRename()
{
std::vector<std::pair<const char *, const char *>> names {
{"automationpattern", "automationclip"},
{"bbtco", "patternclip"},
{"pattern", "midiclip"},
{"sampletco", "sampleclip"},
{"bbtrack", "patterntrack"},
{"bbtrackcontainer", "patternstore"},
};
// Replace names of XML tags
for (auto name : names)
{
QDomNodeList elements = elementsByTagName(name.first);
for (int i = 0; !elements.item(i).isNull(); ++i)
{
elements.item(i).toElement().setTagName(name.second);
}
}
// Replace "Beat/Bassline" with "Pattern" in track names
QDomNodeList elements = elementsByTagName("track");
for (int i = 0; !elements.item(i).isNull(); ++i)
{
auto e = elements.item(i).toElement();
static_assert(Track::Type::Pattern == static_cast<Track::Type>(1), "Must be type=1 for backwards compatibility");
if (static_cast<Track::Type>(e.attribute("type").toInt()) == Track::Type::Pattern)
{
e.setAttribute("name", e.attribute("name").replace("Beat/Bassline", "Pattern"));
}
}
}
// Set LFO speed to 0.01 on projects made before sample-and-hold PR
void DataFile::upgrade_sampleAndHold()
{
QDomNodeList elements = elementsByTagName("lfocontroller");
for (int i = 0; i < elements.length(); ++i)
{
if (elements.item(i).isNull()) { continue; }
auto e = elements.item(i).toElement();
// Correct old random wave LFO speeds
if (e.attribute("wave").toInt() == 6)
{
e.setAttribute("speed", 0.01f);
}
}
}
static QMap<QString, QString> buildReplacementMap()
{
static constexpr auto loopBPMs = std::array{
std::pair{"bassloops/briff01", "140"},
std::pair{"bassloops/briff01", "140"},
std::pair{"bassloops/rave_bass01", "180"},
std::pair{"bassloops/rave_bass02", "180"},
std::pair{"bassloops/tb303_01", "123"},
std::pair{"bassloops/techno_bass01", "140"},
std::pair{"bassloops/techno_bass02", "140"},
std::pair{"bassloops/techno_synth01", "140"},
std::pair{"bassloops/techno_synth02", "140"},
std::pair{"bassloops/techno_synth03", "130"},
std::pair{"bassloops/techno_synth04", "140"},
std::pair{"beats/909beat01", "122"},
std::pair{"beats/break01", "168"},
std::pair{"beats/break02", "141"},
std::pair{"beats/break03", "168"},
std::pair{"beats/electro_beat01", "120"},
std::pair{"beats/electro_beat02", "119"},
std::pair{"beats/house_loop01", "142"},
std::pair{"beats/jungle01", "168"},
std::pair{"beats/rave_hihat01", "180"},
std::pair{"beats/rave_hihat02", "180"},
std::pair{"beats/rave_kick01", "180"},
std::pair{"beats/rave_kick02", "180"},
std::pair{"beats/rave_snare01", "180"},
std::pair{"latin/latin_brass01", "140"},
std::pair{"latin/latin_guitar01", "126"},
std::pair{"latin/latin_guitar02", "140"},
std::pair{"latin/latin_guitar03", "120"},
};
QMap<QString, QString> namesToNamesWithBPMsMap;
auto insertEntry = [&namesToNamesWithBPMsMap](const QString& originalName, const QString& bpm, const QString& prefix = "", const QString& extension = "ogg")
{
const QString original = prefix + originalName + "." + extension;
const QString replacement = prefix + originalName + " - " + bpm + " BPM." + extension;
namesToNamesWithBPMsMap.insert(original, replacement);
};
for (const auto & loopBPM : loopBPMs)
{
insertEntry(loopBPM.first, loopBPM.second);
insertEntry(loopBPM.first, loopBPM.second, "factorysample:");
}
return namesToNamesWithBPMsMap;
}
// Change loops' filenames in <sampleclip>s
void DataFile::upgrade_loopsRename()
{
static const QMap<QString, QString> namesToNamesWithBPMsMap = buildReplacementMap();
mapSrcAttributeInElementsWithResources(namesToNamesWithBPMsMap);
}
//! Update MIDI CC indexes, so that they are counted from 0. Older releases of LMMS
//! count the CCs from 1.
void DataFile::upgrade_midiCCIndexing()
{
static constexpr std::array attributesToUpdate{"inputcontroller", "outputcontroller"};
QDomNodeList elements = elementsByTagName("Midicontroller");
for(int i = 0; i < elements.length(); i++)
{
if (elements.item(i).isNull()) { continue; }
auto element = elements.item(i).toElement();
for (const char* attrName : attributesToUpdate)
{
if (element.hasAttribute(attrName))
{
int cc = element.attribute(attrName).toInt();
element.setAttribute(attrName, cc - 1);
}
}
}
}
void DataFile::findProblematicLadspaPlugins()
{
// This is not an upgrade but a check for potentially problematic LADSPA
// controls. See #5738 for more details.
const QDomNodeList ladspacontrols = elementsByTagName("ladspacontrols");
uint numberOfProblematicPlugins = 0;
for (int i = 0; i < ladspacontrols.size(); ++i)
{
const QDomElement ladspacontrol = ladspacontrols.item(i).toElement();
const auto attributes = ladspacontrol.attributes();
for (int j = 0; j < attributes.length(); ++j)
{
const auto attribute = attributes.item(j);
const auto name = attribute.nodeName();
if (name != "ports" && name.startsWith("port"))
{
++numberOfProblematicPlugins;
break;
}
}
}
if (numberOfProblematicPlugins > 0)
{
QMessageBox::warning(nullptr, QObject::tr("LADSPA plugins"),
QObject::tr("The project contains %1 LADSPA plugin(s) which might have not been restored correctly! Please check the project.").arg(numberOfProblematicPlugins));
}
}
void DataFile::upgrade_fixBassLoopsTypo()
{
static const QMap<QString, QString> replacementMap = {
{ "bassloopes/briff01.ogg", "bassloops/briff01 - 140 BPM.ogg" },
{ "bassloopes/rave_bass01.ogg", "bassloops/rave_bass01 - 180 BPM.ogg" },
{ "bassloopes/rave_bass02.ogg", "bassloops/rave_bass02 - 180 BPM.ogg" },
{ "bassloopes/tb303_01.ogg","bassloops/tb303_01 - 123 BPM.ogg" },
{ "bassloopes/techno_bass01.ogg", "bassloops/techno_bass01 - 140 BPM.ogg" },
{ "bassloopes/techno_bass02.ogg", "bassloops/techno_bass02 - 140 BPM.ogg" },
{ "bassloopes/techno_synth01.ogg", "bassloops/techno_synth01 - 140 BPM.ogg" },
{ "bassloopes/techno_synth02.ogg", "bassloops/techno_synth02 - 140 BPM.ogg" },
{ "bassloopes/techno_synth03.ogg", "bassloops/techno_synth03 - 130 BPM.ogg" },
{ "bassloopes/techno_synth04.ogg", "bassloops/techno_synth04 - 140 BPM.ogg" }
};
mapSrcAttributeInElementsWithResources(replacementMap);
}
void DataFile::upgrade()
{
// Runs all necessary upgrade methods
std::size_t max = std::min(static_cast<std::size_t>(m_fileVersion), UPGRADE_METHODS.size());
std::for_each( UPGRADE_METHODS.begin() + max, UPGRADE_METHODS.end(),
[this](UpgradeMethod um)
{
(this->*um)();
}
);
// Bump the file version (which should be the size of the upgrade methods vector)
m_fileVersion = UPGRADE_METHODS.size();
// update document meta data
documentElement().setAttribute( "version", m_fileVersion );
documentElement().setAttribute( "type", typeName( type() ) );
documentElement().setAttribute( "creator", "LMMS" );
documentElement().setAttribute( "creatorversion", LMMS_VERSION );
if( type() == Type::SongProject || type() == Type::SongProjectTemplate )
{
// Time-signature
if ( !m_head.hasAttribute( "timesig_numerator" ) )
{
m_head.setAttribute( "timesig_numerator", 4 );
m_head.setAttribute( "timesig_denominator", 4 );
}
if( !m_head.hasAttribute( "mastervol" ) )
{
m_head.setAttribute( "mastervol", 100 );
}
}
}
void DataFile::loadData( const QByteArray & _data, const QString & _sourceFile )
{
QString errorMsg;
int line = -1, col = -1;
if( !setContent( _data, &errorMsg, &line, &col ) )
{
// parsing failed? then try to uncompress data
QByteArray uncompressed = qUncompress( _data );
if( !uncompressed.isEmpty() )
{
if( setContent( uncompressed, &errorMsg, &line, &col ) )
{
line = col = -1;
}
}
if( line >= 0 && col >= 0 )
{
using gui::SongEditor;
qWarning() << "at line" << line << "column" << errorMsg;
if (gui::getGUI() != nullptr)
{
QMessageBox::critical( nullptr,
SongEditor::tr( "Error in file" ),
SongEditor::tr( "The file %1 seems to contain "
"errors and therefore can't be "
"loaded." ).
arg( _sourceFile ) );
}
return;
}
}
QDomElement root = documentElement();
m_type = type( root.attribute( "type" ) );
m_head = root.elementsByTagName( "head" ).item( 0 ).toElement();
if (!root.hasAttribute("version") || root.attribute("version")=="1.0")
{
// The file versioning is now a unsigned int, not maj.min, so we use
// legacyFileVersion() to retrieve the appropriate version
m_fileVersion = legacyFileVersion();
}
else
{
bool success;
m_fileVersion = root.attribute( "version" ).toUInt( &success );
if( !success ) qWarning("File Version conversion failure.");
}
if (root.hasAttribute("creatorversion"))
{
using gui::SongEditor;
// compareType defaults to All, so it doesn't have to be set here
ProjectVersion createdWith = root.attribute("creatorversion");
ProjectVersion openedWith = LMMS_VERSION;
if (createdWith.setCompareType(ProjectVersion::CompareType::Minor)
!= openedWith.setCompareType(ProjectVersion::CompareType::Minor)
&& gui::getGUI() != nullptr && root.attribute("type") == "song"
){
auto projectType = _sourceFile.endsWith(".mpt") ?
SongEditor::tr("template") : SongEditor::tr("project");
gui::TextFloat::displayMessage(
SongEditor::tr("Version difference"),
SongEditor::tr("This %1 was created with LMMS %2")
.arg(projectType).arg(createdWith.getVersion()),
embed::getIconPixmap("whatsthis", 24, 24),
2500
);
}
}
// Perform upgrade routines
if (m_fileVersion < UPGRADE_METHODS.size()) { upgrade(); }
m_content = root.elementsByTagName(typeName(m_type)).item(0).toElement();
}
void findIds(const QDomElement& elem, QList<jo_id_t>& idList)
{
if(elem.hasAttribute("id"))
{
idList.append(elem.attribute("id").toInt());
}
QDomElement child = elem.firstChildElement();
while(!child.isNull())
{
findIds(child, idList);
child = child.nextSiblingElement();
}
}
unsigned int DataFile::legacyFileVersion()
{
// Version of LMMs that created this project
ProjectVersion creator =
documentElement().attribute( "creatorversion" ).
replace( "svn", "" );
// Get an iterator pointing at the first upgrade we need to run (or at the end if there is no such upgrade)
auto firstRequiredUpgrade = std::upper_bound( UPGRADE_VERSIONS.begin(), UPGRADE_VERSIONS.end(), creator );
// Convert the iterator to an index, which is our file version (starting at 0)
return std::distance( UPGRADE_VERSIONS.begin(), firstRequiredUpgrade );
}
} // namespace lmms
| 60,020
|
C++
|
.cpp
| 1,919
| 27.430433
| 164
| 0.653941
|
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,809
|
PlayHandle.cpp
|
LMMS_lmms/src/core/PlayHandle.cpp
|
/*
* PlayHandle.cpp - base class PlayHandle - core of rendering engine
*
* 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 "PlayHandle.h"
#include "AudioEngine.h"
#include "BufferManager.h"
#include "Engine.h"
#include <QThread>
namespace lmms
{
PlayHandle::PlayHandle(const Type type, f_cnt_t offset) :
m_type(type),
m_offset(offset),
m_affinity(QThread::currentThread()),
m_playHandleBuffer(BufferManager::acquire()),
m_bufferReleased(true),
m_usesBuffer(true)
{
}
PlayHandle::~PlayHandle()
{
BufferManager::release(m_playHandleBuffer);
}
void PlayHandle::doProcessing()
{
if( m_usesBuffer )
{
m_bufferReleased = false;
zeroSampleFrames(m_playHandleBuffer, Engine::audioEngine()->framesPerPeriod());
play( buffer() );
}
else
{
play( nullptr );
}
}
void PlayHandle::releaseBuffer()
{
m_bufferReleased = true;
}
SampleFrame* PlayHandle::buffer()
{
return m_bufferReleased ? nullptr : m_playHandleBuffer;
};
} // namespace lmms
| 1,802
|
C++
|
.cpp
| 65
| 25.738462
| 81
| 0.75348
|
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,810
|
BufferManager.cpp
|
LMMS_lmms/src/core/BufferManager.cpp
|
/*
* BufferManager.cpp - A buffer caching/memory management system
*
* Copyright (c) 2017 Lukas W <lukaswhl/at/gmail.com>
* 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 "BufferManager.h"
#include "SampleFrame.h"
#include <cstring>
namespace lmms
{
fpp_t BufferManager::s_framesPerPeriod;
void BufferManager::init( fpp_t fpp )
{
s_framesPerPeriod = fpp;
}
SampleFrame* BufferManager::acquire()
{
return new SampleFrame[s_framesPerPeriod];
}
void BufferManager::release( SampleFrame* buf )
{
delete[] buf;
}
} // namespace lmms
| 1,450
|
C++
|
.cpp
| 44
| 31.045455
| 77
| 0.759512
|
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,811
|
ControllerConnection.cpp
|
LMMS_lmms/src/core/ControllerConnection.cpp
|
/*
* ControllerConnection.cpp - implementation of class controller connection
* which handles the link between AutomatableModels and controllers
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail.com>
* Copyright (c) 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 <QDomElement>
#include <QObject>
#include "Song.h"
#include "ControllerConnection.h"
namespace lmms
{
ControllerConnectionVector ControllerConnection::s_connections;
ControllerConnection::ControllerConnection(Controller * _controller) :
m_controller( nullptr ),
m_controllerId( -1 ),
m_ownsController(false)
{
if( _controller != nullptr )
{
setController( _controller );
}
else
{
m_controller = Controller::create( Controller::ControllerType::Dummy,
nullptr );
}
s_connections.push_back(this);
}
ControllerConnection::ControllerConnection( int _controllerId ) :
m_controller( Controller::create( Controller::ControllerType::Dummy, nullptr ) ),
m_controllerId( _controllerId ),
m_ownsController( false )
{
s_connections.push_back(this);
}
ControllerConnection::~ControllerConnection()
{
if( m_controller && m_controller->type() != Controller::ControllerType::Dummy )
{
m_controller->removeConnection( this );
}
auto it = std::find(s_connections.begin(), s_connections.end(), this);
if (it != s_connections.end()) { s_connections.erase(it); };
if( m_ownsController )
{
delete m_controller;
}
}
void ControllerConnection::setController( int /*_controllerId*/ )
{
}
void ControllerConnection::setController( Controller * _controller )
{
if( m_ownsController && m_controller )
{
delete m_controller;
m_controller = nullptr;
}
if( m_controller && m_controller->type() != Controller::ControllerType::Dummy )
{
m_controller->removeConnection( this );
}
if( !_controller )
{
m_controller = Controller::create( Controller::ControllerType::Dummy, nullptr );
}
else
{
m_controller = _controller;
}
m_controllerId = -1;
if( _controller->type() != Controller::ControllerType::Dummy )
{
_controller->addConnection( this );
QObject::connect( _controller, SIGNAL(valueChanged()),
this, SIGNAL(valueChanged()), Qt::DirectConnection );
}
m_ownsController =
(_controller->type() == Controller::ControllerType::Midi);
// If we don't own the controller, allow deletion of controller
// to delete the connection
if( !m_ownsController ) {
QObject::connect( _controller, SIGNAL(destroyed()),
this, SLOT(deleteConnection()));
}
}
inline void ControllerConnection::setTargetName( const QString & _name )
{
m_targetName = _name;
if( m_controller )
{
// m_controller->getMidiPort()->setName( _name );
}
}
/*
* A connection may not be finalized. This means, the connection should exist,
* but the controller does not yet exist. This happens when loading. Even
* loading connections last won't help, since there can be connections BETWEEN
* controllers. So, we remember the controller-ID and use a dummyController
* instead. Once the song is loaded, finalizeConnections() connects to the proper controllers
*/
void ControllerConnection::finalizeConnections()
{
for (auto i = std::size_t{0}; i < s_connections.size(); ++i)
{
ControllerConnection * c = s_connections[i];
if (!c->isFinalized() && static_cast<std::size_t>(c->m_controllerId) < Engine::getSong()->controllers().size())
{
c->setController( Engine::getSong()->
controllers().at( c->m_controllerId ) );
}
else if (c->getController()->type() == Controller::ControllerType::Dummy)
{
delete c;
--i;
}
}
}
void ControllerConnection::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
if( Engine::getSong() )
{
if( m_ownsController )
{
m_controller->saveState( _doc, _this );
}
else
{
const auto& controllers = Engine::getSong()->controllers();
const auto it = std::find(controllers.begin(), controllers.end(), m_controller);
if (it != controllers.end())
{
const int id = std::distance(controllers.begin(), it);
_this.setAttribute("id", id);
}
}
}
}
void ControllerConnection::loadSettings( const QDomElement & _this )
{
QDomNode node = _this.firstChild();
if( !node.isNull() )
{
setController( Controller::create( node.toElement(), Engine::getSong() ) );
}
else
{
m_controllerId = _this.attribute( "id", "-1" ).toInt();
if( m_controllerId < 0 )
{
qWarning( "controller index invalid\n" );
m_controllerId = -1;
}
if (!Engine::getSong()->isLoadingProject()
&& m_controllerId != -1
&& static_cast<std::size_t>(m_controllerId) < Engine::getSong()->controllers().size())
{
setController( Engine::getSong()->
controllers().at( m_controllerId ) );
}
else
{
m_controller = Controller::create( Controller::ControllerType::Dummy, nullptr );
}
}
}
void ControllerConnection::deleteConnection()
{
delete this;
}
} // namespace lmms
| 5,725
|
C++
|
.cpp
| 191
| 27.413613
| 113
| 0.719081
|
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,812
|
InstrumentSoundShaping.cpp
|
LMMS_lmms/src/core/InstrumentSoundShaping.cpp
|
/*
* InstrumentSoundShaping.cpp - implementation of class InstrumentSoundShaping
*
* 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 <QVarLengthArray>
#include <QDomElement>
#include "InstrumentSoundShaping.h"
#include "AudioEngine.h"
#include "BasicFilters.h"
#include "embed.h"
#include "Engine.h"
#include "EnvelopeAndLfoParameters.h"
#include "Instrument.h"
#include "InstrumentTrack.h"
namespace lmms
{
const float CUT_FREQ_MULTIPLIER = 6000.0f;
const float RES_MULTIPLIER = 2.0f;
const float RES_PRECISION = 1000.0f;
// names for env- and lfo-targets - first is name being displayed to user
// and second one is used internally, e.g. for saving/restoring settings
const char *const InstrumentSoundShaping::targetNames[InstrumentSoundShaping::NumTargets][3] =
{
{ QT_TRANSLATE_NOOP("InstrumentSoundShaping", "VOLUME"), "vol",
QT_TRANSLATE_NOOP("InstrumentSoundShaping", "Volume") },
{ QT_TRANSLATE_NOOP("InstrumentSoundShaping", "CUTOFF"), "cut",
QT_TRANSLATE_NOOP("InstrumentSoundShaping", "Cutoff frequency") },
{ QT_TRANSLATE_NOOP("InstrumentSoundShaping", "RESO"), "res",
QT_TRANSLATE_NOOP("InstrumentSoundShaping", "Resonance") }
} ;
InstrumentSoundShaping::InstrumentSoundShaping(
InstrumentTrack * _instrument_track ) :
Model( _instrument_track, tr( "Envelopes/LFOs" ) ),
m_instrumentTrack( _instrument_track ),
m_filterEnabledModel( false, this ),
m_filterModel( this, tr( "Filter type" ) ),
m_filterCutModel( 14000.0, 1.0, 14000.0, 1.0, this, tr( "Cutoff frequency" ) ),
m_filterResModel(0.5f, BasicFilters<>::minQ(), 10.f, 0.01f, this, tr("Q/Resonance"))
{
for (auto i = std::size_t{0}; i < NumTargets; ++i)
{
float value_for_zero_amount = 0.0;
if( static_cast<Target>(i) == Target::Volume )
{
value_for_zero_amount = 1.0;
}
m_envLfoParameters[i] = new EnvelopeAndLfoParameters(
value_for_zero_amount,
this );
m_envLfoParameters[i]->setDisplayName(
tr( targetNames[i][2] ) );
}
m_filterModel.addItem( tr( "Low-pass" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filterModel.addItem( tr( "Hi-pass" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filterModel.addItem( tr( "Band-pass csg" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filterModel.addItem( tr( "Band-pass czpg" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filterModel.addItem( tr( "Notch" ), std::make_unique<PixmapLoader>( "filter_notch" ) );
m_filterModel.addItem( tr( "All-pass" ), std::make_unique<PixmapLoader>( "filter_ap" ) );
m_filterModel.addItem( tr( "Moog" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filterModel.addItem( tr( "2x Low-pass" ), std::make_unique<PixmapLoader>( "filter_2lp" ) );
m_filterModel.addItem( tr( "RC Low-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filterModel.addItem( tr( "RC Band-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filterModel.addItem( tr( "RC High-pass 12 dB/oct" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filterModel.addItem( tr( "RC Low-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filterModel.addItem( tr( "RC Band-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filterModel.addItem( tr( "RC High-pass 24 dB/oct" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filterModel.addItem( tr( "Vocal Formant" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filterModel.addItem( tr( "2x Moog" ), std::make_unique<PixmapLoader>( "filter_2lp" ) );
m_filterModel.addItem( tr( "SV Low-pass" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
m_filterModel.addItem( tr( "SV Band-pass" ), std::make_unique<PixmapLoader>( "filter_bp" ) );
m_filterModel.addItem( tr( "SV High-pass" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filterModel.addItem( tr( "SV Notch" ), std::make_unique<PixmapLoader>( "filter_notch" ) );
m_filterModel.addItem( tr( "Fast Formant" ), std::make_unique<PixmapLoader>( "filter_hp" ) );
m_filterModel.addItem( tr( "Tripole" ), std::make_unique<PixmapLoader>( "filter_lp" ) );
}
float InstrumentSoundShaping::volumeLevel( NotePlayHandle* n, const f_cnt_t frame )
{
f_cnt_t envReleaseBegin = frame - n->releaseFramesDone() + n->framesBeforeRelease();
if( n->isReleased() == false )
{
envReleaseBegin += Engine::audioEngine()->framesPerPeriod();
}
float level;
m_envLfoParameters[static_cast<std::size_t>(Target::Volume)]->fillLevel( &level, frame, envReleaseBegin, 1 );
return level;
}
void InstrumentSoundShaping::processAudioBuffer( SampleFrame* buffer,
const fpp_t frames,
NotePlayHandle* n )
{
const f_cnt_t envTotalFrames = n->totalFramesPlayed();
f_cnt_t envReleaseBegin = envTotalFrames - n->releaseFramesDone() + n->framesBeforeRelease();
if( !n->isReleased() || ( n->instrumentTrack()->isSustainPedalPressed() &&
!n->isReleaseStarted() ) )
{
envReleaseBegin += frames;
}
// because of optimizations, there's special code for several cases:
// - cut- and res-lfo/envelope active
// - cut-lfo/envelope active
// - res-lfo/envelope active
// - no lfo/envelope active but filter is used
// only use filter, if it is really needed
if( m_filterEnabledModel.value() )
{
QVarLengthArray<float> cutBuffer(frames);
QVarLengthArray<float> resBuffer(frames);
int old_filter_cut = 0;
int old_filter_res = 0;
if( n->m_filter == nullptr )
{
n->m_filter = std::make_unique<BasicFilters<>>( Engine::audioEngine()->outputSampleRate() );
}
n->m_filter->setFilterType( static_cast<BasicFilters<>::FilterType>(m_filterModel.value()) );
if( m_envLfoParameters[static_cast<std::size_t>(Target::Cut)]->isUsed() )
{
m_envLfoParameters[static_cast<std::size_t>(Target::Cut)]->fillLevel( cutBuffer.data(), envTotalFrames, envReleaseBegin, frames );
}
if( m_envLfoParameters[static_cast<std::size_t>(Target::Resonance)]->isUsed() )
{
m_envLfoParameters[static_cast<std::size_t>(Target::Resonance)]->fillLevel( resBuffer.data(), envTotalFrames, envReleaseBegin, frames );
}
const float fcv = m_filterCutModel.value();
const float frv = m_filterResModel.value();
if( m_envLfoParameters[static_cast<std::size_t>(Target::Cut)]->isUsed() &&
m_envLfoParameters[static_cast<std::size_t>(Target::Resonance)]->isUsed() )
{
for( fpp_t frame = 0; frame < frames; ++frame )
{
const float new_cut_val = EnvelopeAndLfoParameters::expKnobVal( cutBuffer[frame] ) *
CUT_FREQ_MULTIPLIER + fcv;
const float new_res_val = frv + RES_MULTIPLIER * resBuffer[frame];
if( static_cast<int>( new_cut_val ) != old_filter_cut ||
static_cast<int>( new_res_val*RES_PRECISION ) != old_filter_res )
{
n->m_filter->calcFilterCoeffs( new_cut_val, new_res_val );
old_filter_cut = static_cast<int>( new_cut_val );
old_filter_res = static_cast<int>( new_res_val*RES_PRECISION );
}
buffer[frame][0] = n->m_filter->update( buffer[frame][0], 0 );
buffer[frame][1] = n->m_filter->update( buffer[frame][1], 1 );
}
}
else if( m_envLfoParameters[static_cast<std::size_t>(Target::Cut)]->isUsed() )
{
for( fpp_t frame = 0; frame < frames; ++frame )
{
float new_cut_val = EnvelopeAndLfoParameters::expKnobVal( cutBuffer[frame] ) *
CUT_FREQ_MULTIPLIER + fcv;
if( static_cast<int>( new_cut_val ) != old_filter_cut )
{
n->m_filter->calcFilterCoeffs( new_cut_val, frv );
old_filter_cut = static_cast<int>( new_cut_val );
}
buffer[frame][0] = n->m_filter->update( buffer[frame][0], 0 );
buffer[frame][1] = n->m_filter->update( buffer[frame][1], 1 );
}
}
else if( m_envLfoParameters[static_cast<std::size_t>(Target::Resonance)]->isUsed() )
{
for( fpp_t frame = 0; frame < frames; ++frame )
{
float new_res_val = frv + RES_MULTIPLIER * resBuffer[frame];
if( static_cast<int>( new_res_val*RES_PRECISION ) != old_filter_res )
{
n->m_filter->calcFilterCoeffs( fcv, new_res_val );
old_filter_res = static_cast<int>( new_res_val*RES_PRECISION );
}
buffer[frame][0] = n->m_filter->update( buffer[frame][0], 0 );
buffer[frame][1] = n->m_filter->update( buffer[frame][1], 1 );
}
}
else
{
n->m_filter->calcFilterCoeffs( fcv, frv );
for( fpp_t frame = 0; frame < frames; ++frame )
{
buffer[frame][0] = n->m_filter->update( buffer[frame][0], 0 );
buffer[frame][1] = n->m_filter->update( buffer[frame][1], 1 );
}
}
}
if( m_envLfoParameters[static_cast<std::size_t>(Target::Volume)]->isUsed() )
{
QVarLengthArray<float> volBuffer(frames);
m_envLfoParameters[static_cast<std::size_t>(Target::Volume)]->fillLevel( volBuffer.data(), envTotalFrames, envReleaseBegin, frames );
for( fpp_t frame = 0; frame < frames; ++frame )
{
float vol_level = volBuffer[frame];
vol_level = vol_level * vol_level;
buffer[frame][0] = vol_level * buffer[frame][0];
buffer[frame][1] = vol_level * buffer[frame][1];
}
}
/* else if( m_envLfoParameters[static_cast<std::size_t>(Target::Volume)]->isUsed() == false && m_envLfoParameters[PANNING]->isUsed() )
{
// only use panning-envelope...
for( fpp_t frame = 0; frame < frames; ++frame )
{
float vol_level = pan_buf[frame];
vol_level = vol_level*vol_level;
for( ch_cnt_t chnl = 0; chnl < DEFAULT_CHANNELS; ++chnl )
{
buffer[frame][chnl] = vol_level * buffer[frame][chnl];
}
}
}*/
}
f_cnt_t InstrumentSoundShaping::envFrames( const bool _only_vol ) const
{
f_cnt_t ret_val = m_envLfoParameters[static_cast<std::size_t>(Target::Volume)]->PAHD_Frames();
if( _only_vol == false )
{
for (auto i = static_cast<std::size_t>(Target::Volume) + 1; i < NumTargets; ++i)
{
if( m_envLfoParameters[i]->isUsed() &&
m_envLfoParameters[i]->PAHD_Frames() > ret_val )
{
ret_val = m_envLfoParameters[i]->PAHD_Frames();
}
}
}
return ret_val;
}
f_cnt_t InstrumentSoundShaping::releaseFrames() const
{
if( !m_instrumentTrack->instrument() )
{
return 0;
}
f_cnt_t ret_val = m_instrumentTrack->instrument()->desiredReleaseFrames();
if (m_instrumentTrack->instrument()->isSingleStreamed())
{
return ret_val;
}
if( m_envLfoParameters[static_cast<std::size_t>(Target::Volume)]->isUsed() )
{
return m_envLfoParameters[static_cast<std::size_t>(Target::Volume)]->releaseFrames();
}
for (auto i = static_cast<std::size_t>(Target::Volume) + 1; i < NumTargets; ++i)
{
if( m_envLfoParameters[i]->isUsed() )
{
ret_val = std::max(ret_val, m_envLfoParameters[i]->releaseFrames());
}
}
return ret_val;
}
void InstrumentSoundShaping::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
m_filterModel.saveSettings( _doc, _this, "ftype" );
m_filterCutModel.saveSettings( _doc, _this, "fcut" );
m_filterResModel.saveSettings( _doc, _this, "fres" );
m_filterEnabledModel.saveSettings( _doc, _this, "fwet" );
for (auto i = std::size_t{0}; i < NumTargets; ++i)
{
m_envLfoParameters[i]->saveState( _doc, _this ).setTagName(
m_envLfoParameters[i]->nodeName() +
QString( targetNames[i][1] ).toLower() );
}
}
void InstrumentSoundShaping::loadSettings( const QDomElement & _this )
{
m_filterModel.loadSettings( _this, "ftype" );
m_filterCutModel.loadSettings( _this, "fcut" );
m_filterResModel.loadSettings( _this, "fres" );
m_filterEnabledModel.loadSettings( _this, "fwet" );
QDomNode node = _this.firstChild();
while( !node.isNull() )
{
if( node.isElement() )
{
for (auto i = std::size_t{0}; i < NumTargets; ++i)
{
if( node.nodeName() ==
m_envLfoParameters[i]->nodeName() +
QString( targetNames[i][1] ).
toLower() )
{
m_envLfoParameters[i]->restoreState( node.toElement() );
}
}
}
node = node.nextSibling();
}
}
} // namespace lmms
| 12,608
|
C++
|
.cpp
| 306
| 38.055556
| 139
| 0.687137
|
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,813
|
Microtuner.cpp
|
LMMS_lmms/src/core/Microtuner.cpp
|
/*
* Microtuner.cpp - manage tuning and scale information of an instrument
*
* Copyright (c) 2020 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 "Microtuner.h"
#include <vector>
#include <cmath>
#include "Engine.h"
#include "Keymap.h"
#include "Note.h"
#include "Scale.h"
#include "Song.h"
namespace lmms
{
Microtuner::Microtuner() :
Model(nullptr, tr("Microtuner")),
m_enabledModel(false, this, tr("Microtuner on / off")),
m_scaleModel(this, tr("Selected scale")),
m_keymapModel(this, tr("Selected keyboard mapping")),
m_keyRangeImportModel(true)
{
for (unsigned int i = 0; i < MaxScaleCount; i++)
{
m_scaleModel.addItem(QString::number(i) + ": " + Engine::getSong()->getScale(i)->getDescription());
}
for (unsigned int i = 0; i < MaxKeymapCount; i++)
{
m_keymapModel.addItem(QString::number(i) + ": " + Engine::getSong()->getKeymap(i)->getDescription());
}
connect(Engine::getSong(), SIGNAL(scaleListChanged(int)), this, SLOT(updateScaleList(int)));
connect(Engine::getSong(), SIGNAL(keymapListChanged(int)), this, SLOT(updateKeymapList(int)));
}
/** \brief Return frequency for a given MIDI key, using the active mapping and scale.
* \param key A MIDI key number ranging from 0 to 127.
* \return Frequency in Hz; 0 if key is out of range or not mapped.
*/
float Microtuner::keyToFreq(int key, int userBaseNote) const
{
if (key < 0 || key >= NumKeys) {return 0;}
Song *song = Engine::getSong();
if (!song) {return 0;}
// Get keymap and scale selected at this moment
std::shared_ptr<const Keymap> keymap = song->getKeymap(m_keymapModel.value());
std::shared_ptr<const Scale> scale = song->getScale(m_scaleModel.value());
const std::vector<Interval> &intervals = scale->getIntervals();
// Convert MIDI key to scale degree + octave offset.
// The octaves are primarily driven by the keymap wraparound: octave count is increased or decreased if the key
// goes over or under keymap range. In case the keymap refers to a degree that does not exist in the scale, it is
// assumed the keymap is non-repeating or just really big, so the octaves are also driven by the scale wraparound.
const int keymapDegree = keymap->getDegree(key); // which interval should be used according to the keymap
if (keymapDegree == -1) {return 0;} // key is not mapped, abort
const int keymapOctave = keymap->getOctave(key); // how many times did the keymap repeat
const int octaveDegree = intervals.size() - 1; // index of the interval with octave ratio
if (octaveDegree == 0) { // octave interval is 1/1, i.e. constant base frequency
return keymap->getBaseFreq(); // → return the baseFreq directly
}
const int scaleOctave = keymapDegree / octaveDegree;
// which interval should be used according to the scale and keymap together
const int degree_rem = keymapDegree % octaveDegree;
const int scaleDegree = degree_rem >= 0 ? degree_rem : degree_rem + octaveDegree; // get true modulo
// Compute base note (the "A4 reference") degree and octave
const int baseNote = m_keyRangeImportModel.value() ? keymap->getBaseKey() : userBaseNote;
const int baseKeymapDegree = keymap->getDegree(baseNote);
if (baseKeymapDegree == -1) {return 0;} // base key is not mapped, umm...
const int baseKeymapOctave = keymap->getOctave(baseNote);
const int baseScaleOctave = baseKeymapDegree / octaveDegree;
const int baseDegree_rem = baseKeymapDegree % octaveDegree;
const int baseScaleDegree = baseDegree_rem >= 0 ? baseDegree_rem : baseDegree_rem + octaveDegree;
// Compute frequency of the middle note and return the final frequency
const double octaveRatio = intervals[octaveDegree].getRatio();
const float middleFreq = (keymap->getBaseFreq() / pow(octaveRatio, (baseScaleOctave + baseKeymapOctave)))
/ intervals[baseScaleDegree].getRatio();
return middleFreq * intervals[scaleDegree].getRatio() * pow(octaveRatio, keymapOctave + scaleOctave);
}
int Microtuner::octaveSize() const
{
const int keymapSize = Engine::getSong()->getKeymap(currentKeymap())->getSize();
if (keymapSize > 0)
{
return keymapSize;
}
// Determine octave size from the scale if the keymap isn't in use.
return Engine::getSong()->getScale(currentScale())->getIntervals().size() - 1;
}
/**
* \brief Update scale name displayed in the microtuner scale list.
* \param index Index of the scale to update; update all scales if -1 or out of range.
*/
void Microtuner::updateScaleList(int index)
{
if (index >= 0 && static_cast<std::size_t>(index) < MaxScaleCount)
{
m_scaleModel.replaceItem(index,
QString::number(index) + ": " + Engine::getSong()->getScale(index)->getDescription());
}
else
{
for (auto i = std::size_t{0}; i < MaxScaleCount; i++)
{
m_scaleModel.replaceItem(i,
QString::number(i) + ": " + Engine::getSong()->getScale(i)->getDescription());
}
}
}
/**
* \brief Update keymap name displayed in the microtuner scale list.
* \param index Index of the keymap to update; update all keymaps if -1 or out of range.
*/
void Microtuner::updateKeymapList(int index)
{
if (index >= 0 && static_cast<std::size_t>(index) < MaxKeymapCount)
{
m_keymapModel.replaceItem(index,
QString::number(index) + ": " + Engine::getSong()->getKeymap(index)->getDescription());
}
else
{
for (auto i = std::size_t{0}; i < MaxKeymapCount; i++)
{
m_keymapModel.replaceItem(i,
QString::number(i) + ": " + Engine::getSong()->getKeymap(i)->getDescription());
}
}
}
void Microtuner::saveSettings(QDomDocument &document, QDomElement &element)
{
m_enabledModel.saveSettings(document, element, "enabled");
m_scaleModel.saveSettings(document, element, "scale");
m_keymapModel.saveSettings(document, element, "keymap");
m_keyRangeImportModel.saveSettings(document, element, "range_import");
}
void Microtuner::loadSettings(const QDomElement &element)
{
m_enabledModel.loadSettings(element, "enabled");
m_scaleModel.loadSettings(element, "scale");
m_keymapModel.loadSettings(element, "keymap");
m_keyRangeImportModel.loadSettings(element, "range_import");
}
} // namespace lmms
| 6,857
|
C++
|
.cpp
| 158
| 41.253165
| 115
| 0.734452
|
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,814
|
LfoController.cpp
|
LMMS_lmms/src/core/LfoController.cpp
|
/*
* LfoController.cpp - implementation of class controller which handles
* remote-control of AutomatableModels
*
* Copyright (c) 2008 Paul Giblock <drfaygo/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 "LfoController.h"
#include <QDomElement>
#include <QFileInfo>
#include "AudioEngine.h"
#include "PathUtil.h"
#include "SampleLoader.h"
#include "Song.h"
namespace lmms
{
LfoController::LfoController( Model * _parent ) :
Controller( ControllerType::Lfo, _parent, tr( "LFO Controller" ) ),
m_baseModel(0.5f, 0.f, 1.f, 0.001f, this, tr("Base value")),
m_speedModel(2.f, 0.01f, 20.f, 0.0001f, 20000.f, this, tr("Oscillator speed")),
m_amountModel(1.f, -1.f, 1.f, 0.005f, this, tr("Oscillator amount")),
m_phaseModel( 0.0, 0.0, 360.0, 4.0, this, tr( "Oscillator phase" ) ),
m_waveModel( static_cast<int>(Oscillator::WaveShape::Sine), 0, Oscillator::NumWaveShapes,
this, tr( "Oscillator waveform" ) ),
m_multiplierModel( 0, 0, 2, this, tr( "Frequency Multiplier" ) ),
m_duration( 1000 ),
m_phaseOffset( 0 ),
m_currentPhase( 0 ),
m_sampleFunction( &Oscillator::sinSample ),
m_userDefSampleBuffer(std::make_shared<SampleBuffer>())
{
setSampleExact( true );
connect( &m_waveModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleFunction()), Qt::DirectConnection );
connect( &m_speedModel, SIGNAL(dataChanged()),
this, SLOT(updateDuration()), Qt::DirectConnection );
connect( &m_multiplierModel, SIGNAL(dataChanged()),
this, SLOT(updateDuration()), Qt::DirectConnection );
connect( Engine::audioEngine(), SIGNAL(sampleRateChanged()),
this, SLOT(updateDuration()));
connect( Engine::getSong(), SIGNAL(playbackStateChanged()),
this, SLOT(updatePhase()));
connect( Engine::getSong(), SIGNAL(playbackPositionChanged()),
this, SLOT(updatePhase()));
updateDuration();
}
LfoController::~LfoController()
{
m_baseModel.disconnect( this );
m_speedModel.disconnect( this );
m_amountModel.disconnect( this );
m_phaseModel.disconnect( this );
m_waveModel.disconnect( this );
m_multiplierModel.disconnect( this );
}
void LfoController::updateValueBuffer()
{
m_phaseOffset = m_phaseModel.value() / 360.0;
float phase = m_currentPhase + m_phaseOffset;
float phasePrev = 0.0f;
// roll phase up until we're in sync with period counter
m_bufferLastUpdated++;
if( m_bufferLastUpdated < s_periods )
{
int diff = s_periods - m_bufferLastUpdated;
phase += static_cast<float>( Engine::audioEngine()->framesPerPeriod() * diff ) / m_duration;
m_bufferLastUpdated += diff;
}
float amount = m_amountModel.value();
ValueBuffer *amountBuffer = m_amountModel.valueBuffer();
int amountInc = amountBuffer ? 1 : 0;
float *amountPtr = amountBuffer ? &(amountBuffer->values()[ 0 ] ) : &amount;
Oscillator::WaveShape waveshape = static_cast<Oscillator::WaveShape>(m_waveModel.value());
for( float& f : m_valueBuffer )
{
float currentSample = 0;
switch (waveshape)
{
case Oscillator::WaveShape::WhiteNoise:
{
if (absFraction(phase) < absFraction(phasePrev))
{
// Resample when phase period has completed
m_heldSample = m_sampleFunction(phase);
}
currentSample = m_heldSample;
break;
}
case Oscillator::WaveShape::UserDefined:
{
currentSample = Oscillator::userWaveSample(m_userDefSampleBuffer.get(), phase);
break;
}
default:
{
if (m_sampleFunction != nullptr)
{
currentSample = m_sampleFunction(phase);
}
}
}
f = std::clamp(m_baseModel.value() + (*amountPtr * currentSample / 2.0f), 0.0f, 1.0f);
phasePrev = phase;
phase += 1.0 / m_duration;
amountPtr += amountInc;
}
m_currentPhase = absFraction(phase - m_phaseOffset);
m_bufferLastUpdated = s_periods;
}
void LfoController::updatePhase()
{
m_currentPhase = ( Engine::getSong()->getFrames() ) / m_duration;
m_bufferLastUpdated = s_periods - 1;
}
void LfoController::updateDuration()
{
float newDurationF = Engine::audioEngine()->outputSampleRate() * m_speedModel.value();
switch(m_multiplierModel.value() )
{
case 1:
newDurationF /= 100.0;
break;
case 2:
newDurationF *= 100.0;
break;
default:
break;
}
m_duration = newDurationF;
}
void LfoController::updateSampleFunction()
{
switch( static_cast<Oscillator::WaveShape>(m_waveModel.value()) )
{
case Oscillator::WaveShape::Sine:
default:
m_sampleFunction = &Oscillator::sinSample;
break;
case Oscillator::WaveShape::Triangle:
m_sampleFunction = &Oscillator::triangleSample;
break;
case Oscillator::WaveShape::Saw:
m_sampleFunction = &Oscillator::sawSample;
break;
case Oscillator::WaveShape::Square:
m_sampleFunction = &Oscillator::squareSample;
break;
case Oscillator::WaveShape::MoogSaw:
m_sampleFunction = &Oscillator::moogSawSample;
break;
case Oscillator::WaveShape::Exponential:
m_sampleFunction = &Oscillator::expSample;
break;
case Oscillator::WaveShape::WhiteNoise:
m_sampleFunction = &Oscillator::noiseSample;
break;
case Oscillator::WaveShape::UserDefined:
m_sampleFunction = nullptr;
/*TODO: If C++11 is allowed, should change the type of
m_sampleFunction be std::function<sample_t(const float)>
and use the line below:
*/
//m_sampleFunction = &(m_userDefSampleBuffer->userWaveSample)
break;
}
}
void LfoController::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
Controller::saveSettings( _doc, _this );
m_baseModel.saveSettings( _doc, _this, "base" );
m_speedModel.saveSettings( _doc, _this, "speed" );
m_amountModel.saveSettings( _doc, _this, "amount" );
m_phaseModel.saveSettings( _doc, _this, "phase" );
m_waveModel.saveSettings( _doc, _this, "wave" );
m_multiplierModel.saveSettings( _doc, _this, "multiplier" );
_this.setAttribute("userwavefile", m_userDefSampleBuffer->audioFile());
}
void LfoController::loadSettings( const QDomElement & _this )
{
Controller::loadSettings( _this );
m_baseModel.loadSettings( _this, "base" );
m_speedModel.loadSettings( _this, "speed" );
m_amountModel.loadSettings( _this, "amount" );
m_phaseModel.loadSettings( _this, "phase" );
m_waveModel.loadSettings( _this, "wave" );
m_multiplierModel.loadSettings( _this, "multiplier" );
if (const auto userWaveFile = _this.attribute("userwavefile"); !userWaveFile.isEmpty())
{
if (QFileInfo(PathUtil::toAbsolute(userWaveFile)).exists())
{
m_userDefSampleBuffer = gui::SampleLoader::createBufferFromFile(_this.attribute("userwavefile"));
}
else { Engine::getSong()->collectError(QString("%1: %2").arg(tr("Sample not found"), userWaveFile)); }
}
updateSampleFunction();
}
QString LfoController::nodeName() const
{
return( "lfocontroller" );
}
gui::ControllerDialog * LfoController::createDialog( QWidget * _parent )
{
return new gui::LfoControllerDialog( this, _parent );
}
} // namespace lmms
| 7,589
|
C++
|
.cpp
| 222
| 31.554054
| 104
| 0.727322
|
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,815
|
Engine.cpp
|
LMMS_lmms/src/core/Engine.cpp
|
/*
* Engine.cpp - implementation of LMMS' engine-system
*
* 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 "Engine.h"
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "Mixer.h"
#include "Ladspa2LMMS.h"
#include "Lv2Manager.h"
#include "PatternStore.h"
#include "Plugin.h"
#include "PresetPreviewPlayHandle.h"
#include "ProjectJournal.h"
#include "Song.h"
#include "BandLimitedWave.h"
#include "Oscillator.h"
namespace lmms
{
float Engine::s_framesPerTick;
AudioEngine* Engine::s_audioEngine = nullptr;
Mixer * Engine::s_mixer = nullptr;
PatternStore * Engine::s_patternStore = nullptr;
Song * Engine::s_song = nullptr;
ProjectJournal * Engine::s_projectJournal = nullptr;
#ifdef LMMS_HAVE_LV2
Lv2Manager * Engine::s_lv2Manager = nullptr;
#endif
Ladspa2LMMS * Engine::s_ladspaManager = nullptr;
void* Engine::s_dndPluginKey = nullptr;
void Engine::init( bool renderOnly )
{
Engine *engine = inst();
emit engine->initProgress(tr("Generating wavetables"));
// generate (load from file) bandlimited wavetables
BandLimitedWave::generateWaves();
//initilize oscillators
Oscillator::waveTableInit();
emit engine->initProgress(tr("Initializing data structures"));
s_projectJournal = new ProjectJournal;
s_audioEngine = new AudioEngine( renderOnly );
s_song = new Song;
s_mixer = new Mixer;
s_patternStore = new PatternStore;
#ifdef LMMS_HAVE_LV2
s_lv2Manager = new Lv2Manager;
s_lv2Manager->initPlugins();
#endif
s_ladspaManager = new Ladspa2LMMS;
s_projectJournal->setJournalling( true );
emit engine->initProgress(tr("Opening audio and midi devices"));
s_audioEngine->initDevices();
PresetPreviewPlayHandle::init();
emit engine->initProgress(tr("Launching audio engine threads"));
s_audioEngine->startProcessing();
}
void Engine::destroy()
{
s_projectJournal->stopAllJournalling();
s_audioEngine->stopProcessing();
PresetPreviewPlayHandle::cleanup();
s_song->clearProject();
deleteHelper( &s_patternStore );
deleteHelper( &s_mixer );
deleteHelper( &s_audioEngine );
#ifdef LMMS_HAVE_LV2
deleteHelper( &s_lv2Manager );
#endif
deleteHelper( &s_ladspaManager );
//delete ConfigManager::inst();
deleteHelper( &s_projectJournal );
deleteHelper( &s_song );
delete ConfigManager::inst();
// The oscillator FFT plans remain throughout the application lifecycle
// due to being expensive to create, and being used whenever a userwave form is changed
Oscillator::destroyFFTPlans();
}
float Engine::framesPerTick(sample_rate_t sampleRate)
{
return sampleRate * 60.0f * 4 /
DefaultTicksPerBar / s_song->getTempo();
}
void Engine::updateFramesPerTick()
{
s_framesPerTick = s_audioEngine->outputSampleRate() * 60.0f * 4 / DefaultTicksPerBar / s_song->getTempo();
}
void Engine::setDndPluginKey(void *newKey)
{
Q_ASSERT(static_cast<Plugin::Descriptor::SubPluginFeatures::Key*>(newKey));
s_dndPluginKey = newKey;
}
void *Engine::pickDndPluginKey()
{
return s_dndPluginKey;
}
Engine * Engine::s_instanceOfMe = nullptr;
} // namespace lmms
| 3,856
|
C++
|
.cpp
| 116
| 31.241379
| 107
| 0.76971
|
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,816
|
EffectChain.cpp
|
LMMS_lmms/src/core/EffectChain.cpp
|
/*
* EffectChain.cpp - class for processing and effects chain
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
* Copyright (c) 2008-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 <QDomElement>
#include <cassert>
#include "EffectChain.h"
#include "Effect.h"
#include "DummyEffect.h"
#include "MixHelpers.h"
namespace lmms
{
EffectChain::EffectChain( Model * _parent ) :
Model( _parent ),
SerializingObject(),
m_enabledModel( false, nullptr, tr( "Effects enabled" ) )
{
}
EffectChain::~EffectChain()
{
clear();
}
void EffectChain::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
m_enabledModel.saveSettings( _doc, _this, "enabled" );
_this.setAttribute("numofeffects", static_cast<int>(m_effects.size()));
for( Effect* effect : m_effects)
{
if (auto dummy = dynamic_cast<DummyEffect*>(effect)) { _this.appendChild(dummy->originalPluginData()); }
else
{
QDomElement ef = effect->saveState( _doc, _this );
ef.setAttribute( "name", QString::fromUtf8( effect->descriptor()->name ) );
ef.appendChild( effect->key().saveXML( _doc ) );
}
}
}
void EffectChain::loadSettings( const QDomElement & _this )
{
clear();
// TODO This method should probably also lock the audio engine
m_enabledModel.loadSettings( _this, "enabled" );
const int plugin_cnt = _this.attribute( "numofeffects" ).toInt();
QDomNode node = _this.firstChild();
int fx_loaded = 0;
while( !node.isNull() && fx_loaded < plugin_cnt )
{
if( node.isElement() && node.nodeName() == "effect" )
{
QDomElement effectData = node.toElement();
const QString name = effectData.attribute( "name" );
EffectKey key( effectData.elementsByTagName( "key" ).item( 0 ).toElement() );
Effect* e = Effect::instantiate( name.toUtf8(), this, &key );
if( e != nullptr && e->isOkay() && e->nodeName() == node.nodeName() )
{
e->restoreState( effectData );
}
else
{
delete e;
e = new DummyEffect( parentModel(), effectData );
}
m_effects.push_back( e );
++fx_loaded;
}
node = node.nextSibling();
}
emit dataChanged();
}
void EffectChain::appendEffect( Effect * _effect )
{
Engine::audioEngine()->requestChangeInModel();
m_effects.push_back(_effect);
Engine::audioEngine()->doneChangeInModel();
m_enabledModel.setValue( true );
emit dataChanged();
}
void EffectChain::removeEffect( Effect * _effect )
{
Engine::audioEngine()->requestChangeInModel();
auto found = std::find(m_effects.begin(), m_effects.end(), _effect);
if( found == m_effects.end() )
{
Engine::audioEngine()->doneChangeInModel();
return;
}
m_effects.erase( found );
Engine::audioEngine()->doneChangeInModel();
if (m_effects.empty())
{
m_enabledModel.setValue( false );
}
emit dataChanged();
}
void EffectChain::moveDown( Effect * _effect )
{
if (_effect != m_effects.back())
{
auto it = std::find(m_effects.begin(), m_effects.end(), _effect);
assert(it != m_effects.end());
std::swap(*std::next(it), *it);
}
}
void EffectChain::moveUp( Effect * _effect )
{
if (_effect != m_effects.front())
{
auto it = std::find(m_effects.begin(), m_effects.end(), _effect);
assert(it != m_effects.end());
std::swap(*std::prev(it), *it);
}
}
bool EffectChain::processAudioBuffer( SampleFrame* _buf, const fpp_t _frames, bool hasInputNoise )
{
if( m_enabledModel.value() == false )
{
return false;
}
MixHelpers::sanitize( _buf, _frames );
bool moreEffects = false;
for (const auto& effect : m_effects)
{
if (hasInputNoise || effect->isRunning())
{
moreEffects |= effect->processAudioBuffer(_buf, _frames);
MixHelpers::sanitize(_buf, _frames);
}
}
return moreEffects;
}
void EffectChain::startRunning()
{
if( m_enabledModel.value() == false )
{
return;
}
for (const auto& effect : m_effects)
{
effect->startRunning();
}
}
void EffectChain::clear()
{
emit aboutToClear();
Engine::audioEngine()->requestChangeInModel();
while (m_effects.size())
{
auto e = m_effects[m_effects.size() - 1];
m_effects.pop_back();
delete e;
}
Engine::audioEngine()->doneChangeInModel();
m_enabledModel.setValue( false );
}
} // namespace lmms
| 4,999
|
C++
|
.cpp
| 175
| 26.005714
| 106
| 0.702441
|
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,817
|
UpgradeExtendedNoteRange.cpp
|
LMMS_lmms/src/core/UpgradeExtendedNoteRange.cpp
|
/*
* UpgradeExtendedNoteRange.cpp - Upgrades the extended note range
*
* 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 "UpgradeExtendedNoteRange.h"
#include "Track.h"
#include <QDomElement>
#include <set>
#include <cassert>
namespace lmms
{
/**
* @brief Used by the helper function that analyzes automation patterns.
*/
struct PatternAnalysisResult
{
PatternAnalysisResult(bool hasBaseNoteAutomations, bool hasNonBaseNoteAutomations)
{
this->hasBaseNoteAutomations = hasBaseNoteAutomations;
this->hasNonBaseNoteAutomations = hasNonBaseNoteAutomations;
}
bool hasBaseNoteAutomations;
bool hasNonBaseNoteAutomations;
};
/**
* @brief Helper function that checks for an automation pattern if it contains automation for
* targets that are base notes and/or other targets.
* @param automationPattern The automation pattern to be checked.
* @param automatedBaseNoteIds A set of id of automated base notes that are used in the check.
* @return A struct that contains the results.
*/
static PatternAnalysisResult analyzeAutomationPattern(QDomElement const & automationPattern, std::set<unsigned int> const & automatedBaseNoteIds)
{
bool hasBaseNoteAutomations = false;
bool hasNonBaseNoteAutomations = false;
// Iterate the objects. These contain the ids of the automated objects.
QDomElement object = automationPattern.firstChildElement("object");
while (!object.isNull())
{
unsigned int const id = object.attribute("id").toUInt();
// Check if the automated object is a base note.
if (automatedBaseNoteIds.find(id) != automatedBaseNoteIds.end())
{
hasBaseNoteAutomations = true;
}
else
{
hasNonBaseNoteAutomations = true;
}
object = object.nextSiblingElement("object");
}
return PatternAnalysisResult(hasBaseNoteAutomations, hasNonBaseNoteAutomations);
}
static void fixNotePatterns(QDomNodeList & patterns)
{
for (int i = 0; i < patterns.size(); ++i)
{
QDomNodeList notes = patterns.item(i).toElement().elementsByTagName("note");
for (int j = 0; j < notes.size(); ++j)
{
QDomElement note = notes.item(j).toElement();
if (note.hasAttribute("key"))
{
int const currentKey = note.attribute("key").toInt();
note.setAttribute("key", currentKey + 12);
}
}
}
}
static void fixInstrumentBaseNoteAndCollectIds(QDomElement & instrument, std::set<unsigned int> & automatedBaseNoteIds)
{
// Raise the base note of every instrument by 12 to compensate for the change
// of A4 key code from 57 to 69. This ensures that notes are labeled correctly.
QDomElement instrumentParent = instrument.parentNode().toElement();
// Correct the base note of the instrument. Base notes which are automated are
// stored as elements. Non-automated base notes are stored as attributes.
if (instrumentParent.hasAttribute("basenote"))
{
// TODO Base notes can have float values in the save file! This might need to be changed!
int const currentBaseNote = instrumentParent.attribute("basenote").toInt();
instrumentParent.setAttribute("basenote", currentBaseNote + 12);
}
else
{
// Check if the instrument track has an automated base note.
// Correct the value of the base note and collect their ids while doing so.
// The ids are used later to find the automations that automate these corrected base
// notes so that we can correct the automation values as well.
QDomNodeList baseNotes = instrumentParent.elementsByTagName("basenote");
for (int j = 0; j < baseNotes.size(); ++j)
{
QDomElement baseNote = baseNotes.item(j).toElement();
if (!baseNote.isNull())
{
if (baseNote.hasAttribute("value"))
{
// Base notes can have float values in the save file, e.g. if the file
// is saved after a linear automation has run on the base note. Therefore
// it is fixed here as a float even if the nominal values of base notes
// are integers.
float const value = baseNote.attribute("value").toFloat();
baseNote.setAttribute("value", value + 12);
}
// The ids of base notes are of type jo_id_t which are in fact uint32_t.
// So let's just use these here to save some casting.
unsigned int const id = baseNote.attribute("id").toUInt();
automatedBaseNoteIds.insert(id);
}
}
}
}
/**
* @brief Helper method that fixes the values and out values for an automation pattern.
* @param automationPattern The automation pattern to be fixed.
*/
static void fixAutomationPattern(QDomElement & automationPattern)
{
QDomElement time = automationPattern.firstChildElement("time");
while (!time.isNull())
{
// Automation patterns can automate base notes as floats
// so we read and correct them as floats here.
float const value = time.attribute("value").toFloat();
time.setAttribute("value", value + 12.);
// The method "upgrade_automationNodes" adds some attributes
// with the name "outValue". We have to correct these as well.
float const outValue = time.attribute("outValue").toFloat();
time.setAttribute("outValue", outValue + 12.);
time = time.nextSiblingElement("time");
};
}
static bool affected(QDomElement & instrument)
{
assert(instrument.hasAttribute("name"));
QString const name = instrument.attribute("name");
return name == "zynaddsubfx" ||
name == "vestige" || name == "lv2instrument" ||
name == "carlapatchbay" || name == "carlarack";
}
static void fixTrack(QDomElement & track, std::set<unsigned int> & automatedBaseNoteIds)
{
if (!track.hasAttribute("type"))
{
return;
}
Track::Type const trackType = static_cast<Track::Type>(track.attribute("type").toInt());
// BB tracks need special handling because they contain a track container of their own
if (trackType == Track::Type::Pattern)
{
// Assuming that a BB track cannot contain another BB track here...
QDomNodeList subTracks = track.elementsByTagName("track");
for (int i = 0; i < subTracks.size(); ++i)
{
QDomElement subTrack = subTracks.item(i).toElement();
assert (static_cast<Track::Type>(subTrack.attribute("type").toInt()) != Track::Type::Pattern);
fixTrack(subTrack, automatedBaseNoteIds);
}
}
else
{
QDomNodeList instruments = track.elementsByTagName("instrument");
for (int i = 0; i < instruments.size(); ++i)
{
QDomElement instrument = instruments.item(i).toElement();
fixInstrumentBaseNoteAndCollectIds(instrument, automatedBaseNoteIds);
// Raise the pitch of all notes in patterns assigned to instruments not affected
// by #1857 by an octave. This negates the base note change for normal instruments,
// but leaves the MIDI-based instruments sounding an octave lower, preserving their
// pitch in existing projects.
if (!affected(instrument))
{
QDomNodeList patterns = track.elementsByTagName("pattern");
fixNotePatterns(patterns);
}
}
}
}
static void fixAutomationTracks(QDomElement & song, std::set<unsigned int> const & automatedBaseNoteIds)
{
// Now fix all the automation tracks.
QDomNodeList tracks = song.elementsByTagName("track");
// We have to collect the tracks that we need to duplicate and cannot do this in-place
// because if we did the iteration might never stop.
std::vector<QDomElement> tracksToDuplicate;
tracksToDuplicate.reserve(tracks.size());
// Iterate the tracks again. This time work on all automation tracks.
for (int i = 0; i < tracks.size(); ++i)
{
QDomElement currentTrack = tracks.item(i).toElement();
if (static_cast<Track::Type>(currentTrack.attribute("type").toInt()) != Track::Type::Automation)
{
continue;
}
// Check each track for the types of automations it contains in its patterns.
bool containsPatternsWithBaseNoteTargets = false;
bool containsPatternsWithNonBaseNoteTargets = false;
QDomElement automationPattern = currentTrack.firstChildElement("automationpattern");
while (!automationPattern.isNull())
{
auto const analysis = analyzeAutomationPattern(automationPattern, automatedBaseNoteIds);
containsPatternsWithBaseNoteTargets |= analysis.hasBaseNoteAutomations;
containsPatternsWithNonBaseNoteTargets |= analysis.hasNonBaseNoteAutomations;
automationPattern = automationPattern.nextSiblingElement("automationpattern");
}
if (!containsPatternsWithBaseNoteTargets)
{
// No base notes are automated by this automation track so we have nothing to do
continue;
}
else
{
if (!containsPatternsWithNonBaseNoteTargets)
{
// Only base note targets. This means we can simply keep the track and fix it.
automationPattern = currentTrack.firstChildElement("automationpattern");
while (!automationPattern.isNull())
{
fixAutomationPattern(automationPattern);
automationPattern = automationPattern.nextSiblingElement("automationpattern");
}
}
else
{
// The automation track has automations for base notes and other targets in its patterns.
// We will later need to duplicate/split the track.
tracksToDuplicate.push_back(currentTrack);
}
}
}
// Now fix the tracks that need duplication/splitting
for (QDomElement & track : tracksToDuplicate)
{
// First clone the original track
QDomNode cloneOfTrack = track.cloneNode();
// Now that we have the original and the clone we can manipulate both of them.
// The original track will keep only patterns without base note automations.
// Note: for the original track these might also be automation patterns without
// any targets. We will keep these because they might have been saved by the users
// like this.
QDomElement automationPattern = track.firstChildElement("automationpattern");
while (!automationPattern.isNull())
{
auto const analysis = analyzeAutomationPattern(automationPattern, automatedBaseNoteIds);
if (!analysis.hasBaseNoteAutomations)
{
// This pattern has no base note automations. Leave it alone.
automationPattern = automationPattern.nextSiblingElement("automationpattern");
}
else if (!analysis.hasNonBaseNoteAutomations)
{
// The pattern only has base note automations. Remove it completely as it would become empty.
QDomElement patternToRemove = automationPattern;
automationPattern = automationPattern.nextSiblingElement("automationpattern");
track.removeChild(patternToRemove);
}
else
{
// The pattern itself is mixed. Remove the base note objects.
QDomElement object = automationPattern.firstChildElement("object");
while (!object.isNull())
{
unsigned int const id = object.attribute("id").toUInt();
if (automatedBaseNoteIds.find(id) != automatedBaseNoteIds.end())
{
QDomElement objectToRemove = object;
object = object.nextSiblingElement("object");
automationPattern.removeChild(objectToRemove);
}
else
{
object = object.nextSiblingElement("object");
}
}
automationPattern = automationPattern.nextSiblingElement("automationpattern");
}
}
// The clone will only keep non-empty patterns with base note automations
// and the values of the patterns will be corrected.
automationPattern = cloneOfTrack.firstChildElement("automationpattern");
while (!automationPattern.isNull())
{
auto const analysis = analyzeAutomationPattern(automationPattern, automatedBaseNoteIds);
if (analysis.hasBaseNoteAutomations)
{
// This pattern has base note automations. Remove all other ones and fix the pattern.
QDomElement object = automationPattern.firstChildElement("object");
while (!object.isNull())
{
unsigned int const id = object.attribute("id").toUInt();
if (automatedBaseNoteIds.find(id) == automatedBaseNoteIds.end())
{
QDomElement objectToRemove = object;
object = object.nextSiblingElement("object");
automationPattern.removeChild(objectToRemove);
}
else
{
object = object.nextSiblingElement("object");
}
}
fixAutomationPattern(automationPattern);
automationPattern = automationPattern.nextSiblingElement("automationpattern");
}
else
{
// The pattern has no base note automations. Remove it completely.
QDomElement patternToRemove = automationPattern;
automationPattern = automationPattern.nextSiblingElement("automationpattern");
cloneOfTrack.removeChild(patternToRemove);
}
}
track.parentNode().appendChild(cloneOfTrack);
}
}
UpgradeExtendedNoteRange::UpgradeExtendedNoteRange(QDomElement & domElement) :
m_domElement(domElement)
{
}
void UpgradeExtendedNoteRange::upgrade()
{
QDomElement song = m_domElement.firstChildElement("song");
while (!song.isNull())
{
// This set will later contain all ids of automated base notes. They are
// used to find out which automation patterns must to be corrected, i.e. to
// check if an automation pattern has one or more base notes as its target.
std::set<unsigned int> automatedBaseNoteIds;
QDomElement trackContainer = song.firstChildElement("trackcontainer");
while (!trackContainer.isNull())
{
QDomElement track = trackContainer.firstChildElement("track");
while (!track.isNull())
{
fixTrack(track, automatedBaseNoteIds);
track = track.nextSiblingElement("track");
}
trackContainer = trackContainer.nextSiblingElement("trackcontainer");
}
fixAutomationTracks(song, automatedBaseNoteIds);
song = song.nextSiblingElement("song");
};
if (m_domElement.elementsByTagName("song").item(0).isNull())
{
// Dealing with a preset, not a song
QDomNodeList presets = m_domElement.elementsByTagName("instrumenttrack");
if (presets.item(0).isNull()) { return; }
QDomElement preset = presets.item(0).toElement();
// Common correction for all instrument presets (make base notes match the new MIDI range).
// NOTE: Many older presets do not have any basenote defined, assume they were "made for 57".
// (Specifying a default like this also happens to fix a FileBrowser bug where previews of presets
// with undefined basenote always play with the basenote inherited from previously played preview.)
int oldBase = preset.attribute("basenote", "57").toInt();
preset.setAttribute("basenote", oldBase + 12);
// Extra correction for Zyn, VeSTige, LV2 and Carla (to preserve the original buggy behavior).
QDomNodeList instruments = presets.item(0).toElement().elementsByTagName("instrument");
if (instruments.isEmpty()) { return; }
QDomElement instrument = instruments.item(0).toElement();
if (affected(instrument))
{
preset.setAttribute("basenote", preset.attribute("basenote").toInt() + 12);
}
}
}
} // namespace lmms
| 15,365
|
C++
|
.cpp
| 381
| 36.76378
| 145
| 0.747907
|
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,818
|
PatternStore.cpp
|
LMMS_lmms/src/core/PatternStore.cpp
|
/*
* PatternStore.cpp - model-component of Pattern Editor
*
* 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 "PatternStore.h"
#include "Clip.h"
#include "Engine.h"
#include "PatternTrack.h"
#include "Song.h"
namespace lmms
{
PatternStore::PatternStore() :
TrackContainer(),
m_patternComboBoxModel(this)
{
connect(&m_patternComboBoxModel, SIGNAL(dataChanged()),
this, SLOT(currentPatternChanged()));
// we *always* want to receive updates even in case pattern actually did
// not change upon setCurrentPattern()-call
connect(&m_patternComboBoxModel, SIGNAL(dataUnchanged()),
this, SLOT(currentPatternChanged()));
setType(Type::Pattern);
}
bool PatternStore::play(TimePos start, fpp_t frames, f_cnt_t offset, int clipNum)
{
bool notePlayed = false;
if (lengthOfPattern(clipNum) <= 0)
{
return false;
}
start = start % (lengthOfPattern(clipNum) * TimePos::ticksPerBar());
const TrackList& tl = tracks();
for (Track * t : tl)
{
if (t->play(start, frames, offset, clipNum))
{
notePlayed = true;
}
}
return notePlayed;
}
void PatternStore::updateAfterTrackAdd()
{
if (numOfPatterns() == 0 && !Engine::getSong()->isLoadingProject())
{
Engine::getSong()->addPatternTrack();
}
}
bar_t PatternStore::lengthOfPattern(int pattern) const
{
TimePos maxLength = TimePos::ticksPerBar();
const TrackList & tl = tracks();
for (Track * t : tl)
{
// Don't create Clips here if they don't exist
if (pattern < t->numOfClips())
{
maxLength = std::max(maxLength, t->getClip(pattern)->length());
}
}
return maxLength.nextFullBar();
}
int PatternStore::numOfPatterns() const
{
return Engine::getSong()->countTracks(Track::Type::Pattern);
}
void PatternStore::removePattern(int pattern)
{
const TrackList& tl = tracks();
for (Track * t : tl)
{
delete t->getClip(pattern);
t->removeBar(pattern * DefaultTicksPerBar);
}
if (pattern <= currentPattern())
{
setCurrentPattern(std::max(currentPattern() - 1, 0));
}
}
void PatternStore::swapPattern(int pattern1, int pattern2)
{
const TrackList& tl = tracks();
for (Track * t : tl)
{
t->swapPositionOfClips(pattern1, pattern2);
}
updateComboBox();
}
void PatternStore::updatePatternTrack(Clip* clip)
{
PatternTrack * t = PatternTrack::findPatternTrack(clip->startPosition() / DefaultTicksPerBar);
if (t != nullptr)
{
t->dataChanged();
}
}
void PatternStore::fixIncorrectPositions()
{
const TrackList& tl = tracks();
for (Track * t : tl)
{
for (int i = 0; i < numOfPatterns(); ++i)
{
t->getClip(i)->movePosition(TimePos(i, 0));
}
}
}
void PatternStore::play()
{
if (Engine::getSong()->playMode() != Song::PlayMode::Pattern)
{
Engine::getSong()->playPattern();
}
else
{
Engine::getSong()->togglePause();
}
}
void PatternStore::stop()
{
Engine::getSong()->stop();
}
void PatternStore::updateComboBox()
{
const int curPattern = currentPattern();
m_patternComboBoxModel.clear();
for (int i = 0; i < numOfPatterns(); ++i)
{
PatternTrack* pt = PatternTrack::findPatternTrack(i);
m_patternComboBoxModel.addItem(pt->name());
}
setCurrentPattern(curPattern);
}
void PatternStore::currentPatternChanged()
{
// now update all track-labels (the current one has to become white, the others gray)
const TrackList& tl = Engine::getSong()->tracks();
for (Track * t : tl)
{
if (t->type() == Track::Type::Pattern)
{
t->dataChanged();
}
}
}
void PatternStore::createClipsForPattern(int pattern)
{
const TrackList& tl = tracks();
for (Track * t : tl)
{
t->createClipsForPattern(pattern);
}
}
AutomatedValueMap PatternStore::automatedValuesAt(TimePos time, int clipNum) const
{
Q_ASSERT(clipNum >= 0);
Q_ASSERT(time.getTicks() >= 0);
auto lengthBars = lengthOfPattern(clipNum);
auto lengthTicks = lengthBars * TimePos::ticksPerBar();
if (time > lengthTicks)
{
time = lengthTicks;
}
return TrackContainer::automatedValuesAt(time + (TimePos::ticksPerBar() * clipNum), clipNum);
}
} // namespace lmms
| 4,843
|
C++
|
.cpp
| 185
| 23.886486
| 95
| 0.726678
|
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,819
|
AutomatableModel.cpp
|
LMMS_lmms/src/core/AutomatableModel.cpp
|
/*
* AutomatableModel.cpp - some implementations of AutomatableModel-class
*
* 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 "AutomatableModel.h"
#include "lmms_math.h"
#include "AudioEngine.h"
#include "AutomationClip.h"
#include "ControllerConnection.h"
#include "LocaleHelper.h"
#include "ProjectJournal.h"
#include "Song.h"
namespace lmms
{
long AutomatableModel::s_periodCounter = 0;
AutomatableModel::AutomatableModel(
const float val, const float min, const float max, const float step,
Model* parent, const QString & displayName, bool defaultConstructed ) :
Model( parent, displayName, defaultConstructed ),
m_scaleType( ScaleType::Linear ),
m_minValue( min ),
m_maxValue( max ),
m_step( step ),
m_range( max - min ),
m_centerValue( m_minValue ),
m_valueChanged( false ),
m_setValueDepth( 0 ),
m_hasStrictStepSize( false ),
m_controllerConnection( nullptr ),
m_valueBuffer( static_cast<int>( Engine::audioEngine()->framesPerPeriod() ) ),
m_lastUpdatedPeriod( -1 ),
m_hasSampleExactData(false),
m_useControllerValue(true)
{
m_value = fittedValue( val );
setInitValue( val );
}
AutomatableModel::~AutomatableModel()
{
while( m_linkedModels.empty() == false )
{
m_linkedModels.back()->unlinkModel(this);
m_linkedModels.erase( m_linkedModels.end() - 1 );
}
if( m_controllerConnection )
{
delete m_controllerConnection;
}
m_valueBuffer.clear();
emit destroyed( id() );
}
bool AutomatableModel::isAutomated() const
{
return AutomationClip::isAutomated( this );
}
bool AutomatableModel::mustQuoteName(const QString& name)
{
QRegularExpression reg("^[A-Za-z0-9._-]+$");
return !reg.match(name).hasMatch();
}
void AutomatableModel::saveSettings( QDomDocument& doc, QDomElement& element, const QString& name )
{
bool mustQuote = mustQuoteName(name);
if( isAutomated() || m_scaleType != ScaleType::Linear )
{
// automation needs tuple of data (name, id, value)
// scale type also needs an extra value
// => it must be appended as a node
QDomElement me = doc.createElement( mustQuote ? QString("automatablemodel") : name );
me.setAttribute( "id", ProjectJournal::idToSave( id() ) );
me.setAttribute( "value", m_value );
me.setAttribute( "scale_type", m_scaleType == ScaleType::Logarithmic ? "log" : "linear" );
if(mustQuote) {
me.setAttribute( "nodename", name );
}
element.appendChild( me );
}
else
{
if(mustQuote)
{
QDomElement me = doc.createElement( "automatablemodel" );
me.setAttribute( "nodename", name );
me.setAttribute( "value", m_value );
element.appendChild( me );
}
else
{
// non automation, linear scale (default), can be saved as attribute
element.setAttribute( name, m_value );
}
}
// Skip saving MIDI connections if we're saving project and
// the discardMIDIConnections option is true.
auto controllerType = m_controllerConnection
? m_controllerConnection->getController()->type()
: Controller::ControllerType::Dummy;
bool skipMidiController = Engine::getSong()->isSavingProject()
&& Engine::getSong()->getSaveOptions().discardMIDIConnections.value();
if (m_controllerConnection && controllerType != Controller::ControllerType::Dummy
&& !(skipMidiController && controllerType == Controller::ControllerType::Midi))
{
QDomElement controllerElement;
// get "connection" element (and create it if needed)
QDomNode node = element.namedItem( "connection" );
if( node.isElement() )
{
controllerElement = node.toElement();
}
else
{
controllerElement = doc.createElement( "connection" );
element.appendChild( controllerElement );
}
bool mustQuote = mustQuoteName(name);
QString elementName = mustQuote ? "controllerconnection"
: name;
QDomElement element = doc.createElement( elementName );
if(mustQuote)
element.setAttribute( "nodename", name );
m_controllerConnection->saveSettings( doc, element );
controllerElement.appendChild( element );
}
}
void AutomatableModel::loadSettings( const QDomElement& element, const QString& name )
{
// compat code
QDomNode node = element.namedItem( AutomationClip::classNodeName() );
if( node.isElement() )
{
node = node.namedItem( name );
if( node.isElement() )
{
AutomationClip * p = AutomationClip::globalAutomationClip( this );
p->loadSettings( node.toElement() );
setValue( p->valueAt( 0 ) );
// in older projects we sometimes have odd automations
// with just one value in - eliminate if necessary
if( !p->hasAutomation() )
{
delete p;
}
return;
}
// logscales were not existing at this point of time
// so they can be ignored
}
QDomNode connectionNode = element.namedItem( "connection" );
// reads controller connection
if( connectionNode.isElement() )
{
QDomNode thisConnection = connectionNode.toElement().namedItem( name );
if( !thisConnection.isElement() )
{
thisConnection = connectionNode.toElement().namedItem( "controllerconnection" );
QDomElement tcElement = thisConnection.toElement();
// sanity check
if( tcElement.isNull() || tcElement.attribute( "nodename" ) != name )
{
// no, that wasn't it, act as if we never found one
thisConnection.clear();
}
}
if( thisConnection.isElement() )
{
setControllerConnection(new ControllerConnection(nullptr));
m_controllerConnection->loadSettings( thisConnection.toElement() );
//m_controllerConnection->setTargetName( displayName() );
}
}
// models can be stored as elements (port00) or attributes (port10):
// <ladspacontrols port10="4.41">
// <port00 value="4.41" id="4249278"/>
// </ladspacontrols>
// element => there is automation data, or scaletype information
node = element.namedItem( name ); // maybe we have luck?
// either: no node with name "name" found
// => look for nodes with attribute name="nodename"
// or: element with namedItem() "name" was found, but it's real nodename
// is given as attribute and does not match
// => look for the right node
if(node.isNull() ||
( node.isElement() &&
node.toElement().hasAttribute("nodename") &&
node.toElement().attribute("nodename") != name))
{
for(QDomElement othernode = element.firstChildElement();
!othernode.isNull();
othernode = othernode.nextSiblingElement())
{
if((!othernode.hasAttribute("nodename") &&
othernode.nodeName() == name) ||
othernode.attribute("nodename") == name)
{
node = othernode;
break;
}
}
}
if( node.isElement() )
{
QDomElement nodeElement = node.toElement();
changeID( nodeElement.attribute( "id" ).toInt() );
setValue( LocaleHelper::toFloat( nodeElement.attribute( "value" ) ) );
if( nodeElement.hasAttribute( "scale_type" ) )
{
if( nodeElement.attribute( "scale_type" ) == "linear" )
{
setScaleType( ScaleType::Linear );
}
else if( nodeElement.attribute( "scale_type" ) == "log" )
{
setScaleType( ScaleType::Logarithmic );
}
}
}
else
{
setScaleType( ScaleType::Linear );
if( element.hasAttribute( name ) )
// attribute => read the element's value from the attribute list
{
setInitValue( LocaleHelper::toFloat( element.attribute( name ) ) );
}
else
{
reset();
}
}
}
void AutomatableModel::setValue( const float value )
{
m_oldValue = m_value;
++m_setValueDepth;
const float old_val = m_value;
m_value = fittedValue( value );
if( old_val != m_value )
{
// add changes to history so user can undo it
addJournalCheckPoint();
// notify linked models
for (const auto& linkedModel : m_linkedModels)
{
if (linkedModel->m_setValueDepth < 1 && linkedModel->fittedValue(value) != linkedModel->m_value)
{
bool journalling = linkedModel->testAndSetJournalling(isJournalling());
linkedModel->setValue(value);
linkedModel->setJournalling(journalling);
}
}
m_valueChanged = true;
emit dataChanged();
}
else
{
emit dataUnchanged();
}
--m_setValueDepth;
}
template<class T> T AutomatableModel::logToLinearScale( T value ) const
{
return castValue<T>( lmms::logToLinearScale( minValue<float>(), maxValue<float>(), static_cast<float>( value ) ) );
}
float AutomatableModel::scaledValue( float value ) const
{
return m_scaleType == ScaleType::Linear
? value
: logToLinearScale<float>( ( value - minValue<float>() ) / m_range );
}
float AutomatableModel::inverseScaledValue( float value ) const
{
return m_scaleType == ScaleType::Linear
? value
: lmms::linearToLogScale( minValue<float>(), maxValue<float>(), value );
}
template<class T>
void AutomatableModel::roundAt( T& value, const T& where ) const
{
lmms::roundAt(value, where, m_step);
}
void AutomatableModel::setAutomatedValue( const float value )
{
setUseControllerValue(false);
m_oldValue = m_value;
++m_setValueDepth;
const float oldValue = m_value;
const float scaled_value = scaledValue( value );
m_value = fittedValue( scaled_value );
if( oldValue != m_value )
{
// notify linked models
for (const auto& linkedModel : m_linkedModels)
{
if (!(linkedModel->controllerConnection()) && linkedModel->m_setValueDepth < 1 &&
linkedModel->fittedValue(m_value) != linkedModel->m_value)
{
linkedModel->setAutomatedValue(value);
}
}
m_valueChanged = true;
emit dataChanged();
}
--m_setValueDepth;
}
void AutomatableModel::setRange( const float min, const float max,
const float step )
{
if( ( m_maxValue != max ) || ( m_minValue != min ) )
{
m_minValue = min;
m_maxValue = max;
if( m_minValue > m_maxValue )
{
qSwap<float>( m_minValue, m_maxValue );
}
m_range = m_maxValue - m_minValue;
setStep( step );
// re-adjust value
setValue( value<float>() );
emit propertiesChanged();
}
}
void AutomatableModel::setStep( const float step )
{
if( m_step != step )
{
m_step = step;
emit propertiesChanged();
}
}
float AutomatableModel::fittedValue( float value ) const
{
value = std::clamp(value, m_minValue, m_maxValue);
if( m_step != 0 && m_hasStrictStepSize )
{
value = nearbyintf( value / m_step ) * m_step;
}
roundAt( value, m_maxValue );
roundAt( value, m_minValue );
roundAt( value, 0.0f );
if( value < m_minValue )
{
return m_minValue;
}
else if( value > m_maxValue )
{
return m_maxValue;
}
return value;
}
void AutomatableModel::linkModel( AutomatableModel* model )
{
auto containsModel = std::find(m_linkedModels.begin(), m_linkedModels.end(), model) != m_linkedModels.end();
if (!containsModel && model != this)
{
m_linkedModels.push_back( model );
if( !model->hasLinkedModels() )
{
QObject::connect( this, SIGNAL(dataChanged()),
model, SIGNAL(dataChanged()), Qt::DirectConnection );
}
}
}
void AutomatableModel::unlinkModel( AutomatableModel* model )
{
auto it = std::find(m_linkedModels.begin(), m_linkedModels.end(), model);
if( it != m_linkedModels.end() )
{
m_linkedModels.erase( it );
}
}
void AutomatableModel::linkModels( AutomatableModel* model1, AutomatableModel* model2 )
{
auto model1ContainsModel2 = std::find(model1->m_linkedModels.begin(), model1->m_linkedModels.end(), model2) != model1->m_linkedModels.end();
if (!model1ContainsModel2 && model1 != model2)
{
// copy data
model1->m_value = model2->m_value;
if (model1->valueBuffer() && model2->valueBuffer())
{
std::copy_n(model2->valueBuffer()->data(),
model1->valueBuffer()->length(),
model1->valueBuffer()->data());
}
// send dataChanged() before linking (because linking will
// connect the two dataChanged() signals)
emit model1->dataChanged();
// finally: link the models
model1->linkModel( model2 );
model2->linkModel( model1 );
}
}
void AutomatableModel::unlinkModels( AutomatableModel* model1, AutomatableModel* model2 )
{
model1->unlinkModel( model2 );
model2->unlinkModel( model1 );
}
void AutomatableModel::unlinkAllModels()
{
for( AutomatableModel* model : m_linkedModels )
{
unlinkModels( this, model );
}
}
void AutomatableModel::setControllerConnection( ControllerConnection* c )
{
m_controllerConnection = c;
if( c )
{
QObject::connect( m_controllerConnection, SIGNAL(valueChanged()),
this, SIGNAL(dataChanged()), Qt::DirectConnection );
QObject::connect( m_controllerConnection, SIGNAL(destroyed()), this, SLOT(unlinkControllerConnection()));
m_valueChanged = true;
emit dataChanged();
}
}
float AutomatableModel::controllerValue( int frameOffset ) const
{
if( m_controllerConnection )
{
float v = 0;
switch(m_scaleType)
{
case ScaleType::Linear:
v = minValue<float>() + ( range() * controllerConnection()->currentValue( frameOffset ) );
break;
case ScaleType::Logarithmic:
v = logToLinearScale(
controllerConnection()->currentValue( frameOffset ));
break;
default:
qFatal("AutomatableModel::controllerValue(int)"
"lacks implementation for a scale type");
break;
}
if (approximatelyEqual(m_step, 1) && m_hasStrictStepSize)
{
return std::round(v);
}
return v;
}
AutomatableModel* lm = m_linkedModels.front();
if (lm->controllerConnection() && lm->useControllerValue())
{
return fittedValue( lm->controllerValue( frameOffset ) );
}
return fittedValue( lm->m_value );
}
ValueBuffer * AutomatableModel::valueBuffer()
{
QMutexLocker m( &m_valueBufferMutex );
// if we've already calculated the valuebuffer this period, return the cached buffer
if( m_lastUpdatedPeriod == s_periodCounter )
{
return m_hasSampleExactData
? &m_valueBuffer
: nullptr;
}
float val = m_value; // make sure our m_value doesn't change midway
if (m_controllerConnection && m_useControllerValue && m_controllerConnection->getController()->isSampleExact())
{
auto vb = m_controllerConnection->valueBuffer();
if( vb )
{
float * values = vb->values();
float * nvalues = m_valueBuffer.values();
switch( m_scaleType )
{
case ScaleType::Linear:
for( int i = 0; i < m_valueBuffer.length(); i++ )
{
nvalues[i] = minValue<float>() + ( range() * values[i] );
}
break;
case ScaleType::Logarithmic:
for( int i = 0; i < m_valueBuffer.length(); i++ )
{
nvalues[i] = logToLinearScale( values[i] );
}
break;
default:
qFatal("AutomatableModel::valueBuffer() "
"lacks implementation for a scale type");
break;
}
m_lastUpdatedPeriod = s_periodCounter;
m_hasSampleExactData = true;
return &m_valueBuffer;
}
}
if (!m_controllerConnection)
{
AutomatableModel* lm = nullptr;
if (hasLinkedModels())
{
lm = m_linkedModels.front();
}
if (lm && lm->controllerConnection() && lm->useControllerValue() &&
lm->controllerConnection()->getController()->isSampleExact())
{
auto vb = lm->valueBuffer();
float * values = vb->values();
float * nvalues = m_valueBuffer.values();
for (int i = 0; i < vb->length(); i++)
{
nvalues[i] = fittedValue(values[i]);
}
m_lastUpdatedPeriod = s_periodCounter;
m_hasSampleExactData = true;
return &m_valueBuffer;
}
}
if( m_oldValue != val )
{
m_valueBuffer.interpolate( m_oldValue, val );
m_oldValue = val;
m_lastUpdatedPeriod = s_periodCounter;
m_hasSampleExactData = true;
return &m_valueBuffer;
}
// if we have no sample-exact source for a ValueBuffer, return NULL to signify that no data is available at the moment
// in which case the recipient knows to use the static value() instead
m_lastUpdatedPeriod = s_periodCounter;
m_hasSampleExactData = false;
return nullptr;
}
void AutomatableModel::unlinkControllerConnection()
{
if( m_controllerConnection )
{
m_controllerConnection->disconnect( this );
}
m_controllerConnection = nullptr;
}
void AutomatableModel::setInitValue( const float value )
{
m_initValue = fittedValue( value );
bool journalling = testAndSetJournalling( false );
setValue( value );
m_oldValue = m_value;
setJournalling( journalling );
emit initValueChanged( value );
}
void AutomatableModel::reset()
{
setValue( initValue<float>() );
}
float AutomatableModel::globalAutomationValueAt( const TimePos& time )
{
// get clips that connect to this model
auto clips = AutomationClip::clipsForModel(this);
if (clips.empty())
{
// if no such clips exist, return current value
return m_value;
}
else
{
// of those clips:
// find the clips which overlap with the time position
std::vector<AutomationClip*> clipsInRange;
for (const auto& clip : clips)
{
int s = clip->startPosition();
int e = clip->endPosition();
if (s <= time && e >= time) { clipsInRange.push_back(clip); }
}
AutomationClip * latestClip = nullptr;
if (!clipsInRange.empty())
{
// if there are more than one overlapping clips, just use the first one because
// multiple clip behaviour is undefined anyway
latestClip = clipsInRange[0];
}
else
// if we find no clips at the exact time, we need to search for the last clip before time and use that
{
int latestPosition = 0;
for (const auto& clip : clips)
{
int e = clip->endPosition();
if (e <= time && e > latestPosition)
{
latestPosition = e;
latestClip = clip;
}
}
}
if( latestClip )
{
// scale/fit the value appropriately and return it
const float value = latestClip->valueAt( time - latestClip->startPosition() );
const float scaled_value = scaledValue( value );
return fittedValue( scaled_value );
}
// if we still find no clip, the value at that time is undefined so
// just return current value as the best we can do
else return m_value;
}
}
void AutomatableModel::setUseControllerValue(bool b)
{
if (b)
{
m_useControllerValue = true;
emit dataChanged();
}
else if (m_controllerConnection && m_useControllerValue)
{
m_useControllerValue = false;
emit dataChanged();
}
}
float FloatModel::getRoundedValue() const
{
return std::round(value() / step<float>()) * step<float>();
}
int FloatModel::getDigitCount() const
{
auto steptemp = step<float>();
int digits = 0;
while ( steptemp < 1 )
{
steptemp = steptemp * 10.0f;
digits++;
}
return digits;
}
QString FloatModel::displayValue( const float val ) const
{
return QString::number( castValue<float>( scaledValue( val ) ) );
}
QString IntModel::displayValue( const float val ) const
{
return QString::number( castValue<int>( scaledValue( val ) ) );
}
QString BoolModel::displayValue( const float val ) const
{
return QString::number( castValue<bool>( scaledValue( val ) ) );
}
} // namespace lmms
| 19,312
|
C++
|
.cpp
| 660
| 26.381818
| 141
| 0.713204
|
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,820
|
TempoSyncKnobModel.cpp
|
LMMS_lmms/src/core/TempoSyncKnobModel.cpp
|
/*
* TempoSyncKnobModel.cpp - adds bpm to ms conversion for knob class
*
* Copyright (c) 2005-2007 Danny McRae <khjklujn/at/yahoo.com>
* Copyright (c) 2005-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 <QAction>
#include <QDomElement>
#include "TempoSyncKnobModel.h"
#include "Engine.h"
#include "Song.h"
namespace lmms
{
TempoSyncKnobModel::TempoSyncKnobModel( const float _val, const float _min,
const float _max, const float _step,
const float _scale, Model * _parent,
const QString & _display_name ) :
FloatModel( _val, _min, _max, _step, _parent, _display_name ),
m_tempoSyncMode( SyncMode::None ),
m_tempoLastSyncMode( SyncMode::None ),
m_scale( _scale ),
m_custom( _parent )
{
connect( Engine::getSong(), SIGNAL(tempoChanged(lmms::bpm_t)),
this, SLOT(calculateTempoSyncTime(lmms::bpm_t)),
Qt::DirectConnection );
}
void TempoSyncKnobModel::setTempoSync( QAction * _item )
{
setTempoSync( static_cast<SyncMode>(_item->data().toInt()) );
}
void TempoSyncKnobModel::setTempoSync( SyncMode _note_type )
{
setSyncMode( _note_type );
Engine::getSong()->setModified();
}
void TempoSyncKnobModel::calculateTempoSyncTime( bpm_t _bpm )
{
float conversionFactor = 1.0;
if( m_tempoSyncMode != SyncMode::None )
{
switch( m_tempoSyncMode )
{
case SyncMode::Custom:
conversionFactor =
static_cast<float>( m_custom.getDenominator() ) /
static_cast<float>( m_custom.getNumerator() );
break;
case SyncMode::DoubleWholeNote:
conversionFactor = 0.125;
break;
case SyncMode::WholeNote:
conversionFactor = 0.25;
break;
case SyncMode::HalfNote:
conversionFactor = 0.5;
break;
case SyncMode::QuarterNote:
conversionFactor = 1.0;
break;
case SyncMode::EighthNote:
conversionFactor = 2.0;
break;
case SyncMode::SixteenthNote:
conversionFactor = 4.0;
break;
case SyncMode::ThirtysecondNote:
conversionFactor = 8.0;
break;
default: ;
}
bool journalling = testAndSetJournalling( false );
float oneUnit = 60000.0 / ( _bpm * conversionFactor * m_scale );
setValue( oneUnit * maxValue() );
setJournalling( journalling );
}
if( m_tempoSyncMode != m_tempoLastSyncMode )
{
emit syncModeChanged( m_tempoSyncMode );
m_tempoLastSyncMode = m_tempoSyncMode;
}
else if (m_tempoSyncMode == SyncMode::Custom)
{
emit syncModeChanged(m_tempoSyncMode);
}
}
void TempoSyncKnobModel::saveSettings( QDomDocument & _doc, QDomElement & _this,
const QString & _name )
{
_this.setAttribute( _name + "_syncmode", (int) syncMode() );
m_custom.saveSettings( _doc, _this, _name );
FloatModel::saveSettings( _doc, _this, _name );
}
void TempoSyncKnobModel::loadSettings( const QDomElement & _this,
const QString & _name )
{
FloatModel::loadSettings( _this, _name );
m_custom.loadSettings( _this, _name );
setSyncMode( ( SyncMode ) _this.attribute( _name + "_syncmode" ).toInt() );
}
void TempoSyncKnobModel::setSyncMode( SyncMode _new_mode )
{
if( m_tempoSyncMode != _new_mode )
{
m_tempoSyncMode = _new_mode;
if( _new_mode == SyncMode::Custom )
{
connect( &m_custom, SIGNAL(dataChanged()),
this, SLOT(updateCustom()),
Qt::DirectConnection );
}
}
calculateTempoSyncTime( Engine::getSong()->getTempo() );
}
void TempoSyncKnobModel::setScale( float _new_scale )
{
m_scale = _new_scale;
calculateTempoSyncTime( Engine::getSong()->getTempo() );
emit scaleChanged( _new_scale );
}
void TempoSyncKnobModel::updateCustom()
{
setSyncMode( SyncMode::Custom );
}
} // namespace lmms
| 4,386
|
C++
|
.cpp
| 143
| 27.783217
| 80
| 0.72119
|
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,821
|
ProjectRenderer.cpp
|
LMMS_lmms/src/core/ProjectRenderer.cpp
|
/*
* ProjectRenderer.cpp - ProjectRenderer-class for easily rendering projects
*
* 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 <QFile>
#include "ProjectRenderer.h"
#include "Song.h"
#include "PerfLog.h"
#include "AudioFileWave.h"
#include "AudioFileOgg.h"
#include "AudioFileMP3.h"
#include "AudioFileFlac.h"
namespace lmms
{
const std::array<ProjectRenderer::FileEncodeDevice, 5> ProjectRenderer::fileEncodeDevices
{
FileEncodeDevice{ ProjectRenderer::ExportFileFormat::Wave,
QT_TRANSLATE_NOOP( "ProjectRenderer", "WAV (*.wav)" ),
".wav", &AudioFileWave::getInst },
FileEncodeDevice{ ProjectRenderer::ExportFileFormat::Flac,
QT_TRANSLATE_NOOP("ProjectRenderer", "FLAC (*.flac)"),
".flac",
&AudioFileFlac::getInst
},
FileEncodeDevice{ ProjectRenderer::ExportFileFormat::Ogg,
QT_TRANSLATE_NOOP( "ProjectRenderer", "OGG (*.ogg)" ),
".ogg",
#ifdef LMMS_HAVE_OGGVORBIS
&AudioFileOgg::getInst
#else
nullptr
#endif
},
FileEncodeDevice{ ProjectRenderer::ExportFileFormat::MP3,
QT_TRANSLATE_NOOP( "ProjectRenderer", "MP3 (*.mp3)" ),
".mp3",
#ifdef LMMS_HAVE_MP3LAME
&AudioFileMP3::getInst
#else
nullptr
#endif
},
// Insert your own file-encoder infos here.
// Maybe one day the user can add own encoders inside the program.
FileEncodeDevice{ ProjectRenderer::ExportFileFormat::Count, nullptr, nullptr, nullptr }
} ;
ProjectRenderer::ProjectRenderer( const AudioEngine::qualitySettings & qualitySettings,
const OutputSettings & outputSettings,
ExportFileFormat exportFileFormat,
const QString & outputFilename ) :
QThread( Engine::audioEngine() ),
m_fileDev( nullptr ),
m_qualitySettings( qualitySettings ),
m_progress( 0 ),
m_abort( false )
{
AudioFileDeviceInstantiaton audioEncoderFactory = fileEncodeDevices[static_cast<std::size_t>(exportFileFormat)].m_getDevInst;
if (audioEncoderFactory)
{
bool successful = false;
m_fileDev = audioEncoderFactory(
outputFilename, outputSettings, DEFAULT_CHANNELS,
Engine::audioEngine(), successful );
if( !successful )
{
delete m_fileDev;
m_fileDev = nullptr;
}
}
}
// Little help function for getting file format from a file extension
// (only for registered file-encoders).
ProjectRenderer::ExportFileFormat ProjectRenderer::getFileFormatFromExtension(
const QString & _ext )
{
int idx = 0;
while( fileEncodeDevices[idx].m_fileFormat != ExportFileFormat::Count )
{
if( QString( fileEncodeDevices[idx].m_extension ) == _ext )
{
return( fileEncodeDevices[idx].m_fileFormat );
}
++idx;
}
return( ExportFileFormat::Wave ); // Default.
}
QString ProjectRenderer::getFileExtensionFromFormat(
ExportFileFormat fmt )
{
return fileEncodeDevices[static_cast<std::size_t>(fmt)].m_extension;
}
void ProjectRenderer::startProcessing()
{
if( isReady() )
{
// Have to do audio engine stuff with GUI-thread affinity in order to
// make slots connected to sampleRateChanged()-signals being called immediately.
Engine::audioEngine()->setAudioDevice( m_fileDev, m_qualitySettings, false, false );
start(
#ifndef LMMS_BUILD_WIN32
QThread::HighPriority
#endif
);
}
}
void ProjectRenderer::run()
{
PerfLogTimer perfLog("Project Render");
Engine::getSong()->startExport();
// Skip first empty buffer.
Engine::audioEngine()->nextBuffer();
m_progress = 0;
// Now start processing
Engine::audioEngine()->startProcessing(false);
// Continually track and emit progress percentage to listeners.
while (!Engine::getSong()->isExportDone() && !m_abort)
{
m_fileDev->processNextBuffer();
const int nprog = Engine::getSong()->getExportProgress();
if (m_progress != nprog)
{
m_progress = nprog;
emit progressChanged( m_progress );
}
}
// Notify the audio engine of the end of processing.
Engine::audioEngine()->stopProcessing();
Engine::getSong()->stopExport();
perfLog.end();
// If the user aborted export-process, the file has to be deleted.
const QString f = m_fileDev->outputFile();
if( m_abort )
{
QFile( f ).remove();
}
}
void ProjectRenderer::abortProcessing()
{
m_abort = true;
wait();
}
void ProjectRenderer::updateConsoleProgress()
{
constexpr int cols = 50;
static int rot = 0;
auto buf = std::array<char, 80>{};
auto prog = std::array<char, cols + 1>{};
for( int i = 0; i < cols; ++i )
{
prog[i] = ( i*100/cols <= m_progress ? '-' : ' ' );
}
prog[cols] = 0;
const auto activity = "|/-\\";
std::fill(buf.begin(), buf.end(), 0);
std::snprintf(buf.data(), buf.size(), "\r|%s| %3d%% %c ", prog.data(), m_progress,
activity[rot] );
rot = ( rot+1 ) % 4;
fprintf( stderr, "%s", buf.data() );
fflush( stderr );
}
} // namespace lmms
| 5,561
|
C++
|
.cpp
| 180
| 28.177778
| 126
| 0.726812
|
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,822
|
StepRecorder.cpp
|
LMMS_lmms/src/core/StepRecorder.cpp
|
/*
* 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 "StepRecorder.h"
#include <QKeyEvent>
#include "MidiClip.h"
#include "StepRecorderWidget.h"
#include "PianoRoll.h"
namespace lmms
{
using std::min;
using std::max;
const int REMOVE_RELEASED_NOTE_TIME_THRESHOLD_MS = 70;
StepRecorder::StepRecorder(gui::PianoRoll& pianoRoll, gui::StepRecorderWidget& stepRecorderWidget):
m_pianoRoll(pianoRoll),
m_stepRecorderWidget(stepRecorderWidget),
m_midiClip(nullptr)
{
m_stepRecorderWidget.hide();
}
void StepRecorder::initialize()
{
connect(&m_updateReleasedTimer, SIGNAL(timeout()), this, SLOT(removeNotesReleasedForTooLong()));
}
void StepRecorder::start(const TimePos& currentPosition, const TimePos& stepLength)
{
m_isRecording = true;
setStepsLength(stepLength);
// quantize current position to get start recording position
const int q = m_pianoRoll.quantization();
const int curPosTicks = currentPosition.getTicks();
const int QuantizedPosTicks = (curPosTicks / q) * q;
const TimePos& QuantizedPos = TimePos(QuantizedPosTicks);
m_curStepStartPos = QuantizedPos;
m_curStepLength = 0;
m_stepRecorderWidget.show();
m_stepRecorderWidget.showHint();
prepareNewStep();
}
void StepRecorder::stop()
{
m_stepRecorderWidget.hide();
m_isRecording = false;
}
void StepRecorder::notePressed(const Note & n)
{
//if this is the first pressed note in step, advance position
if(!m_isStepInProgress)
{
m_isStepInProgress = true;
//move curser one step forwards
stepForwards();
}
StepNote* stepNote = findCurStepNote(n.key());
if(stepNote == nullptr)
{
m_curStepNotes.push_back(new StepNote(Note(m_curStepLength, m_curStepStartPos, n.key(), n.getVolume(), n.getPanning())));
m_pianoRoll.update();
}
else if (stepNote->isReleased())
{
stepNote->setPressed();
}
}
void StepRecorder::noteReleased(const Note & n)
{
StepNote* stepNote = findCurStepNote(n.key());
if(stepNote != nullptr && stepNote->isPressed())
{
stepNote->setReleased();
//if m_updateReleasedTimer is not already active, activate it
//(when activated, the timer will re-set itself as long as there are released notes)
if(!m_updateReleasedTimer.isActive())
{
m_updateReleasedTimer.start(REMOVE_RELEASED_NOTE_TIME_THRESHOLD_MS);
}
//check if all note are released, apply notes to clips (or dimiss if length is zero) and prepare to record next step
if(allCurStepNotesReleased())
{
if(m_curStepLength > 0)
{
applyStep();
}
else
{
dismissStep();
}
}
}
}
bool StepRecorder::keyPressEvent(QKeyEvent* ke)
{
bool event_handled = false;
switch(ke->key())
{
case Qt::Key_Right:
{
if(!ke->isAutoRepeat())
{
stepForwards();
}
event_handled = true;
break;
}
case Qt::Key_Left:
{
if(!ke->isAutoRepeat())
{
stepBackwards();
}
event_handled = true;
break;
}
}
return event_handled;
}
void StepRecorder::setStepsLength(const TimePos& newLength)
{
if(m_isStepInProgress)
{
//update current step length by the new amount : (number_of_steps * newLength)
m_curStepLength = (m_curStepLength / m_stepsLength) * newLength;
updateCurStepNotes();
}
m_stepsLength = newLength;
updateWidget();
}
std::vector<Note*> StepRecorder::getCurStepNotes()
{
std::vector<Note*> notes;
if(m_isStepInProgress)
{
for (StepNote* stepNote: m_curStepNotes)
{
notes.push_back(&stepNote->m_note);
}
}
return notes;
}
void StepRecorder::stepForwards()
{
if(m_isStepInProgress)
{
m_curStepLength += m_stepsLength;
updateCurStepNotes();
}
else
{
m_curStepStartPos += m_stepsLength;
}
updateWidget();
}
void StepRecorder::stepBackwards()
{
if(m_isStepInProgress)
{
if(m_curStepLength > 0)
{
m_curStepLength = max(m_curStepLength - m_stepsLength, 0);
}
else
{
//if length is already zero - move starting position backwards
m_curStepStartPos = max(m_curStepStartPos - m_stepsLength, 0);
}
updateCurStepNotes();
}
else
{
m_curStepStartPos = max(m_curStepStartPos - m_stepsLength, 0);
}
updateWidget();
}
void StepRecorder::applyStep()
{
m_midiClip->addJournalCheckPoint();
for (const StepNote* stepNote : m_curStepNotes)
{
m_midiClip->addNote(stepNote->m_note, false);
}
m_midiClip->rearrangeAllNotes();
m_midiClip->updateLength();
m_midiClip->dataChanged();
Engine::getSong()->setModified();
prepareNewStep();
}
void StepRecorder::dismissStep()
{
if(!m_isStepInProgress)
{
return;
}
prepareNewStep();
}
void StepRecorder::prepareNewStep()
{
for(StepNote* stepNote : m_curStepNotes)
{
delete stepNote;
}
m_curStepNotes.clear();
m_isStepInProgress = false;
m_curStepStartPos = getCurStepEndPos();
m_curStepLength = 0;
updateWidget();
}
void StepRecorder::setCurrentMidiClip( MidiClip* newMidiClip )
{
if(m_midiClip != nullptr && m_midiClip != newMidiClip)
{
dismissStep();
}
m_midiClip = newMidiClip;
}
void StepRecorder::removeNotesReleasedForTooLong()
{
int nextTimout = std::numeric_limits<int>::max();
bool notesRemoved = false;
for (const auto& stepNote : m_curStepNotes)
{
if (stepNote->isReleased())
{
const int timeSinceReleased = stepNote->timeSinceReleased(); // capture value to avoid wraparound when calculting nextTimout
if (timeSinceReleased >= REMOVE_RELEASED_NOTE_TIME_THRESHOLD_MS)
{
notesRemoved = true;
}
else
{
nextTimout = min(nextTimout, REMOVE_RELEASED_NOTE_TIME_THRESHOLD_MS - timeSinceReleased);
}
}
}
m_curStepNotes.erase(std::remove_if(m_curStepNotes.begin(), m_curStepNotes.end(), [](auto stepNote)
{
bool shouldRemove = stepNote->isReleased() && stepNote->timeSinceReleased() >= REMOVE_RELEASED_NOTE_TIME_THRESHOLD_MS;
if (shouldRemove)
{
delete stepNote;
}
return shouldRemove;
}), m_curStepNotes.end());
if(notesRemoved)
{
m_pianoRoll.update();
}
if(nextTimout != std::numeric_limits<int>::max())
{
m_updateReleasedTimer.start(nextTimout);
}
else
{
// no released note found for next timout, stop timer
m_updateReleasedTimer.stop();
}
}
TimePos StepRecorder::getCurStepEndPos()
{
return m_curStepStartPos + m_curStepLength;
}
void StepRecorder::updateCurStepNotes()
{
for (StepNote* stepNote : m_curStepNotes)
{
stepNote->m_note.setLength(m_curStepLength);
stepNote->m_note.setPos(m_curStepStartPos);
}
}
void StepRecorder::updateWidget()
{
m_stepRecorderWidget.setStartPosition(m_curStepStartPos);
m_stepRecorderWidget.setEndPosition(getCurStepEndPos());
m_stepRecorderWidget.setStepsLength(m_stepsLength);
}
bool StepRecorder::allCurStepNotesReleased()
{
for (const StepNote* stepNote : m_curStepNotes)
{
if(stepNote->isPressed())
{
return false;
}
}
return true;
}
StepRecorder::StepNote* StepRecorder::findCurStepNote(const int key)
{
for (StepNote* stepNote : m_curStepNotes)
{
if(stepNote->m_note.key() == key)
{
return stepNote;
}
}
return nullptr;
}
} // namespace lmms
| 7,677
|
C++
|
.cpp
| 313
| 22.095847
| 127
| 0.744416
|
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,823
|
Sample.cpp
|
LMMS_lmms/src/core/Sample.cpp
|
/*
* Sample.cpp - State for container-class SampleBuffer
*
* Copyright (c) 2023 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 "Sample.h"
#include "lmms_math.h"
#include <cassert>
namespace lmms {
Sample::Sample(const QString& audioFile)
: m_buffer(std::make_shared<SampleBuffer>(audioFile))
, m_startFrame(0)
, m_endFrame(m_buffer->size())
, m_loopStartFrame(0)
, m_loopEndFrame(m_buffer->size())
{
}
Sample::Sample(const QByteArray& base64, int sampleRate)
: m_buffer(std::make_shared<SampleBuffer>(base64, sampleRate))
, m_startFrame(0)
, m_endFrame(m_buffer->size())
, m_loopStartFrame(0)
, m_loopEndFrame(m_buffer->size())
{
}
Sample::Sample(const SampleFrame* data, size_t numFrames, int sampleRate)
: m_buffer(std::make_shared<SampleBuffer>(data, numFrames, sampleRate))
, m_startFrame(0)
, m_endFrame(m_buffer->size())
, m_loopStartFrame(0)
, m_loopEndFrame(m_buffer->size())
{
}
Sample::Sample(std::shared_ptr<const SampleBuffer> buffer)
: m_buffer(buffer)
, m_startFrame(0)
, m_endFrame(m_buffer->size())
, m_loopStartFrame(0)
, m_loopEndFrame(m_buffer->size())
{
}
Sample::Sample(const Sample& other)
: m_buffer(other.m_buffer)
, m_startFrame(other.startFrame())
, m_endFrame(other.endFrame())
, m_loopStartFrame(other.loopStartFrame())
, m_loopEndFrame(other.loopEndFrame())
, m_amplification(other.amplification())
, m_frequency(other.frequency())
, m_reversed(other.reversed())
{
}
Sample::Sample(Sample&& other)
: m_buffer(std::move(other.m_buffer))
, m_startFrame(other.startFrame())
, m_endFrame(other.endFrame())
, m_loopStartFrame(other.loopStartFrame())
, m_loopEndFrame(other.loopEndFrame())
, m_amplification(other.amplification())
, m_frequency(other.frequency())
, m_reversed(other.reversed())
{
}
auto Sample::operator=(const Sample& other) -> Sample&
{
m_buffer = other.m_buffer;
m_startFrame = other.startFrame();
m_endFrame = other.endFrame();
m_loopStartFrame = other.loopStartFrame();
m_loopEndFrame = other.loopEndFrame();
m_amplification = other.amplification();
m_frequency = other.frequency();
m_reversed = other.reversed();
return *this;
}
auto Sample::operator=(Sample&& other) -> Sample&
{
m_buffer = std::move(other.m_buffer);
m_startFrame = other.startFrame();
m_endFrame = other.endFrame();
m_loopStartFrame = other.loopStartFrame();
m_loopEndFrame = other.loopEndFrame();
m_amplification = other.amplification();
m_frequency = other.frequency();
m_reversed = other.reversed();
return *this;
}
bool Sample::play(SampleFrame* dst, PlaybackState* state, size_t numFrames, float desiredFrequency, Loop loopMode) const
{
assert(numFrames > 0);
assert(desiredFrequency > 0);
const auto pastBounds = state->m_frameIndex >= m_endFrame || (state->m_frameIndex < 0 && state->m_backwards);
if (loopMode == Loop::Off && pastBounds) { return false; }
const auto outputSampleRate = Engine::audioEngine()->outputSampleRate() * m_frequency / desiredFrequency;
const auto inputSampleRate = m_buffer->sampleRate();
const auto resampleRatio = outputSampleRate / inputSampleRate;
const auto marginSize = s_interpolationMargins[state->resampler().interpolationMode()];
state->m_frameIndex = std::max<int>(m_startFrame, state->m_frameIndex);
auto playBuffer = std::vector<SampleFrame>(numFrames / resampleRatio + marginSize);
playRaw(playBuffer.data(), playBuffer.size(), state, loopMode);
state->resampler().setRatio(resampleRatio);
const auto resampleResult
= state->resampler().resample(&playBuffer[0][0], playBuffer.size(), &dst[0][0], numFrames, resampleRatio);
advance(state, resampleResult.inputFramesUsed, loopMode);
const auto outputFrames = static_cast<f_cnt_t>(resampleResult.outputFramesGenerated);
if (outputFrames < numFrames) { std::fill_n(dst + outputFrames, numFrames - outputFrames, SampleFrame{}); }
if (!approximatelyEqual(m_amplification, 1.0f))
{
for (auto i = std::size_t{0}; i < numFrames; ++i)
{
dst[i][0] *= m_amplification;
dst[i][1] *= m_amplification;
}
}
return true;
}
auto Sample::sampleDuration() const -> std::chrono::milliseconds
{
const auto numFrames = endFrame() - startFrame();
const auto duration = numFrames / static_cast<float>(m_buffer->sampleRate()) * 1000;
return std::chrono::milliseconds{static_cast<int>(duration)};
}
void Sample::setAllPointFrames(int startFrame, int endFrame, int loopStartFrame, int loopEndFrame)
{
setStartFrame(startFrame);
setEndFrame(endFrame);
setLoopStartFrame(loopStartFrame);
setLoopEndFrame(loopEndFrame);
}
void Sample::playRaw(SampleFrame* dst, size_t numFrames, const PlaybackState* state, Loop loopMode) const
{
if (m_buffer->size() < 1) { return; }
auto index = state->m_frameIndex;
auto backwards = state->m_backwards;
for (size_t i = 0; i < numFrames; ++i)
{
switch (loopMode)
{
case Loop::Off:
if (index < 0 || index >= m_endFrame) { return; }
break;
case Loop::On:
if (index < m_loopStartFrame && backwards) { index = m_loopEndFrame - 1; }
else if (index >= m_loopEndFrame) { index = m_loopStartFrame; }
break;
case Loop::PingPong:
if (index < m_loopStartFrame && backwards)
{
index = m_loopStartFrame;
backwards = false;
}
else if (index >= m_loopEndFrame)
{
index = m_loopEndFrame - 1;
backwards = true;
}
break;
default:
break;
}
dst[i] = m_buffer->data()[m_reversed ? m_buffer->size() - index - 1 : index];
backwards ? --index : ++index;
}
}
void Sample::advance(PlaybackState* state, size_t advanceAmount, Loop loopMode) const
{
state->m_frameIndex += (state->m_backwards ? -1 : 1) * advanceAmount;
if (loopMode == Loop::Off) { return; }
const auto distanceFromLoopStart = std::abs(state->m_frameIndex - m_loopStartFrame);
const auto distanceFromLoopEnd = std::abs(state->m_frameIndex - m_loopEndFrame);
const auto loopSize = m_loopEndFrame - m_loopStartFrame;
if (loopSize == 0) { return; }
switch (loopMode)
{
case Loop::On:
if (state->m_frameIndex < m_loopStartFrame && state->m_backwards)
{
state->m_frameIndex = m_loopEndFrame - 1 - distanceFromLoopStart % loopSize;
}
else if (state->m_frameIndex >= m_loopEndFrame)
{
state->m_frameIndex = m_loopStartFrame + distanceFromLoopEnd % loopSize;
}
break;
case Loop::PingPong:
if (state->m_frameIndex < m_loopStartFrame && state->m_backwards)
{
state->m_frameIndex = m_loopStartFrame + distanceFromLoopStart % loopSize;
state->m_backwards = false;
}
else if (state->m_frameIndex >= m_loopEndFrame)
{
state->m_frameIndex = m_loopEndFrame - 1 - distanceFromLoopEnd % loopSize;
state->m_backwards = true;
}
break;
default:
break;
}
}
} // namespace lmms
| 7,467
|
C++
|
.cpp
| 219
| 31.771689
| 120
| 0.727197
|
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,824
|
PatternClip.cpp
|
LMMS_lmms/src/core/PatternClip.cpp
|
/*
* PatternClip.cpp - implementation of class PatternClip
*
* 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 "PatternClip.h"
#include <QDomElement>
#include "Engine.h"
#include "PatternClipView.h"
#include "PatternStore.h"
#include "PatternTrack.h"
namespace lmms
{
PatternClip::PatternClip(Track* track) :
Clip(track)
{
bar_t t = Engine::patternStore()->lengthOfPattern(patternIndex());
if( t > 0 )
{
saveJournallingState( false );
changeLength( TimePos( t, 0 ) );
restoreJournallingState();
}
setAutoResize( false );
}
void PatternClip::saveSettings(QDomDocument& doc, QDomElement& element)
{
element.setAttribute( "name", name() );
if( element.parentNode().nodeName() == "clipboard" )
{
element.setAttribute( "pos", -1 );
}
else
{
element.setAttribute( "pos", startPosition() );
}
element.setAttribute( "len", length() );
element.setAttribute("off", startTimeOffset());
element.setAttribute( "muted", isMuted() );
if (const auto& c = color())
{
element.setAttribute("color", c->name());
}
}
void PatternClip::loadSettings(const QDomElement& element)
{
setName( element.attribute( "name" ) );
if( element.attribute( "pos" ).toInt() >= 0 )
{
movePosition( element.attribute( "pos" ).toInt() );
}
changeLength( element.attribute( "len" ).toInt() );
setStartTimeOffset(element.attribute("off").toInt());
if (static_cast<bool>(element.attribute("muted").toInt()) != isMuted())
{
toggleMute();
}
if (element.hasAttribute("color"))
{
if (!element.hasAttribute("usestyle"))
{
// for colors saved in 1.3-onwards
setColor(QColor{element.attribute("color")});
}
else if (element.attribute("usestyle").toUInt() == 0)
{
// for colors saved before 1.3
setColor(QColor{element.attribute("color").toUInt()});
}
}
}
int PatternClip::patternIndex()
{
return dynamic_cast<PatternTrack*>(getTrack())->patternIndex();
}
gui::ClipView* PatternClip::createView(gui::TrackView* tv)
{
return new gui::PatternClipView(this, tv);
}
} // namespace lmms
| 2,860
|
C++
|
.cpp
| 98
| 26.969388
| 77
| 0.724982
|
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,825
|
EnvelopeAndLfoParameters.cpp
|
LMMS_lmms/src/core/EnvelopeAndLfoParameters.cpp
|
/*
* EnvelopeAndLfoParameters.cpp - class EnvelopeAndLfoParameters
*
* 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 "EnvelopeAndLfoParameters.h"
#include <QDomElement>
#include <QFileInfo>
#include "AudioEngine.h"
#include "Engine.h"
#include "Oscillator.h"
#include "PathUtil.h"
#include "SampleLoader.h"
#include "Song.h"
namespace lmms
{
// how long should be each envelope-segment maximal (e.g. attack)?
extern const float SECS_PER_ENV_SEGMENT = 5.0f;
// how long should be one LFO-oscillation maximal?
extern const float SECS_PER_LFO_OSCILLATION = 20.0f;
// minimum number of frames for ENV/LFO stages that mustn't be '0'
const f_cnt_t minimumFrames = 1;
EnvelopeAndLfoParameters::LfoInstances * EnvelopeAndLfoParameters::s_lfoInstances = nullptr;
void EnvelopeAndLfoParameters::LfoInstances::trigger()
{
QMutexLocker m( &m_lfoListMutex );
for (const auto& lfo : m_lfos)
{
lfo->m_lfoFrame += Engine::audioEngine()->framesPerPeriod();
lfo->m_bad_lfoShapeData = true;
}
}
void EnvelopeAndLfoParameters::LfoInstances::reset()
{
QMutexLocker m( &m_lfoListMutex );
for (const auto& lfo : m_lfos)
{
lfo->m_lfoFrame = 0;
lfo->m_bad_lfoShapeData = true;
}
}
void EnvelopeAndLfoParameters::LfoInstances::add( EnvelopeAndLfoParameters * lfo )
{
QMutexLocker m( &m_lfoListMutex );
m_lfos.append( lfo );
}
void EnvelopeAndLfoParameters::LfoInstances::remove( EnvelopeAndLfoParameters * lfo )
{
QMutexLocker m( &m_lfoListMutex );
m_lfos.removeAll( lfo );
}
EnvelopeAndLfoParameters::EnvelopeAndLfoParameters(
float _value_for_zero_amount,
Model * _parent ) :
Model( _parent ),
m_used( false ),
m_predelayModel(0.f, 0.f, 2.f, 0.001f, this, tr("Env pre-delay")),
m_attackModel(0.f, 0.f, 2.f, 0.001f, this, tr("Env attack")),
m_holdModel(0.5f, 0.f, 2.f, 0.001f, this, tr("Env hold")),
m_decayModel(0.5f, 0.f, 2.f, 0.001f, this, tr("Env decay")),
m_sustainModel(0.5f, 0.f, 1.f, 0.001f, this, tr("Env sustain")),
m_releaseModel(0.1f, 0.f, 2.f, 0.001f, this, tr("Env release")),
m_amountModel(0.f, -1.f, 1.f, 0.005f, this, tr("Env mod amount")),
m_valueForZeroAmount( _value_for_zero_amount ),
m_pahdFrames( 0 ),
m_rFrames( 0 ),
m_pahdEnv( nullptr ),
m_rEnv( nullptr ),
m_pahdBufSize( 0 ),
m_rBufSize( 0 ),
m_lfoPredelayModel(0.f, 0.f, 1.f, 0.001f, this, tr("LFO pre-delay")),
m_lfoAttackModel(0.f, 0.f, 1.f, 0.001f, this, tr("LFO attack")),
m_lfoSpeedModel(0.1f, 0.001f, 1.f, 0.0001f,
SECS_PER_LFO_OSCILLATION * 1000.f, this,
tr("LFO frequency")),
m_lfoAmountModel(0.f, -1.f, 1.f, 0.005f, this, tr("LFO mod amount")),
m_lfoWaveModel( static_cast<int>(LfoShape::SineWave), 0, NumLfoShapes, this, tr( "LFO wave shape" ) ),
m_x100Model( false, this, tr( "LFO frequency x 100" ) ),
m_controlEnvAmountModel( false, this, tr( "Modulate env amount" ) ),
m_lfoFrame( 0 ),
m_lfoAmountIsZero( false ),
m_lfoShapeData(nullptr)
{
m_amountModel.setCenterValue( 0 );
m_lfoAmountModel.setCenterValue( 0 );
if( s_lfoInstances == nullptr )
{
s_lfoInstances = new LfoInstances();
}
instances()->add( this );
connect( &m_predelayModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_attackModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_holdModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_decayModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_sustainModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_releaseModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_amountModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_lfoPredelayModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_lfoAttackModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_lfoSpeedModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_lfoAmountModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_lfoWaveModel, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( &m_x100Model, SIGNAL(dataChanged()),
this, SLOT(updateSampleVars()), Qt::DirectConnection );
connect( Engine::audioEngine(), SIGNAL(sampleRateChanged()),
this, SLOT(updateSampleVars()));
m_lfoShapeData =
new sample_t[Engine::audioEngine()->framesPerPeriod()];
updateSampleVars();
}
EnvelopeAndLfoParameters::~EnvelopeAndLfoParameters()
{
m_predelayModel.disconnect( this );
m_attackModel.disconnect( this );
m_holdModel.disconnect( this );
m_decayModel.disconnect( this );
m_sustainModel.disconnect( this );
m_releaseModel.disconnect( this );
m_amountModel.disconnect( this );
m_lfoPredelayModel.disconnect( this );
m_lfoAttackModel.disconnect( this );
m_lfoSpeedModel.disconnect( this );
m_lfoAmountModel.disconnect( this );
m_lfoWaveModel.disconnect( this );
m_x100Model.disconnect( this );
delete[] m_pahdEnv;
delete[] m_rEnv;
delete[] m_lfoShapeData;
instances()->remove( this );
if( instances()->isEmpty() )
{
delete instances();
s_lfoInstances = nullptr;
}
}
inline sample_t EnvelopeAndLfoParameters::lfoShapeSample( fpp_t _frame_offset )
{
f_cnt_t frame = ( m_lfoFrame + _frame_offset ) % m_lfoOscillationFrames;
const float phase = frame / static_cast<float>(
m_lfoOscillationFrames );
sample_t shape_sample;
switch( static_cast<LfoShape>(m_lfoWaveModel.value()) )
{
case LfoShape::TriangleWave:
shape_sample = Oscillator::triangleSample( phase );
break;
case LfoShape::SquareWave:
shape_sample = Oscillator::squareSample( phase );
break;
case LfoShape::SawWave:
shape_sample = Oscillator::sawSample( phase );
break;
case LfoShape::UserDefinedWave:
shape_sample = Oscillator::userWaveSample(m_userWave.get(), phase);
break;
case LfoShape::RandomWave:
if( frame == 0 )
{
m_random = Oscillator::noiseSample( 0.0f );
}
shape_sample = m_random;
break;
case LfoShape::SineWave:
default:
shape_sample = Oscillator::sinSample( phase );
break;
}
return shape_sample * m_lfoAmount;
}
void EnvelopeAndLfoParameters::updateLfoShapeData()
{
const fpp_t frames = Engine::audioEngine()->framesPerPeriod();
for( fpp_t offset = 0; offset < frames; ++offset )
{
m_lfoShapeData[offset] = lfoShapeSample( offset );
}
m_bad_lfoShapeData = false;
}
inline void EnvelopeAndLfoParameters::fillLfoLevel( float * _buf,
f_cnt_t _frame,
const fpp_t _frames )
{
if( m_lfoAmountIsZero || _frame <= m_lfoPredelayFrames )
{
for( fpp_t offset = 0; offset < _frames; ++offset )
{
*_buf++ = 0.0f;
}
return;
}
_frame -= m_lfoPredelayFrames;
if( m_bad_lfoShapeData )
{
updateLfoShapeData();
}
fpp_t offset = 0;
const float lafI = 1.0f / std::max(minimumFrames, m_lfoAttackFrames);
for( ; offset < _frames && _frame < m_lfoAttackFrames; ++offset,
++_frame )
{
*_buf++ = m_lfoShapeData[offset] * _frame * lafI;
}
for( ; offset < _frames; ++offset )
{
*_buf++ = m_lfoShapeData[offset];
}
}
void EnvelopeAndLfoParameters::fillLevel( float * _buf, f_cnt_t _frame,
const f_cnt_t _release_begin,
const fpp_t _frames )
{
QMutexLocker m(&m_paramMutex);
fillLfoLevel( _buf, _frame, _frames );
for( fpp_t offset = 0; offset < _frames; ++offset, ++_buf, ++_frame )
{
float env_level;
if( _frame < _release_begin )
{
if( _frame < m_pahdFrames )
{
env_level = m_pahdEnv[_frame];
}
else
{
env_level = m_sustainLevel;
}
}
else if( ( _frame - _release_begin ) < m_rFrames )
{
env_level = m_rEnv[_frame - _release_begin] *
( ( _release_begin < m_pahdFrames ) ?
m_pahdEnv[_release_begin] : m_sustainLevel );
}
else
{
env_level = 0.0f;
}
// at this point, *_buf is LFO level
*_buf = m_controlEnvAmountModel.value() ?
env_level * ( 0.5f + *_buf ) :
env_level + *_buf;
}
}
void EnvelopeAndLfoParameters::saveSettings( QDomDocument & _doc,
QDomElement & _parent )
{
m_predelayModel.saveSettings( _doc, _parent, "pdel" );
m_attackModel.saveSettings( _doc, _parent, "att" );
m_holdModel.saveSettings( _doc, _parent, "hold" );
m_decayModel.saveSettings( _doc, _parent, "dec" );
m_sustainModel.saveSettings( _doc, _parent, "sustain" );
m_releaseModel.saveSettings( _doc, _parent, "rel" );
m_amountModel.saveSettings( _doc, _parent, "amt" );
m_lfoWaveModel.saveSettings( _doc, _parent, "lshp" );
m_lfoPredelayModel.saveSettings( _doc, _parent, "lpdel" );
m_lfoAttackModel.saveSettings( _doc, _parent, "latt" );
m_lfoSpeedModel.saveSettings( _doc, _parent, "lspd" );
m_lfoAmountModel.saveSettings( _doc, _parent, "lamt" );
m_x100Model.saveSettings( _doc, _parent, "x100" );
m_controlEnvAmountModel.saveSettings( _doc, _parent, "ctlenvamt" );
_parent.setAttribute("userwavefile", m_userWave->audioFile());
}
void EnvelopeAndLfoParameters::loadSettings( const QDomElement & _this )
{
m_predelayModel.loadSettings( _this, "pdel" );
m_attackModel.loadSettings( _this, "att" );
m_holdModel.loadSettings( _this, "hold" );
m_decayModel.loadSettings( _this, "dec" );
m_sustainModel.loadSettings( _this, "sustain" );
m_releaseModel.loadSettings( _this, "rel" );
m_amountModel.loadSettings( _this, "amt" );
m_lfoWaveModel.loadSettings( _this, "lshp" );
m_lfoPredelayModel.loadSettings( _this, "lpdel" );
m_lfoAttackModel.loadSettings( _this, "latt" );
m_lfoSpeedModel.loadSettings( _this, "lspd" );
m_lfoAmountModel.loadSettings( _this, "lamt" );
m_x100Model.loadSettings( _this, "x100" );
m_controlEnvAmountModel.loadSettings( _this, "ctlenvamt" );
/* ### TODO:
Old reversed sustain kept for backward compatibility
with 4.15 file format*/
if( _this.hasAttribute( "sus" ) )
{
m_sustainModel.loadSettings( _this, "sus" );
m_sustainModel.setValue( 1.0 - m_sustainModel.value() );
}
if (const auto userWaveFile = _this.attribute("userwavefile"); !userWaveFile.isEmpty())
{
if (QFileInfo(PathUtil::toAbsolute(userWaveFile)).exists())
{
m_userWave = gui::SampleLoader::createBufferFromFile(_this.attribute("userwavefile"));
}
else { Engine::getSong()->collectError(QString("%1: %2").arg(tr("Sample not found"), userWaveFile)); }
}
updateSampleVars();
}
void EnvelopeAndLfoParameters::updateSampleVars()
{
QMutexLocker m(&m_paramMutex);
const float frames_per_env_seg = SECS_PER_ENV_SEGMENT *
Engine::audioEngine()->outputSampleRate();
// TODO: Remove the expKnobVals, time should be linear
const auto predelay_frames = static_cast<f_cnt_t>(frames_per_env_seg * expKnobVal(m_predelayModel.value()));
const f_cnt_t attack_frames = std::max(minimumFrames,
static_cast<f_cnt_t>(frames_per_env_seg *
expKnobVal(m_attackModel.value())));
const auto hold_frames = static_cast<f_cnt_t>(frames_per_env_seg * expKnobVal(m_holdModel.value()));
const f_cnt_t decay_frames = std::max(minimumFrames,
static_cast<f_cnt_t>(frames_per_env_seg *
expKnobVal(m_decayModel.value() *
(1 - m_sustainModel.value()))));
m_sustainLevel = m_sustainModel.value();
m_amount = m_amountModel.value();
if( m_amount >= 0 )
{
m_amountAdd = ( 1.0f - m_amount ) * m_valueForZeroAmount;
}
else
{
m_amountAdd = m_valueForZeroAmount;
}
m_pahdFrames = predelay_frames + attack_frames + hold_frames +
decay_frames;
m_rFrames = static_cast<f_cnt_t>( frames_per_env_seg *
expKnobVal( m_releaseModel.value() ) );
m_rFrames = std::max(minimumFrames, m_rFrames);
if( static_cast<int>( floorf( m_amount * 1000.0f ) ) == 0 )
{
m_rFrames = minimumFrames;
}
// if the buffers are too small, make bigger ones - so we only alloc new memory when necessary
if( m_pahdBufSize < m_pahdFrames )
{
sample_t * tmp = m_pahdEnv;
m_pahdEnv = new sample_t[m_pahdFrames];
delete[] tmp;
m_pahdBufSize = m_pahdFrames;
}
if( m_rBufSize < m_rFrames )
{
sample_t * tmp = m_rEnv;
m_rEnv = new sample_t[m_rFrames];
delete[] tmp;
m_rBufSize = m_rFrames;
}
const float aa = m_amountAdd;
for( f_cnt_t i = 0; i < predelay_frames; ++i )
{
m_pahdEnv[i] = aa;
}
f_cnt_t add = predelay_frames;
const float afI = ( 1.0f / attack_frames ) * m_amount;
for( f_cnt_t i = 0; i < attack_frames; ++i )
{
m_pahdEnv[add+i] = i * afI + aa;
}
add += attack_frames;
const float amsum = m_amount + m_amountAdd;
for( f_cnt_t i = 0; i < hold_frames; ++i )
{
m_pahdEnv[add + i] = amsum;
}
add += hold_frames;
const float dfI = ( 1.0 / decay_frames ) * ( m_sustainLevel -1 ) * m_amount;
for( f_cnt_t i = 0; i < decay_frames; ++i )
{
/*
m_pahdEnv[add + i] = ( m_sustainLevel + ( 1.0f -
(float)i / decay_frames ) *
( 1.0f - m_sustainLevel ) ) *
m_amount + m_amountAdd;
*/
m_pahdEnv[add + i] = amsum + i*dfI;
}
const float rfI = ( 1.0f / m_rFrames ) * m_amount;
for( f_cnt_t i = 0; i < m_rFrames; ++i )
{
m_rEnv[i] = (float)( m_rFrames - i ) * rfI;
}
// save this calculation in real-time-part
m_sustainLevel = m_sustainLevel * m_amount + m_amountAdd;
const float frames_per_lfo_oscillation = SECS_PER_LFO_OSCILLATION *
Engine::audioEngine()->outputSampleRate();
m_lfoPredelayFrames = static_cast<f_cnt_t>( frames_per_lfo_oscillation *
expKnobVal( m_lfoPredelayModel.value() ) );
m_lfoAttackFrames = static_cast<f_cnt_t>( frames_per_lfo_oscillation *
expKnobVal( m_lfoAttackModel.value() ) );
m_lfoOscillationFrames = static_cast<f_cnt_t>(
frames_per_lfo_oscillation *
m_lfoSpeedModel.value() );
if( m_x100Model.value() )
{
m_lfoOscillationFrames /= 100;
}
m_lfoAmount = m_lfoAmountModel.value() * 0.5f;
m_used = true;
if( static_cast<int>( floorf( m_lfoAmount * 1000.0f ) ) == 0 )
{
m_lfoAmountIsZero = true;
if( static_cast<int>( floorf( m_amount * 1000.0f ) ) == 0 )
{
m_used = false;
}
}
else
{
m_lfoAmountIsZero = false;
}
m_bad_lfoShapeData = true;
emit dataChanged();
}
} // namespace lmms
| 15,069
|
C++
|
.cpp
| 442
| 31.330317
| 109
| 0.699215
|
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,826
|
MidiPort.cpp
|
LMMS_lmms/src/core/midi/MidiPort.cpp
|
/*
* MidiPort.cpp - abstraction of MIDI-ports which are part of LMMS's MIDI-
* sequencing system
*
* 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 <QDomElement>
#include "MidiPort.h"
#include "MidiClient.h"
#include "MidiDummy.h"
#include "MidiEventProcessor.h"
#include "Note.h"
#include "Song.h"
#include "MidiController.h"
namespace lmms
{
static MidiDummy s_dummyClient;
MidiPort::MidiPort( const QString& name,
MidiClient* client,
MidiEventProcessor* eventProcessor,
Model* parent,
Mode mode ) :
Model( parent ),
m_readablePortsMenu( nullptr ),
m_writablePortsMenu( nullptr ),
m_midiClient( client ),
m_midiEventProcessor( eventProcessor ),
m_mode( mode ),
m_inputChannelModel( 0, 0, MidiChannelCount, this, tr( "Input channel" ) ),
m_outputChannelModel( 1, 0, MidiChannelCount, this, tr( "Output channel" ) ),
m_inputControllerModel(MidiController::NONE, MidiController::NONE, MidiControllerCount - 1, this, tr( "Input controller" )),
m_outputControllerModel(MidiController::NONE, MidiController::NONE, MidiControllerCount - 1, this, tr( "Output controller" )),
m_fixedInputVelocityModel( -1, -1, MidiMaxVelocity, this, tr( "Fixed input velocity" ) ),
m_fixedOutputVelocityModel( -1, -1, MidiMaxVelocity, this, tr( "Fixed output velocity" ) ),
m_fixedOutputNoteModel( -1, -1, MidiMaxKey, this, tr( "Fixed output note" ) ),
m_outputProgramModel( 1, 1, MidiProgramCount, this, tr( "Output MIDI program" ) ),
m_baseVelocityModel( MidiMaxVelocity/2, 1, MidiMaxVelocity, this, tr( "Base velocity" ) ),
m_readableModel( false, this, tr( "Receive MIDI-events" ) ),
m_writableModel( false, this, tr( "Send MIDI-events" ) )
{
m_midiClient->addPort( this );
m_readableModel.setValue( m_mode == Mode::Input || m_mode == Mode::Duplex );
m_writableModel.setValue( m_mode == Mode::Output || m_mode == Mode::Duplex );
connect( &m_readableModel, SIGNAL(dataChanged()),
this, SLOT(updateMidiPortMode()), Qt::DirectConnection );
connect( &m_writableModel, SIGNAL(dataChanged()),
this, SLOT(updateMidiPortMode()), Qt::DirectConnection );
connect( &m_outputProgramModel, SIGNAL(dataChanged()),
this, SLOT(updateOutputProgram()), Qt::DirectConnection );
// when using with non-raw-clients we can provide buttons showing
// our port-menus when being clicked
if( m_midiClient->isRaw() == false )
{
updateReadablePorts();
updateWritablePorts();
// we want to get informed about port-changes!
m_midiClient->connectRPChanged( this, SLOT(updateReadablePorts()));
m_midiClient->connectWPChanged( this, SLOT(updateWritablePorts()));
}
updateMidiPortMode();
}
MidiPort::~MidiPort()
{
// unsubscribe ports
m_readableModel.setValue( false );
m_writableModel.setValue( false );
// and finally unregister ourself
m_midiClient->removePort( this );
}
void MidiPort::setName( const QString& name )
{
setDisplayName( name );
m_midiClient->applyPortName( this );
}
void MidiPort::setMode( Mode mode )
{
m_mode = mode;
m_midiClient->applyPortMode( this );
}
void MidiPort::processInEvent( const MidiEvent& event, const TimePos& time )
{
// mask event
if( isInputEnabled() &&
( inputChannel() == 0 || inputChannel()-1 == event.channel() ) )
{
MidiEvent inEvent = event;
if( event.type() == MidiNoteOn ||
event.type() == MidiNoteOff ||
event.type() == MidiKeyPressure )
{
if( inEvent.key() < 0 || inEvent.key() >= NumKeys )
{
return;
}
if( fixedInputVelocity() >= 0 && inEvent.velocity() > 0 )
{
inEvent.setVelocity( fixedInputVelocity() );
}
}
m_midiEventProcessor->processInEvent( inEvent, time );
}
}
void MidiPort::processOutEvent( const MidiEvent& event, const TimePos& time )
{
// When output is enabled, route midi events if the selected channel matches
// the event channel or if there's no selected channel (value 0, represented by "--")
if( isOutputEnabled() && ( outputChannel() == 0 || realOutputChannel() == event.channel() ) )
{
MidiEvent outEvent = event;
if( fixedOutputVelocity() >= 0 && event.velocity() > 0 &&
( event.type() == MidiNoteOn || event.type() == MidiKeyPressure ) )
{
outEvent.setVelocity( fixedOutputVelocity() );
}
if( fixedOutputNote() >= 0 &&
( event.type() == MidiNoteOn || event.type() == MidiNoteOff || event.type() == MidiKeyPressure ) )
{
outEvent.setKey( fixedOutputNote() );
}
m_midiClient->processOutEvent( outEvent, time, this );
}
}
void MidiPort::saveSettings( QDomDocument& doc, QDomElement& thisElement )
{
m_inputChannelModel.saveSettings( doc, thisElement, "inputchannel" );
m_outputChannelModel.saveSettings( doc, thisElement, "outputchannel" );
m_inputControllerModel.saveSettings( doc, thisElement, "inputcontroller" );
m_outputControllerModel.saveSettings( doc, thisElement, "outputcontroller" );
m_fixedInputVelocityModel.saveSettings( doc, thisElement, "fixedinputvelocity" );
m_fixedOutputVelocityModel.saveSettings( doc, thisElement, "fixedoutputvelocity" );
m_fixedOutputNoteModel.saveSettings( doc, thisElement, "fixedoutputnote" );
m_outputProgramModel.saveSettings( doc, thisElement, "outputprogram" );
m_baseVelocityModel.saveSettings( doc, thisElement, "basevelocity" );
m_readableModel.saveSettings( doc, thisElement, "readable" );
m_writableModel.saveSettings( doc, thisElement, "writable" );
if( isInputEnabled() )
{
QString rp;
for( Map::ConstIterator it = m_readablePorts.begin(); it != m_readablePorts.end(); ++it )
{
if( it.value() )
{
rp += it.key() + ",";
}
}
// cut off comma
if( rp.length() > 0 )
{
rp.truncate( rp.length() - 1 );
}
thisElement.setAttribute( "inports", rp );
}
if( isOutputEnabled() )
{
QString wp;
for( Map::ConstIterator it = m_writablePorts.begin(); it != m_writablePorts.end(); ++it )
{
if( it.value() )
{
wp += it.key() + ",";
}
}
// cut off comma
if( wp.length() > 0 )
{
wp.truncate( wp.length() - 1 );
}
thisElement.setAttribute( "outports", wp );
}
}
void MidiPort::loadSettings( const QDomElement& thisElement )
{
m_inputChannelModel.loadSettings( thisElement, "inputchannel" );
m_outputChannelModel.loadSettings( thisElement, "outputchannel" );
m_inputControllerModel.loadSettings( thisElement, "inputcontroller" );
m_outputControllerModel.loadSettings( thisElement, "outputcontroller" );
m_fixedInputVelocityModel.loadSettings( thisElement, "fixedinputvelocity" );
m_fixedOutputVelocityModel.loadSettings( thisElement, "fixedoutputvelocity" );
m_fixedOutputNoteModel.loadSettings( thisElement, "fixedoutputnote" );
m_outputProgramModel.loadSettings( thisElement, "outputprogram" );
m_baseVelocityModel.loadSettings( thisElement, "basevelocity" );
m_readableModel.loadSettings( thisElement, "readable" );
m_writableModel.loadSettings( thisElement, "writable" );
// restore connections
if( isInputEnabled() )
{
QStringList rp = thisElement.attribute( "inports" ).split( ',' );
for( Map::ConstIterator it = m_readablePorts.begin(); it != m_readablePorts.end(); ++it )
{
if( it.value() != ( rp.indexOf( it.key() ) != -1 ) )
{
subscribeReadablePort( it.key() );
}
}
emit readablePortsChanged();
}
if( isOutputEnabled() )
{
QStringList wp = thisElement.attribute( "outports" ).split( ',' );
for( Map::ConstIterator it = m_writablePorts.begin(); it != m_writablePorts.end(); ++it )
{
if( it.value() != ( wp.indexOf( it.key() ) != -1 ) )
{
subscribeWritablePort( it.key() );
}
}
emit writablePortsChanged();
}
if( thisElement.hasAttribute( "basevelocity" ) == false )
{
// for projects created by LMMS < 0.9.92 there's no value for the base
// velocity and for compat reasons we have to stick with maximum velocity
// which did not allow note volumes > 100%
m_baseVelocityModel.setValue( MidiMaxVelocity );
}
}
void MidiPort::subscribeReadablePort( const QString& port, bool subscribe )
{
m_readablePorts[port] = subscribe;
// make sure, MIDI-port is configured for input
if( subscribe == true && !isInputEnabled() )
{
m_readableModel.setValue( true );
}
m_midiClient->subscribeReadablePort( this, port, subscribe );
}
void MidiPort::subscribeWritablePort( const QString& port, bool subscribe )
{
m_writablePorts[port] = subscribe;
// make sure, MIDI-port is configured for output
if( subscribe == true && !isOutputEnabled() )
{
m_writableModel.setValue( true );
}
m_midiClient->subscribeWritablePort( this, port, subscribe );
}
void MidiPort::updateMidiPortMode()
{
// this small lookup-table makes everything easier
static const Mode modeTable[2][2] =
{
{ Mode::Disabled, Mode::Output },
{ Mode::Input, Mode::Duplex }
} ;
setMode( modeTable[m_readableModel.value()][m_writableModel.value()] );
// check whether we have to dis-check items in connection-menu
if( !isInputEnabled() )
{
for( Map::ConstIterator it = m_readablePorts.begin(); it != m_readablePorts.end(); ++it )
{
// subscribed?
if( it.value() )
{
subscribeReadablePort( it.key(), false );
}
}
}
if( !isOutputEnabled() )
{
for( Map::ConstIterator it = m_writablePorts.begin(); it != m_writablePorts.end(); ++it )
{
// subscribed?
if( it.value() )
{
subscribeWritablePort( it.key(), false );
}
}
}
emit readablePortsChanged();
emit writablePortsChanged();
emit modeChanged();
if( Engine::getSong() )
{
Engine::getSong()->setModified();
}
}
void MidiPort::updateReadablePorts()
{
// first save all selected ports
QStringList selectedPorts;
for( Map::ConstIterator it = m_readablePorts.begin(); it != m_readablePorts.end(); ++it )
{
if( it.value() )
{
selectedPorts.push_back( it.key() );
}
}
m_readablePorts.clear();
const QStringList& wp = m_midiClient->readablePorts();
// now insert new ports and restore selections
for (const auto& port : wp)
{
m_readablePorts[port] = (selectedPorts.indexOf(port) != -1);
}
emit readablePortsChanged();
}
void MidiPort::updateWritablePorts()
{
// first save all selected ports
QStringList selectedPorts;
for( Map::ConstIterator it = m_writablePorts.begin(); it != m_writablePorts.end(); ++it )
{
if( it.value() )
{
selectedPorts.push_back( it.key() );
}
}
m_writablePorts.clear();
const QStringList & wp = m_midiClient->writablePorts();
// now insert new ports and restore selections
for (const auto& port : wp)
{
m_writablePorts[port] = (selectedPorts.indexOf(port) != -1);
}
emit writablePortsChanged();
}
void MidiPort::updateOutputProgram()
{
processOutEvent( MidiEvent( MidiProgramChange, realOutputChannel(), outputProgram()-1 ) );
}
void MidiPort::invalidateCilent()
{
m_midiClient = &s_dummyClient;
}
} // namespace lmms
| 11,585
|
C++
|
.cpp
| 343
| 31.113703
| 127
| 0.716734
|
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,827
|
MidiOss.cpp
|
LMMS_lmms/src/core/midi/MidiOss.cpp
|
/*
* MidiOss.cpp - OSS raw MIDI client
*
* Copyright (c) 2005-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 "MidiOss.h"
#ifdef LMMS_HAVE_OSS
#include "ConfigManager.h"
namespace lmms
{
MidiOss::MidiOss() :
MidiClientRaw(),
m_midiDev( probeDevice() ),
m_quit( false )
{
// only start thread, if opening of MIDI-device is successful,
// otherwise isRunning()==false indicates error
if( m_midiDev.open( QIODevice::ReadWrite |
QIODevice::Unbuffered ) ||
m_midiDev.open( QIODevice::ReadOnly |
QIODevice::Unbuffered ) )
{
start( QThread::LowPriority );
}
}
MidiOss::~MidiOss()
{
if( isRunning() )
{
m_quit = true;
wait( 1000 );
terminate();
}
}
QString MidiOss::probeDevice()
{
QString dev = ConfigManager::inst()->value( "midioss", "device" );
if( dev.isEmpty() )
{
if( getenv( "MIDIDEV" ) != nullptr )
{
return getenv( "MIDIDEV" );
}
#ifdef __NetBSD__
return "/dev/rmidi0";
#else
return "/dev/midi";
#endif
}
return dev;
}
void MidiOss::sendByte( const unsigned char c )
{
m_midiDev.putChar( c );
}
void MidiOss::run()
{
while( m_quit == false && m_midiDev.isOpen() )
{
char c;
if( !m_midiDev.getChar( &c ) )
{
continue;
}
parseData( c );
}
}
} // namespace lmms
#endif // LMMS_HAVE_OSS
| 2,087
|
C++
|
.cpp
| 87
| 21.724138
| 77
| 0.707045
|
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,828
|
MidiAlsaSeq.cpp
|
LMMS_lmms/src/core/midi/MidiAlsaSeq.cpp
|
/*
* MidiAlsaSeq.cpp - ALSA sequencer client
*
* 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 "MidiAlsaSeq.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "Song.h"
#include "MidiPort.h"
#ifdef LMMS_HAVE_ALSA
namespace lmms
{
const int EventPollTimeOut = 250;
// static helper functions
static QString portName( snd_seq_client_info_t * _cinfo,
snd_seq_port_info_t * _pinfo )
{
return QString( "%1:%2 %3:%4" ).
arg( snd_seq_port_info_get_client( _pinfo ) ).
arg( snd_seq_port_info_get_port( _pinfo ) ).
arg( snd_seq_client_info_get_name( _cinfo ) ).
arg( snd_seq_port_info_get_name( _pinfo ) );
}
static QString portName( snd_seq_t * _seq, const snd_seq_addr_t * _addr )
{
snd_seq_client_info_t * cinfo;
snd_seq_port_info_t * pinfo;
snd_seq_client_info_malloc( &cinfo );
snd_seq_port_info_malloc( &pinfo );
snd_seq_get_any_port_info( _seq, _addr->client, _addr->port, pinfo );
snd_seq_get_any_client_info( _seq, _addr->client, cinfo );
const QString name = portName( cinfo, pinfo );
snd_seq_client_info_free( cinfo );
snd_seq_port_info_free( pinfo );
return name;
}
MidiAlsaSeq::MidiAlsaSeq() :
MidiClient(),
m_seqMutex(),
m_seqHandle( nullptr ),
m_queueID( -1 ),
m_quit( false ),
m_portListUpdateTimer( this )
{
if (int err = snd_seq_open(&m_seqHandle, probeDevice().toLatin1().constData(), SND_SEQ_OPEN_DUPLEX, 0); err < 0)
{
fprintf( stderr, "cannot open sequencer: %s\n",
snd_strerror( err ) );
return;
}
snd_seq_set_client_name( m_seqHandle, "LMMS" );
m_queueID = snd_seq_alloc_queue( m_seqHandle );
snd_seq_queue_tempo_t * tempo;
snd_seq_queue_tempo_malloc( &tempo );
snd_seq_queue_tempo_set_tempo( tempo, 6000000 /
Engine::getSong()->getTempo() );
snd_seq_queue_tempo_set_ppq( tempo, 16 );
snd_seq_set_queue_tempo( m_seqHandle, m_queueID, tempo );
snd_seq_queue_tempo_free( tempo );
snd_seq_start_queue( m_seqHandle, m_queueID, nullptr );
changeQueueTempo( Engine::getSong()->getTempo() );
connect( Engine::getSong(), SIGNAL(tempoChanged(lmms::bpm_t)),
this, SLOT(changeQueueTempo(lmms::bpm_t)), Qt::DirectConnection );
// initial list-update
updatePortList();
connect( &m_portListUpdateTimer, SIGNAL(timeout()),
this, SLOT(updatePortList()));
// we check for port-changes every second
m_portListUpdateTimer.start( 1000 );
// use a pipe to detect shutdown
if( pipe( m_pipe ) == -1 )
{
perror( "MidiAlsaSeq: pipe" );
}
start( QThread::IdlePriority );
}
MidiAlsaSeq::~MidiAlsaSeq()
{
if( isRunning() )
{
m_quit = true;
wait( EventPollTimeOut*2 );
m_seqMutex.lock();
snd_seq_stop_queue( m_seqHandle, m_queueID, nullptr );
snd_seq_free_queue( m_seqHandle, m_queueID );
snd_seq_close( m_seqHandle );
m_seqMutex.unlock();
}
}
QString MidiAlsaSeq::probeDevice()
{
QString dev = ConfigManager::inst()->value( "Midialsaseq", "device" );
if( dev.isEmpty() )
{
if( getenv( "MIDIDEV" ) != nullptr )
{
return getenv( "MIDIDEV" );
}
return "default";
}
return dev;
}
void MidiAlsaSeq::processOutEvent( const MidiEvent& event, const TimePos& time, const MidiPort* port )
{
// HACK!!! - need a better solution which isn't that easy since we
// cannot store const-ptrs in our map because we need to call non-const
// methods of MIDI-port - it's a mess...
auto p = const_cast<MidiPort*>(port);
snd_seq_event_t ev;
snd_seq_ev_clear( &ev );
snd_seq_ev_set_source( &ev, ( m_portIDs[p][1] != -1 ) ?
m_portIDs[p][1] : m_portIDs[p][0] );
snd_seq_ev_set_subs( &ev );
snd_seq_ev_schedule_tick( &ev, m_queueID, 1, static_cast<int>( time ) );
ev.queue = m_queueID;
switch( event.type() )
{
case MidiNoteOn:
snd_seq_ev_set_noteon( &ev,
event.channel(),
event.key(),
event.velocity() );
break;
case MidiNoteOff:
snd_seq_ev_set_noteoff( &ev,
event.channel(),
event.key(),
event.velocity() );
break;
case MidiKeyPressure:
snd_seq_ev_set_keypress( &ev,
event.channel(),
event.key(),
event.velocity() );
break;
case MidiControlChange:
snd_seq_ev_set_controller( &ev,
event.channel(),
event.controllerNumber(),
event.controllerValue() );
break;
case MidiProgramChange:
snd_seq_ev_set_pgmchange( &ev,
event.channel(),
event.program() );
break;
case MidiChannelPressure:
snd_seq_ev_set_chanpress( &ev,
event.channel(),
event.channelPressure() );
break;
case MidiPitchBend:
snd_seq_ev_set_pitchbend( &ev,
event.channel(),
event.param( 0 ) - 8192 );
break;
default:
qWarning( "MidiAlsaSeq: unhandled output event %d\n", (int) event.type() );
return;
}
m_seqMutex.lock();
snd_seq_event_output( m_seqHandle, &ev );
snd_seq_drain_output( m_seqHandle );
m_seqMutex.unlock();
}
void MidiAlsaSeq::applyPortMode( MidiPort * _port )
{
m_seqMutex.lock();
// determine port-capabilities
auto caps = std::array<unsigned int, 2>{};
switch( _port->mode() )
{
case MidiPort::Mode::Duplex:
caps[1] |= SND_SEQ_PORT_CAP_READ |
SND_SEQ_PORT_CAP_SUBS_READ;
case MidiPort::Mode::Input:
caps[0] |= SND_SEQ_PORT_CAP_WRITE |
SND_SEQ_PORT_CAP_SUBS_WRITE;
break;
case MidiPort::Mode::Output:
caps[1] |= SND_SEQ_PORT_CAP_READ |
SND_SEQ_PORT_CAP_SUBS_READ;
break;
default:
break;
}
for( int i = 0; i < 2; ++i )
{
if( caps[i] != 0 )
{
// no port there yet?
if( m_portIDs[_port][i] == -1 )
{
// then create one;
m_portIDs[_port][i] =
snd_seq_create_simple_port(
m_seqHandle,
_port->displayName().toUtf8().constData(),
caps[i],
SND_SEQ_PORT_TYPE_MIDI_GENERIC |
SND_SEQ_PORT_TYPE_APPLICATION );
continue;
}
snd_seq_port_info_t * port_info;
snd_seq_port_info_malloc( &port_info );
snd_seq_get_port_info( m_seqHandle, m_portIDs[_port][i],
port_info );
snd_seq_port_info_set_capability( port_info, caps[i] );
snd_seq_set_port_info( m_seqHandle, m_portIDs[_port][i],
port_info );
snd_seq_port_info_free( port_info );
}
// still a port there although no caps? ( = dummy port)
else if( m_portIDs[_port][i] != -1 )
{
// then remove this port
snd_seq_delete_simple_port( m_seqHandle,
m_portIDs[_port][i] );
m_portIDs[_port][i] = -1;
}
}
m_seqMutex.unlock();
}
void MidiAlsaSeq::applyPortName( MidiPort * _port )
{
m_seqMutex.lock();
for( int i = 0; i < 2; ++i )
{
if( m_portIDs[_port][i] == -1 )
{
continue;
}
snd_seq_port_info_t * port_info;
snd_seq_port_info_malloc( &port_info );
snd_seq_get_port_info( m_seqHandle, m_portIDs[_port][i],
port_info );
snd_seq_port_info_set_name( port_info,
_port->displayName().toUtf8().constData() );
snd_seq_set_port_info( m_seqHandle, m_portIDs[_port][i],
port_info );
snd_seq_port_info_free( port_info );
}
m_seqMutex.unlock();
}
void MidiAlsaSeq::removePort( MidiPort * _port )
{
if( m_portIDs.contains( _port ) )
{
m_seqMutex.lock();
snd_seq_delete_simple_port( m_seqHandle, m_portIDs[_port][0] );
snd_seq_delete_simple_port( m_seqHandle, m_portIDs[_port][1] );
m_seqMutex.unlock();
m_portIDs.remove( _port );
}
MidiClient::removePort( _port );
}
QString MidiAlsaSeq::sourcePortName( const MidiEvent & _event ) const
{
if( _event.sourcePort() )
{
const auto addr = static_cast<const snd_seq_addr_t*>(_event.sourcePort());
return portName( m_seqHandle, addr );
}
return MidiClient::sourcePortName( _event );
}
void MidiAlsaSeq::subscribeReadablePort( MidiPort * _port,
const QString & _dest,
bool _subscribe )
{
if( !m_portIDs.contains( _port ) || m_portIDs[_port][0] < 0 )
{
return;
}
m_seqMutex.lock();
snd_seq_addr_t sender;
if( snd_seq_parse_address( m_seqHandle, &sender,
_dest.section( ' ', 0, 0 ).toLatin1().constData() ) )
{
fprintf( stderr, "error parsing sender-address!\n" );
m_seqMutex.unlock();
return;
}
snd_seq_port_info_t * port_info;
snd_seq_port_info_malloc( &port_info );
snd_seq_get_port_info( m_seqHandle, m_portIDs[_port][0], port_info );
const snd_seq_addr_t * dest = snd_seq_port_info_get_addr( port_info );
snd_seq_port_subscribe_t * subs;
snd_seq_port_subscribe_malloc( &subs );
snd_seq_port_subscribe_set_sender( subs, &sender );
snd_seq_port_subscribe_set_dest( subs, dest );
if( _subscribe )
{
snd_seq_subscribe_port( m_seqHandle, subs );
}
else
{
snd_seq_unsubscribe_port( m_seqHandle, subs );
}
snd_seq_port_subscribe_free( subs );
snd_seq_port_info_free( port_info );
m_seqMutex.unlock();
}
void MidiAlsaSeq::subscribeWritablePort( MidiPort * _port,
const QString & _dest,
bool _subscribe )
{
if( !m_portIDs.contains( _port ) )
{
return;
}
const int pid = m_portIDs[_port][1] < 0 ? m_portIDs[_port][0] :
m_portIDs[_port][1];
if( pid < 0 )
{
return;
}
m_seqMutex.lock();
snd_seq_addr_t dest;
if( snd_seq_parse_address( m_seqHandle, &dest,
_dest.section( ' ', 0, 0 ).toLatin1().constData() ) )
{
fprintf( stderr, "error parsing dest-address!\n" );
m_seqMutex.unlock();
return;
}
snd_seq_port_info_t * port_info;
snd_seq_port_info_malloc( &port_info );
snd_seq_get_port_info( m_seqHandle, pid, port_info );
const snd_seq_addr_t * sender = snd_seq_port_info_get_addr( port_info );
snd_seq_port_subscribe_t * subs;
snd_seq_port_subscribe_malloc( &subs );
snd_seq_port_subscribe_set_sender( subs, sender );
snd_seq_port_subscribe_set_dest( subs, &dest );
if( _subscribe )
{
snd_seq_subscribe_port( m_seqHandle, subs );
}
else
{
snd_seq_unsubscribe_port( m_seqHandle, subs );
}
snd_seq_port_subscribe_free( subs );
snd_seq_port_info_free( port_info );
m_seqMutex.unlock();
}
void MidiAlsaSeq::run()
{
// watch the pipe and sequencer input events
int pollfd_count = snd_seq_poll_descriptors_count( m_seqHandle,
POLLIN );
auto pollfd_set = new struct pollfd[pollfd_count + 1];
snd_seq_poll_descriptors( m_seqHandle, pollfd_set + 1, pollfd_count,
POLLIN );
pollfd_set[0].fd = m_pipe[0];
pollfd_set[0].events = POLLIN;
++pollfd_count;
while( m_quit == false )
{
int pollRet = poll( pollfd_set, pollfd_count, EventPollTimeOut );
if( pollRet == 0 )
{
continue;
}
else if( pollRet == -1 )
{
// gdb may interrupt the poll
if( errno == EINTR )
{
continue;
}
qCritical( "error while polling ALSA sequencer handle" );
break;
}
// shutdown?
if( m_quit )
{
break;
}
m_seqMutex.lock();
// while event queue is not empty
while( snd_seq_event_input_pending( m_seqHandle, true ) > 0 )
{
snd_seq_event_t * ev;
if( snd_seq_event_input( m_seqHandle, &ev ) < 0 )
{
m_seqMutex.unlock();
qCritical( "error while fetching MIDI event from sequencer" );
break;
}
m_seqMutex.unlock();
snd_seq_addr_t * source = nullptr;
MidiPort * dest = nullptr;
for( int i = 0; i < m_portIDs.size(); ++i )
{
if( m_portIDs.values()[i][0] == ev->dest.port )
{
dest = m_portIDs.keys()[i];
}
if( ( m_portIDs.values()[i][1] != -1 &&
m_portIDs.values()[i][1] == ev->source.port ) ||
m_portIDs.values()[i][0] == ev->source.port )
{
source = &ev->source;
}
}
if( dest == nullptr )
{
continue;
}
switch( ev->type )
{
case SND_SEQ_EVENT_NOTEON:
dest->processInEvent( MidiEvent( MidiNoteOn,
ev->data.note.channel,
ev->data.note.note,
ev->data.note.velocity,
source
),
TimePos( ev->time.tick ) );
break;
case SND_SEQ_EVENT_NOTEOFF:
dest->processInEvent( MidiEvent( MidiNoteOff,
ev->data.note.channel,
ev->data.note.note,
ev->data.note.velocity,
source
),
TimePos( ev->time.tick) );
break;
case SND_SEQ_EVENT_KEYPRESS:
dest->processInEvent( MidiEvent(
MidiKeyPressure,
ev->data.note.channel,
ev->data.note.note,
ev->data.note.velocity,
source
), TimePos() );
break;
case SND_SEQ_EVENT_CONTROLLER:
dest->processInEvent( MidiEvent(
MidiControlChange,
ev->data.control.channel,
ev->data.control.param,
ev->data.control.value, source ),
TimePos() );
break;
case SND_SEQ_EVENT_PGMCHANGE:
dest->processInEvent( MidiEvent(
MidiProgramChange,
ev->data.control.channel,
ev->data.control.value, 0,
source ),
TimePos() );
break;
case SND_SEQ_EVENT_CHANPRESS:
dest->processInEvent( MidiEvent(
MidiChannelPressure,
ev->data.control.channel,
ev->data.control.param,
ev->data.control.value, source ),
TimePos() );
break;
case SND_SEQ_EVENT_PITCHBEND:
dest->processInEvent( MidiEvent( MidiPitchBend,
ev->data.control.channel,
ev->data.control.value + 8192, 0, source ),
TimePos() );
break;
case SND_SEQ_EVENT_SENSING:
case SND_SEQ_EVENT_CLOCK:
break;
default:
fprintf( stderr,
"ALSA-sequencer: unhandled input "
"event %d\n", ev->type );
break;
} // end switch
m_seqMutex.lock();
} // end while
m_seqMutex.unlock();
}
delete[] pollfd_set;
}
void MidiAlsaSeq::changeQueueTempo( bpm_t _bpm )
{
m_seqMutex.lock();
snd_seq_change_queue_tempo( m_seqHandle, m_queueID,
60000000 / (int) _bpm, nullptr );
snd_seq_drain_output( m_seqHandle );
m_seqMutex.unlock();
}
void MidiAlsaSeq::updatePortList()
{
QStringList readablePorts;
QStringList writablePorts;
// get input- and output-ports
snd_seq_client_info_t * cinfo;
snd_seq_port_info_t * pinfo;
snd_seq_client_info_malloc( &cinfo );
snd_seq_port_info_malloc( &pinfo );
snd_seq_client_info_set_client( cinfo, -1 );
m_seqMutex.lock();
while( snd_seq_query_next_client( m_seqHandle, cinfo ) >= 0 )
{
int client = snd_seq_client_info_get_client( cinfo );
snd_seq_port_info_set_client( pinfo, client );
snd_seq_port_info_set_port( pinfo, -1 );
while( snd_seq_query_next_port( m_seqHandle, pinfo ) >= 0 )
{
// we need both READ and SUBS_READ
if( ( snd_seq_port_info_get_capability( pinfo )
& ( SND_SEQ_PORT_CAP_READ |
SND_SEQ_PORT_CAP_SUBS_READ ) ) ==
( SND_SEQ_PORT_CAP_READ |
SND_SEQ_PORT_CAP_SUBS_READ ) )
{
readablePorts.push_back( portName( cinfo, pinfo ) );
}
if( ( snd_seq_port_info_get_capability( pinfo )
& ( SND_SEQ_PORT_CAP_WRITE |
SND_SEQ_PORT_CAP_SUBS_WRITE ) ) ==
( SND_SEQ_PORT_CAP_WRITE |
SND_SEQ_PORT_CAP_SUBS_WRITE ) )
{
writablePorts.push_back( portName( cinfo, pinfo ) );
}
}
}
m_seqMutex.unlock();
snd_seq_client_info_free( cinfo );
snd_seq_port_info_free( pinfo );
if( m_readablePorts != readablePorts )
{
m_readablePorts = readablePorts;
emit readablePortsChanged();
}
if( m_writablePorts != writablePorts )
{
m_writablePorts = writablePorts;
emit writablePortsChanged();
}
}
} // namespace lmms
#endif // LMMS_HAVE_ALSA
| 15,917
|
C++
|
.cpp
| 563
| 24.451155
| 113
| 0.65508
|
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,830
|
MidiJack.cpp
|
LMMS_lmms/src/core/midi/MidiJack.cpp
|
/*
* MidiJack.cpp - MIDI client for Jack
*
* Copyright (c) 2015 Shane Ambler <develop/at/shaneware.biz>
*
* 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 "MidiJack.h"
#ifdef LMMS_HAVE_JACK
#include <QMessageBox>
#include "AudioEngine.h"
#include "AudioJack.h"
#include "ConfigManager.h"
#include "GuiApplication.h"
#include "Engine.h"
#include "MainWindow.h"
namespace lmms
{
/* callback functions for jack */
static int JackMidiProcessCallback(jack_nframes_t nframes, void *arg)
{
auto jmd = (MidiJack*)arg;
if (nframes <= 0)
return (0);
jmd->JackMidiRead(nframes);
jmd->JackMidiWrite(nframes);
return (0);
}
static void JackMidiShutdown(void *arg)
{
//: When JACK(JACK Audio Connection Kit) disconnects, it will show the following message (title)
QString msg_short = MidiJack::tr("JACK server down");
//: When JACK(JACK Audio Connection Kit) disconnects, it will show the following message (dialog message)
QString msg_long = MidiJack::tr("The JACK server seems to be shuted down.");
QMessageBox::information(gui::getGUI()->mainWindow(), msg_short, msg_long);
}
MidiJack::MidiJack() :
MidiClientRaw(),
m_jackClient( nullptr ),
m_input_port( nullptr ),
m_output_port( nullptr ),
m_quit( false )
{
// if jack is currently used for audio then we share the connection
// AudioJack creates and maintains the jack connection
// and also handles the callback, we pass it our address
// so that we can also process during the callback
m_jackAudio = dynamic_cast<AudioJack*>(Engine::audioEngine()->audioDev());
if( m_jackAudio )
{
// if a jack connection has been created for audio we use that
m_jackAudio->addMidiClient(this);
}else{
m_jackAudio = nullptr;
m_jackClient = jack_client_open(probeDevice().toLatin1().data(),
JackNoStartServer, nullptr);
if(m_jackClient)
{
jack_set_process_callback(m_jackClient,
JackMidiProcessCallback, this);
jack_on_shutdown(m_jackClient,
JackMidiShutdown, 0);
}
}
if(jackClient())
{
/* jack midi out not implemented
JackMidiWrite and sendByte needs to be functional
before enabling this
If you enable this, also enable the
corresponding jack_port_unregister line below
m_output_port = jack_port_register(
jackClient(), "MIDI out", JACK_DEFAULT_MIDI_TYPE,
JackPortIsOutput, 0);
*/
m_input_port = jack_port_register(
jackClient(), "MIDI in", JACK_DEFAULT_MIDI_TYPE,
JackPortIsInput, 0);
if(jack_activate(jackClient()) == 0 )
{
// only start thread, if we have an active jack client.
start( QThread::LowPriority );
}
}
}
MidiJack::~MidiJack()
{
if(jackClient())
{
if (m_jackAudio) {
// remove ourselves first (atomically), so we will not get called again
m_jackAudio->removeMidiClient();
}
if( jack_port_unregister( jackClient(), m_input_port) != 0){
printf("Failed to unregister jack midi input\n");
}
/* Unused yet, see the corresponding jack_port_register call
if( jack_port_unregister( jackClient(), m_output_port) != 0){
printf("Failed to unregister jack midi output\n");
}
*/
if(m_jackClient)
{
// an m_jackClient means we are handling the jack connection
if( jack_deactivate(m_jackClient) != 0){
printf("Failed to deactivate jack midi client\n");
}
if( jack_client_close(m_jackClient) != 0){
printf("Failed close jack midi client\n");
}
}
}
if( isRunning() )
{
m_quit = true;
wait( 1000 );
terminate();
}
}
jack_client_t* MidiJack::jackClient()
{
if( m_jackAudio == nullptr && m_jackClient == nullptr)
return nullptr;
if( m_jackAudio == nullptr && m_jackClient )
return m_jackClient;
return m_jackAudio->jackClient();
}
QString MidiJack::probeDevice()
{
QString jid = ConfigManager::inst()->value( "midijack", "lmms" );
if( jid.isEmpty() )
{
return "lmms";
}
return jid;
}
// we read data from jack
void MidiJack::JackMidiRead(jack_nframes_t nframes)
{
void* port_buf = jack_port_get_buffer(m_input_port, nframes);
jack_midi_event_t in_event;
jack_nframes_t event_index = 0;
jack_nframes_t event_count = jack_midi_get_event_count(port_buf);
int rval = jack_midi_event_get(&in_event, port_buf, 0);
if (rval == 0 /* 0 = success */)
{
for (unsigned int i = 0; i < nframes; i++)
{
while((in_event.time == i) && (event_index < event_count))
{
// lmms is setup to parse bytes coming from a device
// parse it byte by byte as it expects
for (unsigned int b = 0; b < in_event.size; b++)
parseData( *(in_event.buffer + b) );
event_index++;
if(event_index < event_count)
jack_midi_event_get(&in_event, port_buf, event_index);
}
}
}
}
/* jack midi out is not implemented
sending plain bytes to jack midi outputs doesn't work
once working the output port needs to be enabled in the constructor
*/
void MidiJack::sendByte( const unsigned char c )
{
//m_midiDev.putChar( c );
}
// we write data to jack
void MidiJack::JackMidiWrite(jack_nframes_t nframes)
{
// TODO: write midi data to jack port
}
void MidiJack::run()
{
while( m_quit == false )
{
// we sleep the thread to keep it alive
// midi processing is handled by jack server callbacks
sleep(1);
}
}
} // namespace lmms
#endif // LMMS_HAVE_JACK
| 6,008
|
C++
|
.cpp
| 201
| 27.134328
| 113
| 0.710376
|
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,831
|
MidiApple.cpp
|
LMMS_lmms/src/core/midi/MidiApple.cpp
|
/*
* MidiApple.cpp - Apple MIDI client
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2015 Maurizio Lo Bosco (rageboge on github)
*
* 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 "MidiApple.h"
#ifdef LMMS_BUILD_APPLE
#include <QtAlgorithms>
#include <algorithm>
#include "ConfigManager.h"
#include "MidiPort.h"
#include "Note.h"
#include <CoreMIDI/CoreMIDI.h>
namespace lmms
{
const unsigned int SYSEX_LENGTH=1024;
MidiApple::MidiApple() :
MidiClient(),
m_inputDevices(),
m_outputDevices(),
m_inputSubs(),
m_outputSubs()
{
openDevices();
}
MidiApple::~MidiApple()
{
closeDevices();
}
void MidiApple::processOutEvent( const MidiEvent& event, const TimePos& time, const MidiPort* port )
{
qDebug("MidiApple:processOutEvent displayName:'%s'",port->displayName().toLatin1().constData());
QStringList outDevs;
for( SubMap::ConstIterator it = m_outputSubs.begin(); it != m_outputSubs.end(); ++it )
{
for( MidiPortList::ConstIterator jt = it.value().begin(); jt != it.value().end(); ++jt )
{
if( *jt == port )
{
outDevs += it.key();
break;
}
}
}
for( QMap<QString, MIDIEndpointRef>::Iterator it = m_outputDevices.begin(); it != m_outputDevices.end(); ++it )
{
if( outDevs.contains( it.key() ) )
{
sendMidiOut( it.value(), event );
}
}
}
void MidiApple::sendMidiOut( MIDIEndpointRef &endPointRef, const MidiEvent& event )
{
MIDIPacketList packetList=createMidiPacketList(event);
MIDIPortRef port = m_sourcePortRef.value(endPointRef);
MIDISend(port, endPointRef, &packetList);
}
MIDIPacketList MidiApple::createMidiPacketList( const MidiEvent& event )
{
MIDIPacketList packetList;
packetList.numPackets = 1;
MIDIPacket* firstPacket = &packetList.packet[0];
firstPacket->timeStamp = 0; // send immediately
firstPacket->length = 3;
firstPacket->data[0] = ( event.type() + event.channel() );
firstPacket->data[1] = ( event.param( 0 ) & 0xff );
firstPacket->data[2] = ( event.param( 1 ) & 0xff );
return packetList;
}
void MidiApple::applyPortMode( MidiPort* port )
{
qDebug("applyPortMode displayName:'%s'",port->displayName().toLatin1().constData());
// make sure no subscriptions exist which are not possible with
// current port-mode
if( !port->isInputEnabled() )
{
for( SubMap::Iterator it = m_inputSubs.begin(); it != m_inputSubs.end(); ++it )
{
it.value().removeAll( port );
}
}
if( !port->isOutputEnabled() )
{
for( SubMap::Iterator it = m_outputSubs.begin(); it != m_outputSubs.end(); ++it )
{
it.value().removeAll( port );
}
}
}
void MidiApple::removePort( MidiPort* port )
{
qDebug("removePort displayName:'%s'",port->displayName().toLatin1().constData());
for( SubMap::Iterator it = m_inputSubs.begin(); it != m_inputSubs.end(); ++it )
{
it.value().removeAll( port );
}
for( SubMap::Iterator it = m_outputSubs.begin(); it != m_outputSubs.end(); ++it )
{
it.value().removeAll( port );
}
MidiClient::removePort( port );
}
QString MidiApple::sourcePortName( const MidiEvent& event ) const
{
qDebug("sourcePortName");
/*
if( event.sourcePort() )
{
return m_inputDevices.value( *static_cast<const HMIDIIN *>( event.sourcePort() ) );
}
*/
return MidiClient::sourcePortName( event );
}
void MidiApple::subscribeReadablePort( MidiPort* port, const QString& dest, bool subscribe )
{
qDebug("subscribeReadablePort %s subscribe=%d",dest.toLatin1().constData(),subscribe);
if( subscribe && port->isInputEnabled() == false )
{
qWarning( "port %s can't be (un)subscribed!", port->displayName().toLatin1().constData() );
return;
}
m_inputSubs[dest].removeAll( port );
if( subscribe )
{
qDebug("Subscribing %s",dest.toLatin1().constData());
m_inputSubs[dest].push_back( port );
}
else
{
MidiPortList list = m_inputSubs[dest];
if(list.empty()){
m_inputSubs.remove(dest);
}
}
}
void MidiApple::subscribeWritablePort( MidiPort* port, const QString& dest, bool subscribe )
{
qDebug("subscribeWritablePort %s", port->displayName().toLatin1().constData());
if( subscribe && port->isOutputEnabled() == false )
{
qWarning( "port %s can't be (un)subscribed!", port->displayName().toLatin1().constData() );
return;
}
m_outputSubs[dest].removeAll( port );
if( subscribe )
{
m_outputSubs[dest].push_back( port );
}
else
{
MidiPortList list = m_outputSubs[dest];
if(list.empty()){
m_outputSubs.remove(dest);
}
}
}
void MidiApple::ReadCallback( const MIDIPacketList *pktlist, void *readProcRefCon, void *srcConnRefCon )
{
MidiApple *caller = static_cast<MidiApple*>(readProcRefCon);
if (!caller)
{
qDebug("Error: !caller: MidiApple::ReadCallback");
return;
}
caller->HandleReadCallback(pktlist,srcConnRefCon);
}
void MidiApple::HandleReadCallback( const MIDIPacketList *pktlist, void *srcConnRefCon )
{
const char * refName = (const char *) srcConnRefCon;
MIDIEndpointRef endPointRef = m_inputDevices.value(refName);
if( !m_inputSubs.contains( refName ) )
{
// qDebug("HandleReadCallback '%s' not subscribed",refName);
// printQStringKeys("m_inputDevices", m_inputDevices);
return;
}
// qDebug("HandleReadCallback '%s' subscribed",refName);
bool continueSysEx = false;
unsigned int nBytes;
const MIDIPacket *packet = &pktlist->packet[0];
unsigned char sysExMessage[SYSEX_LENGTH];
unsigned int sysExLength = 0;
for (uint32_t i=0; i<pktlist->numPackets; ++i)
{
nBytes = packet->length;
// Check if this is the end of a continued SysEx message
if (continueSysEx) {
unsigned int lengthToCopy = std::min(nBytes, SYSEX_LENGTH - sysExLength);
// Copy the message into our SysEx message buffer,
// making sure not to overrun the buffer
memcpy(sysExMessage + sysExLength, packet->data, lengthToCopy);
sysExLength += lengthToCopy;
// Check if the last byte is SysEx End.
continueSysEx = (packet->data[nBytes - 1] == 0xF7);
if (!continueSysEx || sysExLength == SYSEX_LENGTH) {
// We would process the SysEx message here, as it is we're just ignoring it
sysExLength = 0;
}
}
else
{
UInt16 iByte, size;
iByte = 0;
while (iByte < nBytes)
{
size = 0;
// First byte should be status
unsigned char status = packet->data[iByte];
if (status < 0xC0) {
size = 3;
}
else if (status < 0xE0)
{
size = 2;
}
else if (status < 0xF0)
{
size = 3;
}
else if (status == 0xF0)
{
// MIDI SysEx then we copy the rest of the message into the SysEx message buffer
unsigned int lengthLeftInMessage = nBytes - iByte;
unsigned int lengthToCopy = std::min(lengthLeftInMessage, SYSEX_LENGTH);
memcpy(sysExMessage + sysExLength, packet->data, lengthToCopy);
sysExLength += lengthToCopy;
size = 0;
iByte = nBytes;
// Check whether the message at the end is the end of the SysEx
continueSysEx = (packet->data[nBytes - 1] != 0xF7);
}
else if (status < 0xF3)
{
size = 3;
}
else if (status == 0xF3)
{
size = 2;
}
else
{
size = 1;
}
unsigned char messageChannel = status & 0xF;
const MidiEventTypes cmdtype = static_cast<MidiEventTypes>(status & 0xF0);
const int par1 = packet->data[iByte + 1];
const int par2 = packet->data[iByte + 2];
switch (cmdtype)
{
case MidiNoteOff: //0x80:
case MidiNoteOn: //0x90:
case MidiKeyPressure: //0xA0:
case MidiControlChange: //0xB0:
case MidiProgramChange: //0xC0:
case MidiChannelPressure: //0xD0:
notifyMidiPortList(
m_inputSubs[refName],
MidiEvent(cmdtype, messageChannel, par1, par2 & 0xff, &endPointRef));
break;
case MidiPitchBend: //0xE0:
notifyMidiPortList(
m_inputSubs[refName],
MidiEvent(cmdtype, messageChannel, par1 + par2 * 128, 0, &endPointRef));
break;
case MidiActiveSensing: //0xF0
case 0xF0:
break;
default:
qDebug("endPointRef name='%s':Some other message %d", refName, cmdtype);
break;
}
iByte += size;
}
}
packet = MIDIPacketNext(packet);
}
}
void MidiApple::updateDeviceList()
{
closeDevices();
openDevices();
emit readablePortsChanged();
emit writablePortsChanged();
}
void MidiApple::closeDevices()
{
m_inputSubs.clear();
m_outputSubs.clear();
QMapIterator<QString, MIDIEndpointRef> i( m_inputDevices );
while( i.hasNext() )
{
midiInClose( i.next().value() );
}
QMapIterator<QString, MIDIEndpointRef> o( m_outputDevices );
while( o.hasNext() )
{
midiInClose( o.next().value() );
}
m_inputDevices.clear();
m_outputDevices.clear();
}
void MidiApple::midiInClose( MIDIEndpointRef reference )
{
qDebug("midiInClose '%s'", getFullName(reference));
MIDIPortRef portRef = m_sourcePortRef[reference];
MIDIPortDisconnectSource(portRef, reference);
}
char *getName( const MIDIObjectRef &object )
{
// Returns the name of a given MIDIObjectRef as char *
CFStringRef name = nullptr;
if (noErr != MIDIObjectGetStringProperty(object, kMIDIPropertyName, &name))
return nullptr;
int len = CFStringGetLength(name)+1;
char *value = (char *) malloc(len);
CFStringGetCString(name, value, len, 0);
CFRelease(name);
return value;
}
const void printQStringKeys( char const * mapName, const QMap<QString,MIDIEndpointRef> &inputMap )
{
qDebug("%s:", mapName);
QMapIterator<QString, MIDIEndpointRef> i( inputMap );
while( i.hasNext() )
{
QString key = i.next().key();
qDebug(" key='%s'", key.toLatin1().constData());
}
}
void MidiApple::openDevices()
{
qDebug("openDevices");
m_inputDevices.clear();
// How many MIDI devices do we have?
ItemCount deviceCount = MIDIGetNumberOfDevices();
// Iterate through all MIDI devices
for (ItemCount i = 0 ; i < deviceCount ; ++i)
{
// Grab a reference to current device
MIDIDeviceRef device = MIDIGetDevice(i);
char * deviceName = getName(device);
QString qsDeviceName = QString::fromUtf8((char*)(deviceName));
qDebug("Device name:%s",deviceName);
// Is this device online? (Currently connected?)
SInt32 isOffline = 0;
MIDIObjectGetIntegerProperty(device, kMIDIPropertyOffline, &isOffline);
qDebug(" is online: %s", (isOffline ? "No" : "Yes"));
// How many entities do we have?
ItemCount entityCount = MIDIDeviceGetNumberOfEntities(device);
// Iterate through this device's entities
for (ItemCount j = 0 ; j < entityCount ; ++j)
{
// Grab a reference to an entity
MIDIEntityRef entity = MIDIDeviceGetEntity(device, j);
qDebug(" Entity: %s", getName(entity));
// Iterate through this device's source endpoints (MIDI In)
ItemCount sourceCount = MIDIEntityGetNumberOfSources(entity);
for ( ItemCount k = 0 ; k < sourceCount ; ++k )
{
// Grab a reference to a source endpoint
MIDIEndpointRef source = MIDIEntityGetSource(entity, k);
char * name = getName(source);
qDebug(" Source: '%s'", name);
QString sourceName = qsDeviceName + ":" + QString::fromUtf8((char*)(name));
qDebug(" Source name: '%s'", sourceName.toLatin1().constData() );
m_inputDevices.insert(sourceName, source);
openMidiReference(source,sourceName,true);
}
// Iterate through this device's destination endpoints (MIDI Out)
ItemCount destCount = MIDIEntityGetNumberOfDestinations(entity);
for ( ItemCount k = 0 ; k < destCount ; ++k )
{
// Grab a reference to a destination endpoint
MIDIEndpointRef dest = MIDIEntityGetDestination(entity, k);
char * name = getName(dest);
qDebug(" Destination: '%s'", name);
QString destinationName = qsDeviceName + ":" + QString::fromUtf8((char*)(name));
qDebug(" Destination name: '%s'", destinationName.toLatin1().constData() );
m_outputDevices.insert(destinationName, dest);
openMidiReference(dest,destinationName,false);
}
}
qDebug("------");
}
printQStringKeys("m_inputDevices:",m_inputDevices);
printQStringKeys("m_outputDevices:",m_outputDevices);
}
void MidiApple::openMidiReference( MIDIEndpointRef reference, QString refName, bool isIn )
{
char * registeredName = (char*) malloc(refName.length()+1);
std::snprintf(registeredName, refName.length() + 1, "%s",refName.toLatin1().constData());
qDebug("openMidiReference refName '%s'",refName.toLatin1().constData());
MIDIClientRef mClient = getMidiClientRef();
MIDIPortRef mPort = 0;
CFStringRef inName = CFStringCreateWithCString(0, registeredName, kCFStringEncodingASCII);
if(isIn)
{
MIDIInputPortCreate(mClient, inName, &MidiApple::ReadCallback, this, &mPort);
}
else
{
MIDIOutputPortCreate(mClient, inName, &mPort);
}
MIDIPortConnectSource(mPort, reference, (void *)registeredName);
m_sourcePortRef.insert(reference, mPort);
CFRelease(inName);
qDebug("openMidiReference registeredName '%s'",registeredName);
}
MIDIClientRef MidiApple::getMidiClientRef()
{
if(mClient==0)
{
CFStringRef deviceClientName = CFSTR("MIDI In Device Client");
MIDIClientCreate(deviceClientName, NotifyCallback, this, &mClient);
CFRelease(deviceClientName);
}
return mClient;
}
void MidiApple::notifyMidiPortList( MidiPortList l, MidiEvent event )
{
for( MidiPortList::ConstIterator it = l.begin(); it != l.end(); ++it )
{
( *it )->processInEvent( event);
}
}
void MidiApple::NotifyCallback( const MIDINotification *message, void *refCon )
{
//refCon is a pointer to MidiApple class
MidiApple *midiApple = (MidiApple *)refCon;
qDebug("MidiApple::NotifyCallback '%d'",message->messageID);
switch (message->messageID)
{
case kMIDIMsgObjectAdded:
{
MIDIObjectAddRemoveNotification* msg = (MIDIObjectAddRemoveNotification*)message ;
MIDIEndpointRef endpoint_ref = (MIDIEndpointRef)msg->child ;
char * fullName = midiApple->getFullName(endpoint_ref);
if (msg->childType == kMIDIObjectType_Source) {
qDebug("kMIDIMsgObjectAdded source '%s'",fullName);
// Here your code to save the new source ref
// and update your internal "clients" (eg
// update a popup menu, a list, ...)
}
if (msg->childType == kMIDIObjectType_Destination) {
qDebug("kMIDIMsgObjectAdded destination '%s'",fullName);
// Here your code to save the new destination ref
// and update your internal "clients"
}
break;
}
case kMIDIMsgObjectRemoved:
{
MIDIObjectAddRemoveNotification*
msg = (MIDIObjectAddRemoveNotification*)message ;
MIDIEndpointRef endpoint_ref = (MIDIEndpointRef)msg->child ;
char * fullName = midiApple->getFullName(endpoint_ref);
if (msg->childType == kMIDIObjectType_Source) {
// Here your code to remove the source ref
// and update your internal "clients"
qDebug("kMIDIMsgObjectRemoved source '%s'",fullName);
}
if (msg->childType == kMIDIObjectType_Destination) {
// Here your code to remove the destination ref
// and update your internal "clients"
qDebug("kMIDIMsgObjectRemoved destination '%s'",fullName); }
break;
}
case kMIDIMsgPropertyChanged:
// Currently ignored
qDebug("kMIDIMsgPropertyChanged");
break;
case kMIDIMsgThruConnectionsChanged:
// Currently ignored
qDebug("kMIDIMsgThruConnectionsChanged");
break;
case kMIDIMsgSerialPortOwnerChanged:
// Currently ignored
qDebug("kMIDIMsgSerialPortOwnerChanged");
break;
default:
qDebug("unhandled message type");
break;
}
}
char * MidiApple::getFullName(MIDIEndpointRef &endpoint_ref)
{
MIDIEntityRef entity = 0;
MIDIEndpointGetEntity(endpoint_ref, &entity); //get the entity
MIDIDeviceRef device = 0;
MIDIEntityGetDevice(entity, &device);
char * deviceName = getName(device);
char * endPointName = getName(endpoint_ref);
qDebug("device name='%s' endpoint name='%s'",deviceName,endPointName);
size_t deviceNameLen = deviceName == nullptr ? 0 : strlen(deviceName);
size_t endPointNameLen = endPointName == nullptr ? 0 : strlen(endPointName);
char * fullName = (char *)malloc(deviceNameLen + endPointNameLen + 2);
std::snprintf(fullName, deviceNameLen + endPointNameLen + 2, "%s:%s", deviceName,endPointName);
if (deviceName != nullptr) { free(deviceName); }
if (endPointName != nullptr) { free(endPointName); }
return fullName;
}
} // namespace lmms
#endif // LMMS_BUILD_APPLE
| 17,003
|
C++
|
.cpp
| 523
| 29.294455
| 112
| 0.715311
|
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,832
|
MidiAlsaRaw.cpp
|
LMMS_lmms/src/core/midi/MidiAlsaRaw.cpp
|
/*
* MidiAlsaRaw.cpp - MIDI client for RawMIDI via ALSA
*
* 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 "MidiAlsaRaw.h"
#include "ConfigManager.h"
#ifdef LMMS_HAVE_ALSA
namespace lmms
{
MidiAlsaRaw::MidiAlsaRaw() :
MidiClientRaw(),
m_inputp( &m_input ),
m_outputp( &m_output ),
m_quit( false )
{
if (int err = snd_rawmidi_open(m_inputp, m_outputp, probeDevice().toLatin1().constData(), 0); err < 0)
{
printf( "cannot open MIDI-device: %s\n", snd_strerror( err ) );
return;
}
snd_rawmidi_read( m_input, nullptr, 0 );
snd_rawmidi_nonblock( m_input, 1 );
m_npfds = snd_rawmidi_poll_descriptors_count( m_input );
m_pfds = new pollfd[m_npfds];
snd_rawmidi_poll_descriptors( m_input, m_pfds, m_npfds );
start( QThread::LowPriority );
}
MidiAlsaRaw::~MidiAlsaRaw()
{
if( isRunning() )
{
m_quit = true;
wait( 1000 );
terminate();
snd_rawmidi_close( m_input );
snd_rawmidi_close( m_output );
delete[] m_pfds;
}
}
QString MidiAlsaRaw::probeDevice()
{
QString dev = ConfigManager::inst()->value( "MidiAlsaRaw", "device" );
if( dev == "" )
{
if( getenv( "MIDIDEV" ) != nullptr )
{
return getenv( "MIDIDEV" );
}
return "default";
}
return dev;
}
void MidiAlsaRaw::sendByte( unsigned char c )
{
snd_rawmidi_write( m_output, &c, sizeof( c ) );
}
void MidiAlsaRaw::run()
{
auto buf = std::array<unsigned char, 128>{};
//int cnt = 0;
while( m_quit == false )
{
msleep( 5 ); // must do that, otherwise this thread takes
// too much CPU-time, even with LowPriority...
if (int err = poll(m_pfds, m_npfds, 10000); err < 0 && errno == EINTR)
{
printf( "MidiAlsaRaw::run(): Got EINTR while "
"polling. Will stop polling MIDI-events from "
"MIDI-port.\n" );
break;
}
else if (err < 0)
{
printf( "poll failed: %s\nWill stop polling "
"MIDI-events from MIDI-port.\n",
strerror( errno ) );
break;
}
else if (err == 0)
{
//printf( "there seems to be no active MIDI-device %d\n", ++cnt );
continue;
}
unsigned short revents = 0;
if (int err = snd_rawmidi_poll_descriptors_revents(m_input, m_pfds, m_npfds, &revents); err < 0)
{
printf( "cannot get poll events: %s\nWill stop polling "
"MIDI-events from MIDI-port.\n",
snd_strerror( errno ) );
break;
}
if( revents & ( POLLERR | POLLHUP ) )
{
printf( "POLLERR or POLLHUP\n" );
break;
}
if( !( revents & POLLIN ) )
{
continue;
}
if (int err = snd_rawmidi_read(m_input, buf.data(), buf.size()); err == -EAGAIN) { continue; }
else if (err < 0)
{
printf( "cannot read from port \"%s\": %s\nWill stop "
"polling MIDI-events from MIDI-port.\n",
/*port_name*/"default", snd_strerror( err ) );
break;
}
else if (err == 0) { continue; }
else
{
for (int i = 0; i < err; ++i) { parseData(buf[i]); }
}
}
}
} // namespace lmms
#endif // LMMS_HAVE_ALSA
| 3,722
|
C++
|
.cpp
| 136
| 24.544118
| 103
| 0.664041
|
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,833
|
MidiClient.cpp
|
LMMS_lmms/src/core/midi/MidiClient.cpp
|
/*
* MidiClient.cpp - base-class for MIDI-clients like ALSA-sequencer-client
*
* Copyright (c) 2005-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* This file partly contains code from Fluidsynth, Peter Hanappe
*
* 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 "MidiClient.h"
#include <array>
#include "MidiPort.h"
namespace lmms
{
MidiClient::~MidiClient()
{
//TODO: noteOffAll(); / clear all ports
for (MidiPort* port : m_midiPorts)
{
port->invalidateCilent();
}
}
void MidiClient::applyPortMode( MidiPort* )
{
}
void MidiClient::applyPortName( MidiPort* )
{
}
void MidiClient::addPort( MidiPort* port )
{
m_midiPorts.push_back( port );
}
void MidiClient::removePort( MidiPort* port )
{
if( ! port )
{
return;
}
auto it = std::find(m_midiPorts.begin(), m_midiPorts.end(), port);
if( it != m_midiPorts.end() )
{
m_midiPorts.erase( it );
}
}
void MidiClient::subscribeReadablePort( MidiPort*, const QString& , bool )
{
}
void MidiClient::subscribeWritablePort( MidiPort* , const QString& , bool )
{
}
void MidiClientRaw::parseData( const unsigned char c )
{
/*********************************************************************/
/* 'Process' system real-time messages */
/*********************************************************************/
/* There are not too many real-time messages that are of interest here.
* They can occur anywhere, even in the middle of a noteon message!
* Real-time range: 0xF8 .. 0xFF
* Note: Real-time does not affect (running) status.
*/
if( c >= 0xF8 )
{
if( c == MidiSystemReset )
{
m_midiParseData.m_midiEvent.setType( MidiSystemReset );
m_midiParseData.m_status = 0;
processParsedEvent();
}
return;
}
/*********************************************************************/
/* 'Process' system common messages (again, just skip them) */
/*********************************************************************/
/* There are no system common messages that are of interest here.
* System common range: 0xF0 .. 0xF7
*/
if( c > 0xF0 )
{
/* MIDI spec say: To ignore a non-real-time message, just discard all
* data up to the next status byte. And our parser will ignore data
* that is received without a valid status.
* Note: system common cancels running status. */
m_midiParseData.m_status = 0;
return;
}
/*********************************************************************/
/* Process voice category messages: */
/*********************************************************************/
/* Now that we have handled realtime and system common messages, only
* voice messages are left.
* Only a status byte has bit # 7 set.
* So no matter the status of the parser (in case we have lost sync),
* as soon as a byte >= 0x80 comes in, we are dealing with a status byte
* and start a new event.
*/
if( c & 0x80 )
{
m_midiParseData.m_channel = c & 0x0F;
m_midiParseData.m_status = c & 0xF0;
/* The event consumes x bytes of data...
(subtract 1 for the status byte) */
m_midiParseData.m_bytesTotal = eventLength( m_midiParseData.m_status ) - 1;
/* of which we have read 0 at this time. */
m_midiParseData.m_bytes = 0;
return;
}
/*********************************************************************/
/* Process data */
/*********************************************************************/
/* If we made it this far, then the received char belongs to the data
* of the last event. */
if( m_midiParseData.m_status == 0 )
{
/* We are not interested in the event currently received.
Discard the data. */
return;
}
/* Store the first couple of bytes */
if( m_midiParseData.m_bytes < RAW_MIDI_PARSE_BUF_SIZE )
{
m_midiParseData.m_buffer[m_midiParseData.m_bytes] = c;
}
++m_midiParseData.m_bytes;
/* Do we still need more data to get this event complete? */
if( m_midiParseData.m_bytes < m_midiParseData.m_bytesTotal )
{
return;
}
/*********************************************************************/
/* Send the event */
/*********************************************************************/
/* The event is ready-to-go. About 'running status':
*
* The MIDI protocol has a built-in compression mechanism. If several
* similar events are sent in-a-row, for example note-ons, then the
* event type is only sent once. For this case, the last event type
* (status) is remembered.
* We simply keep the status as it is, just reset the parameter counter.
* If another status byte comes in, it will overwrite the status.
*/
m_midiParseData.m_midiEvent.setType(static_cast<MidiEventTypes>(m_midiParseData.m_status));
m_midiParseData.m_midiEvent.setChannel(m_midiParseData.m_channel);
m_midiParseData.m_bytes = 0; /* Related to running status! */
switch (m_midiParseData.m_midiEvent.type())
{
case MidiNoteOff:
case MidiNoteOn:
case MidiKeyPressure:
m_midiParseData.m_midiEvent.setKey(m_midiParseData.m_buffer[0]);
m_midiParseData.m_midiEvent.setVelocity(m_midiParseData.m_buffer[1]);
break;
case MidiChannelPressure:
case MidiProgramChange:
m_midiParseData.m_midiEvent.setParam(0, m_midiParseData.m_buffer[0]);
break;
case MidiControlChange:
m_midiParseData.m_midiEvent.setControllerNumber(m_midiParseData.m_buffer[0]);
m_midiParseData.m_midiEvent.setControllerValue( m_midiParseData.m_buffer[1]);
break;
case MidiPitchBend:
// Pitch-bend is transmitted with 14-bit precision.
// Note: '|' does here the same as '+' (no common bits),
// but might be faster
m_midiParseData.m_midiEvent.setPitchBend((m_midiParseData.m_buffer[1] * 128) | m_midiParseData.m_buffer[0]);
break;
default:
// Unlikely
return;
}
processParsedEvent();
}
void MidiClientRaw::processParsedEvent()
{
for (const auto& midiPort : m_midiPorts)
{
midiPort->processInEvent(m_midiParseData.m_midiEvent);
}
}
void MidiClientRaw::processOutEvent(const MidiEvent& event, const TimePos&, const MidiPort* port)
{
// TODO: also evaluate _time and queue event if necessary
switch (event.type())
{
case MidiNoteOn:
case MidiNoteOff:
case MidiKeyPressure:
sendByte(event.type() | event.channel());
sendByte(event.key());
sendByte(event.velocity());
break;
default:
qWarning("MidiClientRaw: unhandled MIDI-event %d\n", (int)event.type());
break;
}
}
// Taken from Nagano Daisuke's USB-MIDI driver
static const auto REMAINS_F0F6 = std::array<unsigned char, 7>
{
0, /* 0xF0 */
2, /* 0XF1 */
3, /* 0XF2 */
2, /* 0XF3 */
2, /* 0XF4 (Undefined by MIDI Spec, and subject to change) */
2, /* 0XF5 (Undefined by MIDI Spec, and subject to change) */
1 /* 0XF6 */
} ;
static const auto REMAINS_80E0 = std::array<unsigned char, 7>
{
3, /* 0x8X Note Off */
3, /* 0x9X Note On */
3, /* 0xAX Poly-key pressure */
3, /* 0xBX Control Change */
2, /* 0xCX Program Change */
2, /* 0xDX Channel pressure */
3 /* 0xEX PitchBend Change */
} ;
// Returns the length of the MIDI message starting with _event.
// Taken from Nagano Daisuke's USB-MIDI driver
int MidiClientRaw::eventLength( const unsigned char event )
{
if ( event < 0xF0 )
{
return REMAINS_80E0[( ( event - 0x80 ) >> 4 ) & 0x0F];
}
else if ( event < 0xF7 )
{
return REMAINS_F0F6[event - 0xF0];
}
return 1;
}
} // namespace lmms
| 8,241
|
C++
|
.cpp
| 246
| 30.947154
| 111
| 0.635802
|
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,834
|
MidiWinMM.cpp
|
LMMS_lmms/src/core/midi/MidiWinMM.cpp
|
/*
* MidiWinMM.cpp - WinMM MIDI client
*
* 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 "MidiWinMM.h"
#ifdef LMMS_BUILD_WIN32
namespace lmms
{
MidiWinMM::MidiWinMM() :
MidiClient(),
m_inputDevices(),
m_outputDevices(),
m_inputSubs(),
m_outputSubs()
{
openDevices();
}
MidiWinMM::~MidiWinMM()
{
closeDevices();
}
void MidiWinMM::processOutEvent( const MidiEvent& event, const TimePos& time, const MidiPort* port )
{
const DWORD shortMsg = ( event.type() + event.channel() ) +
( ( event.param( 0 ) & 0xff ) << 8 ) +
( ( event.param( 1 ) & 0xff ) << 16 );
QStringList outDevs;
for( SubMap::ConstIterator it = m_outputSubs.begin(); it != m_outputSubs.end(); ++it )
{
for( MidiPortList::ConstIterator jt = it.value().begin(); jt != it.value().end(); ++jt )
{
if( *jt == port )
{
outDevs += it.key();
break;
}
}
}
for( QMap<HMIDIOUT, QString>::Iterator it = m_outputDevices.begin(); it != m_outputDevices.end(); ++it )
{
if( outDevs.contains( *it ) )
{
midiOutShortMsg( it.key(), shortMsg );
}
}
}
void MidiWinMM::applyPortMode( MidiPort* port )
{
// make sure no subscriptions exist which are not possible with
// current port-mode
if( !port->isInputEnabled() )
{
for( SubMap::Iterator it = m_inputSubs.begin(); it != m_inputSubs.end(); ++it )
{
it.value().removeAll( port );
}
}
if( !port->isOutputEnabled() )
{
for( SubMap::Iterator it = m_outputSubs.begin(); it != m_outputSubs.end(); ++it )
{
it.value().removeAll( port );
}
}
}
void MidiWinMM::removePort( MidiPort* port )
{
for( SubMap::Iterator it = m_inputSubs.begin(); it != m_inputSubs.end(); ++it )
{
it.value().removeAll( port );
}
for( SubMap::Iterator it = m_outputSubs.begin(); it != m_outputSubs.end(); ++it )
{
it.value().removeAll( port );
}
MidiClient::removePort( port );
}
QString MidiWinMM::sourcePortName( const MidiEvent& event ) const
{
if( event.sourcePort() )
{
return m_inputDevices.value( *static_cast<const HMIDIIN *>( event.sourcePort() ) );
}
return MidiClient::sourcePortName( event );
}
void MidiWinMM::subscribeReadablePort( MidiPort* port, const QString& dest, bool subscribe )
{
if( subscribe && port->isInputEnabled() == false )
{
qWarning( "port %s can't be (un)subscribed!\n", port->displayName().toLatin1().constData() );
return;
}
m_inputSubs[dest].removeAll( port );
if( subscribe )
{
m_inputSubs[dest].push_back( port );
}
}
void MidiWinMM::subscribeWritablePort( MidiPort* port, const QString& dest, bool subscribe )
{
if( subscribe && port->isOutputEnabled() == false )
{
qWarning( "port %s can't be (un)subscribed!\n", port->displayName().toLatin1().constData() );
return;
}
m_outputSubs[dest].removeAll( port );
if( subscribe )
{
m_outputSubs[dest].push_back( port );
}
}
void WINAPI CALLBACK MidiWinMM::inputCallback( HMIDIIN hm, UINT msg, DWORD_PTR inst, DWORD_PTR param1, DWORD_PTR param2 )
{
if( msg == MIM_DATA )
{
( (MidiWinMM *) inst )->handleInputEvent( hm, param1 );
}
}
void MidiWinMM::handleInputEvent( HMIDIIN hm, DWORD ev )
{
const int cmd = ev & 0xff;
if( cmd == MidiActiveSensing )
{
return;
}
const int par1 = ( ev >> 8 ) & 0xff;
const int par2 = ev >> 16;
const MidiEventTypes cmdtype = static_cast<MidiEventTypes>( cmd & 0xf0 );
const int chan = cmd & 0x0f;
const QString d = m_inputDevices.value( hm );
if( d.isEmpty() || !m_inputSubs.contains( d ) )
{
return;
}
const MidiPortList & l = m_inputSubs[d];
for (MidiPortList::ConstIterator it = l.begin(); it != l.end(); ++it)
{
switch (cmdtype)
{
case MidiNoteOn:
case MidiNoteOff:
case MidiKeyPressure:
case MidiControlChange:
case MidiProgramChange:
case MidiChannelPressure:
(*it)->processInEvent(MidiEvent(cmdtype, chan, par1, par2 & 0xff, &hm));
break;
case MidiPitchBend:
(*it)->processInEvent(MidiEvent(cmdtype, chan, par1 + par2 * 128, 0, &hm));
break;
default:
qWarning("MidiWinMM: unhandled input event %d\n", cmdtype);
break;
}
}
}
void MidiWinMM::updateDeviceList()
{
closeDevices();
openDevices();
emit readablePortsChanged();
emit writablePortsChanged();
}
void MidiWinMM::closeDevices()
{
m_inputSubs.clear();
m_outputSubs.clear();
QMapIterator<HMIDIIN, QString> i( m_inputDevices );
HMIDIIN hInDev;
while( i.hasNext() )
{
hInDev = i.next().key();
midiInReset( hInDev );
midiInClose( hInDev );
}
QMapIterator<HMIDIOUT, QString> o( m_outputDevices );
while( o.hasNext() )
{
midiOutClose( o.next().key() );
}
m_inputDevices.clear();
m_outputDevices.clear();
}
void MidiWinMM::openDevices()
{
m_inputDevices.clear();
for( unsigned int i = 0; i < midiInGetNumDevs(); ++i )
{
MIDIINCAPS c;
midiInGetDevCaps( i, &c, sizeof( c ) );
HMIDIIN hm = 0;
MMRESULT res = midiInOpen( &hm, i, (DWORD_PTR) &inputCallback,
(DWORD_PTR) this,
CALLBACK_FUNCTION );
if( res == MMSYSERR_NOERROR )
{
m_inputDevices[hm] = qstrdup( c.szPname );
midiInStart( hm );
}
}
m_outputDevices.clear();
for( unsigned int i = 0; i < midiOutGetNumDevs(); ++i )
{
MIDIOUTCAPS c;
midiOutGetDevCaps( i, &c, sizeof( c ) );
HMIDIOUT hm = 0;
MMRESULT res = midiOutOpen( &hm, i, 0, 0, CALLBACK_NULL );
if( res == MMSYSERR_NOERROR )
{
m_outputDevices[hm] = qstrdup( c.szPname );
}
}
}
} // namespace lmms
#endif // LMMS_BUILD_WIN32
| 6,256
|
C++
|
.cpp
| 234
| 24.102564
| 121
| 0.685104
|
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,835
|
MidiEventToByteSeq.cpp
|
LMMS_lmms/src/core/midi/MidiEventToByteSeq.cpp
|
/*
* MidiEventToByteSeq.cpp - writeToByteSeq implementation
*
* Copyright (c) 2020-2020 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 "MidiEventToByteSeq.h"
#include <QtGlobal>
#include "MidiEvent.h"
namespace lmms
{
std::size_t writeToByteSeq(
const MidiEvent& ev, uint8_t *data, std::size_t bufsize)
{
Q_ASSERT(bufsize >= 3);
std::size_t size = 0;
data[0] = ev.type() | (ev.channel() & 0x0F);
switch (ev.type())
{
case MidiNoteOn:
if (ev.velocity() > 0)
{
if (ev.key() < 0 || ev.key() > MidiMaxKey)
break;
data[1] = ev.key();
data[2] = ev.velocity();
size = 3;
break;
}
else
{
// Lv2 MIDI specs:
// "Note On messages with velocity 0 are not allowed.
// These messages are equivalent to Note Off in standard
// MIDI streams, but here only proper Note Off messages
// are allowed."
data[0] = MidiNoteOff | (ev.channel() & 0x0F);
// nobreak
}
case MidiNoteOff:
if (ev.key() < 0 || ev.key() > MidiMaxKey)
break;
data[1] = ev.key();
data[2] = ev.velocity(); // release time
size = 3;
break;
case MidiKeyPressure:
data[1] = ev.key();
data[2] = ev.velocity();
size = 3;
break;
case MidiControlChange:
data[1] = ev.controllerNumber();
data[2] = ev.controllerValue();
size = 3;
break;
case MidiProgramChange:
data[1] = ev.program();
size = 2;
break;
case MidiChannelPressure:
data[1] = ev.channelPressure();
size = 2;
break;
case MidiPitchBend:
data[1] = ev.pitchBend() & 0x7f;
data[2] = ev.pitchBend() >> 7;
size = 3;
break;
default:
// unhandled
break;
}
return size;
}
} // namespace lmms
| 2,514
|
C++
|
.cpp
| 93
| 23.709677
| 80
| 0.66514
|
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,836
|
MidiController.cpp
|
LMMS_lmms/src/core/midi/MidiController.cpp
|
/*
* MidiController.cpp - implementation of class midi-controller which handles
* MIDI control change messages
*
* Copyright (c) 2008 Paul Giblock <drfaygo/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 "AudioEngine.h"
#include "MidiController.h"
namespace lmms
{
MidiController::MidiController( Model * _parent ) :
Controller( ControllerType::Midi, _parent, tr( "MIDI Controller" ) ),
MidiEventProcessor(),
m_midiPort( tr( "unnamed_midi_controller" ), Engine::audioEngine()->midiClient(), this, this, MidiPort::Mode::Input ),
m_lastValue( 0.0f ),
m_previousValue( 0.0f )
{
setSampleExact( true );
connect( &m_midiPort, SIGNAL(modeChanged()),
this, SLOT(updateName()));
}
void MidiController::updateValueBuffer()
{
if( m_previousValue != m_lastValue )
{
m_valueBuffer.interpolate( m_previousValue, m_lastValue );
m_previousValue = m_lastValue;
}
else
{
m_valueBuffer.fill( m_lastValue );
}
m_bufferLastUpdated = s_periods;
}
void MidiController::updateName()
{
setName( QString("MIDI ch%1 ctrl%2").
arg( m_midiPort.inputChannel() ).
arg( m_midiPort.inputController() ) );
}
void MidiController::processInEvent(const MidiEvent& event, const TimePos& time, f_cnt_t offset)
{
switch(event.type())
{
case MidiControlChange:
{
unsigned char controllerNum = event.controllerNumber();
if (m_midiPort.inputController() == controllerNum &&
(m_midiPort.inputChannel() == event.channel() + 1 || m_midiPort.inputChannel() == 0))
{
unsigned char val = event.controllerValue();
m_previousValue = m_lastValue;
m_lastValue = static_cast<float>(val) / 127.0f;
emit valueChanged();
}
break;
}
default:
// Don't care - maybe add special cases for pitch and mod later
break;
}
}
void MidiController::subscribeReadablePorts( const MidiPort::Map & _map )
{
for( MidiPort::Map::ConstIterator it = _map.constBegin();
it != _map.constEnd(); ++it )
{
m_midiPort.subscribeReadablePort( it.key(), *it );
}
}
void MidiController::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
Controller::saveSettings( _doc, _this );
m_midiPort.saveSettings( _doc, _this );
}
void MidiController::loadSettings( const QDomElement & _this )
{
Controller::loadSettings( _this );
m_midiPort.loadSettings( _this );
updateName();
}
QString MidiController::nodeName() const
{
return( "Midicontroller" );
}
gui::ControllerDialog* MidiController::createDialog( QWidget * _parent )
{
return nullptr;
}
} // namespace lmms
| 3,339
|
C++
|
.cpp
| 109
| 28.119266
| 119
| 0.726474
|
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,837
|
Lv2Proc.cpp
|
LMMS_lmms/src/core/lv2/Lv2Proc.cpp
|
/*
* Lv2Proc.cpp - Lv2 processor class
*
* Copyright (c) 2019-2024 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 "Lv2Proc.h"
#ifdef LMMS_HAVE_LV2
#include <cmath>
#include <lv2/midi/midi.h>
#include <lv2/atom/atom.h>
#include <lv2/resize-port/resize-port.h>
#include <lv2/worker/worker.h>
#include <QDebug>
#include <QDomDocument>
#include <QtGlobal>
#include "AudioEngine.h"
#include "AutomatableModel.h"
#include "ComboBoxModel.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "Lv2Features.h"
#include "Lv2Manager.h"
#include "Lv2Ports.h"
#include "Lv2Evbuf.h"
#include "MidiEvent.h"
#include "MidiEventToByteSeq.h"
#include "NoCopyNoMove.h"
namespace lmms
{
// container for everything required to store MIDI events going to the plugin
struct MidiInputEvent
{
MidiEvent ev;
TimePos time;
f_cnt_t offset;
};
Plugin::Type Lv2Proc::check(const LilvPlugin *plugin,
std::vector<PluginIssue>& issues)
{
unsigned maxPorts = lilv_plugin_get_num_ports(plugin);
enum { inCount, outCount, maxCount };
auto audioChannels = std::array<unsigned, maxCount>{}; // audio input and output count
auto midiChannels = std::array<unsigned, maxCount>{}; // MIDI input and output count
const char* pluginUri = lilv_node_as_uri(lilv_plugin_get_uri(plugin));
//qDebug() << "Checking plugin" << pluginUri << "...";
// TODO: manage a global list of blocked plugins outside of the code
// for now, this will help
// this is only a fix for the meantime
if (!ConfigManager::enableBlockedPlugins())
{
if( // plugin unstable?
Lv2Manager::pluginIsUnstable(pluginUri) ||
// plugins only useful with UI?
(!Lv2Manager::wantUi() &&
Lv2Manager::pluginIsOnlyUsefulWithUi(pluginUri)) ||
// plugin unstable with 32 or less fpp?
(Engine::audioEngine()->framesPerPeriod() <= 32 &&
Lv2Manager::pluginIsUnstableWithBuffersizeLessEqual32(pluginUri)) )
{
issues.emplace_back(PluginIssueType::Blocked);
}
}
for (unsigned portNum = 0; portNum < maxPorts; ++portNum)
{
Lv2Ports::Meta meta;
// does all port checks:
std::vector<PluginIssue> tmp = meta.get(plugin, portNum);
std::move(tmp.begin(), tmp.end(), std::back_inserter(issues));
bool portMustBeUsed =
!portIsSideChain(plugin,
lilv_plugin_get_port_by_index(plugin, portNum)) &&
!meta.m_optional;
if (meta.m_type == Lv2Ports::Type::Audio && portMustBeUsed)
{
++audioChannels[meta.m_flow == Lv2Ports::Flow::Output
? outCount : inCount];
}
else if(meta.m_type == Lv2Ports::Type::AtomSeq && portMustBeUsed)
{
++midiChannels[meta.m_flow == Lv2Ports::Flow::Output
? outCount : inCount];
}
}
if (audioChannels[inCount] > 2)
issues.emplace_back(PluginIssueType::TooManyInputChannels,
std::to_string(audioChannels[inCount]));
if (audioChannels[outCount] == 0)
issues.emplace_back(PluginIssueType::NoOutputChannel);
else if (audioChannels[outCount] > 2)
issues.emplace_back(PluginIssueType::TooManyOutputChannels,
std::to_string(audioChannels[outCount]));
if (midiChannels[inCount] > 1)
issues.emplace_back(PluginIssueType::TooManyMidiInputChannels,
std::to_string(midiChannels[inCount]));
if (midiChannels[outCount] > 1)
issues.emplace_back(PluginIssueType::TooManyMidiOutputChannels,
std::to_string(midiChannels[outCount]));
AutoLilvNodes reqFeats(lilv_plugin_get_required_features(plugin));
LILV_FOREACH (nodes, itr, reqFeats.get())
{
const char* reqFeatName = lilv_node_as_string(
lilv_nodes_get(reqFeats.get(), itr));
if(!Lv2Features::isFeatureSupported(reqFeatName))
{
issues.emplace_back(PluginIssueType::FeatureNotSupported, reqFeatName);
}
}
Lv2Manager* mgr = Engine::getLv2Manager();
AutoLilvNode requiredOptionNode(mgr->uri(LV2_OPTIONS__requiredOption));
AutoLilvNodes requiredOptions = mgr->findNodes(lilv_plugin_get_uri (plugin), requiredOptionNode.get(), nullptr);
if (requiredOptions)
{
LILV_FOREACH(nodes, i, requiredOptions.get())
{
const char* ro = lilv_node_as_uri (lilv_nodes_get (requiredOptions.get(), i));
if (!Lv2Options::isOptionSupported(mgr->uridMap().map(ro)))
{
// yes, this is not a Lv2 feature,
// but it's a feature in abstract sense
issues.emplace_back(PluginIssueType::FeatureNotSupported, ro);
}
}
}
return (audioChannels[inCount] > 2 || audioChannels[outCount] > 2)
? Plugin::Type::Undefined
: (audioChannels[inCount] > 0)
? Plugin::Type::Effect
: Plugin::Type::Instrument;
}
class Lv2ProcSuspender : NoCopyNoMove
{
public:
Lv2ProcSuspender(Lv2Proc* proc)
: m_proc(proc)
, m_wasActive(proc->m_instance)
{
if (m_wasActive) { m_proc->shutdownPlugin(); }
}
~Lv2ProcSuspender()
{
if (m_wasActive) { m_proc->initPlugin(); }
}
private:
Lv2Proc* const m_proc;
const bool m_wasActive;
};
Lv2Proc::Lv2Proc(const LilvPlugin *plugin, Model* parent) :
LinkedModelGroup(parent),
m_plugin(plugin),
m_workLock(1),
m_midiInputBuf(m_maxMidiInputEvents),
m_midiInputReader(m_midiInputBuf)
{
createPorts();
initPlugin();
}
Lv2Proc::~Lv2Proc() { shutdownPlugin(); }
void Lv2Proc::reload() { Lv2ProcSuspender(this); }
void Lv2Proc::dumpPorts()
{
std::size_t num = 0;
for (const std::unique_ptr<Lv2Ports::PortBase>& port: m_ports)
{
(void)port;
dumpPort(num++);
}
}
void Lv2Proc::copyModelsFromCore()
{
struct FloatFromModelVisitor : public ConstModelVisitor
{
const std::vector<float>* m_scalePointMap; // in
float m_res; // out
void visit(const FloatModel& m) override { m_res = m.value(); }
void visit(const IntModel& m) override {
m_res = static_cast<float>(m.value()); }
void visit(const BoolModel& m) override {
m_res = static_cast<float>(m.value()); }
void visit(const ComboBoxModel& m) override {
m_res = (*m_scalePointMap)[static_cast<std::size_t>(m.value())]; }
};
struct Copy : public Lv2Ports::Visitor
{
void visit(Lv2Ports::Control& ctrl) override
{
FloatFromModelVisitor ffm;
ffm.m_scalePointMap = &ctrl.m_scalePointMap;
ctrl.m_connectedModel->accept(ffm);
ctrl.m_val = ffm.m_res;
}
void visit(Lv2Ports::Cv& cv) override
{
FloatFromModelVisitor ffm;
ffm.m_scalePointMap = &cv.m_scalePointMap;
cv.m_connectedModel->accept(ffm);
// dirty fix, needs better interpolation
std::fill(cv.m_buffer.begin(), cv.m_buffer.end(), ffm.m_res);
}
void visit(Lv2Ports::AtomSeq& atomPort) override
{
lv2_evbuf_reset(atomPort.m_buf.get(), true);
}
} copy;
// feed each input port with the respective data from the LMMS core
for (const std::unique_ptr<Lv2Ports::PortBase>& port : m_ports)
{
if (port->m_flow == Lv2Ports::Flow::Input)
{
port->accept(copy);
}
}
// send pending MIDI events to atom port
if(m_midiIn)
{
LV2_Evbuf_Iterator iter = lv2_evbuf_begin(m_midiIn->m_buf.get());
// MIDI events waiting to go to the plugin?
while(m_midiInputReader.read_space() > 0)
{
const MidiInputEvent ev = m_midiInputReader.read(1)[0];
uint32_t atomStamp =
ev.time.frames(Engine::framesPerTick()) + ev.offset;
uint32_t type = Engine::getLv2Manager()->
uridCache()[Lv2UridCache::Id::midi_MidiEvent];
auto buf = std::array<uint8_t, 4>{};
std::size_t bufsize = writeToByteSeq(ev.ev, buf.data(), buf.size());
if(bufsize)
{
lv2_evbuf_write(&iter, atomStamp, type, bufsize, buf.data());
}
}
}
}
void Lv2Proc::copyModelsToCore()
{
struct Copy : public Lv2Ports::Visitor
{
void visit(Lv2Ports::AtomSeq& atomPort) override
{
// we currently don't copy anything, but we need to clear the buffer
// for the plugin to write again
lv2_evbuf_reset(atomPort.m_buf.get(), false);
}
} copy;
// fetch data from each output port and bring it to the LMMS core
for (const std::unique_ptr<Lv2Ports::PortBase>& port : m_ports)
{
if (port->m_flow == Lv2Ports::Flow::Output)
{
port->accept(copy);
}
}
}
void Lv2Proc::copyBuffersFromCore(const SampleFrame* buf,
unsigned firstChan, unsigned num,
fpp_t frames)
{
inPorts().m_left->copyBuffersFromCore(buf, firstChan, frames);
if (num > 1)
{
// if the caller requests to take input from two channels, but we only
// have one input channel... take medium of left and right for
// mono input
// (this happens if we have two outputs and only one input)
if (inPorts().m_right)
{
inPorts().m_right->copyBuffersFromCore(buf, firstChan + 1, frames);
}
else
{
inPorts().m_left->averageWithBuffersFromCore(buf, firstChan + 1, frames);
}
}
}
void Lv2Proc::copyBuffersToCore(SampleFrame* buf,
unsigned firstChan, unsigned num,
fpp_t frames) const
{
outPorts().m_left->copyBuffersToCore(buf, firstChan + 0, frames);
if (num > 1)
{
// if the caller requests to copy into two channels, but we only have
// one output channel, duplicate our output
// (this happens if we have two inputs and only one output)
Lv2Ports::Audio* ap = outPorts().m_right
? outPorts().m_right : outPorts().m_left;
ap->copyBuffersToCore(buf, firstChan + 1, frames);
}
}
void Lv2Proc::run(fpp_t frames)
{
if (m_worker)
{
// Process any worker replies
m_worker->emitResponses();
}
lilv_instance_run(m_instance, static_cast<uint32_t>(frames));
if (m_worker)
{
// Notify the plugin the run() cycle is finished
m_worker->notifyPluginThatRunFinished();
}
}
// in case there will be a PR which removes this callback and instead adds a
// `ringbuffer_t<MidiEvent + time info>` to `class Instrument`, this
// function (and the ringbuffer and its reader in `Lv2Proc`) will simply vanish
void Lv2Proc::handleMidiInputEvent(const MidiEvent &event, const TimePos &time, f_cnt_t offset)
{
if(m_midiIn)
{
// ringbuffer allows only one writer at a time
// however, this function can be called by multiple threads
// (different RT and non-RT!) at the same time
// for now, a spinlock looks like the most safe/easy compromise
// source: https://en.cppreference.com/w/cpp/atomic/atomic_flag
while (m_ringLock.test_and_set(std::memory_order_acquire)) // acquire lock
; // spin
MidiInputEvent ev { event, time, offset };
std::size_t written = m_midiInputBuf.write(&ev, 1);
if(written != 1)
{
qWarning("MIDI ringbuffer is too small! Discarding MIDI event.");
}
m_ringLock.clear(std::memory_order_release);
}
else
{
qWarning() << "Warning: Caught MIDI event for an Lv2 instrument"
<< "that can not handle MIDI... Ignoring";
}
}
AutomatableModel *Lv2Proc::modelAtPort(const QString &uri)
{
const auto itr = m_connectedModels.find(uri.toUtf8().data());
return itr != m_connectedModels.end() ? itr->second : nullptr;
}
void Lv2Proc::initPlugin()
{
m_features.initCommon();
initPluginSpecificFeatures();
m_features.createFeatureVectors();
m_instance = lilv_plugin_instantiate(m_plugin,
Engine::audioEngine()->outputSampleRate(),
m_features.featurePointers());
if (m_instance)
{
const auto iface = static_cast<const LV2_Worker_Interface*>(
lilv_instance_get_extension_data(m_instance, LV2_WORKER__interface));
if (iface)
{
m_worker->setHandle(lilv_instance_get_handle(m_instance));
m_worker->setInterface(iface);
}
for (std::size_t portNum = 0; portNum < m_ports.size(); ++portNum)
{
connectPort(portNum);
}
lilv_instance_activate(m_instance);
}
else
{
qCritical() << "Failed to create an instance of"
<< qStringFromPluginNode(m_plugin, lilv_plugin_get_name)
<< "(URI:"
<< lilv_node_as_uri(lilv_plugin_get_uri(m_plugin))
<< ")";
throw std::runtime_error("Failed to create Lv2 processor");
}
}
void Lv2Proc::shutdownPlugin()
{
lilv_instance_deactivate(m_instance);
lilv_instance_free(m_instance);
m_instance = nullptr;
m_features.clear();
m_options.clear();
}
bool Lv2Proc::hasNoteInput() const
{
return m_midiIn;
// we could additionally check for
// http://lv2plug.in/ns/lv2core#InstrumentPlugin
// however, jalv does not do that, too
// so, if there's any MIDI input, we just assume we can send notes there
}
void Lv2Proc::initMOptions()
{
/*
sampleRate:
LMMS can in theory inform plugins of a new sample rate.
However, Lv2 plugins seem to not allow sample rate changes
(not even through LV2_Options_Interface) - it's assumed to be
fixed after being passed via LV2_Descriptor::instantiate.
So, if the sampleRate would change, the plugin will need to
re-initialize, and this code section will be
executed again, creating a new option vector.
*/
float sampleRate = Engine::audioEngine()->outputSampleRate();
int32_t blockLength = Engine::audioEngine()->framesPerPeriod();
int32_t sequenceSize = defaultEvbufSize();
using Id = Lv2UridCache::Id;
m_options.initOption<float>(Id::param_sampleRate, sampleRate);
m_options.initOption<int32_t>(Id::bufsz_maxBlockLength, blockLength);
m_options.initOption<int32_t>(Id::bufsz_minBlockLength, blockLength);
m_options.initOption<int32_t>(Id::bufsz_nominalBlockLength, blockLength);
m_options.initOption<int32_t>(Id::bufsz_sequenceSize, sequenceSize);
m_options.createOptionVectors();
}
void Lv2Proc::initPluginSpecificFeatures()
{
// options
initMOptions();
m_features[LV2_OPTIONS__options] = const_cast<LV2_Options_Option*>(m_options.feature());
// worker (if plugin has worker extension)
Lv2Manager* mgr = Engine::getLv2Manager();
if (lilv_plugin_has_extension_data(m_plugin, mgr->uri(LV2_WORKER__interface).get()))
{
bool threaded = !Engine::audioEngine()->renderOnly();
m_worker.emplace(&m_workLock, threaded);
m_features[LV2_WORKER__schedule] = m_worker->feature();
// note: the worker interface can not be instantiated yet - it requires m_instance. see initPlugin()
}
}
void Lv2Proc::loadFileInternal(const QString &file)
{
(void)file;
}
void Lv2Proc::createPort(std::size_t portNum)
{
Lv2Ports::Meta meta;
meta.get(m_plugin, portNum);
const LilvPort* lilvPort = lilv_plugin_get_port_by_index(m_plugin,
static_cast<uint32_t>(portNum));
Lv2Ports::PortBase* port;
switch (meta.m_type)
{
case Lv2Ports::Type::Control:
{
auto ctrl = new Lv2Ports::Control;
if (meta.m_flow == Lv2Ports::Flow::Input)
{
AutoLilvNode node(lilv_port_get_name(m_plugin, lilvPort));
QString dispName = lilv_node_as_string(node.get());
sample_rate_t sr = Engine::audioEngine()->outputSampleRate();
if(meta.def() < meta.min(sr) || meta.def() > meta.max(sr))
{
qWarning() << "Warning: Plugin"
<< qStringFromPluginNode(m_plugin, lilv_plugin_get_name)
<< "(URI:"
<< lilv_node_as_uri(lilv_plugin_get_uri(m_plugin))
<< ") has a default value for port"
<< dispName
<< "which is not in range [min, max].";
}
switch (meta.m_vis)
{
case Lv2Ports::Vis::Generic:
{
// allow ~1000 steps
float stepSize = (meta.max(sr) - meta.min(sr)) / 1000.0f;
// make multiples of 0.01 (or 0.1 for larger values)
float minStep = (stepSize >= 1.0f) ? 0.1f : 0.01f;
stepSize -= fmodf(stepSize, minStep);
stepSize = std::max(stepSize, minStep);
ctrl->m_connectedModel.reset(
new FloatModel(meta.def(), meta.min(sr), meta.max(sr),
stepSize, nullptr, dispName));
break;
}
case Lv2Ports::Vis::Integer:
ctrl->m_connectedModel.reset(
new IntModel(static_cast<int>(meta.def()),
static_cast<int>(meta.min(sr)),
static_cast<int>(meta.max(sr)),
nullptr, dispName));
break;
case Lv2Ports::Vis::Enumeration:
{
ComboBoxModel* comboModel = new ComboBoxModel(nullptr, dispName);
{
AutoLilvScalePoints sps (static_cast<LilvScalePoints*>(lilv_port_get_scale_points(m_plugin, lilvPort)));
// temporary map, since lilv may return scale points in random order
std::map<float, const char*> scalePointMap;
LILV_FOREACH(scale_points, i, sps.get())
{
const LilvScalePoint* sp = lilv_scale_points_get(sps.get(), i);
const float f = lilv_node_as_float(lilv_scale_point_get_value(sp));
const char* s = lilv_node_as_string(lilv_scale_point_get_label(sp));
scalePointMap[f] = s;
}
for (const auto& [f,s] : scalePointMap)
{
ctrl->m_scalePointMap.push_back(f);
comboModel->addItem(s);
}
}
for(std::size_t i = 0; i < ctrl->m_scalePointMap.size(); ++i)
{
if(meta.def() == ctrl->m_scalePointMap[i])
{
comboModel->setValue(i);
comboModel->setInitValue(i);
break;
}
}
ctrl->m_connectedModel.reset(comboModel);
break;
}
case Lv2Ports::Vis::Toggled:
ctrl->m_connectedModel.reset(
new BoolModel(static_cast<bool>(meta.def()),
nullptr, dispName));
break;
}
if(meta.m_logarithmic)
{
ctrl->m_connectedModel->setScaleLogarithmic();
}
} // if m_flow == Input
port = ctrl;
break;
}
case Lv2Ports::Type::Audio:
{
auto audio = new Lv2Ports::Audio(static_cast<std::size_t>(Engine::audioEngine()->framesPerPeriod()),
portIsSideChain(m_plugin, lilvPort));
port = audio;
break;
}
case Lv2Ports::Type::AtomSeq:
{
auto atomPort = new Lv2Ports::AtomSeq;
{
AutoLilvNode uriAtomSupports(Engine::getLv2Manager()->uri(LV2_ATOM__supports));
AutoLilvNodes atomSupports(lilv_port_get_value(m_plugin, lilvPort, uriAtomSupports.get()));
AutoLilvNode uriMidiEvent(Engine::getLv2Manager()->uri(LV2_MIDI__MidiEvent));
LILV_FOREACH (nodes, itr, atomSupports.get())
{
if(lilv_node_equals(lilv_nodes_get(atomSupports.get(), itr), uriMidiEvent.get()))
{
atomPort->flags |= Lv2Ports::AtomSeq::FlagType::Midi;
}
}
}
int minimumSize = defaultEvbufSize();
Lv2Manager* mgr = Engine::getLv2Manager();
// check for alternative minimum size
{
AutoLilvNode rszMinimumSize = mgr->uri(LV2_RESIZE_PORT__minimumSize);
AutoLilvNodes minSizeV(lilv_port_get_value(m_plugin, lilvPort, rszMinimumSize.get()));
LilvNode* minSize = minSizeV ? lilv_nodes_get_first(minSizeV.get()) : nullptr;
if (minSize && lilv_node_is_int(minSize))
{
minimumSize = std::max(minimumSize, lilv_node_as_int(minSize));
}
}
atomPort->m_buf.reset(
lv2_evbuf_new(static_cast<uint32_t>(minimumSize),
mgr->uridMap().map(LV2_ATOM__Chunk),
mgr->uridMap().map(LV2_ATOM__Sequence)));
port = atomPort;
break;
}
default:
port = new Lv2Ports::Unknown;
}
// `meta` is of class `Lv2Ports::Meta` and `port` is of a child class
// we can now assign the `Lv2Ports::Meta` part of meta to ports, leaving
// the additional members of `port` unchanged
*static_cast<Lv2Ports::Meta*>(port) = meta;
port->m_port = lilvPort;
port->m_plugin = m_plugin;
m_ports[portNum].reset(port);
}
void Lv2Proc::createPorts()
{
// register ports at the processor after creation,
// i.e. link their data or count them
struct RegisterPort : public Lv2Ports::Visitor
{
Lv2Proc* m_proc;
void visit(Lv2Ports::Control& ctrl) override
{
if (ctrl.m_flow == Lv2Ports::Flow::Input)
{
AutomatableModel* amo = ctrl.m_connectedModel.get();
m_proc->m_connectedModels.emplace(
lilv_node_as_string(lilv_port_get_symbol(
m_proc->m_plugin, ctrl.m_port)),
amo);
m_proc->addModel(amo, ctrl.uri());
}
}
void visit(Lv2Ports::Audio& audio) override
{
if (audio.mustBeUsed())
{
StereoPortRef dummy;
StereoPortRef* portRef = &dummy;
switch (audio.m_flow)
{
case Lv2Ports::Flow::Input:
portRef = &m_proc->m_inPorts;
break;
case Lv2Ports::Flow::Output:
portRef = &m_proc->m_outPorts;
break;
case Lv2Ports::Flow::Unknown:
break;
}
// in Lv2, leftPort is defined to be the first port
if (!portRef->m_left) { portRef->m_left = &audio; }
else if (!portRef->m_right) { portRef->m_right = &audio; }
}
}
void visit(Lv2Ports::AtomSeq& atomPort) override
{
if(atomPort.m_flow == Lv2Ports::Flow::Input)
{
if(atomPort.flags & Lv2Ports::AtomSeq::FlagType::Midi)
{
// take any MIDI input, prefer mandatory MIDI input
// (Lv2Proc::check() assures there are <=1 mandatory MIDI
// input ports)
if(!m_proc->m_midiIn || !atomPort.m_optional)
m_proc->m_midiIn = &atomPort;
}
}
else if(atomPort.m_flow == Lv2Ports::Flow::Output)
{
if(atomPort.flags & Lv2Ports::AtomSeq::FlagType::Midi)
{
// take any MIDI output, prefer mandatory MIDI output
// (Lv2Proc::check() assures there are <=1 mandatory MIDI
// output ports)
if(!m_proc->m_midiOut || !atomPort.m_optional)
m_proc->m_midiOut = &atomPort;
}
}
else { Q_ASSERT(false); }
}
};
std::size_t maxPorts = lilv_plugin_get_num_ports(m_plugin);
m_ports.resize(maxPorts);
for (std::size_t portNum = 0; portNum < maxPorts; ++portNum)
{
createPort(portNum);
RegisterPort registerPort;
registerPort.m_proc = this;
m_ports[portNum]->accept(registerPort);
}
// initially assign model values to port values
copyModelsFromCore();
// debugging:
//dumpPorts();
}
struct ConnectPortVisitor : public Lv2Ports::Visitor
{
std::size_t m_num;
LilvInstance* m_instance;
void connectPort(void* location)
{
lilv_instance_connect_port(m_instance,
static_cast<uint32_t>(m_num), location);
}
void visit(Lv2Ports::AtomSeq& atomSeq) override
{
connectPort(lv2_evbuf_get_buffer(atomSeq.m_buf.get()));
}
void visit(Lv2Ports::Control& ctrl) override { connectPort(&ctrl.m_val); }
void visit(Lv2Ports::Audio& audio) override
{
connectPort((audio.mustBeUsed()) ? audio.m_buffer.data() : nullptr);
}
void visit(Lv2Ports::Unknown&) override { connectPort(nullptr); }
~ConnectPortVisitor() override = default;
};
// !This function must be realtime safe!
// use createPort to create any port before connecting
void Lv2Proc::connectPort(std::size_t num)
{
ConnectPortVisitor connect;
connect.m_num = num;
connect.m_instance = m_instance;
m_ports[num]->accept(connect);
}
void Lv2Proc::dumpPort(std::size_t num)
{
struct DumpPortDetail : public Lv2Ports::ConstVisitor
{
void visit(const Lv2Ports::Control& ctrl) override
{
qDebug() << " control port";
// output ports may be uninitialized yet, only print inputs
if (ctrl.m_flow == Lv2Ports::Flow::Input)
{
qDebug() << " value:" << ctrl.m_val;
}
}
void visit(const Lv2Ports::Audio& audio) override
{
qDebug() << (audio.isSideChain() ? " audio port (sidechain)"
: " audio port");
qDebug() << " buffer size:" << audio.bufferSize();
}
};
const Lv2Ports::PortBase& port = *m_ports[num];
qDebug().nospace() << "port " << num << ":";
qDebug() << " name:"
<< qStringFromPortName(m_plugin, port.m_port);
qDebug() << " flow: " << Lv2Ports::toStr(port.m_flow);
qDebug() << " type: " << Lv2Ports::toStr(port.m_type);
qDebug() << " visualization: " << Lv2Ports::toStr(port.m_vis);
if (port.m_type == Lv2Ports::Type::Control || port.m_type == Lv2Ports::Type::Cv)
{
sample_rate_t sr = Engine::audioEngine()->outputSampleRate();
qDebug() << " default:" << port.def();
qDebug() << " min:" << port.min(sr);
qDebug() << " max:" << port.max(sr);
}
qDebug() << " optional: " << port.m_optional;
qDebug() << " => USED: " << port.m_used;
DumpPortDetail dumper;
port.accept(dumper);
}
bool Lv2Proc::portIsSideChain(const LilvPlugin *plugin, const LilvPort *port)
{
return lilv_port_has_property(plugin, port,
uri(LV2_CORE_PREFIX "isSidechain").get());
}
bool Lv2Proc::portIsOptional(const LilvPlugin *plugin, const LilvPort *port)
{
return lilv_port_has_property(plugin, port,
uri(LV2_CORE__connectionOptional).get());
}
AutoLilvNode Lv2Proc::uri(const char *uriStr)
{
return Engine::getLv2Manager()->uri(uriStr);
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 24,696
|
C++
|
.cpp
| 758
| 29.040897
| 113
| 0.696109
|
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,838
|
Lv2Worker.cpp
|
LMMS_lmms/src/core/lv2/Lv2Worker.cpp
|
/*
* Lv2Worker.cpp - Lv2Worker implementation
*
* Copyright (c) 2022-2022 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 "Lv2Worker.h"
#include <cassert>
#include <QDebug>
#ifdef LMMS_HAVE_LV2
#include "Engine.h"
namespace lmms
{
// static wrappers
static LV2_Worker_Status
staticWorkerRespond(LV2_Worker_Respond_Handle handle,
uint32_t size, const void* data)
{
Lv2Worker* worker = static_cast<Lv2Worker*>(handle);
return worker->respond(size, data);
}
std::size_t Lv2Worker::bufferSize() const
{
// ardour uses this fixed size for ALSA:
return 8192 * 4;
// for jack, they use 4 * jack_port_type_get_buffer_size (..., JACK_DEFAULT_MIDI_TYPE)
// (possible extension for AudioDevice)
}
Lv2Worker::Lv2Worker(Semaphore* commonWorkLock, bool threaded) :
m_threaded(threaded),
m_response(bufferSize()),
m_requests(bufferSize()),
m_responses(bufferSize()),
m_requestsReader(m_requests),
m_responsesReader(m_responses),
m_sem(0),
m_workLock(commonWorkLock)
{
m_scheduleFeature.handle = static_cast<LV2_Worker_Schedule_Handle>(this);
m_scheduleFeature.schedule_work = [](LV2_Worker_Schedule_Handle handle,
uint32_t size, const void* data) -> LV2_Worker_Status
{
Lv2Worker* worker = static_cast<Lv2Worker*>(handle);
return worker->scheduleWork(size, data);
};
if (threaded) { m_thread = std::thread(&Lv2Worker::workerFunc, this); }
m_requests.mlock();
m_responses.mlock();
}
void Lv2Worker::setHandle(LV2_Handle handle)
{
assert(handle);
m_handle = handle;
}
void Lv2Worker::setInterface(const LV2_Worker_Interface* newInterface)
{
assert(newInterface);
m_interface = newInterface;
}
Lv2Worker::~Lv2Worker()
{
m_exit = true;
if(m_threaded) {
m_sem.post();
m_thread.join();
}
}
// Let the worker send responses to the audio thread
LV2_Worker_Status Lv2Worker::respond(uint32_t size, const void* data)
{
if(m_threaded)
{
if(m_responses.free() < sizeof(size) + size)
{
return LV2_WORKER_ERR_NO_SPACE;
}
else
{
m_responses.write((const char*)&size, sizeof(size));
if(size && data) { m_responses.write((const char*)data, size); }
}
}
else
{
assert(m_handle);
assert(m_interface);
m_interface->work_response(m_handle, size, data);
}
return LV2_WORKER_SUCCESS;
}
// Let the worker receive work from the audio thread and "work" on it
void Lv2Worker::workerFunc()
{
std::vector<char> buf;
uint32_t size;
while (true) {
m_sem.wait();
if (m_exit) { break; }
const std::size_t readSpace = m_requestsReader.read_space();
if (readSpace <= sizeof(size)) { continue; } // (should not happen)
m_requestsReader.read(sizeof(size)).copy((char*)&size, sizeof(size));
assert(size <= readSpace - sizeof(size));
if(size > buf.size()) { buf.resize(size); }
if(size) { m_requestsReader.read(size).copy(buf.data(), size); }
assert(m_handle);
assert(m_interface);
m_workLock->wait();
m_interface->work(m_handle, staticWorkerRespond, this, size, buf.data());
m_workLock->post();
}
}
// Let the audio thread schedule work for the worker
LV2_Worker_Status Lv2Worker::scheduleWork(uint32_t size, const void *data)
{
if (m_threaded)
{
if(m_requests.free() < sizeof(size) + size)
{
return LV2_WORKER_ERR_NO_SPACE;
}
else
{
// Schedule a request to be executed by the worker thread
m_requests.write((const char*)&size, sizeof(size));
if(size && data) { m_requests.write((const char*)data, size); }
m_sem.post();
}
}
else
{
assert(m_handle);
assert(m_interface);
// Execute work immediately in this thread
m_workLock->wait();
m_interface->work(m_handle, staticWorkerRespond, this, size, data);
m_workLock->post();
}
return LV2_WORKER_SUCCESS;
}
// Let the audio thread read incoming worker responses, and process it
void Lv2Worker::emitResponses()
{
std::size_t read_space = m_responsesReader.read_space();
uint32_t size;
while (read_space > sizeof(size))
{
assert(m_handle);
assert(m_interface);
m_responsesReader.read(sizeof(size)).copy((char*)&size, sizeof(size));
if(size) { m_responsesReader.read(size).copy(m_response.data(), size); }
m_interface->work_response(m_handle, size, m_response.data());
read_space -= sizeof(size) + size;
}
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 5,079
|
C++
|
.cpp
| 173
| 26.936416
| 87
| 0.722795
|
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,839
|
Lv2Basics.cpp
|
LMMS_lmms/src/core/lv2/Lv2Basics.cpp
|
/*
* Lv2Basics.cpp - basic Lv2 functions
*
* Copyright (c) 2019-2020 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 "Lv2Basics.h"
#ifdef LMMS_HAVE_LV2
namespace lmms
{
QString qStringFromPluginNode(const LilvPlugin* plug,
LilvNode* (*getFunc)(const LilvPlugin*))
{
return QString::fromUtf8(
lilv_node_as_string(AutoLilvNode((*getFunc)(plug)).get()));
}
QString qStringFromPortName(const LilvPlugin* plug, const LilvPort* port)
{
return QString::fromUtf8(
lilv_node_as_string(AutoLilvNode(lilv_port_get_name(plug, port)).get()));
}
std::string stdStringFromPortName(const LilvPlugin* plug, const LilvPort* port)
{
return std::string(
lilv_node_as_string(AutoLilvNode(lilv_port_get_name(plug, port)).get()));
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 1,586
|
C++
|
.cpp
| 45
| 33.311111
| 80
| 0.756527
|
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,840
|
Lv2Features.cpp
|
LMMS_lmms/src/core/lv2/Lv2Features.cpp
|
/*
* Lv2Features.cpp - Lv2Features implementation
*
* Copyright (c) 2020-2020 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 "Lv2Features.h"
#ifdef LMMS_HAVE_LV2
#include <QtGlobal>
#include "Engine.h"
#include "Lv2Manager.h"
namespace lmms
{
bool Lv2Features::isFeatureSupported(const char* featName)
{
return Engine::getLv2Manager()->isFeatureSupported(featName);
}
Lv2Features::Lv2Features()
{
const Lv2Manager* man = Engine::getLv2Manager();
// create (yet empty) map feature URI -> feature
for(auto uri : man->supportedFeatureURIs())
{
m_featureByUri.emplace(uri, nullptr);
}
}
void Lv2Features::initCommon()
{
Lv2Manager* man = Engine::getLv2Manager();
// init m_featureByUri with the plugin-common features
operator[](LV2_URID__map) = man->uridMap().mapFeature();
operator[](LV2_URID__unmap) = man->uridMap().unmapFeature();
}
void Lv2Features::createFeatureVectors()
{
// create vector of features
for(const auto& [uri, feature] : m_featureByUri)
{
/*
If pr.second is nullptr here, this means that the LV2_feature
has no "data". If this happens here, this means
* either that this feature is static
(e.g. LV2_BUF_SIZE__boundedBlockLength)
* or that the programmer forgot to use operator[] before feature
vector creation (This can be done in
Lv2Proc::initPluginSpecificFeatures or in Lv2Features::initCommon)
*/
m_features.push_back(LV2_Feature{(const char*)uri.data(), (void*)feature});
}
// create pointer vector (for lilv_plugin_instantiate)
m_featurePointers.reserve(m_features.size() + 1);
for (const auto& feature : m_features)
{
m_featurePointers.push_back(&feature);
}
m_featurePointers.push_back(nullptr);
}
void *&Lv2Features::operator[](const char *featName)
{
auto itr = m_featureByUri.find(featName);
Q_ASSERT(itr != m_featureByUri.end());
return itr->second;
}
void Lv2Features::clear()
{
m_features.clear();
for (auto& [uri, feature] : m_featureByUri)
{
(void) uri;
feature = nullptr;
}
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 2,869
|
C++
|
.cpp
| 91
| 29.175824
| 80
| 0.742805
|
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,841
|
Lv2UridCache.cpp
|
LMMS_lmms/src/core/lv2/Lv2UridCache.cpp
|
/*
* Lv2UridCache.cpp - Lv2UridCache implementation
*
* Copyright (c) 2020-2020 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 "Lv2UridCache.h"
#ifdef LMMS_HAVE_LV2
#include <lv2/atom/atom.h>
#include <lv2/buf-size/buf-size.h>
#include <lv2/midi/midi.h>
#include <lv2/parameters/parameters.h>
#include <QtGlobal>
#include "Lv2UridMap.h"
// support newer URIs on old systems
#ifndef LV2_BUF_SIZE__nominalBlockLength
#define LV2_BUF_SIZE__nominalBlockLength LV2_BUF_SIZE_PREFIX "nominalBlockLength"
#endif
namespace lmms
{
uint32_t Lv2UridCache::operator[](Lv2UridCache::Id id) const
{
Q_ASSERT(id != Id::size);
return m_cache[static_cast<std::size_t>(id)];
}
Lv2UridCache::Lv2UridCache(UridMap &mapper)
{
const uint32_t noIdYet = 0;
std::fill_n(m_cache, static_cast<std::size_t>(Id::size), noIdYet);
auto init = [this, &mapper](Id id, const char* uridStr)
{
m_cache[static_cast<std::size_t>(id)] = mapper.map(uridStr);
};
init(Id::atom_Float, LV2_ATOM__Float);
init(Id::atom_Int, LV2_ATOM__Int);
init(Id::bufsz_minBlockLength, LV2_BUF_SIZE__minBlockLength);
init(Id::bufsz_maxBlockLength, LV2_BUF_SIZE__maxBlockLength);
init(Id::bufsz_nominalBlockLength, LV2_BUF_SIZE__nominalBlockLength);
init(Id::bufsz_sequenceSize, LV2_BUF_SIZE__sequenceSize);
init(Id::midi_MidiEvent, LV2_MIDI__MidiEvent);
init(Id::param_sampleRate, LV2_PARAMETERS__sampleRate);
for(uint32_t urid : m_cache) { Q_ASSERT(urid != noIdYet); }
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 2,304
|
C++
|
.cpp
| 62
| 35.241935
| 81
| 0.749663
|
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,842
|
Lv2SubPluginFeatures.cpp
|
LMMS_lmms/src/core/lv2/Lv2SubPluginFeatures.cpp
|
/*
* Lv2SubPluginFeatures.cpp - derivation from
* Plugin::Descriptor::SubPluginFeatures for
* hosting LV2 plugins
*
* Copyright (c) 2018-2024 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 "Lv2SubPluginFeatures.h"
#ifdef LMMS_HAVE_LV2
#include <QDesktopServices>
#include <QHBoxLayout>
#include <QLabel>
#include <QUrl>
#include "Engine.h"
#include "Lv2Basics.h"
#include "Lv2Manager.h"
namespace lmms
{
const LilvPlugin* Lv2SubPluginFeatures::getPlugin(
const Plugin::Descriptor::SubPluginFeatures::Key& k)
{
const LilvPlugin* result = Engine::getLv2Manager()->
getPlugin(k.attributes["uri"]);
Q_ASSERT(result);
return result;
}
QString Lv2SubPluginFeatures::pluginName(const LilvPlugin* plug)
{
return qStringFromPluginNode(plug, lilv_plugin_get_name);
}
Lv2SubPluginFeatures::Lv2SubPluginFeatures(Plugin::Type type) :
SubPluginFeatures(type)
{
}
static void addHbox(QWidget* parent, QString left, QString right)
{
if (right.isEmpty()) { return; }
auto container = new QWidget(parent);
auto l = new QHBoxLayout(container);
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
auto leftLabel = new QLabel(container);
leftLabel->setText(left);
leftLabel->setAlignment(Qt::AlignTop);
auto rightLabel = new QLabel(container);
if (right.startsWith("http") && !right.contains(' ') && !right.contains('\n'))
{
right = QString("<a href=\"%1\">%1</a>").arg(right);
rightLabel->setTextInteractionFlags(rightLabel->textInteractionFlags()
| Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
rightLabel->setTextFormat(Qt::RichText);
rightLabel->setOpenExternalLinks(true);
}
rightLabel->setText(right);
rightLabel->setWordWrap(true);
l->addWidget(leftLabel);
l->addWidget(rightLabel, 1);
}
static void addLabel(QWidget* parent, QString left, QString right)
{
auto lbl = new QLabel(parent);
if (right.isEmpty()) { return; }
if (right.startsWith("http") && !right.contains(' ') && !right.contains('\n'))
{
right = QString("<a href=\"%1\">%1</a>").arg(right);
lbl->setTextInteractionFlags(lbl->textInteractionFlags()
| Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard);
lbl->setTextFormat(Qt::RichText);
lbl->setOpenExternalLinks(true);
}
lbl->setText(left + right);
}
AutoLilvNodes pluginGetValues(const LilvPlugin* plug, const char* valueUri)
{
assert(plug);
AutoLilvNode valueUriNode{Engine::getLv2Manager()->uri(valueUri)};
return AutoLilvNodes{lilv_plugin_get_value(plug, valueUriNode.get())};
}
void Lv2SubPluginFeatures::fillDescriptionWidget(QWidget* parent,
const Key* k) const
{
const LilvPlugin* plug = getPlugin(*k);
QString pluginNameAndVersion = "<b>" + pluginName(plug) + "</b>";
{
AutoLilvNodes minorVersions = pluginGetValues(plug, LILV_NS_LV2 "minorVersion");
AutoLilvNodes microVersions = pluginGetValues(plug, LILV_NS_LV2 "microVersion");
if (minorVersions && microVersions)
{
QString min = lilv_node_as_string(lilv_nodes_get_first(minorVersions.get()));
QString mic = lilv_node_as_string(lilv_nodes_get_first(microVersions.get()));
pluginNameAndVersion += QString(" v%1.%2").arg(min).arg(mic);
}
}
(new QLabel(parent))->setText(pluginNameAndVersion);
{
AutoLilvNodes comments = pluginGetValues(plug, LILV_NS_RDFS "comment");
if (comments)
{
QString description{lilv_node_as_string(lilv_nodes_get_first(comments.get()))};
auto descLabel = new QLabel(parent);
descLabel->setText("<i>" + description.trimmed() + "</i>");
descLabel->setWordWrap(true);
}
}
addLabel(parent, QObject::tr("URI: "), lilv_node_as_uri(lilv_plugin_get_uri(plug)));
addHbox(parent, QObject::tr("Project: "),
qStringFromPluginNode(plug, lilv_plugin_get_project));
addHbox(parent, QObject::tr("Maker: "),
qStringFromPluginNode(plug, lilv_plugin_get_author_name));
{
AutoLilvNodes homepages = pluginGetValues(plug, LILV_NS_DOAP "homepage");
if (homepages)
{
const char* homepage = lilv_node_as_uri(lilv_nodes_get_first(homepages.get()));
QString homepageStr{homepage};
addLabel(parent, QObject::tr("Homepage: "), homepageStr);
}
}
{
AutoLilvNodes licenses = pluginGetValues(plug, LILV_NS_DOAP "license");
addLabel(parent, QObject::tr("License: "),
licenses
? lilv_node_as_uri(lilv_nodes_get_first(licenses.get()))
: "<unknown>");
}
{
const LilvNode* libraryUriNode = lilv_plugin_get_bundle_uri(plug);
const char* libraryUri = lilv_node_as_uri(libraryUriNode);
auto filename = AutoLilvPtr<char>(lilv_file_uri_parse(libraryUri, nullptr));
if (filename)
{
new QLabel(QObject::tr("File: %1").arg(filename.get()), parent);
}
}
}
QString Lv2SubPluginFeatures::additionalFileExtensions(
const Plugin::Descriptor::SubPluginFeatures::Key& k) const
{
(void)k;
// lv2 only loads .lv2 files
// maybe add conversions later, e.g. for loading xmz
return QString();
}
QString Lv2SubPluginFeatures::displayName(
const Plugin::Descriptor::SubPluginFeatures::Key& k) const
{
return pluginName(getPlugin(k));
}
QString Lv2SubPluginFeatures::description(
const Plugin::Descriptor::SubPluginFeatures::Key& k) const
{
auto mgr = Engine::getLv2Manager();
const LilvPlugin* plug = mgr->getPlugin(k.attributes["uri"]);
if (plug)
{
QString result;
AutoLilvNode rdfs_comment{mgr->uri(LILV_NS_RDFS "comment")};
AutoLilvNodes comments{lilv_plugin_get_value(plug, rdfs_comment.get())};
if (comments)
{
result += lilv_node_as_string(lilv_nodes_get_first(comments.get()));
result += "\n\n";
}
result += lilv_node_as_uri(lilv_plugin_get_uri(plug));
return result.trimmed();
}
return QObject::tr("failed to load description");
}
const PixmapLoader* Lv2SubPluginFeatures::logo(
const Plugin::Descriptor::SubPluginFeatures::Key& k) const
{
(void)k;
return nullptr; // Lv2 currently does not support this
}
void Lv2SubPluginFeatures::listSubPluginKeys(const Plugin::Descriptor* desc,
KeyList& kl) const
{
Lv2Manager* lv2Mgr = Engine::getLv2Manager();
for (const auto& uriInfoPair : *lv2Mgr)
{
if (uriInfoPair.second.type() == m_type && uriInfoPair.second.isValid())
{
using KeyType =
Plugin::Descriptor::SubPluginFeatures::Key;
KeyType::AttributeMap atm;
atm["uri"] = QString::fromUtf8(uriInfoPair.first.c_str());
const LilvPlugin* plug = uriInfoPair.second.plugin();
kl.push_back(KeyType(desc, pluginName(plug), atm));
//qDebug() << "Found LV2 sub plugin key of type" <<
// m_type << ":" << pr.first.c_str();
}
}
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 7,408
|
C++
|
.cpp
| 213
| 32.159624
| 85
| 0.731772
|
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,843
|
Lv2ControlBase.cpp
|
LMMS_lmms/src/core/lv2/Lv2ControlBase.cpp
|
/*
* Lv2ControlBase.cpp - Lv2 control base class
*
* 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 "Lv2ControlBase.h"
#ifdef LMMS_HAVE_LV2
#include <algorithm>
#include <QDebug>
#include <QtGlobal>
#include "Engine.h"
#include "Lv2Manager.h"
#include "Lv2Proc.h"
namespace lmms
{
Plugin::Type Lv2ControlBase::check(const LilvPlugin *plugin,
std::vector<PluginIssue> &issues)
{
// for some reason, all checks can be done by one processor...
return Lv2Proc::check(plugin, issues);
}
Lv2ControlBase::Lv2ControlBase(Model* that, const QString &uri) :
m_plugin(Engine::getLv2Manager()->getPlugin(uri))
{
if (m_plugin)
{
init(that);
}
else
{
qCritical() << "No Lv2 plugin found for URI" << uri;
throw std::runtime_error("No Lv2 plugin found for given URI");
}
}
Lv2ControlBase::~Lv2ControlBase() = default;
void Lv2ControlBase::init(Model* meAsModel)
{
int channelsLeft = DEFAULT_CHANNELS; // LMMS plugins are stereo
while (channelsLeft > 0)
{
std::unique_ptr<Lv2Proc> newOne = std::make_unique<Lv2Proc>(m_plugin, meAsModel);
channelsLeft -= std::max(
1 + static_cast<bool>(newOne->inPorts().m_right),
1 + static_cast<bool>(newOne->outPorts().m_right));
Q_ASSERT(channelsLeft >= 0);
m_procs.push_back(std::move(newOne));
}
m_channelsPerProc = DEFAULT_CHANNELS / m_procs.size();
linkAllModels();
}
void Lv2ControlBase::shutdown()
{
// currently nothing to do here
}
void Lv2ControlBase::reload()
{
for (const auto& c : m_procs) { c->reload(); }
}
LinkedModelGroup *Lv2ControlBase::getGroup(std::size_t idx)
{
return (m_procs.size() > idx) ? m_procs[idx].get() : nullptr;
}
const LinkedModelGroup *Lv2ControlBase::getGroup(std::size_t idx) const
{
return (m_procs.size() > idx) ? m_procs[idx].get() : nullptr;
}
void Lv2ControlBase::copyModelsFromLmms() {
for (const auto& c : m_procs) { c->copyModelsFromCore(); }
}
void Lv2ControlBase::copyModelsToLmms() const
{
for (const auto& c : m_procs) { c->copyModelsToCore(); }
}
void Lv2ControlBase::copyBuffersFromLmms(const SampleFrame* buf, fpp_t frames) {
unsigned firstChan = 0; // tell the procs which channels they shall read from
for (const auto& c : m_procs)
{
c->copyBuffersFromCore(buf, firstChan, m_channelsPerProc, frames);
firstChan += m_channelsPerProc;
}
}
void Lv2ControlBase::copyBuffersToLmms(SampleFrame* buf, fpp_t frames) const {
unsigned firstChan = 0; // tell the procs which channels they shall write to
for (const auto& c : m_procs) {
c->copyBuffersToCore(buf, firstChan, m_channelsPerProc, frames);
firstChan += m_channelsPerProc;
}
}
void Lv2ControlBase::run(fpp_t frames) {
for (const auto& c : m_procs) { c->run(frames); }
}
void Lv2ControlBase::saveSettings(QDomDocument &doc, QDomElement &that)
{
LinkedModelGroups::saveSettings(doc, that);
// TODO: save state if supported by plugin
}
void Lv2ControlBase::loadSettings(const QDomElement &that)
{
LinkedModelGroups::loadSettings(that);
// TODO: load state if supported by plugin
}
void Lv2ControlBase::loadFile(const QString &file)
{
(void)file;
}
std::size_t Lv2ControlBase::controlCount() const {
std::size_t res = 0;
for (const auto& c : m_procs) { res += c->controlCount(); }
return res;
}
bool Lv2ControlBase::hasNoteInput() const
{
return std::any_of(m_procs.begin(), m_procs.end(),
[](const auto& c) { return c->hasNoteInput(); });
}
void Lv2ControlBase::handleMidiInputEvent(const MidiEvent &event,
const TimePos &time, f_cnt_t offset)
{
for (const auto& c : m_procs) { c->handleMidiInputEvent(event, time, offset); }
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 4,489
|
C++
|
.cpp
| 140
| 29.764286
| 83
| 0.737386
|
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,844
|
Lv2Ports.cpp
|
LMMS_lmms/src/core/lv2/Lv2Ports.cpp
|
/*
* Lv2Ports.cpp - Lv2 port classes implementation
*
* Copyright (c) 2019-2020 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 "Lv2Ports.h"
#ifdef LMMS_HAVE_LV2
#include <lv2/atom/atom.h>
#include <lv2/port-props/port-props.h>
#include "Engine.h"
#include "Lv2Basics.h"
#include "Lv2Manager.h"
#include "Lv2Evbuf.h"
#include "SampleFrame.h"
namespace lmms::Lv2Ports
{
const char *toStr(Flow pf)
{
switch(pf)
{
case Flow::Unknown: return "unknown";
case Flow::Input: return "input";
case Flow::Output: return "output";
}
return "";
}
const char *toStr(Type pt)
{
switch(pt)
{
case Type::Unknown: return "unknown";
case Type::Control: return "control";
case Type::Audio: return "audio";
case Type::AtomSeq: return "atom-sequence";
case Type::Cv: return "cv";
}
return "";
}
const char *toStr(Vis pv)
{
switch(pv)
{
case Vis::Toggled: return "toggled";
case Vis::Enumeration: return "enumeration";
case Vis::Integer: return "integer";
case Vis::Generic: return "none";
}
return "";
}
std::vector<PluginIssue> Meta::get(const LilvPlugin *plugin,
std::size_t portNum)
{
std::vector<PluginIssue> portIssues;
auto issue = [&portIssues](PluginIssueType i, std::string msg = "") {
portIssues.emplace_back(i, std::move(msg)); };
Lv2Manager* man = Engine::getLv2Manager();
const LilvPort* lilvPort = lilv_plugin_get_port_by_index(
plugin, static_cast<uint32_t>(portNum));
auto portFunc = [&plugin, &lilvPort, &man](
bool (*fptr)(const LilvPlugin*, const LilvPort*, const LilvNode*),
const char* str) {
return fptr(plugin, lilvPort, man->uri(str).get());
};
auto hasProperty = [&portFunc](const char* str) {
return portFunc(lilv_port_has_property, str); };
auto isA = [&portFunc](const char* str) {
return portFunc(lilv_port_is_a, str); };
const std::string portName = stdStringFromPortName(plugin, lilvPort);
m_optional = hasProperty(LV2_CORE__connectionOptional);
m_vis = hasProperty(LV2_CORE__toggled)
? Vis::Toggled
: hasProperty(LV2_CORE__enumeration)
? Vis::Enumeration
: hasProperty(LV2_CORE__integer)
? Vis::Integer // WARNING: this may still be changed below
: Vis::Generic;
if (isA(LV2_CORE__InputPort)) { m_flow = Flow::Input; }
else if (isA(LV2_CORE__OutputPort)) { m_flow = Flow::Output; }
else {
m_flow = Flow::Unknown;
issue(PluginIssueType::UnknownPortFlow, portName);
}
m_def = .0f;
m_min = std::numeric_limits<decltype(m_min)>::lowest();
m_max = std::numeric_limits<decltype(m_max)>::max();
auto m_min_set = [this]{ return m_min != std::numeric_limits<decltype(m_min)>::lowest(); };
auto m_max_set = [this]{ return m_max != std::numeric_limits<decltype(m_max)>::max(); };
m_type = Type::Unknown;
if (isA(LV2_CORE__ControlPort) || isA(LV2_CORE__CVPort))
{
// Read metadata for control ports
// CV ports are mostly the same as control ports, so we take
// mostly the same metadata
if (isA(LV2_CORE__CVPort))
{
// currently not supported, but we can still check the metadata
issue(PluginIssueType::BadPortType, "cvPort");
}
m_type = isA(LV2_CORE__CVPort) ? Type::Cv : Type::Control;
bool isToggle = m_vis == Vis::Toggled;
LilvNode * defN, * minN = nullptr, * maxN = nullptr;
lilv_port_get_range(plugin, lilvPort, &defN,
isToggle ? nullptr : &minN,
isToggle ? nullptr : &maxN);
AutoLilvNode def(defN), min(minN), max(maxN);
auto takeRangeValue = [&](LilvNode* node,
float& storeHere, PluginIssueType it)
{
if (node) { storeHere = lilv_node_as_float(node); }
else
{
// CV ports do not require ranges
if(m_flow == Flow::Input && m_type != Type::Cv)
{
issue(it, portName);
}
}
};
takeRangeValue(def.get(), m_def, PluginIssueType::PortHasNoDef);
if (isToggle)
{
m_min = .0f;
m_max = 1.f;
if(def.get() && m_def != m_min && m_def != m_max)
{
issue(PluginIssueType::DefaultValueNotInRange, portName);
}
}
else
{
// take min/max
takeRangeValue(min.get(), m_min, PluginIssueType::PortHasNoMin);
takeRangeValue(max.get(), m_max, PluginIssueType::PortHasNoMax);
if(m_type == Type::Cv)
{
// no range is allowed and bashed to [-1,+1],
// but only min or only max does not make sense
if(!m_min_set() && !m_max_set())
{
m_min = -1.f;
m_max = +1.f;
}
else if(!m_min_set()) { issue(PluginIssueType::PortHasNoMin, portName); }
else if(!m_max_set()) { issue(PluginIssueType::PortHasNoMax, portName); }
}
if(m_min > m_max) { issue(PluginIssueType::MinGreaterMax, portName); }
// sampleRate
if (hasProperty(LV2_CORE__sampleRate)) { m_sampleRate = true; }
// default value
if (def.get())
{
if (m_def < m_min) { issue(PluginIssueType::DefaultValueNotInRange, portName); }
else if (m_def > m_max)
{
if(m_sampleRate)
{
// multiplying with sample rate will hopefully lead us
// to a good default value
}
else { issue(PluginIssueType::DefaultValueNotInRange, portName); }
}
}
// visualization
if (!m_min_set() ||
!m_max_set() ||
// if we get here, min and max are set, so max-min should not overflow:
(m_vis == Vis::Integer && m_max - m_min > 15.0f))
{
// range too large for spinbox visualisation, use knobs
// e.g. 0...15 would be OK
m_vis = Vis::Generic;
}
}
}
else if (isA(LV2_CORE__AudioPort)) { m_type = Type::Audio; }
else if (isA(LV2_ATOM__AtomPort))
{
AutoLilvNode uriAtomSequence(Engine::getLv2Manager()->uri(LV2_ATOM__Sequence));
AutoLilvNode uriAtomBufferType(Engine::getLv2Manager()->uri(LV2_ATOM__bufferType));
AutoLilvNodes bufferTypes(lilv_port_get_value(plugin, lilvPort, uriAtomBufferType.get()));
if (lilv_nodes_contains(bufferTypes.get(), uriAtomSequence.get()))
{
// we accept all kinds of atom sequence ports, even if they take or
// offer atom types that we do not support:
// * atom input ports only say what *can* be input, but not what is
// required as input
// * atom output ports only say what *can* be output, but not what must
// be evaluated
m_type = Type::AtomSeq;
}
}
if(m_type == Type::Unknown)
{
if (m_optional) { m_used = false; }
else {
issue(PluginIssueType::UnknownPortType, portName);
}
}
if (hasProperty(LV2_PORT_PROPS__logarithmic))
{
// check min/max available
// we requre them anyways, but this will detect plugins that will
// be non-Lv2-conforming
if(m_min == std::numeric_limits<decltype(m_min)>::lowest())
{
issue(PluginIssueType::LogScaleMinMissing, portName);
}
if(m_max == std::numeric_limits<decltype(m_max)>::max())
{
issue(PluginIssueType::LogScaleMaxMissing, portName);
}
// forbid min < 0 < max
if(m_min < 0.f && m_max > 0.f)
{
issue(PluginIssueType::LogScaleMinMaxDifferentSigns, portName);
}
m_logarithmic = true;
}
return portIssues;
}
QString PortBase::name() const
{
AutoLilvNode node(lilv_port_get_name(m_plugin, m_port));
QString res = lilv_node_as_string(node.get());
return res;
}
QString PortBase::uri() const
{
return lilv_node_as_string(lilv_port_get_symbol(m_plugin, m_port));
}
Audio::Audio(std::size_t bufferSize, bool isSidechain)
: m_buffer(bufferSize), m_sidechain(isSidechain)
{
}
void Audio::copyBuffersFromCore(const SampleFrame* lmmsBuf,
unsigned channel, fpp_t frames)
{
for (std::size_t f = 0; f < static_cast<unsigned>(frames); ++f)
{
m_buffer[f] = lmmsBuf[f][channel];
}
}
void Audio::averageWithBuffersFromCore(const SampleFrame* lmmsBuf,
unsigned channel, fpp_t frames)
{
for (std::size_t f = 0; f < static_cast<unsigned>(frames); ++f)
{
m_buffer[f] = (m_buffer[f] + lmmsBuf[f][channel]) / 2.0f;
}
}
void Audio::copyBuffersToCore(SampleFrame* lmmsBuf,
unsigned channel, fpp_t frames) const
{
for (std::size_t f = 0; f < static_cast<unsigned>(frames); ++f)
{
lmmsBuf[f][channel] = m_buffer[f];
}
}
void AtomSeq::Lv2EvbufDeleter::operator()(LV2_Evbuf *n) { lv2_evbuf_free(n); }
} // namespace lmms::Lv2Ports
#endif // LMMS_HAVE_LV2
| 8,878
|
C++
|
.cpp
| 279
| 28.698925
| 92
| 0.686113
|
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,845
|
Lv2Manager.cpp
|
LMMS_lmms/src/core/lv2/Lv2Manager.cpp
|
/*
* Lv2Manager.cpp - Implementation of Lv2Manager class
*
* Copyright (c) 2018-2024 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 "Lv2Manager.h"
#ifdef LMMS_HAVE_LV2
#include <algorithm>
#include <cstdlib>
#include <lilv/lilv.h>
#include <lv2/buf-size/buf-size.h>
#include <lv2/options/options.h>
#include <lv2/worker/worker.h>
#include <QDebug>
#include <QElapsedTimer>
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "Plugin.h"
#include "Lv2ControlBase.h"
#include "Lv2Options.h"
#include "PluginIssue.h"
namespace lmms
{
const std::set<std::string_view> Lv2Manager::unstablePlugins =
{
// github.com/calf-studio-gear/calf, #278
"http://calf.sourceforge.net/plugins/Analyzer",
"http://calf.sourceforge.net/plugins/BassEnhancer",
"http://calf.sourceforge.net/plugins/CompensationDelay",
"http://calf.sourceforge.net/plugins/Crusher",
"http://calf.sourceforge.net/plugins/Exciter",
"http://calf.sourceforge.net/plugins/Saturator",
"http://calf.sourceforge.net/plugins/StereoTools",
"http://calf.sourceforge.net/plugins/TapeSimulator",
"http://calf.sourceforge.net/plugins/TransientDesigner",
"http://calf.sourceforge.net/plugins/Vinyl",
// https://gitlab.com/drobilla/blop-lv2/-/issues/3
"http://drobilla.net/plugins/blop/pulse",
"http://drobilla.net/plugins/blop/sawtooth",
"http://drobilla.net/plugins/blop/square",
"http://drobilla.net/plugins/blop/triangle",
// unstable
"urn:juced:DrumSynth"
};
const std::set<std::string_view> Lv2Manager::pluginsOnlyUsefulWithUi =
{
// Visualization, meters, and scopes etc., won't work if UI is disabled
"http://distrho.sf.net/plugins/ProM",
"http://distrho.sf.net/plugins/glBars",
"http://gareus.org/oss/lv2/meters#spectr30mono",
"http://gareus.org/oss/lv2/meters#spectr30stereo",
"http://gareus.org/oss/lv2/meters#bitmeter",
"http://gareus.org/oss/lv2/meters#BBCM6",
"http://gareus.org/oss/lv2/meters#BBCmono",
"http://gareus.org/oss/lv2/meters#BBCstereo",
"http://gareus.org/oss/lv2/meters#DINmono",
"http://gareus.org/oss/lv2/meters#DINstereo",
"http://gareus.org/oss/lv2/meters#EBUmono",
"http://gareus.org/oss/lv2/meters#EBUstereo",
"http://gareus.org/oss/lv2/meters#EBUr128",
"http://gareus.org/oss/lv2/meters#BBCM6",
"http://gareus.org/oss/lv2/meters#dr14mono",
"http://gareus.org/oss/lv2/meters#dr14stereo",
"http://gareus.org/oss/lv2/meters#K12mono",
"http://gareus.org/oss/lv2/meters#K12stereo",
"http://gareus.org/oss/lv2/meters#K14mono",
"http://gareus.org/oss/lv2/meters#K14stereo",
"http://gareus.org/oss/lv2/meters#K20mono",
"http://gareus.org/oss/lv2/meters#K20stereo",
"http://gareus.org/oss/lv2/meters#NORmono",
"http://gareus.org/oss/lv2/meters#NORstereo",
"http://gareus.org/oss/lv2/meters#COR",
"http://gareus.org/oss/lv2/meters#dBTPmono",
"http://gareus.org/oss/lv2/meters#dBTPstereo",
"http://gareus.org/oss/lv2/meters#TPnRMSmono",
"http://gareus.org/oss/lv2/meters#TPnRMSstereo",
"http://gareus.org/oss/lv2/meters#VUmono",
"http://gareus.org/oss/lv2/meters#VUstereo",
"http://gareus.org/oss/lv2/meters#goniometer",
"http://gareus.org/oss/lv2/meters#stereoscope",
"http://gareus.org/oss/lv2/meters#SigDistHist",
"http://gareus.org/oss/lv2/tuna#one",
"http://gareus.org/oss/lv2/tuna#two",
"http://gareus.org/oss/lv2/sisco#Mono",
"http://gareus.org/oss/lv2/sisco#Stereo",
"http://gareus.org/oss/lv2/spectra#Mono",
"http://gareus.org/oss/lv2/convoLV2#Mono",
"http://gareus.org/oss/lv2/convoLV2#MonoToStereo",
"http://gareus.org/oss/lv2/convoLV2#Stereo",
"http://gareus.org/oss/lv2/zeroconvolv#CfgMono",
"http://gareus.org/oss/lv2/zeroconvolv#CfgMonoToStereo",
"http://gareus.org/oss/lv2/zeroconvolv#CfgStereo",
"http://gareus.org/oss/lv2/zeroconvolv#Mono",
"http://gareus.org/oss/lv2/zeroconvolv#MonoToStereo",
"http://gareus.org/oss/lv2/zeroconvolv#Stereo",
"http://lsp-plug.in/plugins/lv2/latency_meter",
"http://lsp-plug.in/plugins/lv2/spectrum_analyzer_x1",
"http://lsp-plug.in/plugins/lv2/spectrum_analyzer_x2",
"http://lsp-plug.in/plugins/lv2/phase_detector",
"http://lsp-plug.in/plugins/lv2/profiler_mono",
"http://lsp-plug.in/plugins/lv2/profiler_stereo",
"http://invadarecords.com/plugins/lv2/meter",
"http://guitarix.sourceforge.net/plugins/gxtuner#tuner",
"https://github.com/jpcima/ADLplug",
"https://github.com/HiFi-LoFi/KlangFalter",
"https://github.com/klangfreund/SpectrumAnalyser",
"https://github.com/klangfreund/lufsmeter",
"https://github.com/laixinyuan/StereoSourceSepartion",
"urn:juce:TalFilter2",
"urn:juce:Vex",
"http://zynaddsubfx.sourceforge.net",
"http://geontime.com/geonkick/single"
};
const std::set<std::string_view> Lv2Manager::unstablePluginsBuffersizeLessEqual32 =
{
"http://moddevices.com/plugins/mod-devel/2Voices",
"http://moddevices.com/plugins/mod-devel/Capo",
"http://moddevices.com/plugins/mod-devel/Drop",
"http://moddevices.com/plugins/mod-devel/Harmonizer",
"http://moddevices.com/plugins/mod-devel/Harmonizer2",
"http://moddevices.com/plugins/mod-devel/HarmonizerCS",
"http://moddevices.com/plugins/mod-devel/SuperCapo",
"http://moddevices.com/plugins/mod-devel/SuperWhammy",
"http://moddevices.com/plugins/mod-devel/Gx2Voices",
"http://moddevices.com/plugins/mod-devel/GxCapo",
"http://moddevices.com/plugins/mod-devel/GxDrop",
"http://moddevices.com/plugins/mod-devel/GxHarmonizer",
"http://moddevices.com/plugins/mod-devel/GxHarmonizer2",
"http://moddevices.com/plugins/mod-devel/GxHarmonizerCS",
"http://moddevices.com/plugins/mod-devel/GxSuperCapo",
"http://moddevices.com/plugins/mod-devel/GxSuperWhammy"
};
Lv2Manager::Lv2Manager() :
m_uridCache(m_uridMap)
{
const char* dbgStr = getenv("LMMS_LV2_DEBUG");
m_debug = (dbgStr && *dbgStr);
m_world = lilv_world_new();
lilv_world_load_all(m_world);
m_supportedFeatureURIs.insert(LV2_URID__map);
m_supportedFeatureURIs.insert(LV2_URID__unmap);
m_supportedFeatureURIs.insert(LV2_OPTIONS__options);
m_supportedFeatureURIs.insert(LV2_WORKER__schedule);
// min/max is always passed in the options
m_supportedFeatureURIs.insert(LV2_BUF_SIZE__boundedBlockLength);
// block length is only changed initially in AudioEngine CTOR
m_supportedFeatureURIs.insert(LV2_BUF_SIZE__fixedBlockLength);
if (const auto fpp = Engine::audioEngine()->framesPerPeriod(); (fpp & (fpp - 1)) == 0) // <=> ffp is power of 2 (for ffp > 0)
{
m_supportedFeatureURIs.insert(LV2_BUF_SIZE__powerOf2BlockLength);
}
auto supportOpt = [this](Lv2UridCache::Id id)
{
Lv2Options::supportOption(uridCache()[id]);
};
supportOpt(Lv2UridCache::Id::param_sampleRate);
supportOpt(Lv2UridCache::Id::bufsz_maxBlockLength);
supportOpt(Lv2UridCache::Id::bufsz_minBlockLength);
supportOpt(Lv2UridCache::Id::bufsz_nominalBlockLength);
supportOpt(Lv2UridCache::Id::bufsz_sequenceSize);
}
Lv2Manager::~Lv2Manager()
{
lilv_world_free(m_world);
}
AutoLilvNode Lv2Manager::uri(const char *uriStr)
{
return AutoLilvNode(lilv_new_uri(m_world, uriStr));
}
const LilvPlugin *Lv2Manager::getPlugin(const std::string &uri)
{
auto itr = m_lv2InfoMap.find(uri);
return itr == m_lv2InfoMap.end() ? nullptr : itr->second.plugin();
}
const LilvPlugin *Lv2Manager::getPlugin(const QString &uri)
{
return getPlugin(uri.toStdString());
}
void Lv2Manager::initPlugins()
{
const LilvPlugins* plugins = lilv_world_get_all_plugins(m_world);
std::size_t pluginCount = 0, pluginsLoaded = 0;
QElapsedTimer timer;
timer.start();
unsigned blocked = 0;
LILV_FOREACH(plugins, itr, plugins)
{
const LilvPlugin* curPlug = lilv_plugins_get(plugins, itr);
std::vector<PluginIssue> issues;
Plugin::Type type = Lv2ControlBase::check(curPlug, issues);
std::sort(issues.begin(), issues.end());
auto last = std::unique(issues.begin(), issues.end());
issues.erase(last, issues.end());
if (m_debug && issues.size())
{
qDebug() << "Lv2 plugin"
<< qStringFromPluginNode(curPlug, lilv_plugin_get_name)
<< "(URI:"
<< lilv_node_as_uri(lilv_plugin_get_uri(curPlug))
<< ") can not be loaded:";
for (const PluginIssue& iss : issues) { qDebug() << " - " << iss; }
}
Lv2Info info(curPlug, type, issues.empty());
m_lv2InfoMap[lilv_node_as_uri(lilv_plugin_get_uri(curPlug))]
= std::move(info);
if(issues.empty()) { ++pluginsLoaded; }
else
{
if(std::any_of(issues.begin(), issues.end(),
[](const PluginIssue& iss) {
return iss.type() == PluginIssueType::Blocked; }))
{
++blocked;
}
}
++pluginCount;
}
qDebug() << "Lv2 plugin SUMMARY:"
<< pluginsLoaded << "of" << pluginCount << " loaded in"
<< timer.elapsed() << "msecs.";
if(pluginsLoaded != pluginCount)
{
if (m_debug)
{
qDebug() <<
"If you don't want to see all this debug output, please set\n"
" environment variable \"LMMS_LV2_DEBUG\" to empty or\n"
" do not set it.";
}
else
{
qDebug() <<
"For details about not loaded plugins, please set\n"
" environment variable \"LMMS_LV2_DEBUG\" to nonempty.";
}
}
// TODO: might be better in the LMMS core
if(ConfigManager::enableBlockedPlugins())
{
qWarning() <<
"WARNING! Blocked plugins enabled! If you want to disable them,\n"
" please set environment variable \"LMMS_ENABLE_BLOCKED_PLUGINS\" to empty or\n"
" do not set it.";
}
else if(blocked > 0)
{
qDebug() <<
"Blocked Lv2 Plugins:" << blocked << "of" << pluginCount << "\n"
" If you want to enable them (dangerous!), please set\n"
" environment variable \"LMMS_ENABLE_BLOCKED_PLUGINS\" to nonempty.";
}
}
bool Lv2Manager::isFeatureSupported(const char *featName) const
{
return m_supportedFeatureURIs.find(featName) != m_supportedFeatureURIs.end();
}
AutoLilvNodes Lv2Manager::findNodes(const LilvNode *subject,
const LilvNode *predicate, const LilvNode *object)
{
return AutoLilvNodes(lilv_world_find_nodes (m_world, subject, predicate, object));
}
bool Lv2Manager::wantUi()
{
return false;
}
// unused + untested yet
bool Lv2Manager::isSubclassOf(const LilvPluginClass* clvss, const char* uriStr)
{
const LilvPluginClasses* allClasses = lilv_world_get_plugin_classes(m_world);
const LilvPluginClass* root = lilv_world_get_plugin_class(m_world);
const LilvPluginClass* search = lilv_plugin_classes_get_by_uri(allClasses,
uri(uriStr).get());
auto clssEq = [](const LilvPluginClass* pc1,
const LilvPluginClass* pc2) -> bool
{
return lilv_node_equals(
lilv_plugin_class_get_uri(pc1),
lilv_plugin_class_get_uri(pc2));
};
bool isFound = false;
while (!(isFound = clssEq(clvss, search)) && !clssEq(clvss, root))
{
clvss = lilv_plugin_classes_get_by_uri(allClasses,
lilv_plugin_class_get_parent_uri(clvss));
}
return isFound;
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 11,524
|
C++
|
.cpp
| 308
| 35.064935
| 127
| 0.736795
|
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,846
|
Lv2Options.cpp
|
LMMS_lmms/src/core/lv2/Lv2Options.cpp
|
/*
* Lv2Options.cpp - Lv2Options implementation
*
* Copyright (c) 2020-2020 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 "Lv2Options.h"
#ifdef LMMS_HAVE_LV2
#include <QtGlobal>
namespace lmms
{
std::set<LV2_URID> Lv2Options::s_supportedOptions;
bool Lv2Options::isOptionSupported(LV2_URID key)
{
return s_supportedOptions.find(key) != s_supportedOptions.end();
}
void Lv2Options::supportOption(LV2_URID key)
{
const auto result = s_supportedOptions.insert(key);
Q_ASSERT(result.second);
}
void Lv2Options::createOptionVectors()
{
// create vector of options
for(LV2_URID urid : s_supportedOptions)
{
auto itr = m_optionByUrid.find(urid);
Q_ASSERT(itr != m_optionByUrid.end());
m_options.push_back(itr->second);
}
LV2_Options_Option nullOption;
nullOption.key = 0;
nullOption.value = nullptr;
m_options.push_back(nullOption);
}
void Lv2Options::initOption(LV2_URID key, uint32_t size, LV2_URID type,
std::shared_ptr<void> value,
LV2_Options_Context context, uint32_t subject)
{
Q_ASSERT(isOptionSupported(key));
LV2_Options_Option opt;
opt.key = key;
opt.context = context;
opt.subject = subject;
opt.size = size;
opt.type = type;
opt.value = value.get();
const auto optResult = m_optionByUrid.emplace(key, opt);
const auto valResult = m_optionValues.emplace(key, std::move(value));
Q_ASSERT(optResult.second);
Q_ASSERT(valResult.second);
}
void Lv2Options::clear()
{
m_options.clear();
m_optionValues.clear();
m_optionByUrid.clear();
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 2,361
|
C++
|
.cpp
| 77
| 28.519481
| 80
| 0.755773
|
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,847
|
Lv2UridMap.cpp
|
LMMS_lmms/src/core/lv2/Lv2UridMap.cpp
|
/*
* Lv2UridMap.cpp - Lv2UridMap implementation
*
* Copyright (c) 2019 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 "Lv2UridMap.h"
#ifdef LMMS_HAVE_LV2
namespace lmms
{
static LV2_URID staticMap(LV2_URID_Map_Handle handle, const char* uri)
{
auto map = static_cast<UridMap*>(handle);
return map->map(uri);
}
static const char* staticUnmap(LV2_URID_Unmap_Handle handle, LV2_URID urid)
{
auto map = static_cast<UridMap*>(handle);
return map->unmap(urid);
}
UridMap::UridMap()
{
m_mapFeature.handle = static_cast<LV2_URID_Map_Handle>(this);
m_mapFeature.map = staticMap;
m_unmapFeature.handle = static_cast<LV2_URID_Unmap_Handle>(this);
m_unmapFeature.unmap = staticUnmap;
}
LV2_URID UridMap::map(const char *uri)
{
LV2_URID result = 0u;
// the Lv2 docs say that 0 should be returned in any case
// where creating an ID for the given URI fails
try
{
// TODO:
// when using C++14, we can get around any string allocation
// in the case the URI is already inside the map:
// * use `m_map.find(uri)` instead of `m_map.find(uriStr)`
// * to avoid temporary string construction in the `find` call, create
// m_map like this:
// std::unordered_map<std::string, LV2_URID,
// std::hash<std::string>, std::equal<>> m_map;
// * move the try block inside the case where the URI is not in the map
const std::string uriStr = uri;
std::lock_guard<std::mutex> guard (m_MapMutex);
auto itr = m_map.find(uriStr);
if (itr == m_map.end())
{
// 1 is the first free URID
const auto index = static_cast<LV2_URID>(1u + m_unMap.size());
auto pr = m_map.emplace(std::move(uriStr), index);
if (pr.second)
{
m_unMap.emplace_back(pr.first->first.c_str());
result = index;
}
}
else { result = itr->second; }
}
catch(...) { /* result variable is already 0 */ }
return result;
}
const char *UridMap::unmap(LV2_URID urid)
{
std::size_t idx = static_cast<std::size_t>(urid) - 1;
std::lock_guard<std::mutex> guard (m_MapMutex);
return (idx < m_unMap.size()) ? m_unMap[idx] : nullptr;
}
} // namespace lmms
#endif // LMMS_HAVE_LV2
| 2,904
|
C++
|
.cpp
| 87
| 31.022989
| 75
| 0.705147
|
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.