Files
lmms/include/InstrumentTrack.h
Michael Gregorius 286e62adf5 Simplify sample frame operations (make it a class) (#7156)
* Remove the struct StereoSample

Remove the struct `StereoSample`. Let `AudioEngine::getPeakValues` return a `sampleFrame` instead.

Adjust the calls in `Mixer`  and `Oscilloscope`.

* Simplify AudioEngine::getPeakValues

* Remove surroundSampleFrame

Some code assumes that `surroundSampleFrame` is interchangeable with `sampleFrame`. Thus, if the line `#define LMMS_DISABLE_SURROUND` is commented out in `lmms_basics.h` then the code does not compile anymore because `surroundSampleFrame` now is defined to be an array with four values instead of two. There also does not seem to be any support for surround sound (four channels instead of two) in the application. The faders and mixers do not seem to support more that two channels and the instruments and effects all expect a `sampleFrame`, i.e. stereo channels. It therefore makes sense to remove the "feature" because it also hinders the improvement of `sampleFrame`, e.g. by making it a class with some convenience methods that act on `sampleFrame` instances.

All occurrences of `surroundSampleFrame` are replaced with `sampleFrame`.

The version of `BufferManager::clear` that takes a `surroundSampleFrame` is removed completely.

The define `SURROUND_CHANNELS` is removed. All its occurrences are replaced with `DEFAULT_CHANNELS`.

Most of the audio devices classes, i.e. classes that inherit from `AudioDevice`, now clamp the configuration parameter between two values of `DEFAULT_CHANNELS`. This can be improved/streamlined later.

`BYTES_PER_SURROUND_FRAME` has been removed as it was not used anywhere anyway.

* Make sampleFrame a class

Make `sampleFrame` a class with several convenience methods. As a first step and demonstration adjust the follow methods to make use of the new functionality:
* `AudioEngine::getPeakValues`: Much more concise now.
* `lmms::MixHelpers::sanitize`: Better structure, better readable, less dereferencing and juggling with indices.
* `AddOp`, `AddMultipliedOp`, `multiply`: Make use of operators. Might become superfluous in the future.

* More operators and methods for sampleFrame

Add some more operators and methods to `sampleFrame`:
* Constructor which initializes both channels from a single sample value
* Assignment operator from a single sample value
* Addition/multiplication operators
* Scalar product

Adjust some more plugins to the new functionality of `sampleFrame`.

* Adjust DelayEffect to methods in sampleFrame

* Use composition instead of inheritance

Using inheritance was the quickest way to enable adding methods to `sampleFrame` without having to reimpement much of `std::array`s interface.

This is changed with this commit. The array is now a member of `sampleFrame` and the interface is extended with the necessary methods `data` and the index operator.

An `average` method was added so that no iterators need to be implemented (see changes in `SampleWaveform.cpp`).

* Apply suggestions from code review

Apply Veratil's suggestions from the code review

Co-authored-by: Kevin Zander <veratil@gmail.com>

* Fix warnings: zeroing non-trivial type

Fix several warnings of the following form:

Warnung: »void* memset(void*, int, size_t)« Säubern eines Objekts von nichttrivialem Typ »class lmms::sampleFrame«; use assignment or value-initialization instead [-Wclass-memaccess]

* Remove unnecessary reinterpret_casts

Remove some unnecessary reinterpret_casts with regards to `sampleFrame` buffers.

`PlayHandle::m_playHandleBuffer` already is a `sampleFrame*` and does not need a reinterpret_cast anymore.

In `LadspaEffect::processAudioBuffer` the `QVarLengthArray` is now directly initialized as an array of `sampleFrame` instances.

I guess in both places the `sampleFrame` previously was a `surroundSampleFrame` which has been removed.

* Clean up zeroSampleFrames code

* Fix warnings in RemotePlugin

Fix some warnings related to calls to `memcpy` in conjunction with`sampleFrame` which is now a class.

Add the helper functions `copyToSampleFrames` and `copyFromSampleFrames` and use them. The first function copies data from a `float` buffer into a `sampleFrame` buffer and the second copies vice versa.

* Rename "sampleFrame" to "SampleFrame"

Uppercase the name of `sampleFrame` so that it uses UpperCamelCase convention.

* Move SampleFrame into its own file

Move the class `SampleFrame` into its own class and remove it from `lmms_basics.h`.

Add forward includes to all headers where possible or include the `SampleFrame` header if it's not just referenced but used.

Add include to all cpp files where necessary.

It's a bit surprising that the `SampleFrame` header does not need to be included much more often in the implementation/cpp files. This is an indicator that it seems to be included via an include chain that at one point includes one of the headers where an include instead of a forward declaration had to be added in this commit.

* Return reference for += and *=

Return a reference for the compound assignment operators `+=` and `-=`.

* Explicit float constructor

Make the  constructor that takes a `float` explicit.

Remove the assignment operator that takes a `float`. Clients must use the
explicit `float` constructor and assign the result.

Adjust the code in "BitInvader" accordingly.

* Use std::fill in zeroSampleFrames

* Use zeroSampleFrames in sanitize

* Replace max with absMax

Replace `SampleFrame::max` with `SampleFrame::absMax`.

Use `absMax` in `DelayEffect::processAudioBuffer`. This should also fix
a buggy implementation of the peak computation.

Add the function `getAbsPeakValues`. It  computes the absolute peak
values for a buffer.

Remove `AudioEngine::getPeakValues`. It's not really the business of the
audio engine. Let `Mixer` and `Oscilloscope` use `getAbsPeakValues`.

* Replace scalarProduct

Replace the rather mathematical method `scalarProduct` with
`sumOfSquaredAmplitudes`. It was always called on itself anyway.

* Remove comment/TODO

* Simplify sanitize

Simplify the `sanitize` function by getting rid of the `bool found` and
by zeroing the buffer as soon as a problem is found.

* Put pointer symbols next to type

* Code review adjustments

* Remove "#pragme once"
* Adjust name of include guard
* Remove superfluous includes (leftovers from previous code changes)

---------

Co-authored-by: Kevin Zander <veratil@gmail.com>
2024-06-30 20:21:19 +02:00

327 lines
7.2 KiB
C++

/*
* InstrumentTrack.h - declaration of class InstrumentTrack, a track which
* holds an instrument-plugin
*
* 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.
*
*/
#ifndef LMMS_INSTRUMENT_TRACK_H
#define LMMS_INSTRUMENT_TRACK_H
#include "AudioPort.h"
#include "InstrumentFunctions.h"
#include "InstrumentSoundShaping.h"
#include "Microtuner.h"
#include "Midi.h"
#include "MidiEventProcessor.h"
#include "MidiPort.h"
#include "NotePlayHandle.h"
#include "Piano.h"
#include "Plugin.h"
#include "Track.h"
namespace lmms
{
class Instrument;
class DataFile;
namespace gui
{
class InstrumentTrackView;
class InstrumentTrackWindow;
class InstrumentTuningView;
class MidiCCRackView;
} // namespace gui
class LMMS_EXPORT InstrumentTrack : public Track, public MidiEventProcessor
{
Q_OBJECT
mapPropertyFromModel(int,getVolume,setVolume,m_volumeModel);
public:
InstrumentTrack( TrackContainer* tc );
~InstrumentTrack() override;
// used by instrument
void processAudioBuffer( SampleFrame* _buf, const fpp_t _frames,
NotePlayHandle * _n );
MidiEvent applyMasterKey( const MidiEvent& event );
void processInEvent( const MidiEvent& event, const TimePos& time = TimePos(), f_cnt_t offset = 0 ) override;
void processOutEvent( const MidiEvent& event, const TimePos& time = TimePos(), f_cnt_t offset = 0 ) override;
// silence all running notes played by this track
void silenceAllNotes( bool removeIPH = false );
bool isSustainPedalPressed() const
{
return m_sustainPedalPressed;
}
f_cnt_t beatLen( NotePlayHandle * _n ) const;
// for capturing note-play-events -> need that for arpeggio,
// filter and so on
void playNote( NotePlayHandle * _n, SampleFrame* _working_buffer );
QString instrumentName() const;
const Instrument *instrument() const
{
return m_instrument;
}
Instrument *instrument()
{
return m_instrument;
}
void deleteNotePluginData( NotePlayHandle * _n );
// name-stuff
void setName( const QString & _new_name ) override;
// translate given key of a note-event to absolute key (i.e.
// add global master-pitch and base-note of this instrument track)
int masterKey( int _midi_key ) const;
// translate pitch to midi-pitch [0,16383]
int midiPitch() const
{
return static_cast<int>( ( ( m_pitchModel.value() + m_pitchModel.range()/2 ) * MidiMaxPitchBend ) / m_pitchModel.range() );
}
/*! \brief Returns current range for pitch bend in semitones */
int midiPitchRange() const
{
return m_pitchRangeModel.value();
}
// play everything in given frame-range - creates note-play-handles
bool play( const TimePos & _start, const fpp_t _frames,
const f_cnt_t _frame_base, int _clip_num = -1 ) override;
// create new view for me
gui::TrackView* createView( gui::TrackContainerView* tcv ) override;
// create new track-content-object = clip
Clip* createClip(const TimePos & pos) override;
// called by track
void saveTrackSpecificSettings( QDomDocument & _doc,
QDomElement & _parent ) override;
void loadTrackSpecificSettings( const QDomElement & _this ) override;
using Track::setJournalling;
// load instrument whose name matches given one
Instrument * loadInstrument(const QString & _instrument_name,
const Plugin::Descriptor::SubPluginFeatures::Key* key = nullptr,
bool keyFromDnd = false);
AudioPort * audioPort()
{
return &m_audioPort;
}
MidiPort * midiPort()
{
return &m_midiPort;
}
const IntModel *baseNoteModel() const
{
return &m_baseNoteModel;
}
IntModel *baseNoteModel()
{
return &m_baseNoteModel;
}
IntModel *firstKeyModel()
{
return &m_firstKeyModel;
}
IntModel *lastKeyModel()
{
return &m_lastKeyModel;
}
bool keyRangeImport() const;
bool isKeyMapped(int key) const;
int firstKey() const;
int lastKey() const;
int baseNote() const;
float baseFreq() const;
Piano *pianoModel()
{
return &m_piano;
}
Microtuner *microtuner()
{
return &m_microtuner;
}
bool isArpeggioEnabled() const
{
return m_arpeggio.m_arpEnabledModel.value();
}
// simple helper for removing midiport-XML-node when loading presets
static void removeMidiPortNode( DataFile& dataFile );
FloatModel * pitchModel()
{
return &m_pitchModel;
}
FloatModel * volumeModel()
{
return &m_volumeModel;
}
FloatModel * panningModel()
{
return &m_panningModel;
}
IntModel* pitchRangeModel()
{
return &m_pitchRangeModel;
}
IntModel * mixerChannelModel()
{
return &m_mixerChannelModel;
}
BoolModel* useMasterPitchModel()
{
return &m_useMasterPitchModel;
}
void setPreviewMode( const bool );
bool isPreviewMode() const
{
return m_previewMode;
}
void replaceInstrument(DataFile dataFile);
void autoAssignMidiDevice( bool );
signals:
void instrumentChanged();
void midiNoteOn( const lmms::Note& );
void midiNoteOff( const lmms::Note& );
void newNote();
void endNote();
protected:
QString nodeName() const override
{
return "instrumenttrack";
}
// get the name of the instrument in the saved data
QString getSavedInstrumentName(const QDomElement & thisElement) const;
protected slots:
void updateBaseNote();
void updatePitch();
void updatePitchRange();
void updateMixerChannel();
private:
void processCCEvent(int controller);
MidiPort m_midiPort;
NotePlayHandle* m_notes[NumKeys];
NotePlayHandleList m_sustainedNotes;
int m_runningMidiNotes[NumKeys];
QMutex m_midiNotesMutex;
bool m_sustainPedalPressed;
bool m_silentBuffersProcessed;
bool m_previewMode;
IntModel m_baseNoteModel; //!< The "A4" or "440 Hz" key (default 69)
IntModel m_firstKeyModel; //!< First key the instrument reacts to
IntModel m_lastKeyModel; //!< Last key the instrument reacts to
bool m_hasAutoMidiDev;
static InstrumentTrack *s_autoAssignedTrack;
NotePlayHandleList m_processHandles;
FloatModel m_volumeModel;
FloatModel m_panningModel;
AudioPort m_audioPort;
FloatModel m_pitchModel;
IntModel m_pitchRangeModel;
IntModel m_mixerChannelModel;
BoolModel m_useMasterPitchModel;
Instrument * m_instrument;
InstrumentSoundShaping m_soundShaping;
InstrumentFunctionArpeggio m_arpeggio;
InstrumentFunctionNoteStacking m_noteStacking;
Piano m_piano;
Microtuner m_microtuner;
std::unique_ptr<BoolModel> m_midiCCEnable;
std::unique_ptr<FloatModel> m_midiCCModel[MidiControllerCount];
friend class gui::InstrumentTrackView;
friend class gui::InstrumentTrackWindow;
friend class NotePlayHandle;
friend class gui::InstrumentTuningView;
friend class gui::MidiCCRackView;
} ;
} // namespace lmms
#endif // LMMS_INSTRUMENT_TRACK_H