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,536
|
exportadvancedvideodialog.h
|
olive-editor_olive/app/dialog/export/exportadvancedvideodialog.h
|
#ifndef EXPORTADVANCEDVIDEODIALOG_H
#define EXPORTADVANCEDVIDEODIALOG_H
#include <QComboBox>
#include <QDialog>
#include "codec/encoder.h"
#include "widget/slider/integerslider.h"
namespace olive {
class ExportAdvancedVideoDialog : public QDialog
{
Q_OBJECT
public:
ExportAdvancedVideoDialog(const QList<QString>& pix_fmts,
QWidget* parent = nullptr);
int threads() const
{
return static_cast<int>(thread_slider_->GetValue());
}
void set_threads(int t)
{
thread_slider_->SetValue(t);
}
QString pix_fmt() const
{
return pixel_format_combobox_->currentText();
}
void set_pix_fmt(const QString& s)
{
pixel_format_combobox_->setCurrentText(s);
}
VideoParams::ColorRange yuv_range() const
{
return static_cast<VideoParams::ColorRange>(yuv_color_range_combobox_->currentIndex());
}
void set_yuv_range(VideoParams::ColorRange i)
{
yuv_color_range_combobox_->setCurrentIndex(i);
}
private:
IntegerSlider* thread_slider_;
QComboBox* pixel_format_combobox_;
QComboBox* yuv_color_range_combobox_;
};
}
#endif // EXPORTADVANCEDVIDEODIALOG_H
| 1,143
|
C++
|
.h
| 44
| 22.386364
| 91
| 0.731302
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,537
|
export.h
|
olive-editor_olive/app/dialog/export/export.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef EXPORTDIALOG_H
#define EXPORTDIALOG_H
#include <QComboBox>
#include <QDialog>
#include <QDialogButtonBox>
#include <QLineEdit>
#include <QProgressBar>
#include "codec/exportcodec.h"
#include "codec/exportformat.h"
#include "dialog/export/exportformatcombobox.h"
#include "exportaudiotab.h"
#include "exportsubtitlestab.h"
#include "exportvideotab.h"
#include "task/export/export.h"
#include "widget/nodeparamview/nodeparamviewwidgetbridge.h"
#include "widget/viewer/viewer.h"
namespace olive {
class ExportDialog : public QDialog
{
Q_OBJECT
public:
ExportDialog(ViewerOutput* viewer_node, bool stills_only_mode, QWidget* parent = nullptr);
ExportDialog(ViewerOutput* viewer_node, QWidget* parent = nullptr) :
ExportDialog(viewer_node, false, parent)
{}
rational GetSelectedTimebase() const;
void SetSelectedTimebase(const rational &r);
EncodingParams GenerateParams() const;
void SetParams(const EncodingParams &e);
virtual bool eventFilter(QObject *o, QEvent *e) override;
public slots:
virtual void done(int r) override;
signals:
void RequestImportFile(const QString &s);
private:
void AddPreferencesTab(QWidget *inner_widget, const QString &title);
void LoadPresets();
void SetDefaultFilename();
bool SequenceHasSubtitles() const;
void SetDefaults();
ViewerOutput* viewer_node_;
ExportFormat::Format previously_selected_format_;
rational GetExportLength() const;
int64_t GetExportLengthInTimebaseUnits() const;
enum RangeSelection {
kRangeEntireSequence,
kRangeInToOut
};
enum AutoPreset {
kPresetDefault = -1,
kPresetLastUsed = -2,
};
QTabWidget* preferences_tabs_;
QComboBox* preset_combobox_;
QComboBox* range_combobox_;
std::vector<EncodingParams> presets_;
QCheckBox* video_enabled_;
QCheckBox* audio_enabled_;
QCheckBox* subtitles_enabled_;
ViewerWidget* preview_viewer_;
QLineEdit* filename_edit_;
ExportFormatComboBox* format_combobox_;
ExportVideoTab* video_tab_;
ExportAudioTab* audio_tab_;
ExportSubtitlesTab* subtitle_tab_;
double video_aspect_ratio_;
ColorManager* color_manager_;
QWidget* preferences_area_;
QCheckBox *export_bkg_box_;
QCheckBox *import_file_after_export_;
bool stills_only_mode_;
bool loading_presets_;
private slots:
void BrowseFilename();
void FormatChanged(ExportFormat::Format current_format);
void ResolutionChanged();
void UpdateViewerDimensions();
void StartExport();
void ExportFinished();
void ImageSequenceCheckBoxChanged(bool e);
void SavePreset();
void PresetComboBoxChanged();
};
}
#endif // EXPORTDIALOG_H
| 3,341
|
C++
|
.h
| 99
| 30.767677
| 92
| 0.780976
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,538
|
exportaudiotab.h
|
olive-editor_olive/app/dialog/export/exportaudiotab.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef EXPORTAUDIOTAB_H
#define EXPORTAUDIOTAB_H
#include <QComboBox>
#include <QWidget>
#include "common/define.h"
#include "codec/exportformat.h"
#include "widget/slider/integerslider.h"
#include "widget/standardcombos/standardcombos.h"
namespace olive {
class ExportAudioTab : public QWidget
{
Q_OBJECT
public:
ExportAudioTab(QWidget* parent = nullptr);
ExportCodec::Codec GetCodec() const
{
return static_cast<ExportCodec::Codec>(codec_combobox_->currentData().toInt());
}
void SetCodec(ExportCodec::Codec c)
{
for (int i=0; i<codec_combobox_->count(); i++) {
if (codec_combobox_->itemData(i) == c) {
codec_combobox_->setCurrentIndex(i);
break;
}
}
}
SampleRateComboBox* sample_rate_combobox() const
{
return sample_rate_combobox_;
}
SampleFormatComboBox* sample_format_combobox() const
{
return sample_format_combobox_;
}
ChannelLayoutComboBox* channel_layout_combobox() const
{
return channel_layout_combobox_;
}
IntegerSlider* bit_rate_slider() const
{
return bit_rate_slider_;
}
public slots:
int SetFormat(ExportFormat::Format format);
private:
ExportFormat::Format fmt_;
QComboBox* codec_combobox_;
SampleRateComboBox* sample_rate_combobox_;
ChannelLayoutComboBox* channel_layout_combobox_;
SampleFormatComboBox *sample_format_combobox_;
IntegerSlider* bit_rate_slider_;
static const int kDefaultBitRate;
private slots:
void UpdateSampleFormats();
void UpdateBitRateEnabled();
};
}
#endif // EXPORTAUDIOTAB_H
| 2,266
|
C++
|
.h
| 73
| 27.794521
| 83
| 0.753343
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,539
|
imagesection.h
|
olive-editor_olive/app/dialog/export/codec/imagesection.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef IMAGESECTION_H
#define IMAGESECTION_H
#include <QCheckBox>
#include "codecsection.h"
#include "widget/slider/rationalslider.h"
namespace olive {
class ImageSection : public CodecSection
{
Q_OBJECT
public:
ImageSection(QWidget* parent = nullptr);
bool IsImageSequenceChecked() const
{
return image_sequence_checkbox_->isChecked();
}
void SetImageSequenceChecked(bool e)
{
image_sequence_checkbox_->setChecked(e);
}
void SetTimebase(const rational& r)
{
frame_slider_->SetTimebase(r);
}
rational GetTime() const
{
return frame_slider_->GetValue();
}
void SetTime(const rational &t)
{
frame_slider_->SetValue(t);
}
signals:
void TimeChanged(const rational &t);
private:
QCheckBox* image_sequence_checkbox_;
RationalSlider* frame_slider_;
private slots:
void ImageSequenceCheckBoxToggled(bool e);
};
}
#endif // IMAGESECTION_H
| 1,621
|
C++
|
.h
| 55
| 26.509091
| 71
| 0.760363
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,540
|
av1section.h
|
olive-editor_olive/app/dialog/export/codec/av1section.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef AV1SECTION_H
#define AV1SECTION_H
#include <QSlider>
#include <QStackedWidget>
#include <QComboBox>
#include "codecsection.h"
#include "widget/slider/floatslider.h"
namespace olive {
class AV1CRFSection : public QWidget
{
Q_OBJECT
public:
AV1CRFSection(int default_crf, QWidget* parent = nullptr);
int GetValue() const;
static const int kDefaultAV1CRF = 30;
private:
static const int kMinimumCRF = 0;
static const int kMaximumCRF = 63;
QSlider* crf_slider_;
};
class AV1Section : public CodecSection
{
Q_OBJECT
public:
enum CompressionMethod {
kConstantRateFactor,
};
AV1Section(QWidget* parent = nullptr);
AV1Section(int default_crf, QWidget* parent);
virtual void AddOpts(EncodingParams* params) override;
private:
QStackedWidget* compression_method_stack_;
AV1CRFSection* crf_section_;
QComboBox *preset_combobox_;
};
}
#endif // AV1SECTION_H
| 1,619
|
C++
|
.h
| 51
| 29.117647
| 71
| 0.776052
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,541
|
codecstack.h
|
olive-editor_olive/app/dialog/export/codec/codecstack.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef CODECSTACK_H
#define CODECSTACK_H
#include <QStackedWidget>
namespace olive {
class CodecStack : public QStackedWidget
{
Q_OBJECT
public:
explicit CodecStack(QWidget *parent = nullptr);
void addWidget(QWidget *widget);
signals:
private slots:
void OnChange(int index);
};
}
#endif // CODECSTACK_H
| 1,034
|
C++
|
.h
| 30
| 31.9
| 71
| 0.778564
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,542
|
codecsection.h
|
olive-editor_olive/app/dialog/export/codec/codecsection.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef CODECSECTION_H
#define CODECSECTION_H
#include <QWidget>
#include "codec/encoder.h"
namespace olive {
class CodecSection : public QWidget
{
Q_OBJECT
public:
CodecSection(QWidget* parent = nullptr);
virtual void AddOpts(EncodingParams* params){Q_UNUSED(params)}
virtual void SetOpts(const EncodingParams *p){Q_UNUSED(p)}
};
}
#endif // CODECSECTION_H
| 1,087
|
C++
|
.h
| 29
| 34.862069
| 71
| 0.776606
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,543
|
cineformsection.h
|
olive-editor_olive/app/dialog/export/codec/cineformsection.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef CINEFORMSECTION_H
#define CINEFORMSECTION_H
#include <QComboBox>
#include "codecsection.h"
namespace olive {
class CineformSection : public CodecSection
{
Q_OBJECT
public:
CineformSection(QWidget *parent = nullptr);
virtual void AddOpts(EncodingParams* params) override;
virtual void SetOpts(const EncodingParams *p) override;
private:
QComboBox *quality_combobox_;
};
}
#endif // CINEFORMSECTION_H
| 1,139
|
C++
|
.h
| 31
| 34.129032
| 71
| 0.785714
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,544
|
h264section.h
|
olive-editor_olive/app/dialog/export/codec/h264section.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef H264SECTION_H
#define H264SECTION_H
#include <QSlider>
#include <QStackedWidget>
#include <QComboBox>
#include "codecsection.h"
#include "widget/slider/floatslider.h"
namespace olive {
class H264CRFSection : public QWidget
{
Q_OBJECT
public:
H264CRFSection(int default_crf, QWidget* parent = nullptr);
int GetValue() const;
void SetValue(int c);
static const int kDefaultH264CRF = 18;
static const int kDefaultH265CRF = 23;
private:
static const int kMinimumCRF = 0;
static const int kMaximumCRF = 51;
QSlider* crf_slider_;
};
class H264BitRateSection : public QWidget
{
Q_OBJECT
public:
H264BitRateSection(QWidget* parent = nullptr);
/**
* @brief Get user-selected target bit rate (returns in BITS)
*/
int64_t GetTargetBitRate() const;
void SetTargetBitRate(int64_t b);
/**
* @brief Get user-selected maximum bit rate (returns in BITS)
*/
int64_t GetMaximumBitRate() const;
void SetMaximumBitRate(int64_t b);
private:
FloatSlider* target_rate_;
FloatSlider* max_rate_;
};
class H264FileSizeSection : public QWidget
{
Q_OBJECT
public:
H264FileSizeSection(QWidget* parent = nullptr);
/**
* @brief Returns file size in BITS
*/
int64_t GetFileSize() const;
void SetFileSize(int64_t f);
private:
FloatSlider* file_size_;
};
class H264Section : public CodecSection
{
Q_OBJECT
public:
enum CompressionMethod {
kConstantRateFactor,
kTargetBitRate,
kTargetFileSize
};
H264Section(QWidget* parent = nullptr);
H264Section(int default_crf, QWidget* parent);
virtual void AddOpts(EncodingParams* params) override;
virtual void SetOpts(const EncodingParams *p) override;
private:
QStackedWidget* compression_method_stack_;
H264CRFSection* crf_section_;
H264BitRateSection* bitrate_section_;
H264FileSizeSection* filesize_section_;
QComboBox *preset_combobox_;
};
class H265Section : public H264Section
{
Q_OBJECT
public:
H265Section(QWidget* parent = nullptr);
};
}
#endif // H264SECTION_H
| 2,736
|
C++
|
.h
| 96
| 25.739583
| 71
| 0.766423
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,545
|
renderticket.h
|
olive-editor_olive/app/render/renderticket.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef RENDERTICKET_H
#define RENDERTICKET_H
#include <QDateTime>
#include <QMutex>
#include <QWaitCondition>
#include "codec/frame.h"
#include "common/cancelableobject.h"
#include "node/output/viewer/viewer.h"
namespace olive {
class RenderTicket : public QObject, public CancelableObject
{
Q_OBJECT
public:
RenderTicket();
/**
* @brief Get the ticket's current state
*
* This function is thread safe, unless `lock` is set to false. Then the caller has responsibility
* of locking the mutex before and unlocking after this function is called.
*/
bool IsRunning(bool lock = true);
/**
* @brief Determine how many times ticket has been finished
*
* This function is thread safe, unless `lock` is set to false. Then the caller has responsibility
* of locking the mutex before and unlocking after this function is called.
*/
int GetFinishCount(bool lock = true);
/**
* @brief Check if this ticket has a result
*
* If this ticket is running, this will always return false.
*/
bool HasResult();
/**
* @brief Get value, if any
*/
QVariant Get();
/**
* @brief Wait for ticket to be finished
*
* If this ticket is not running, this function returns immediately.
*/
void WaitForFinished();
void WaitForFinished(QMutex* mutex);
/**
* @brief Access this ticket's mutex
*
* Use if you're doing several operations on a ticket and need to ensure thread safety while
* doing so. Most of the time this isn't necessary since all functions are thread safe by default.
*/
QMutex* lock()
{
return &lock_;
}
/**
* @brief Signal to the ticket that it is running
*
* If any value is set, it is cleared.
*/
void Start();
/**
* @brief Finish ticket with no value
*
* Sets ticket to no longer running and assume it has received no result.
*/
void Finish();
/**
* @brief Finish ticket with value
*
* Sets ticket to no longer running and provide a value generated by the operation requested.
*/
void Finish(QVariant result);
signals:
/**
* @brief Emitted when finish has been called by any means (either cancelled or with a result)
*/
void Finished();
private:
void FinishInternal(bool has_result, QVariant result);
bool is_running_;
QVariant result_;
bool has_result_;
int finish_count_;
QMutex lock_;
QWaitCondition wait_;
};
using RenderTicketPtr = std::shared_ptr<RenderTicket>;
class RenderTicketWatcher : public QObject
{
Q_OBJECT
public:
RenderTicketWatcher(QObject* parent = nullptr);
RenderTicketPtr GetTicket() const
{
return ticket_;
}
void SetTicket(RenderTicketPtr ticket);
bool IsRunning();
void WaitForFinished();
QVariant Get();
bool HasResult();
void Cancel();
signals:
void Finished(RenderTicketWatcher* watcher);
private:
RenderTicketPtr ticket_;
private slots:
void TicketFinished();
};
}
Q_DECLARE_METATYPE(olive::RenderTicketPtr)
#endif // RENDERTICKET_H
| 3,717
|
C++
|
.h
| 127
| 26.023622
| 100
| 0.730964
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,546
|
subtitleparams.h
|
olive-editor_olive/app/render/subtitleparams.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef SUBTITLEPARAMS_H
#define SUBTITLEPARAMS_H
#include <olive/core/core.h>
#include <QRect>
#include <QString>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
using namespace olive::core;
namespace olive {
class Subtitle
{
public:
Subtitle() = default;
Subtitle(const TimeRange &time, const QString &text) :
range_(time),
text_(text)
{
}
const TimeRange &time() const { return range_; }
void set_time(const TimeRange &t) { range_ = t; }
const QString &text() const { return text_; }
void set_text(const QString &t) { text_ = t; }
private:
TimeRange range_;
QString text_;
};
class SubtitleParams : public std::vector<Subtitle>
{
public:
SubtitleParams()
{
stream_index_ = 0;
enabled_ = true;
}
static QString GenerateASSHeader();
void Load(QXmlStreamReader* reader);
void Save(QXmlStreamWriter* writer) const;
bool is_valid() const
{
return !this->empty();
}
rational duration() const
{
if (this->empty()) {
return 0;
} else {
return back().time().out();
}
}
int stream_index() const { return stream_index_; }
void set_stream_index(int i) { stream_index_ = i; }
bool enabled() const { return enabled_; }
void set_enabled(bool e) { enabled_ = e; }
private:
int stream_index_;
bool enabled_;
};
}
Q_DECLARE_METATYPE(olive::Subtitle)
Q_DECLARE_METATYPE(olive::SubtitleParams)
#endif // SUBTITLEPARAMS_H
| 2,148
|
C++
|
.h
| 75
| 25.586667
| 71
| 0.71953
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,547
|
renderer.h
|
olive-editor_olive/app/render/renderer.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef RENDERCONTEXT_H
#define RENDERCONTEXT_H
#include <QMutex>
#include <QObject>
#include <QVariant>
#include "common/define.h"
#include "node/node.h"
#include "render/colorprocessor.h"
#include "render/job/colortransformjob.h"
#include "render/videoparams.h"
#include "texture.h"
namespace olive {
class ShaderJob;
class Renderer : public QObject
{
Q_OBJECT
public:
Renderer(QObject* parent = nullptr);
virtual bool Init() = 0;
TexturePtr CreateTexture(const VideoParams& params, const void *data = nullptr, int linesize = 0);
void DestroyTexture(Texture *texture);
void BlitToTexture(QVariant shader,
olive::ShaderJob job,
olive::Texture* destination,
bool clear_destination = true)
{
Blit(shader, job, destination, destination->params(), clear_destination);
}
void Blit(QVariant shader,
olive::ShaderJob job,
olive::VideoParams params,
bool clear_destination = true)
{
Blit(shader, job, nullptr, params, clear_destination);
}
void BlitColorManaged(const ColorTransformJob &color_job, Texture* destination, const VideoParams ¶ms);
void BlitColorManaged(const ColorTransformJob &job, Texture* destination)
{
BlitColorManaged(job, destination, destination->params());
}
void BlitColorManaged(const ColorTransformJob &job, const VideoParams ¶ms)
{
BlitColorManaged(job, nullptr, params);
}
TexturePtr InterlaceTexture(TexturePtr top, TexturePtr bottom, const VideoParams ¶ms);
QVariant GetDefaultShader();
void Destroy();
virtual void PostDestroy() = 0;
virtual void PostInit() = 0;
virtual void ClearDestination(olive::Texture *texture = nullptr, double r = 0.0, double g = 0.0, double b = 0.0, double a = 1.0) = 0;
virtual QVariant CreateNativeShader(olive::ShaderCode code) = 0;
virtual void DestroyNativeShader(QVariant shader) = 0;
virtual void UploadToTexture(const QVariant &handle, const VideoParams ¶ms, const void* data, int linesize) = 0;
virtual void DownloadFromTexture(const QVariant &handle, const VideoParams ¶ms, void* data, int linesize) = 0;
virtual void Flush() = 0;
virtual Color GetPixelFromTexture(olive::Texture *texture, const QPointF &pt) = 0;
protected:
virtual void Blit(QVariant shader,
olive::ShaderJob job,
olive::Texture* destination,
olive::VideoParams destination_params,
bool clear_destination) = 0;
virtual QVariant CreateNativeTexture(int width, int height, int depth, PixelFormat format, int channel_count, const void* data = nullptr, int linesize = 0) = 0;
virtual void DestroyNativeTexture(QVariant texture) = 0;
virtual void DestroyInternal() = 0;
private:
struct ColorContext {
struct LUT {
TexturePtr texture;
Texture::Interpolation interpolation;
QString name;
};
QVariant compiled_shader;
QVector<LUT> lut3d_textures;
QVector<LUT> lut1d_textures;
};
TexturePtr CreateTextureFromNativeHandle(const QVariant &v, const VideoParams ¶ms);
bool GetColorContext(const ColorTransformJob &color_job, ColorContext* ctx);
void ClearOldTextures();
QHash<QString, ColorContext> color_cache_;
struct CachedTexture
{
int width;
int height;
int depth;
PixelFormat format;
int channel_count;
QVariant handle;
qint64 accessed;
};
static const int MAX_TEXTURE_LIFE = 5000;
static const bool USE_TEXTURE_CACHE = true;
std::list<CachedTexture> texture_cache_;
QMutex color_cache_mutex_;
QVariant default_shader_;
QVariant interlace_texture_;
QMutex texture_cache_lock_;
};
}
#endif // RENDERCONTEXT_H
| 4,468
|
C++
|
.h
| 114
| 34.385965
| 162
| 0.732869
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,548
|
renderprocessor.h
|
olive-editor_olive/app/render/renderprocessor.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef RENDERPROCESSOR_H
#define RENDERPROCESSOR_H
#include "node/block/clip/clip.h"
#include "node/traverser.h"
#include "render/renderer.h"
#include "rendercache.h"
#include "renderticket.h"
namespace olive {
class RenderProcessor : public NodeTraverser
{
public:
virtual NodeValueDatabase GenerateDatabase(const Node *node, const TimeRange &range) override;
static void Process(RenderTicketPtr ticket, Renderer* render_ctx, DecoderCache* decoder_cache, ShaderCache* shader_cache);
struct RenderedWaveform {
const ClipBlock* block;
AudioVisualWaveform waveform;
TimeRange range;
bool silence;
};
protected:
virtual void ProcessVideoFootage(TexturePtr destination, const FootageJob *stream, const rational &input_time) override;
virtual void ProcessAudioFootage(SampleBuffer &destination, const FootageJob *stream, const TimeRange &input_time) override;
virtual void ProcessShader(TexturePtr destination, const Node *node, const ShaderJob *job) override;
virtual void ProcessSamples(SampleBuffer &destination, const Node *node, const TimeRange &range, const SampleJob &job) override;
virtual void ProcessColorTransform(TexturePtr destination, const Node *node, const ColorTransformJob *job) override;
virtual void ProcessFrameGeneration(TexturePtr destination, const Node *node, const GenerateJob *job) override;
virtual TexturePtr ProcessVideoCacheJob(const CacheJob *val) override;
virtual TexturePtr CreateTexture(const VideoParams &p) override;
virtual SampleBuffer CreateSampleBuffer(const AudioParams ¶ms, int sample_count) override
{
return SampleBuffer(params, sample_count);
}
virtual void ConvertToReferenceSpace(TexturePtr destination, TexturePtr source, const QString &input_cs) override;
virtual bool UseCache() const override;
private:
RenderProcessor(RenderTicketPtr ticket, Renderer* render_ctx, DecoderCache* decoder_cache, ShaderCache* shader_cache);
TexturePtr GenerateTexture(const rational& time, const rational& frame_length);
FramePtr GenerateFrame(TexturePtr texture, const rational &time);
void Run();
DecoderPtr ResolveDecoderFromInput(const QString &decoder_id, const Decoder::CodecStream& stream);
RenderTicketPtr ticket_;
Renderer* render_ctx_;
DecoderCache* decoder_cache_;
ShaderCache* shader_cache_;
};
}
Q_DECLARE_METATYPE(olive::RenderProcessor::RenderedWaveform)
#endif // RENDERPROCESSOR_H
| 3,145
|
C++
|
.h
| 62
| 47.612903
| 130
| 0.804134
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,549
|
previewaudiodevice.h
|
olive-editor_olive/app/render/previewaudiodevice.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef PREVIEWAUDIODEVICE_H
#define PREVIEWAUDIODEVICE_H
#include "previewautocacher.h"
namespace olive {
class PreviewAudioDevice : public QIODevice
{
Q_OBJECT
public:
PreviewAudioDevice(QObject *parent = nullptr);
virtual ~PreviewAudioDevice() override;
void StartQueuing();
virtual bool isSequential() const override;
virtual qint64 readData(char *data, qint64 maxSize) override;
virtual qint64 writeData(const char *data, qint64 length) override;
int bytes_per_frame() const
{
return bytes_per_frame_;
}
void set_bytes_per_frame(int b)
{
bytes_per_frame_ = b;
}
void set_notify_interval(qint64 i)
{
notify_interval_ = i;
}
void clear();
signals:
void Notify();
private:
QMutex lock_;
QByteArray buffer_;
int bytes_per_frame_;
qint64 notify_interval_;
qint64 bytes_read_;
};
}
#endif // PREVIEWAUDIODEVICE_H
| 1,603
|
C++
|
.h
| 52
| 27.730769
| 71
| 0.759186
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,550
|
playbackcache.h
|
olive-editor_olive/app/render/playbackcache.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef PLAYBACKCACHE_H
#define PLAYBACKCACHE_H
#include <olive/core/core.h>
#include <QDir>
#include <QMutex>
#include <QObject>
#include <QPainter>
#include <QUuid>
#include "common/jobtime.h"
using namespace olive::core;
namespace olive {
class Node;
class Project;
class ViewerOutput;
class PlaybackCache : public QObject
{
Q_OBJECT
public:
PlaybackCache(QObject* parent = nullptr);
const QUuid &GetUuid() const { return uuid_; }
void SetUuid(const QUuid &u);
TimeRangeList GetInvalidatedRanges(TimeRange intersecting) const;
TimeRangeList GetInvalidatedRanges(const rational &length) const
{
return GetInvalidatedRanges(TimeRange(0, length));
}
bool HasInvalidatedRanges(const TimeRange &intersecting) const;
bool HasInvalidatedRanges(const rational &length) const
{
return HasInvalidatedRanges(TimeRange(0, length));
}
QString GetCacheDirectory() const;
void Invalidate(const TimeRange& r);
bool HasValidatedRanges() const { return !validated_.isEmpty(); }
const TimeRangeList &GetValidatedRanges() const { return validated_; }
Node *parent() const;
QDir GetThisCacheDirectory() const;
static QDir GetThisCacheDirectory(const QString &cache_path, const QUuid &cache_id);
void LoadState();
void SaveState();
void Draw(QPainter *painter, const rational &start, double scale, const QRect &rect) const;
static int GetCacheIndicatorHeight()
{
return QFontMetrics(QFont()).height()/4;
}
bool IsSavingEnabled() const { return saving_enabled_; }
void SetSavingEnabled(bool e) { saving_enabled_ = e; }
virtual void SetPassthrough(PlaybackCache *cache);
QMutex *mutex() { return &mutex_; }
class Passthrough : public TimeRange
{
public:
Passthrough(const TimeRange &r) :
TimeRange(r)
{}
QUuid cache;
};
const std::vector<Passthrough> &GetPassthroughs() const { return passthroughs_; }
void ClearRequestRange(const TimeRange &r)
{
requested_.remove(r);
}
void ResignalRequests()
{
for (const TimeRange &r : requested_) {
emit Requested(request_context_, r);
}
}
public slots:
void InvalidateAll();
void Request(ViewerOutput *context, const TimeRange &r);
signals:
void Invalidated(const TimeRange& r);
void Validated(const TimeRange& r);
void Requested(ViewerOutput *context, const TimeRange& r);
void CancelAll();
protected:
void Validate(const TimeRange& r, bool signal = true);
virtual void InvalidateEvent(const TimeRange& range);
virtual void LoadStateEvent(QDataStream &stream){}
virtual void SaveStateEvent(QDataStream &stream){}
Project* GetProject() const;
private:
TimeRangeList validated_;
TimeRangeList requested_;
ViewerOutput *request_context_;
QUuid uuid_;
bool saving_enabled_;
QMutex mutex_;
std::vector<Passthrough> passthroughs_;
qint64 last_loaded_state_;
};
}
#endif // PLAYBACKCACHE_H
| 3,626
|
C++
|
.h
| 108
| 30.333333
| 93
| 0.759088
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,551
|
previewautocacher.h
|
olive-editor_olive/app/render/previewautocacher.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef AUTOCACHER_H
#define AUTOCACHER_H
#include <QtConcurrent/QtConcurrent>
#include "config/config.h"
#include "node/color/colormanager/colormanager.h"
#include "node/group/group.h"
#include "node/node.h"
#include "node/output/viewer/viewer.h"
#include "node/project.h"
#include "render/projectcopier.h"
#include "render/renderjobtracker.h"
#include "render/renderticket.h"
namespace olive {
/**
* @brief Manager for dynamically caching a sequence in the background
*
* Intended to be used with a Viewer to dynamically cache parts of a sequence based on the playhead.
*/
class PreviewAutoCacher : public QObject
{
Q_OBJECT
public:
PreviewAutoCacher(QObject *parent = nullptr);
virtual ~PreviewAutoCacher() override;
RenderTicketPtr GetSingleFrame(ViewerOutput *viewer, const rational& t, bool dry = false);
RenderTicketPtr GetSingleFrame(Node *n, ViewerOutput *viewer, const rational& t, bool dry = false);
RenderTicketPtr GetRangeOfAudio(ViewerOutput *viewer, TimeRange range);
void ClearSingleFrameRenders();
void ClearSingleFrameRendersThatArentRunning();
/**
* @brief Set the viewer node to auto-cache
*/
void SetProject(Project *project);
/**
* @brief Force a certain range to be cached
*
* Usually, PreviewAutoCacher caches a user-defined range around the playhead, however there are
* times they may want certain non-playhead-related time ranges to be cached (i.e. entire sequence
* or in/out range), so that can be set here.
*/
void ForceCacheRange(ViewerOutput *context, const TimeRange& range);
/**
* @brief Updates the range of frames to auto-cache
*/
void SetPlayhead(const rational& playhead);
/**
* @brief Call cancel on all currently running video tasks
*
* Signalling cancel to a video task indicates that we're no longer interested in its end result.
* This does not end all video tasks immediately, the RenderManager will do what it can to speed
* up finishing the task. The RenderManager will also return "no result", which can be checked
* with watcher->HasResult.
*/
void CancelVideoTasks(bool and_wait_for_them_to_finish = false);
void CancelAudioTasks(bool and_wait_for_them_to_finish = false);
bool IsRenderingCustomRange() const;
void SetRendersPaused(bool e);
void SetThumbnailsPaused(bool e);
void SetMulticamNode(MultiCamNode *n) { multicam_ = n; }
void SetIgnoreCacheRequests(bool e) { ignore_cache_requests_ = e; }
public slots:
void SetDisplayColorProcessor(ColorProcessorPtr processor)
{
display_color_processor_ = processor;
}
signals:
void StopCacheProxyTasks();
void SignalCacheProxyTaskProgress(double d);
private:
void TryRender();
RenderTicketWatcher *RenderFrame(Node *node, ViewerOutput *context, const rational &time, PlaybackCache *cache, bool dry);
RenderTicketPtr RenderAudio(Node *node, ViewerOutput *context, const TimeRange &range, PlaybackCache *cache);
void ConnectToNodeCache(Node *node);
void DisconnectFromNodeCache(Node *node);
void CancelQueuedSingleFrameRender();
void StartCachingRange(const TimeRange &range, TimeRangeList *range_list, RenderJobTracker *tracker);
void StartCachingVideoRange(ViewerOutput *context, PlaybackCache *cache, const TimeRange &range);
void StartCachingAudioRange(ViewerOutput *context, PlaybackCache *cache, const TimeRange &range);
void VideoInvalidatedFromNode(ViewerOutput *context, PlaybackCache *cache, const olive::TimeRange &range);
void AudioInvalidatedFromNode(ViewerOutput *context, PlaybackCache *cache, const olive::TimeRange &range);
Project* project_;
ProjectCopier *copier_;
TimeRange cache_range_;
bool use_custom_range_;
TimeRange custom_autocache_range_;
bool pause_renders_;
bool pause_thumbnails_;
RenderTicketPtr single_frame_render_;
QMap<RenderTicketWatcher*, QVector<RenderTicketPtr> > video_immediate_passthroughs_;
QTimer delayed_requeue_timer_;
JobTime last_conform_task_;
QVector<RenderTicketWatcher*> running_video_tasks_;
QVector<RenderTicketWatcher*> running_audio_tasks_;
ColorManager* copied_color_manager_;
struct VideoJob {
Node *node;
ViewerOutput *context;
PlaybackCache *cache;
TimeRange range;
TimeRangeListFrameIterator iterator;
};
struct VideoCacheData {
RenderJobTracker job_tracker;
};
struct AudioJob {
Node *node;
ViewerOutput *context;
PlaybackCache *cache;
TimeRange range;
};
struct AudioCacheData {
RenderJobTracker job_tracker;
TimeRangeList needs_conform;
};
std::list<VideoJob> pending_video_jobs_;
std::list<AudioJob> pending_audio_jobs_;
QHash<PlaybackCache*, VideoCacheData> video_cache_data_;
QHash<PlaybackCache*, AudioCacheData> audio_cache_data_;
ColorProcessorPtr display_color_processor_;
MultiCamNode *multicam_;
bool ignore_cache_requests_;
private slots:
/**
* @brief Handler for when the NodeGraph reports a video change over a certain time range
*/
void VideoInvalidatedFromCache(ViewerOutput *context, const olive::TimeRange &range);
/**
* @brief Handler for when the NodeGraph reports a audio change over a certain time range
*/
void AudioInvalidatedFromCache(ViewerOutput *context, const olive::TimeRange &range);
void CancelForCache();
/**
* @brief Handler for when the RenderManager has returned rendered audio
*/
void AudioRendered();
/**
* @brief Handler for when the RenderManager has returned rendered video frames
*/
void VideoRendered();
/**
* @brief Generic function called whenever the frames to render need to be (re)queued
*/
//void RequeueFrames();
void ConformFinished();
void CacheProxyTaskCancelled();
};
}
#endif // AUTOCACHER_H
| 6,470
|
C++
|
.h
| 162
| 36.574074
| 124
| 0.770253
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,552
|
framemanager.h
|
olive-editor_olive/app/render/framemanager.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef FRAMEMANAGER_H
#define FRAMEMANAGER_H
#include <QMutex>
#include <QObject>
#include <QTimer>
namespace olive {
class FrameManager : public QObject
{
Q_OBJECT
public:
static void CreateInstance();
static void DestroyInstance();
static FrameManager* instance();
static char* Allocate(int size);
static void Deallocate(int size, char* buffer);
private:
FrameManager();
virtual ~FrameManager() override;
/**
* @brief Allocate buffer
*
* Caller takes ownership of buffer and can delete it if they want. It can also be returned to
* the manager with Deallocate and potentially be re-used later.
*
* Thread-safe.
*/
char* AllocateFromPool(int size);
/**
* @brief Deallocate buffer
*
* Manager will take ownership and buffer will stay allocated for some time in case it can be
* re-used.
*
* Thread-safe.
*/
void DeallocateToPool(int size, char* buffer);
static FrameManager* instance_;
static const int kFrameLifetime;
struct Buffer
{
qint64 time;
char* data;
};
std::map< int, std::list<Buffer> > pool_;
QMutex mutex_;
QTimer clear_timer_;
private slots:
void GarbageCollection();
};
}
#endif // FRAMEMANAGER_H
| 1,938
|
C++
|
.h
| 65
| 26.615385
| 96
| 0.741062
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,553
|
colortransform.h
|
olive-editor_olive/app/render/colortransform.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef COLORTRANSFORM_H
#define COLORTRANSFORM_H
#include <QString>
#include "common/define.h"
#include "common/ocioutils.h"
namespace olive {
class ColorTransform
{
public:
ColorTransform()
{
is_display_ = false;
}
ColorTransform(const QString& output)
{
is_display_ = false;
output_ = output;
}
ColorTransform(const QString& display, const QString& view, const QString& look)
{
is_display_ = true;
output_ = display;
view_ = view;
look_ = look;
}
bool is_display() const {
return is_display_;
}
const QString& display() const {
return output_;
}
const QString& output() const {
return output_;
}
const QString& view() const {
return view_;
}
const QString& look() const {
return look_;
}
private:
QString output_;
bool is_display_;
QString view_;
QString look_;
};
}
#endif // COLORTRANSFORM_H
| 1,619
|
C++
|
.h
| 62
| 22.854839
| 82
| 0.720521
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,554
|
audiowaveformcache.h
|
olive-editor_olive/app/render/audiowaveformcache.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef AUDIOWAVEFORMCACHE_H
#define AUDIOWAVEFORMCACHE_H
#include "audio/audiovisualwaveform.h"
#include "playbackcache.h"
namespace olive {
class AudioWaveformCache : public PlaybackCache
{
Q_OBJECT
public:
AudioWaveformCache(QObject *parent = nullptr);
void WriteWaveform(const TimeRange &range, const TimeRangeList &valid_ranges, const AudioVisualWaveform *waveform);
const AudioParams &GetParameters() const { return params_; }
void SetParameters(const AudioParams &p)
{
params_ = p;
waveforms_->set_channel_count(p.channel_count());
}
void Draw(QPainter* painter, const QRect &rect, const double &scale, const rational &start_time) const;
AudioVisualWaveform::Sample GetSummaryFromTime(const rational &start, const rational &length) const;
rational length() const;
virtual void SetPassthrough(PlaybackCache *cache) override;
protected:
virtual void InvalidateEvent(const TimeRange& range) override;
private:
using WaveformPtr = std::shared_ptr<AudioVisualWaveform>;
WaveformPtr waveforms_;
AudioParams params_;
class WaveformPassthrough : public TimeRange
{
public:
WaveformPassthrough(const TimeRange &r) :
TimeRange(r)
{}
WaveformPtr waveform;
};
std::vector<WaveformPassthrough> passthroughs_;
};
}
#endif // AUDIOWAVEFORMCACHE_H
| 2,036
|
C++
|
.h
| 53
| 35.245283
| 117
| 0.778856
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,555
|
diskmanager.h
|
olive-editor_olive/app/render/diskmanager.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef DISKMANAGER_H
#define DISKMANAGER_H
#include <QMap>
#include <QMutex>
#include <QObject>
#include <QTimer>
#include "common/define.h"
#include "node/project.h"
namespace olive {
class DiskCacheFolder : public QObject
{
Q_OBJECT
public:
DiskCacheFolder(const QString& path, QObject* parent = nullptr);
virtual ~DiskCacheFolder() override;
bool ClearCache();
void Accessed(const QString& filename);
void CreatedFile(const QString& filename);
const QString& GetPath() const
{
return path_;
}
void SetPath(const QString& path);
qint64 GetLimit() const
{
return limit_;
}
bool GetClearOnClose() const
{
return clear_on_close_;
}
void SetLimit(qint64 l)
{
limit_ = l;
}
void SetClearOnClose(bool e)
{
clear_on_close_ = e;
}
bool DeleteSpecificFile(const QString &f);
signals:
void DeletedFrame(const QString& path, const QString& filename);
private:
struct HashTime {
qint64 file_size;
qint64 access_time;
};
bool DeleteFileInternal(QMap<QString, HashTime>::iterator hash_to_delete);
bool DeleteLeastRecent();
void CloseCacheFolder();
QString path_;
QString index_path_;
QMap<QString, HashTime> disk_data_;
qint64 consumption_;
qint64 limit_;
bool clear_on_close_;
QTimer save_timer_;
private slots:
void SaveDiskCacheIndex();
};
class DiskManager : public QObject
{
Q_OBJECT
public:
static void CreateInstance();
static void DestroyInstance();
static DiskManager* instance();
bool ClearDiskCache(const QString& cache_folder);
DiskCacheFolder* GetDefaultCacheFolder() const
{
// The first folder will always be the default
return open_folders_.first();
}
const QString& GetDefaultCachePath() const
{
return GetDefaultCacheFolder()->GetPath();
}
DiskCacheFolder* GetOpenFolder(const QString& path);
const QVector<DiskCacheFolder*>& GetOpenFolders() const
{
return open_folders_;
}
static bool ShowDiskCacheChangeConfirmationDialog(QWidget* parent);
static QString GetDefaultDiskCacheConfigFile();
static QString GetDefaultDiskCachePath();
void ShowDiskCacheSettingsDialog(DiskCacheFolder* folder, QWidget* parent);
void ShowDiskCacheSettingsDialog(const QString& path, QWidget* parent);
public slots:
void Accessed(const QString& cache_folder, const QString& filename);
void CreatedFile(const QString& cache_folder, const QString& filename);
void DeleteSpecificFile(const QString &filename);
signals:
void DeletedFrame(const QString& path, const QString& filename);
void InvalidateProject(Project* p);
private:
DiskManager();
virtual ~DiskManager() override;
static DiskManager* instance_;
QVector<DiskCacheFolder*> open_folders_;
};
}
#endif // DISKMANAGER_H
| 3,502
|
C++
|
.h
| 116
| 26.956897
| 77
| 0.763451
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,556
|
audioplaybackcache.h
|
olive-editor_olive/app/render/audioplaybackcache.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef AUDIOPLAYBACKCACHE_H
#define AUDIOPLAYBACKCACHE_H
#include "audio/audiovisualwaveform.h"
#include "render/playbackcache.h"
namespace olive {
/**
* @brief A fully integrated system of storing and playing cached audio
*
* All audio in Olive is processed and rendered in advance. This makes playback extremely smooth
* and reliable, but provides some challenges as far as storing and manipulating this audio while
* minimizing the amount of re-renders necessary.
*
* Olive's PlaybackCaches support "shifting"; moving cached data to a different spot on the
* timeline without requiring a costly re-render. While video is naturally stored on disk as
* separate frames that are easy to swap out, audio works a little differently. It would be
* extremely inefficient to store each sample as a separate file on the disk, but storing in
* one single contiguous file would be detrimental to shifting, particularly for longer timelines
* since the data will actually have to be shifted on disk.
*
* As such, AudioPlaybackCache compromises by storing audio in several "segments". This makes
* operations like shifting much easier since segments can simply be removed from the playlist
* rather than having to shift or re-render potentially hours of audio in every operation.
*
* Naturally, storing in segments means you can't simply play the PCM data like a file, so
* AudioPlaybackCache also provides a playback device (accessible from CreatePlaybackDevice()) that
* acts identically to a file-based IO device, transparently joining segments together and acting
* like one contiguous file.
*/
class AudioPlaybackCache : public PlaybackCache
{
Q_OBJECT
public:
AudioPlaybackCache(QObject* parent = nullptr);
virtual ~AudioPlaybackCache() override;
AudioParams GetParameters()
{
return params_;
}
void SetParameters(const AudioParams& params);
void WritePCM(const TimeRange &range, const TimeRangeList &valid_ranges, const SampleBuffer &samples);
void WriteSilence(const TimeRange &range);
private:
bool WritePartOfSampleBuffer(const SampleBuffer &samples, const rational &write_start, const rational &buffer_start, const rational &length);
QString GetSegmentFilename(qint64 segment_index, int channel);
static const qint64 kDefaultSegmentSizePerChannel;
AudioParams params_;
};
}
#endif // AUDIOPLAYBACKCACHE_H
| 3,086
|
C++
|
.h
| 63
| 46.444444
| 143
| 0.79547
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,557
|
rendercache.h
|
olive-editor_olive/app/render/rendercache.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef RENDERCACHE_H
#define RENDERCACHE_H
#include "codec/decoder.h"
namespace olive {
template <typename K, typename V>
class RenderCache : public QHash<K, V>
{
public:
QMutex *mutex()
{
return &mutex_;
}
private:
QMutex mutex_;
};
struct DecoderPair
{
DecoderPtr decoder = nullptr;
qint64 last_modified = 0;
};
using DecoderCache = RenderCache<Decoder::CodecStream, DecoderPair>;
using ShaderCache = RenderCache<QString, QVariant>;
}
#endif // RENDERCACHE_H
| 1,199
|
C++
|
.h
| 38
| 29.105263
| 71
| 0.768761
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,558
|
rendermodes.h
|
olive-editor_olive/app/render/rendermodes.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef RENDERMODE_H
#define RENDERMODE_H
#include "common/define.h"
namespace olive {
class RenderMode {
public:
/**
* @brief The primary different "modes" the renderer can function in
*/
enum Mode {
/**
* This render is for realtime preview ONLY and does not need to be "perfect". Nodes can use lower-accuracy functions
* to save performance when possible.
*/
kOffline,
/**
* This render is some sort of export or master copy and Nodes should take time/bandwidth/system resources to produce
* a higher accuracy version.
*/
kOnline
};
};
}
#endif // RENDERMODE_H
| 1,340
|
C++
|
.h
| 38
| 31.789474
| 121
| 0.73876
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,559
|
rendermanager.h
|
olive-editor_olive/app/render/rendermanager.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef RENDERBACKEND_H
#define RENDERBACKEND_H
#include <QtConcurrent/QtConcurrent>
#include "config/config.h"
#include "colorprocessorcache.h"
#include "dialog/rendercancel/rendercancel.h"
#include "node/output/viewer/viewer.h"
#include "node/project.h"
#include "node/traverser.h"
#include "render/previewautocacher.h"
#include "render/renderer.h"
#include "render/renderticket.h"
#include "rendercache.h"
namespace olive {
class RenderThread : public QThread
{
Q_OBJECT
public:
RenderThread(Renderer *renderer, DecoderCache *decoder_cache, ShaderCache *shader_cache, QObject *parent = nullptr);
void AddTicket(RenderTicketPtr ticket);
bool RemoveTicket(RenderTicketPtr ticket);
void quit();
protected:
virtual void run() override;
private:
QMutex mutex_;
QWaitCondition wait_;
std::list<RenderTicketPtr> queue_;
bool cancelled_;
Renderer *context_;
DecoderCache *decoder_cache_;
ShaderCache *shader_cache_;
};
class RenderManager : public QObject
{
Q_OBJECT
public:
enum Backend {
/// Graphics acceleration provided by OpenGL
kOpenGL,
/// No graphics rendering - used to test core threading logic
kDummy
};
static void CreateInstance()
{
instance_ = new RenderManager();
}
static void DestroyInstance()
{
delete instance_;
instance_ = nullptr;
}
static RenderManager* instance()
{
return instance_;
}
enum ReturnType {
kTexture,
kFrame,
kNull
};
struct RenderVideoParams {
RenderVideoParams(Node *n, const VideoParams &vparam, const AudioParams &aparam, const rational &t,
ColorManager *colorman, RenderMode::Mode m)
{
node = n;
video_params = vparam;
audio_params = aparam;
time = t;
color_manager = colorman;
use_cache = false;
return_type = kFrame;
force_format = PixelFormat::INVALID;
force_color_output = nullptr;
force_size = QSize(0, 0);
force_channel_count = 0;
mode = m;
multicam = nullptr;
}
void AddCache(FrameHashCache *cache)
{
cache_dir = cache->GetCacheDirectory();
cache_timebase = cache->GetTimebase();
cache_id = cache->GetUuid().toString();
}
Node *node;
VideoParams video_params;
AudioParams audio_params;
rational time;
ColorManager *color_manager;
bool use_cache;
ReturnType return_type;
RenderMode::Mode mode;
MultiCamNode *multicam;
QString cache_dir;
rational cache_timebase;
QString cache_id;
QSize force_size;
int force_channel_count;
QMatrix4x4 force_matrix;
PixelFormat force_format;
ColorProcessorPtr force_color_output;
};
static const rational kDryRunInterval;
/**
* @brief Asynchronously generate a frame at a given time
*
* The ticket from this function will return a FramePtr - the rendered frame in reference color
* space.
*
* This function is thread-safe.
*/
RenderTicketPtr RenderFrame(const RenderVideoParams ¶ms);
struct RenderAudioParams {
RenderAudioParams(Node *n, const TimeRange &time, const AudioParams &aparam, RenderMode::Mode m)
{
node = n;
range = time;
audio_params = aparam;
generate_waveforms = false;
clamp = true;
mode = m;
}
Node *node;
TimeRange range;
AudioParams audio_params;
bool generate_waveforms;
bool clamp;
RenderMode::Mode mode;
};
/**
* @brief Asynchronously generate a chunk of audio
*
* The ticket from this function will return a SampleBufferPtr - the rendered audio.
*
* This function is thread-safe.
*/
RenderTicketPtr RenderAudio(const RenderAudioParams ¶ms);
bool RemoveTicket(RenderTicketPtr ticket);
enum TicketType {
kTypeVideo,
kTypeAudio
};
Backend backend() const
{
return backend_;
}
PreviewAutoCacher *GetCacher() const
{
return auto_cacher_;
}
void SetProject(Project *p)
{
auto_cacher_->SetProject(p);
}
public slots:
void SetAggressiveGarbageCollection(bool enabled);
signals:
private:
RenderManager(QObject* parent = nullptr);
virtual ~RenderManager() override;
RenderThread *CreateThread(Renderer *renderer = nullptr);
static RenderManager* instance_;
Renderer* context_;
Backend backend_;
DecoderCache* decoder_cache_;
ShaderCache* shader_cache_;
static constexpr auto kDecoderMaximumInactivityAggressive = 1000;
static constexpr auto kDecoderMaximumInactivity = 5000;
int aggressive_gc_;
QTimer *decoder_clear_timer_;
RenderThread *video_thread_;
RenderThread *dry_run_thread_;
RenderThread *audio_thread_;
std::vector<RenderThread *> waveform_threads_;
size_t last_waveform_thread_;
std::list<RenderThread *> render_threads_;
PreviewAutoCacher *auto_cacher_;
private slots:
void ClearOldDecoders();
};
}
Q_DECLARE_METATYPE(olive::RenderManager::TicketType)
#endif // RENDERBACKEND_H
| 5,675
|
C++
|
.h
| 198
| 24.60101
| 118
| 0.727458
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,560
|
colorprocessor.h
|
olive-editor_olive/app/render/colorprocessor.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef COLORPROCESSOR_H
#define COLORPROCESSOR_H
#include "codec/frame.h"
#include "common/ocioutils.h"
#include "render/colortransform.h"
namespace olive {
class ColorManager;
class ColorProcessor;
using ColorProcessorPtr = std::shared_ptr<ColorProcessor>;
class ColorProcessor
{
public:
enum Direction {
kNormal,
kInverse
};
ColorProcessor(ColorManager* config, const QString& input, const ColorTransform& dest_space, Direction direction = kNormal);
ColorProcessor(OCIO::ConstProcessorRcPtr processor);
DISABLE_COPY_MOVE(ColorProcessor)
static ColorProcessorPtr Create(ColorManager* config, const QString& input, const ColorTransform& dest_space, Direction direction = kNormal);
static ColorProcessorPtr Create(OCIO::ConstProcessorRcPtr processor);
OCIO::ConstProcessorRcPtr GetProcessor();
void ConvertFrame(FramePtr f);
void ConvertFrame(Frame* f);
Color ConvertColor(const Color &in);
const char *id() const
{
return processor_->getCacheID();
}
private:
OCIO::ConstProcessorRcPtr processor_;
OCIO::ConstCPUProcessorRcPtr cpu_processor_;
};
using ColorProcessorChain = QVector<ColorProcessorPtr>;
}
Q_DECLARE_METATYPE(olive::ColorProcessorPtr)
#endif // COLORPROCESSOR_H
| 1,951
|
C++
|
.h
| 51
| 35.431373
| 143
| 0.792533
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,561
|
colorprocessorcache.h
|
olive-editor_olive/app/render/colorprocessorcache.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef COLORPROCESSORCACHE_H
#define COLORPROCESSORCACHE_H
#include "render/colorprocessor.h"
namespace olive {
using ColorProcessorCache = QHash<QString, ColorProcessorPtr>;
}
#endif // COLORPROCESSORCACHE_H
| 927
|
C++
|
.h
| 21
| 41.47619
| 71
| 0.788827
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,562
|
loopmode.h
|
olive-editor_olive/app/render/loopmode.h
|
#ifndef LOOPMODE_H
#define LOOPMODE_H
namespace olive {
enum class LoopMode {
kLoopModeOff,
kLoopModeLoop,
kLoopModeClamp
};
}
#endif // LOOPMODE_H
| 158
|
C++
|
.h
| 10
| 13.8
| 21
| 0.791667
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,563
|
videoparams.h
|
olive-editor_olive/app/render/videoparams.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef VIDEOPARAMS_H
#define VIDEOPARAMS_H
#include <olive/core/core.h>
#include <QVector2D>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
namespace olive {
using namespace core;
class VideoParams {
public:
enum Interlacing {
kInterlaceNone,
kInterlacedTopFirst,
kInterlacedBottomFirst
};
enum Type {
kVideoTypeVideo,
kVideoTypeStill,
kVideoTypeImageSequence
};
enum ColorRange
{
kColorRangeLimited, // 16_235
kColorRangeFull, // 0-255
kColorRangeDefault = kColorRangeLimited
};
VideoParams();
VideoParams(int width, int height, PixelFormat format, int nb_channels,
const rational& pixel_aspect_ratio = 1,
Interlacing interlacing = kInterlaceNone, int divider = 1);
VideoParams(int width, int height, int depth,
PixelFormat format, int nb_channels,
const rational& pixel_aspect_ratio = 1,
Interlacing interlacing = kInterlaceNone, int divider = 1);
VideoParams(int width, int height, const rational& time_base,
PixelFormat format, int nb_channels,
const rational& pixel_aspect_ratio = 1,
Interlacing interlacing = kInterlaceNone, int divider = 1);
int width() const
{
return width_;
}
void set_width(int width)
{
width_ = width;
calculate_effective_size();
}
/**
* @brief Returns width multiplied by pixel aspect ratio where applicable
*/
int square_pixel_width() const
{
return par_width_;
}
QVector2D resolution() const
{
return QVector2D(width_, height_);
}
QVector2D square_resolution() const
{
return QVector2D(par_width_, height_);
}
int height() const
{
return height_;
}
void set_height(int height)
{
height_ = height;
calculate_effective_size();
}
int depth() const
{
return depth_;
}
void set_depth(int depth)
{
depth_ = depth;
calculate_effective_size();
}
bool is_3d() const { return depth_ > 1; }
const rational& time_base() const
{
return time_base_;
}
void set_time_base(const rational& r)
{
time_base_ = r;
}
rational frame_rate_as_time_base() const
{
return frame_rate_.flipped();
}
int divider() const
{
return divider_;
}
void set_divider(int d)
{
divider_ = d;
calculate_effective_size();
}
int effective_width() const
{
return effective_width_;
}
int effective_height() const
{
return effective_height_;
}
int effective_depth() const
{
return effective_depth_;
}
PixelFormat format() const
{
return format_;
}
void set_format(PixelFormat f)
{
format_ = f;
}
int channel_count() const
{
return channel_count_;
}
void set_channel_count(int c)
{
channel_count_ = c;
}
const rational& pixel_aspect_ratio() const
{
return pixel_aspect_ratio_;
}
void set_pixel_aspect_ratio(const rational& r)
{
pixel_aspect_ratio_ = r;
validate_pixel_aspect_ratio();
}
Interlacing interlacing() const
{
return interlacing_;
}
void set_interlacing(Interlacing i)
{
interlacing_ = i;
}
static int generate_auto_divider(qint64 width, qint64 height);
bool is_valid() const;
bool operator==(const VideoParams& rhs) const;
bool operator!=(const VideoParams& rhs) const;
static int GetBytesPerChannel(PixelFormat format);
int GetBytesPerChannel() const
{
return GetBytesPerChannel(format_);
}
static int GetBytesPerPixel(PixelFormat format, int channels);
int GetBytesPerPixel() const
{
return GetBytesPerPixel(format_, channel_count_);
}
static int GetBufferSize(int width, int height, PixelFormat format, int channels)
{
return width * height * GetBytesPerPixel(format, channels);
}
int GetBufferSize() const
{
return GetBufferSize(width_, height_, format_, channel_count_);
}
static QString GetNameForDivider(int div);
static bool FormatIsFloat(PixelFormat format)
{
return format.is_float();
}
static QString GetFormatName(PixelFormat format);
static int GetDividerForTargetResolution(int src_width, int src_height, int dst_width, int dst_height);
static const int kInternalChannelCount;
static const rational kPixelAspectSquare;
static const rational kPixelAspectNTSCStandard;
static const rational kPixelAspectNTSCWidescreen;
static const rational kPixelAspectPALStandard;
static const rational kPixelAspectPALWidescreen;
static const rational kPixelAspect1080Anamorphic;
static const QVector<rational> kSupportedFrameRates;
static const QVector<rational> kStandardPixelAspects;
static const QVector<int> kSupportedDividers;
static const int kHSVChannelCount = 3;
static const int kRGBChannelCount = 3;
static const int kRGBAChannelCount = 4;
/**
* @brief Convert rational frame rate (i.e. flipped timebase) to a user-friendly string
*/
static QString FrameRateToString(const rational& frame_rate);
static QStringList GetStandardPixelAspectRatioNames();
static QString FormatPixelAspectRatioString(const QString& format, const rational& ratio);
static int GetScaledDimension(int dim, int divider);
bool enabled() const
{
return enabled_;
}
void set_enabled(bool e)
{
enabled_ = e;
}
float x() const { return x_; }
void set_x(float x) { x_ = x; }
float y() const { return y_; }
void set_y(float y) { y_ = y; }
QVector2D offset() const { return QVector2D(x_, y_); }
int stream_index() const
{
return stream_index_;
}
void set_stream_index(int s)
{
stream_index_ = s;
}
Type video_type() const
{
return video_type_;
}
void set_video_type(Type t)
{
video_type_ = t;
}
const rational& frame_rate() const
{
return frame_rate_;
}
void set_frame_rate(const rational& frame_rate)
{
frame_rate_ = frame_rate;
}
int64_t start_time() const
{
return start_time_;
}
void set_start_time(int64_t start_time)
{
start_time_ = start_time;
}
int64_t duration() const
{
return duration_;
}
void set_duration(int64_t duration)
{
duration_ = duration;
}
bool premultiplied_alpha() const
{
return premultiplied_alpha_;
}
void set_premultiplied_alpha(bool premultiplied_alpha)
{
premultiplied_alpha_ = premultiplied_alpha;
}
const QString& colorspace() const
{
return colorspace_;
}
void set_colorspace(const QString& c)
{
colorspace_ = c;
}
const ColorRange &color_range() const { return color_range_; }
void set_color_range(const ColorRange &color_range) { color_range_ = color_range; }
int64_t get_time_in_timebase_units(const rational& time) const;
void Load(QXmlStreamReader* reader);
void Save(QXmlStreamWriter* writer) const;
private:
void calculate_effective_size();
void validate_pixel_aspect_ratio();
void set_defaults_for_footage();
void calculate_square_pixel_width();
int width_;
int height_;
int depth_;
rational time_base_;
PixelFormat format_;
int channel_count_;
rational pixel_aspect_ratio_;
Interlacing interlacing_;
int divider_;
// Cached values
int effective_width_;
int effective_height_;
int effective_depth_;
int par_width_;
bool enabled_;
int stream_index_;
Type video_type_;
rational frame_rate_;
int64_t start_time_;
int64_t duration_;
bool premultiplied_alpha_;
QString colorspace_;
float x_;
float y_;
ColorRange color_range_;
};
}
Q_DECLARE_METATYPE(olive::VideoParams)
Q_DECLARE_METATYPE(olive::VideoParams::Interlacing)
#endif // VIDEOPARAMS_H
| 8,366
|
C++
|
.h
| 319
| 22.354232
| 105
| 0.71231
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,564
|
renderjobtracker.h
|
olive-editor_olive/app/render/renderjobtracker.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef RENDERJOBTRACKER_H
#define RENDERJOBTRACKER_H
#include <olive/core/core.h>
#include "common/jobtime.h"
namespace olive {
using namespace core;
class RenderJobTracker
{
public:
RenderJobTracker() = default;
void insert(const TimeRange &range, JobTime job_time);
void insert(const TimeRangeList &ranges, JobTime job_time);
void clear();
bool isCurrent(const rational &time, JobTime job_time) const;
TimeRangeList getCurrentSubRanges(const TimeRange &range, const JobTime &job_time) const;
private:
class TimeRangeWithJob : public TimeRange
{
public:
TimeRangeWithJob() = default;
TimeRangeWithJob(const TimeRange &range, const JobTime &job_time)
{
set_range(range.in(), range.out());
job_time_ = job_time;
}
JobTime GetJobTime() const {return job_time_;}
void SetJobTime(JobTime jt) {job_time_ = jt;}
private:
JobTime job_time_;
};
std::vector<TimeRangeWithJob> jobs_;
};
}
#endif // RENDERJOBTRACKER_H
| 1,702
|
C++
|
.h
| 48
| 32.145833
| 91
| 0.754139
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,565
|
cancelatom.h
|
olive-editor_olive/app/render/cancelatom.h
|
#ifndef CANCELATOM_H
#define CANCELATOM_H
#include <QMutex>
namespace olive {
class CancelAtom
{
public:
CancelAtom() :
cancelled_(false),
heard_(false)
{}
bool IsCancelled()
{
QMutexLocker locker(&mutex_);
if (cancelled_) {
heard_ = true;
}
return cancelled_;
}
void Cancel()
{
QMutexLocker locker(&mutex_);
cancelled_ = true;
}
bool HeardCancel()
{
QMutexLocker locker(&mutex_);
return heard_;
}
private:
QMutex mutex_;
bool cancelled_;
bool heard_;
};
}
#endif // CANCELATOM_H
| 566
|
C++
|
.h
| 36
| 12.333333
| 33
| 0.656371
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,566
|
projectcopier.h
|
olive-editor_olive/app/render/projectcopier.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef PROJECTCOPIER_H
#define PROJECTCOPIER_H
#include "node/project.h"
namespace olive {
class ProjectCopier : public QObject
{
Q_OBJECT
public:
ProjectCopier(QObject *parent = nullptr);
void SetProject(Project *project);
template <typename T>
T *GetCopy(T *original)
{
return static_cast<T*>(copy_map_.value(original));
}
template <typename T>
T *GetOriginal(T *copy)
{
return static_cast<T*>(copy_map_.key(copy));
}
Project *GetCopiedProject() const { return copy_; }
const QHash<Node*, Node*> &GetNodeMap() const { return copy_map_; }
const JobTime &GetGraphChangeTime() const { return graph_changed_time_; }
const JobTime &GetLastUpdateTime() const { return last_update_time_; }
bool HasUpdatesInQueue() const { return !graph_update_queue_.empty(); }
/**
* @brief Process all changes to internal NodeGraph copy
*
* PreviewAutoCacher staggers updates to its internal NodeGraph copy, only applying them when the
* RenderManager is not reading from it. This function is called when such an opportunity arises.
*/
void ProcessUpdateQueue();
signals:
void AddedNode(Node *n);
void RemovedNode(Node *n);
private:
void DoNodeAdd(Node* node);
void DoNodeRemove(Node* node);
void DoEdgeAdd(Node *output, const NodeInput& input);
void DoEdgeRemove(Node *output, const NodeInput& input);
void DoValueChange(const NodeInput& input);
void DoValueHintChange(const NodeInput &input);
void DoProjectSettingChange(const QString &key, const QString &value);
void InsertIntoCopyMap(Node* node, Node* copy);
void UpdateGraphChangeValue();
void UpdateLastSyncedValue();
Project *original_;
Project *copy_;
class QueuedJob {
public:
enum Type {
kNodeAdded,
kNodeRemoved,
kEdgeAdded,
kEdgeRemoved,
kValueChanged,
kValueHintChanged,
kProjectSettingChanged
};
Type type;
Node* node;
NodeInput input;
Node *output;
QString key;
QString value;
};
std::list<QueuedJob> graph_update_queue_;
QHash<Node*, Node*> copy_map_;
QHash<Project*, Project*> graph_map_;
QVector<Node*> created_nodes_;
JobTime graph_changed_time_;
JobTime last_update_time_;
private slots:
void QueueNodeAdd(Node* node);
void QueueNodeRemove(Node* node);
void QueueEdgeAdd(Node *output, const NodeInput& input);
void QueueEdgeRemove(Node *output, const NodeInput& input);
void QueueValueChange(const NodeInput& input);
void QueueValueHintChange(const NodeInput &input);
void QueueProjectSettingChange(const QString &key, const QString &value);
};
}
#endif // PROJECTCOPIER_H
| 3,361
|
C++
|
.h
| 97
| 31.030928
| 99
| 0.744964
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,567
|
framehashcache.h
|
olive-editor_olive/app/render/framehashcache.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef VIDEORENDERFRAMECACHE_H
#define VIDEORENDERFRAMECACHE_H
#include "codec/frame.h"
#include "render/playbackcache.h"
#include "render/videoparams.h"
namespace olive {
class FrameHashCache : public PlaybackCache
{
Q_OBJECT
public:
FrameHashCache(QObject* parent = nullptr);
const rational &GetTimebase() const { return timebase_; }
void SetTimebase(const rational& tb);
void ValidateTimestamp(const int64_t &ts);
void ValidateTime(const rational &time);
bool IsFrameCached(const rational &time) const
{
return GetValidatedRanges().contains(time);
}
QString GetValidCacheFilename(const rational &time) const;
static bool SaveCacheFrame(const QString& filename, FramePtr frame);
bool SaveCacheFrame(const int64_t &time, FramePtr frame) const;
static bool SaveCacheFrame(const QString& cache_path, const QUuid &uuid, const int64_t &time, FramePtr frame);
static bool SaveCacheFrame(const QString& cache_path, const QUuid &uuid, const rational &time, const rational &tb, FramePtr frame);
static FramePtr LoadCacheFrame(const QString& cache_path, const QUuid &uuid, const int64_t &time);
FramePtr LoadCacheFrame(const int64_t &time) const;
static FramePtr LoadCacheFrame(const QString& fn);
virtual void SetPassthrough(PlaybackCache *cache) override;
protected:
virtual void LoadStateEvent(QDataStream &stream) override;
virtual void SaveStateEvent(QDataStream &stream) override;
private:
rational ToTime(const int64_t &ts) const;
int64_t ToTimestamp(const rational &ts, Timecode::Rounding rounding = Timecode::kRound) const;
/**
* @brief Return the path of the cached image at this time
*/
QString CachePathName(const int64_t &time) const;
QString CachePathName(const rational &time) const;
static QString CachePathName(const QString& cache_path, const QUuid &cache_id, const int64_t &time);
static QString CachePathName(const QString& cache_path, const QUuid &cache_id, const rational &time, const rational &tb);
rational timebase_;
private slots:
void HashDeleted(const QString &path, const QString &filename);
void ProjectInvalidated(Project* p);
};
class ThumbnailCache : public FrameHashCache
{
Q_OBJECT
public:
ThumbnailCache(QObject* parent = nullptr) :
FrameHashCache(parent)
{
SetTimebase(rational(1, 10));
}
};
}
#endif // VIDEORENDERFRAMECACHE_H
| 3,077
|
C++
|
.h
| 72
| 39.833333
| 133
| 0.78039
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,568
|
managedcolor.h
|
olive-editor_olive/app/render/managedcolor.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef MANAGEDCOLOR_H
#define MANAGEDCOLOR_H
#include <olive/core/core.h>
#include "colortransform.h"
namespace olive {
class ManagedColor : public Color
{
public:
ManagedColor();
ManagedColor(const double& r, const double& g, const double& b, const double& a = 1.0);
ManagedColor(const char *data, const PixelFormat &format, int channel_layout);
ManagedColor(const Color& c);
const QString& color_input() const;
void set_color_input(const QString &color_input);
const ColorTransform& color_output() const;
void set_color_output(const ColorTransform &color_output);
private:
QString color_input_;
ColorTransform color_transform_;
};
}
#endif // MANAGEDCOLOR_H
| 1,404
|
C++
|
.h
| 36
| 36.305556
| 89
| 0.771281
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,569
|
alphaassoc.h
|
olive-editor_olive/app/render/alphaassoc.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef ALPHAASSOC_H
#define ALPHAASSOC_H
namespace olive {
enum AlphaAssociated {
kAlphaNone,
kAlphaUnassociated,
kAlphaAssociated
};
}
#endif // ALPHAASSOC_H
| 882
|
C++
|
.h
| 24
| 34.083333
| 71
| 0.779481
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,570
|
shadercode.h
|
olive-editor_olive/app/render/shadercode.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef SHADERCODE_H
#define SHADERCODE_H
#include "common/filefunctions.h"
namespace olive {
class ShaderCode {
public:
ShaderCode(const QString& frag_code = QString(), const QString& vert_code = QString()) :
frag_code_(frag_code),
vert_code_(vert_code)
{
}
const QString& frag_code() const { return frag_code_; }
void set_frag_code(const QString &f) { frag_code_ = f; }
const QString& vert_code() const { return vert_code_; }
void set_vert_code(const QString &v) { vert_code_ = v; }
private:
QString frag_code_;
QString vert_code_;
};
}
#endif // SHADERCODE_H
| 1,310
|
C++
|
.h
| 35
| 34.542857
| 90
| 0.739476
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,571
|
texture.h
|
olive-editor_olive/app/render/texture.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef RENDERTEXTURE_H
#define RENDERTEXTURE_H
#include <memory>
#include <QVariant>
#include "render/videoparams.h"
namespace olive {
class AcceleratedJob;
class Renderer;
class Texture;
using TexturePtr = std::shared_ptr<Texture>;
class Texture
{
public:
enum Interpolation {
kNearest,
kLinear,
kMipmappedLinear
};
static const Interpolation kDefaultInterpolation;
/**
* @brief Construct a dummy texture with no renderer backend
*/
Texture(const VideoParams& param) :
renderer_(nullptr),
params_(param),
job_(nullptr)
{
}
template <typename T>
Texture(const VideoParams &p, const T &j) :
Texture(p)
{
job_ = new T(j);
}
/**
* @brief Construct a real texture linked to a renderer backend
*/
Texture(Renderer* renderer, const QVariant& native, const VideoParams& param) :
renderer_(renderer),
params_(param),
id_(native),
job_(nullptr)
{
}
~Texture();
QVariant id() const
{
return id_;
}
const VideoParams& params() const
{
return params_;
}
template <typename T>
static TexturePtr Job(const VideoParams &p, const T &j)
{
return std::make_shared<Texture>(p, j);
}
template <typename T>
TexturePtr toJob(const T &job)
{
return Texture::Job(params_, job);
}
void Upload(void* data, int linesize);
void Download(void* data, int linesize);
bool IsDummy() const
{
return !renderer_;
}
int width() const
{
return params_.effective_width();
}
int height() const
{
return params_.effective_height();
}
QVector2D virtual_resolution() const
{
return QVector2D(params_.square_pixel_width(), params_.height());
}
PixelFormat format() const
{
return params_.format();
}
int channel_count() const
{
return params_.channel_count();
}
int divider() const
{
return params_.divider();
}
const rational& pixel_aspect_ratio() const
{
return params_.pixel_aspect_ratio();
}
Renderer* renderer() const
{
return renderer_;
}
bool IsJob() const { return job_; }
AcceleratedJob *job() const { return job_; }
private:
Renderer* renderer_;
VideoParams params_;
QVariant id_;
AcceleratedJob *job_;
};
}
Q_DECLARE_METATYPE(olive::TexturePtr)
#endif // RENDERTEXTURE_H
| 3,029
|
C++
|
.h
| 126
| 20.603175
| 81
| 0.706848
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,572
|
openglrenderer.h
|
olive-editor_olive/app/render/opengl/openglrenderer.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef OPENGLCONTEXT_H
#define OPENGLCONTEXT_H
#include <QOffscreenSurface>
#include <QOpenGLBuffer>
#include <QOpenGLFunctions>
#include <QOpenGLShader>
#include <QOpenGLVertexArrayObject>
#include <QThread>
#include <QTimer>
#include "render/renderer.h"
namespace olive {
class OpenGLRenderer : public Renderer
{
Q_OBJECT
public:
OpenGLRenderer(QObject* parent = nullptr);
virtual ~OpenGLRenderer() override;
void Init(QOpenGLContext* existing_ctx);
virtual bool Init() override;
virtual void PostDestroy() override;
virtual void PostInit() override;
virtual void ClearDestination(olive::Texture *texture = nullptr, double r = 0.0, double g = 0.0, double b = 0.0, double a = 0.0) override;
virtual QVariant CreateNativeShader(olive::ShaderCode code) override;
virtual void DestroyNativeShader(QVariant shader) override;
virtual void UploadToTexture(const QVariant &handle, const VideoParams ¶ms, const void* data, int linesize) override;
virtual void DownloadFromTexture(const QVariant &handle, const VideoParams ¶ms, void* data, int linesize) override;
virtual void Flush() override;
virtual Color GetPixelFromTexture(olive::Texture *texture, const QPointF &pt) override;
protected:
virtual void Blit(QVariant shader,
olive::ShaderJob job,
olive::Texture* destination,
olive::VideoParams destination_params,
bool clear_destination) override;
virtual QVariant CreateNativeTexture(int width, int height, int depth, PixelFormat format, int channel_count, const void* data = nullptr, int linesize = 0) override;
virtual void DestroyNativeTexture(QVariant texture) override;
virtual void DestroyInternal() override;
private:
static GLint GetInternalFormat(PixelFormat format, int channel_layout);
static GLenum GetPixelType(PixelFormat format);
static GLenum GetPixelFormat(int channel_count);
void AttachTextureAsDestination(const QVariant &texture);
void DetachTextureAsDestination();
void PrepareInputTexture(GLenum target, Texture::Interpolation interp);
void ClearDestinationInternal(double r = 0.0, double g = 0.0, double b = 0.0, double a = 0.0);
GLuint CompileShader(GLenum type, const QString &code);
QOpenGLContext* context_;
QOpenGLFunctions* functions_;
QOffscreenSurface surface_;
GLuint framebuffer_;
struct TextureCacheKey {
int width;
int height;
int depth;
PixelFormat format;
int channel_count;
bool operator==(const TextureCacheKey &rhs) const
{
return width == rhs.width && height == rhs.height && depth == rhs.depth
&& format == rhs.format && channel_count == rhs.channel_count;
}
};
QMap<GLuint, TextureCacheKey> texture_params_;
static const int kTextureCacheMaxSize;
};
}
#endif // OPENGLCONTEXT_H
| 3,576
|
C++
|
.h
| 81
| 39.876543
| 167
| 0.76
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,573
|
samplejob.h
|
olive-editor_olive/app/render/job/samplejob.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef SAMPLEJOB_H
#define SAMPLEJOB_H
#include "acceleratedjob.h"
namespace olive {
class SampleJob : public AcceleratedJob
{
public:
SampleJob()
{
}
SampleJob(const TimeRange &time, const NodeValue& value)
{
samples_ = value.toSamples();
time_ = time;
}
SampleJob(const TimeRange &time, const QString& from, const NodeValueRow& row)
{
samples_ = row[from].toSamples();
time_ = time;
}
const SampleBuffer &samples() const
{
return samples_;
}
bool HasSamples() const
{
return samples_.is_allocated();
}
const TimeRange &time() const { return time_; }
private:
SampleBuffer samples_;
TimeRange time_;
};
}
Q_DECLARE_METATYPE(olive::SampleJob)
#endif // SAMPLEJOB_H
| 1,452
|
C++
|
.h
| 50
| 25.96
| 80
| 0.739508
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,574
|
footagejob.h
|
olive-editor_olive/app/render/job/footagejob.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef FOOTAGEJOB_H
#define FOOTAGEJOB_H
#include "node/project/footage/footage.h"
namespace olive {
class FootageJob : public AcceleratedJob
{
public:
FootageJob() :
type_(Track::kNone)
{
}
FootageJob(const TimeRange &time, const QString& decoder, const QString& filename, Track::Type type, const rational& length, LoopMode loop_mode) :
time_(time),
decoder_(decoder),
filename_(filename),
type_(type),
length_(length),
loop_mode_(loop_mode)
{
}
const QString& decoder() const
{
return decoder_;
}
const QString& filename() const
{
return filename_;
}
Track::Type type() const
{
return type_;
}
const VideoParams& video_params() const
{
return video_params_;
}
void set_video_params(const VideoParams& p)
{
video_params_ = p;
}
const AudioParams& audio_params() const
{
return audio_params_;
}
void set_audio_params(const AudioParams& p)
{
audio_params_ = p;
}
const QString& cache_path() const
{
return cache_path_;
}
void set_cache_path(const QString& p)
{
cache_path_ = p;
}
const rational& length() const
{
return length_;
}
void set_length(const rational& length)
{
length_ = length;
}
const TimeRange &time() const { return time_; }
LoopMode loop_mode() const { return loop_mode_; }
void set_loop_mode(LoopMode m) { loop_mode_ = m; }
private:
TimeRange time_;
QString decoder_;
QString filename_;
Track::Type type_;
VideoParams video_params_;
AudioParams audio_params_;
QString cache_path_;
rational length_;
LoopMode loop_mode_;
};
}
Q_DECLARE_METATYPE(olive::FootageJob)
#endif // FOOTAGEJOB_H
| 2,420
|
C++
|
.h
| 95
| 22.010526
| 148
| 0.709917
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,575
|
colortransformjob.h
|
olive-editor_olive/app/render/job/colortransformjob.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef COLORTRANSFORMJOB_H
#define COLORTRANSFORMJOB_H
#include <QMatrix4x4>
#include <QString>
#include "acceleratedjob.h"
#include "render/alphaassoc.h"
#include "render/colorprocessor.h"
#include "render/texture.h"
namespace olive {
class Node;
class ColorTransformJob : public AcceleratedJob
{
public:
ColorTransformJob()
{
processor_ = nullptr;
custom_shader_src_ = nullptr;
input_alpha_association_ = kAlphaNone;
clear_destination_ = true;
force_opaque_ = false;
}
ColorTransformJob(const NodeValueRow &row) :
ColorTransformJob()
{
Insert(row);
}
QString id() const
{
if (id_.isEmpty()) {
return processor_->id();
} else {
return id_;
}
}
void SetOverrideID(const QString &id) { id_ = id; }
const NodeValue &GetInputTexture() const { return input_texture_; }
void SetInputTexture(const NodeValue &tex) { input_texture_ = tex; }
void SetInputTexture(TexturePtr tex)
{
Q_ASSERT(!tex->IsDummy());
input_texture_ = NodeValue(NodeValue::kTexture, tex);
}
ColorProcessorPtr GetColorProcessor() const { return processor_; }
void SetColorProcessor(ColorProcessorPtr p) { processor_ = p; }
const AlphaAssociated &GetInputAlphaAssociation() const { return input_alpha_association_; }
void SetInputAlphaAssociation(const AlphaAssociated &e) { input_alpha_association_ = e; }
const Node *CustomShaderSource() const { return custom_shader_src_; }
const QString &CustomShaderID() const { return custom_shader_id_; }
void SetNeedsCustomShader(const Node *node, const QString &id = QString())
{
custom_shader_src_ = node;
custom_shader_id_ = id;
}
bool IsClearDestinationEnabled() const { return clear_destination_; }
void SetClearDestinationEnabled(bool e) { clear_destination_ = e; }
const QMatrix4x4 &GetTransformMatrix() const { return matrix_; }
void SetTransformMatrix(const QMatrix4x4 &m) { matrix_ = m; }
const QMatrix4x4 &GetCropMatrix() const { return crop_matrix_; }
void SetCropMatrix(const QMatrix4x4 &m) { crop_matrix_ = m; }
const QString &GetFunctionName() const { return function_name_; }
void SetFunctionName(const QString &function_name = QString()) { function_name_ = function_name; };
bool GetForceOpaque() const { return force_opaque_; }
void SetForceOpaque(bool e) { force_opaque_ = e; }
private:
ColorProcessorPtr processor_;
QString id_;
NodeValue input_texture_;
const Node *custom_shader_src_;
QString custom_shader_id_;
AlphaAssociated input_alpha_association_;
bool clear_destination_;
QMatrix4x4 matrix_;
QMatrix4x4 crop_matrix_;
QString function_name_;
bool force_opaque_;
};
}
#endif // COLORTRANSFORMJOB_H
| 3,429
|
C++
|
.h
| 92
| 33.913043
| 101
| 0.74046
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,576
|
cachejob.h
|
olive-editor_olive/app/render/job/cachejob.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef CACHEJOB_H
#define CACHEJOB_H
#include <QString>
#include <QVariant>
#include "node/value.h"
#include "render/job/acceleratedjob.h"
namespace olive {
class CacheJob : public AcceleratedJob
{
public:
CacheJob() = default;
CacheJob(const QString &filename, const NodeValue &fallback = NodeValue())
{
filename_ = filename;
}
const QString &GetFilename() const { return filename_; }
void SetFilename(const QString &s) { filename_ = s; }
const NodeValue &GetFallback() const { return fallback_; }
void SetFallback(const NodeValue &val) { fallback_ = val; }
private:
QString filename_;
NodeValue fallback_;
};
}
#endif // CACHEJOB_H
| 1,382
|
C++
|
.h
| 39
| 32.769231
| 76
| 0.75641
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,577
|
generatejob.h
|
olive-editor_olive/app/render/job/generatejob.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef GENERATEJOB_H
#define GENERATEJOB_H
#include "acceleratedjob.h"
#include "codec/frame.h"
namespace olive {
class GenerateJob : public AcceleratedJob
{
public:
GenerateJob() = default;
GenerateJob(const NodeValueRow &row) :
GenerateJob()
{
Insert(row);
}
};
}
#endif // GENERATEJOB_H
| 1,025
|
C++
|
.h
| 31
| 30.387097
| 71
| 0.765784
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,578
|
acceleratedjob.h
|
olive-editor_olive/app/render/job/acceleratedjob.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef ACCELERATEDJOB_H
#define ACCELERATEDJOB_H
#include "node/param.h"
#include "node/valuedatabase.h"
namespace olive {
class AcceleratedJob
{
public:
AcceleratedJob() = default;
virtual ~AcceleratedJob(){}
NodeValue Get(const QString& input) const
{
return value_map_.value(input);
}
void Insert(const QString &input, const NodeValueRow &row)
{
value_map_.insert(input, row.value(input));
}
void Insert(const QString& input, const NodeValue& value)
{
value_map_.insert(input, value);
}
void Insert(const NodeValueRow &row)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
value_map_.insert(row);
#else
for (auto it=row.cbegin(); it!=row.cend(); it++) {
value_map_.insert(it.key(), it.value());
}
#endif
}
const NodeValueRow &GetValues() const { return value_map_; }
NodeValueRow &GetValues() { return value_map_; }
private:
NodeValueRow value_map_;
};
}
#endif // ACCELERATEDJOB_H
| 1,673
|
C++
|
.h
| 53
| 28.54717
| 71
| 0.732667
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,579
|
shaderjob.h
|
olive-editor_olive/app/render/job/shaderjob.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef SHADERJOB_H
#define SHADERJOB_H
#include <QMatrix4x4>
#include <QVector>
#include "acceleratedjob.h"
#include "render/texture.h"
namespace olive {
class ShaderJob : public AcceleratedJob
{
public:
ShaderJob()
{
iterations_ = 1;
iterative_input_ = nullptr;
}
ShaderJob(const NodeValueRow &row) :
ShaderJob()
{
Insert(row);
}
const QString& GetShaderID() const
{
return shader_id_;
}
void SetShaderID(const QString& id)
{
shader_id_ = id;
}
void SetIterations(int iterations, const NodeInput& iterative_input)
{
SetIterations(iterations, iterative_input.input());
}
void SetIterations(int iterations, const QString& iterative_input)
{
iterations_ = iterations;
iterative_input_ = iterative_input;
}
int GetIterationCount() const
{
return iterations_;
}
const QString& GetIterativeInput() const
{
return iterative_input_;
}
Texture::Interpolation GetInterpolation(const QString& id) const
{
return interpolation_.value(id, Texture::kDefaultInterpolation);
}
const QHash<QString, Texture::Interpolation> &GetInterpolationMap() const
{
return interpolation_;
}
void SetInterpolation(const NodeInput& input, Texture::Interpolation interp)
{
interpolation_.insert(input.input(), interp);
}
void SetInterpolation(const QString& id, Texture::Interpolation interp)
{
interpolation_.insert(id, interp);
}
void SetVertexCoordinates(const QVector<float> &vertex_coords)
{
vertex_overrides_ = vertex_coords;
}
const QVector<float>& GetVertexCoordinates()
{
return vertex_overrides_;
}
private:
QString shader_id_;
int iterations_;
QString iterative_input_;
QHash<QString, Texture::Interpolation> interpolation_;
QVector<float> vertex_overrides_;
};
}
#endif // SHADERJOB_H
| 2,566
|
C++
|
.h
| 92
| 24.532609
| 78
| 0.744576
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,580
|
mainwindowlayoutinfo.h
|
olive-editor_olive/app/window/mainwindow/mainwindowlayoutinfo.h
|
#ifndef MAINWINDOWLAYOUTINFO_H
#define MAINWINDOWLAYOUTINFO_H
#include "node/project/folder/folder.h"
#include "node/project/sequence/sequence.h"
#include "panel/panel.h"
namespace olive {
class MainWindowLayoutInfo
{
public:
MainWindowLayoutInfo() = default;
void toXml(QXmlStreamWriter* writer) const;
static MainWindowLayoutInfo fromXml(QXmlStreamReader* reader, const QHash<quintptr, Node*> &node_map);
void add_folder(Folder* f);
void add_sequence(Sequence *seq);
void add_viewer(ViewerOutput *viewer);
void set_panel_data(const QString &id, const PanelWidget::Info &data);
void move_panel_data(const QString &old, const QString &now);
void set_state(const QByteArray& layout);
const std::vector<Folder*>& open_folders() const
{
return open_folders_;
}
const std::vector<Sequence*>& open_sequences() const
{
return open_sequences_;
}
const std::vector<ViewerOutput*>& open_viewers() const
{
return open_viewers_;
}
const std::map<QString, PanelWidget::Info> &panel_data() const
{
return panel_data_;
}
const QByteArray& state() const
{
return state_;
}
private:
QByteArray state_;
std::vector<Folder*> open_folders_;
std::vector<Sequence*> open_sequences_;
std::vector<ViewerOutput*> open_viewers_;
std::map<QString, PanelWidget::Info> panel_data_;
static const unsigned int kVersion = 1;
};
}
Q_DECLARE_METATYPE(olive::MainWindowLayoutInfo)
#endif // MAINWINDOWLAYOUTINFO_H
| 1,486
|
C++
|
.h
| 49
| 27.163265
| 104
| 0.747697
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,581
|
mainwindow.h
|
olive-editor_olive/app/window/mainwindow/mainwindow.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <kddockwidgets/Config.h>
#include <kddockwidgets/MainWindow.h>
#include "mainwindowlayoutinfo.h"
#include "node/project.h"
#include "panel/multicam/multicampanel.h"
#include "panel/panelmanager.h"
#include "panel/audiomonitor/audiomonitor.h"
#include "panel/curve/curve.h"
#include "panel/history/historypanel.h"
#include "panel/node/node.h"
#include "panel/param/param.h"
#include "panel/project/project.h"
#include "panel/scope/scope.h"
#include "panel/table/table.h"
#include "panel/taskmanager/taskmanager.h"
#include "panel/timeline/timeline.h"
#include "panel/tool/tool.h"
#include "panel/footageviewer/footageviewer.h"
#include "panel/sequenceviewer/sequenceviewer.h"
#include "panel/pixelsampler/pixelsamplerpanel.h"
#ifdef Q_OS_WINDOWS
#include <shobjidl.h>
#endif
namespace olive {
/**
* @brief Olive's main window responsible for docking widgets and the main menu bar.
*/
class MainWindow : public KDDockWidgets::MainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
virtual ~MainWindow() override;
void LoadLayout(const MainWindowLayoutInfo &info);
MainWindowLayoutInfo SaveLayout() const;
TimelinePanel *OpenSequence(Sequence* sequence, bool enable_focus = true);
void CloseSequence(Sequence* sequence);
bool IsSequenceOpen(Sequence* sequence) const;
void OpenFolder(Folder *i, bool floating);
void OpenNodeInViewer(ViewerOutput* node);
enum ProgressStatus {
kProgressNone,
kProgressShow,
kProgressError
};
/**
* @brief Where applicable, show progress on an operating system level
*
* * For Windows, this is shown as progress in the taskbar.
* * For macOS, this is shown as progress in the dock.
*/
void SetApplicationProgressStatus(ProgressStatus status);
/**
* @brief If SetApplicationProgressStatus is set to kShowProgress, set the value with this
*
* Expects a percentage (0-100 inclusive).
*/
void SetApplicationProgressValue(int value);
void SelectFootage(const QVector<Footage*> &e);
public slots:
void SetProject(Project *p);
void SetFullscreen(bool fullscreen);
void ToggleMaximizedPanel();
void SetDefaultLayout();
protected:
virtual void showEvent(QShowEvent* e) override;
virtual void closeEvent(QCloseEvent* e) override;
#ifdef Q_OS_WINDOWS
virtual bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
#endif
private:
TimelinePanel* AppendTimelinePanel();
template <typename T>
T* AppendPanelInternal(const QString &panel_name, QList<T*>& list);
template <typename T>
void RemovePanelInternal(QList<T*>& list, T *panel);
void RemoveTimelinePanel(TimelinePanel *panel);
void TimelineFocused(ViewerOutput *viewer);
static QString GetCustomShortcutsFile();
void LoadCustomShortcuts();
void SaveCustomShortcuts();
void UpdateAudioMonitorParams(ViewerOutput* viewer);
void UpdateNodePanelContextFromTimelinePanel(TimelinePanel *panel);
void SelectFootageForProjectPanel(const QVector<Footage*> &e, ProjectPanel *p);
QByteArray premaximized_state_;
// Standard panels
ProjectPanel *project_panel_;
NodePanel* node_panel_;
ParamPanel* param_panel_;
CurvePanel* curve_panel_;
SequenceViewerPanel* sequence_viewer_panel_;
FootageViewerPanel* footage_viewer_panel_;
QList<ProjectPanel*> folder_panels_;
ToolPanel* tool_panel_;
QList<TimelinePanel*> timeline_panels_;
AudioMonitorPanel* audio_monitor_panel_;
TaskManagerPanel* task_man_panel_;
PixelSamplerPanel* pixel_sampler_panel_;
ScopePanel* scope_panel_;
QList<ViewerPanel*> viewer_panels_;
MulticamPanel *multicam_panel_;
HistoryPanel *history_panel_;
#ifdef Q_OS_WINDOWS
unsigned int taskbar_btn_id_;
ITaskbarList3* taskbar_interface_;
#endif
bool first_show_;
Project *project_;
private slots:
void FocusedPanelChanged(PanelWidget* panel);
void UpdateTitle();
void TimelineCloseRequested();
void ViewerCloseRequested();
void ViewerWithPanelRemovedFromGraph();
void FolderPanelCloseRequested();
void StatusBarDoubleClicked();
void NodePanelGroupOpenedOrClosed();
#ifdef Q_OS_LINUX
void ShowNouveauWarning();
#endif
void TimelinePanelSelectionChanged(const QVector<Block*> &blocks);
void ShowWelcomeDialog();
void RevealViewerInProject(ViewerOutput *r);
void RevealViewerInFootageViewer(ViewerOutput *r, const TimeRange &range);
};
}
#endif
| 5,164
|
C++
|
.h
| 143
| 33.216783
| 94
| 0.786247
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,582
|
mainmenu.h
|
olive-editor_olive/app/window/mainwindow/mainmenu.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef MAINMENU_H
#define MAINMENU_H
#include <QMainWindow>
#include <QMenuBar>
#include "dialog/actionsearch/actionsearch.h"
#include "widget/menu/menu.h"
namespace olive {
class MainWindow;
/**
* @brief Olive's main menubar attached to its main window.
*
* Responsible for creating the menu, connecting signals/slots, and retranslating the items on a language change.
*/
class MainMenu : public QMenuBar
{
Q_OBJECT
public:
MainMenu(MainWindow *parent);
protected:
/**
* @brief changeEvent
*
* Qt changeEvent override to catch a QEvent::LanguageEvent.
*
* @param e
*/
virtual void changeEvent(QEvent* e);
private slots:
/**
* @brief A slot for the Tool selection items
*
* Assumes a QAction* sender() and its data() is a member of enum Tool::Item. Uses the data() to signal a
* Tool change throughout the rest of the application.
*/
void ToolItemTriggered();
/**
* @brief Slot triggered just before the File menu shows
*/
void FileMenuAboutToShow();
/**
* @brief Slot triggered just before the Edit menu shows
*/
void EditMenuAboutToShow();
void EditMenuAboutToHide();
/**
* @brief Slot triggered just before the View menu shows
*/
void ViewMenuAboutToShow();
/**
* @brief Slot triggered just before the Tools menu shows
*/
void ToolsMenuAboutToShow();
/**
* @brief Slot triggered just before the Playback menu shows
*/
void PlaybackMenuAboutToShow();
/**
* @brief Slot triggered just before the Sequence menu shows
*/
void SequenceMenuAboutToShow();
/**
* @brief Slot triggered just before the Window menu shows
*/
void WindowMenuAboutToShow();
/**
* @brief Adds items to open recent menu
*/
void PopulateOpenRecent();
void RepopulateOpenRecent();
/**
* @brief Clears open recent items when menu closes
*/
void CloseOpenRecentMenu();
/**
* @brief Slot for zooming in
*
* Finds the currently focused panel and sends it a "zoom in" signal
*/
void ZoomInTriggered();
/**
* @brief Slot for zooming out
*
* Finds the currently focused panel and sends it a "zoom out" signal
*/
void ZoomOutTriggered();
void IncreaseTrackHeightTriggered();
void DecreaseTrackHeightTriggered();
void GoToStartTriggered();
void PrevFrameTriggered();
/**
* @brief Slot for play/pause
*
* Finds the currently focused panel and sends it a "play/pause" signal
*/
void PlayPauseTriggered();
void PlayInToOutTriggered();
void LoopTriggered(bool enabled);
void NextFrameTriggered();
void GoToEndTriggered();
void SelectAllTriggered();
void DeselectAllTriggered();
void InsertTriggered();
void OverwriteTriggered();
void RippleToInTriggered();
void RippleToOutTriggered();
void EditToInTriggered();
void EditToOutTriggered();
void NudgeLeftTriggered();
void NudgeRightTriggered();
void MoveInToPlayheadTriggered();
void MoveOutToPlayheadTriggered();
void ActionSearchTriggered();
void ShuttleLeftTriggered();
void ShuttleStopTriggered();
void ShuttleRightTriggered();
void GoToPrevCutTriggered();
void GoToNextCutTriggered();
void SetMarkerTriggered();
void FullScreenViewerTriggered();
void ToggleShowAllTriggered();
void DeleteInOutTriggered();
void RippleDeleteInOutTriggered();
void GoToInTriggered();
void GoToOutTriggered();
void OpenRecentItemTriggered();
void SequenceCacheTriggered();
void SequenceCacheInOutTriggered();
void SequenceCacheClearTriggered();
void HelpFeedbackTriggered();
private:
/**
* @brief Set strings based on the current application language.
*/
void Retranslate();
Menu* file_menu_;
Menu* file_new_menu_;
QAction* file_open_item_;
Menu* file_open_recent_menu_;
QAction* file_open_recent_separator_;
QAction* file_open_recent_clear_item_;
QAction* file_save_item_;
QAction* file_save_as_item_;
QAction* file_revert_item_;
QAction* file_import_item_;
Menu* file_export_menu_;
QAction* file_export_media_item_;
QAction* file_project_properties_item_;
QAction* file_exit_item_;
Menu* edit_menu_;
QAction* edit_undo_item_;
QAction* edit_redo_item_;
QAction* edit_delete2_item_;
QAction* edit_select_all_item_;
QAction* edit_deselect_all_item_;
QAction* edit_insert_item_;
QAction* edit_overwrite_item_;
QAction* edit_ripple_to_in_item_;
QAction* edit_ripple_to_out_item_;
QAction* edit_edit_to_in_item_;
QAction* edit_edit_to_out_item_;
QAction* edit_nudge_left_item_;
QAction* edit_nudge_right_item_;
QAction* edit_move_in_to_playhead_item_;
QAction* edit_move_out_to_playhead_item_;
QAction* edit_delete_inout_item_;
QAction* edit_ripple_delete_inout_item_;
QAction* edit_set_marker_item_;
Menu* view_menu_;
QAction* view_zoom_in_item_;
QAction* view_zoom_out_item_;
QAction* view_increase_track_height_item_;
QAction* view_decrease_track_height_item_;
QAction* view_show_all_item_;
QAction* view_full_screen_item_;
QAction* view_full_screen_viewer_item_;
Menu* playback_menu_;
QAction* playback_gotostart_item_;
QAction* playback_prevframe_item_;
QAction* playback_playpause_item_;
QAction* playback_playinout_item_;
QAction* playback_nextframe_item_;
QAction* playback_gotoend_item_;
QAction* playback_prevcut_item_;
QAction* playback_nextcut_item_;
QAction* playback_gotoin_item_;
QAction* playback_gotoout_item_;
QAction* playback_shuttleleft_item_;
QAction* playback_shuttlestop_item_;
QAction* playback_shuttleright_item_;
QAction* playback_loop_item_;
Menu* sequence_menu_;
QAction* sequence_cache_item_;
QAction* sequence_cache_in_to_out_item_;
QAction* sequence_disk_cache_clear_item_;
Menu* window_menu_;
QAction* window_menu_separator_;
QAction* window_maximize_panel_item_;
QAction* window_reset_layout_item_;
Menu* tools_menu_;
QActionGroup* tools_group_;
QAction* tools_pointer_item_;
QAction* tools_trackselect_item_;
QAction* tools_edit_item_;
QAction* tools_ripple_item_;
QAction* tools_rolling_item_;
QAction* tools_razor_item_;
QAction* tools_slip_item_;
QAction* tools_slide_item_;
QAction* tools_hand_item_;
QAction* tools_zoom_item_;
QAction* tools_transition_item_;
QAction* tools_add_item_;
QAction* tools_record_item_;
QAction* tools_snapping_item_;
QAction* tools_preferences_item_;
Menu *tools_add_item_menu_;
#ifndef NDEBUG
QAction* tools_magic_item_;
#endif
Menu* help_menu_;
QAction* help_action_search_item_;
QAction* help_feedback_item_;
QAction* help_about_item_;
};
}
#endif // MAINMENU_H
| 7,337
|
C++
|
.h
| 240
| 27.345833
| 113
| 0.741546
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,583
|
mainwindowundo.h
|
olive-editor_olive/app/window/mainwindow/mainwindowundo.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef MAINWINDOWUNDO_H
#define MAINWINDOWUNDO_H
#include "node/project/sequence/sequence.h"
namespace olive {
class OpenSequenceCommand : public UndoCommand
{
public:
OpenSequenceCommand(Sequence* sequence) :
sequence_(sequence)
{}
virtual Project* GetRelevantProject() const override {return nullptr;}
protected:
virtual void redo() override;
virtual void undo() override;
private:
Sequence* sequence_;
};
class CloseSequenceCommand : public UndoCommand
{
public:
CloseSequenceCommand(Sequence* sequence) :
sequence_(sequence)
{}
virtual Project* GetRelevantProject() const override {return nullptr;}
protected:
virtual void redo() override;
virtual void undo() override;
private:
Sequence* sequence_;
};
}
#endif // MAINWINDOWUNDO_H
| 1,497
|
C++
|
.h
| 46
| 29.847826
| 72
| 0.780266
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,584
|
mainstatusbar.h
|
olive-editor_olive/app/window/mainwindow/mainstatusbar.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef MAINSTATUSBAR_H
#define MAINSTATUSBAR_H
#include <QProgressBar>
#include <QStatusBar>
#include "task/taskmanager.h"
namespace olive {
/**
* @brief Shows abbreviated information from a TaskManager object
*/
class MainStatusBar : public QStatusBar
{
Q_OBJECT
public:
MainStatusBar(QWidget* parent = nullptr);
void ConnectTaskManager(TaskManager* manager);
signals:
void DoubleClicked();
protected:
virtual void mouseDoubleClickEvent(QMouseEvent* e) override;
private slots:
void UpdateStatus();
void SetProgressBarValue(double d);
void ConnectedTaskDeleted();
private:
TaskManager* manager_;
QProgressBar* bar_;
Task* connected_task_;
};
}
#endif // MAINSTATUSBAR_H
| 1,424
|
C++
|
.h
| 44
| 29.772727
| 71
| 0.783505
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,585
|
crashhandler.h
|
olive-editor_olive/app/crashhandler/crashhandler.h
|
/***
Olive - Non-Linear Video Editor
Copyright (C) 2022 Olive Team
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 3 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. If not, see <http://www.gnu.org/licenses/>.
***/
#ifndef CRASHHANDLERDIALOG_H
#define CRASHHANDLERDIALOG_H
#include <client/crash_report_database.h>
#include <QDialog>
#include <QDialogButtonBox>
#include <QNetworkReply>
#include <QPushButton>
#include <QTextEdit>
#include "common/define.h"
namespace olive {
class CrashHandlerDialog : public QDialog
{
Q_OBJECT
public:
CrashHandlerDialog(const QString& report_path);
private:
void SetGUIObjectsEnabled(bool e);
void GenerateReport();
static QString GetSymbolPath();
QTextEdit* summary_edit_;
QTextEdit* crash_report_;
QPushButton* send_report_btn_;
QPushButton* dont_send_btn_;
QString report_filename_;
QByteArray report_data_;
bool waiting_for_upload_;
protected:
virtual void closeEvent(QCloseEvent* e) override;
private slots:
void ReplyFinished(QNetworkReply *reply);
void HandleSslErrors(QNetworkReply *reply, const QList<QSslError> &errors);
void AttemptToFindReport();
void ReadProcessHasData();
void ReadProcessFinished();
void SendErrorReport();
};
}
#endif // CRASHHANDLERDIALOG_H
| 1,769
|
C++
|
.h
| 52
| 31.25
| 77
| 0.787196
|
olive-editor/olive
| 8,144
| 552
| 131
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
19,586
|
StereoEnhancerControls.cpp
|
LMMS_lmms/plugins/StereoEnhancer/StereoEnhancerControls.cpp
|
/*
* StereoEnhancerControls.cpp - control-dialog for StereoEnhancer effect
*
* 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 <QDomElement>
#include "StereoEnhancerControls.h"
#include "StereoEnhancer.h"
namespace lmms
{
StereoEnhancerControls::StereoEnhancerControls( StereoEnhancerEffect * _eff ) :
EffectControls( _eff ),
m_effect( _eff ),
m_widthModel(0.0f, 0.0f, 180.0f, 1.0f, this, tr( "Width" ) )
{
connect( &m_widthModel, SIGNAL( dataChanged() ),
this, SLOT( changeWideCoeff() ) );
changeWideCoeff();
}
void StereoEnhancerControls::changeWideCoeff()
{
m_effect->m_seFX.setWideCoeff( m_widthModel.value() );
}
void StereoEnhancerControls::loadSettings( const QDomElement & _this )
{
m_widthModel.loadSettings( _this, "width" );
}
void StereoEnhancerControls::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
m_widthModel.saveSettings( _doc, _this, "width" );
}
} // namespace lmms
| 1,774
|
C++
|
.cpp
| 51
| 32.529412
| 79
| 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,587
|
StereoEnhancerControlDialog.cpp
|
LMMS_lmms/plugins/StereoEnhancer/StereoEnhancerControlDialog.cpp
|
/*
* StereoEnhancerControlDialog.cpp - control-dialog for StereoEnhancer effect
*
* Copyright (c) 2006-2007 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 "StereoEnhancerControlDialog.h"
#include <QHBoxLayout>
#include "Knob.h"
#include "StereoEnhancerControls.h"
namespace lmms::gui
{
StereoEnhancerControlDialog::StereoEnhancerControlDialog(
StereoEnhancerControls * _controls ) :
EffectControlDialog( _controls )
{
auto l = new QHBoxLayout(this);
auto widthKnob = new Knob(KnobType::Bright26, this);
widthKnob->setModel( &_controls->m_widthModel );
widthKnob->setLabel( tr( "WIDTH" ) );
widthKnob->setHintText( tr( "Width:" ) , " samples" );
l->addWidget( widthKnob );
this->setLayout(l);
}
} // namespace lmms::gui
| 1,551
|
C++
|
.cpp
| 42
| 34.880952
| 77
| 0.760187
|
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,588
|
StereoEnhancer.cpp
|
LMMS_lmms/plugins/StereoEnhancer/StereoEnhancer.cpp
|
/*
* StereoEnhancer.cpp - stereo-enhancer-effect-plugin
*
* 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 "StereoEnhancer.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT stereoenhancer_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"StereoEnhancer Effect",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Plugin for enhancing stereo separation of a stereo input file" ),
"Lou Herard <lherard/at/gmail.com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
StereoEnhancerEffect::StereoEnhancerEffect(
Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Effect( &stereoenhancer_plugin_descriptor, _parent, _key ),
m_seFX( DspEffectLibrary::StereoEnhancer( 0.0f ) ),
m_delayBuffer( new SampleFrame[DEFAULT_BUFFER_SIZE] ),
m_currFrame( 0 ),
m_bbControls( this )
{
// TODO: Make m_delayBuffer customizable?
clearMyBuffer();
}
StereoEnhancerEffect::~StereoEnhancerEffect()
{
if( m_delayBuffer )
{
delete [] m_delayBuffer;
}
m_currFrame = 0;
}
Effect::ProcessStatus StereoEnhancerEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const float d = dryLevel();
const float w = wetLevel();
for (fpp_t f = 0; f < frames; ++f)
{
// copy samples into the delay buffer
m_delayBuffer[m_currFrame][0] = buf[f][0];
m_delayBuffer[m_currFrame][1] = buf[f][1];
// Get the width knob value from the Stereo Enhancer effect
float width = m_seFX.wideCoeff();
// Calculate the correct sample frame for processing
int frameIndex = m_currFrame - width;
if( frameIndex < 0 )
{
// e.g. difference = -10, frameIndex = DBS - 10
frameIndex += DEFAULT_BUFFER_SIZE;
}
//sample_t s[2] = { buf[f][0], buf[f][1] }; //Vanilla
auto s = std::array{buf[f][0], m_delayBuffer[frameIndex][1]}; //Chocolate
m_seFX.nextSample( s[0], s[1] );
buf[f][0] = d * buf[f][0] + w * s[0];
buf[f][1] = d * buf[f][1] + w * s[1];
// Update currFrame
m_currFrame += 1;
m_currFrame %= DEFAULT_BUFFER_SIZE;
}
if( !isRunning() )
{
clearMyBuffer();
}
return ProcessStatus::ContinueIfNotQuiet;
}
void StereoEnhancerEffect::clearMyBuffer()
{
for (auto i = std::size_t{0}; i < DEFAULT_BUFFER_SIZE; i++)
{
m_delayBuffer[i][0] = 0.0f;
m_delayBuffer[i][1] = 0.0f;
}
m_currFrame = 0;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * _parent, void * _data )
{
return( new StereoEnhancerEffect( _parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(
_data ) ) );
}
}
} // namespace lmms
| 3,507
|
C++
|
.cpp
| 117
| 27.521368
| 93
| 0.71309
|
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,589
|
NineButtonSelector.cpp
|
LMMS_lmms/plugins/Vibed/NineButtonSelector.cpp
|
/*
* NineButtonSelector.cpp
*
* Copyright (c) 2006-2007 Danny McRae <khjklujn/at/yahoo/com>
* 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 "NineButtonSelector.h"
#include "CaptionMenu.h"
namespace lmms::gui
{
NineButtonSelector::NineButtonSelector(std::array<QPixmap, 18> onOffIcons, int defaultButton, int x, int y, QWidget* parent) :
QWidget{parent},
IntModelView{new NineButtonSelectorModel{defaultButton, 0, 8, nullptr, QString{}, true}, this}
{
setFixedSize(50, 50);
move(x, y);
for (int i = 0; i < 9; ++i)
{
m_buttons[i] = std::make_unique<PixmapButton>(this, nullptr);
const int buttonX = 1 + (i % 3) * 17;
const int buttonY = 1 + (i / 3) * 17;
m_buttons[i]->move(buttonX, buttonY);
m_buttons[i]->setActiveGraphic(onOffIcons[i * 2]);
m_buttons[i]->setInactiveGraphic(onOffIcons[(i * 2) + 1]);
m_buttons[i]->setChecked(false);
connect(m_buttons[i].get(), &PixmapButton::clicked, this, [=](){ this->buttonClicked(i); });
}
m_lastBtn = m_buttons[defaultButton].get();
m_lastBtn->setChecked(true);
}
void NineButtonSelector::buttonClicked(int id)
{
setSelected(id);
}
void NineButtonSelector::modelChanged()
{
updateButton(model()->value());
}
void NineButtonSelector::setSelected(int newButton)
{
model()->setValue(newButton);
updateButton(newButton);
}
void NineButtonSelector::updateButton(int newButton)
{
m_lastBtn->setChecked(false);
m_lastBtn->update();
m_lastBtn = m_buttons[newButton].get();
m_lastBtn->setChecked(true);
m_lastBtn->update();
emit NineButtonSelection(newButton);
}
void NineButtonSelector::contextMenuEvent(QContextMenuEvent*)
{
CaptionMenu contextMenu{windowTitle(), this};
contextMenu.exec(QCursor::pos());
}
} // namespace lmms::gui
| 2,549
|
C++
|
.cpp
| 76
| 31.539474
| 126
| 0.742776
|
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,590
|
VibratingString.cpp
|
LMMS_lmms/plugins/Vibed/VibratingString.cpp
|
/*
* VibratingString.cpp - model of a vibrating string lifted from pluckedSynth
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/yahoo/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 "VibratingString.h"
#include "interpolation.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "lmms_basics.h"
#include <algorithm>
#include <cstdlib>
namespace lmms
{
VibratingString::VibratingString(float pitch, float pick, float pickup, const float* impulse, int len,
sample_rate_t sampleRate, int oversample, float randomize, float stringLoss, float detune, bool state) :
m_oversample{2 * oversample / static_cast<int>(sampleRate / Engine::audioEngine()->baseSampleRate())},
m_randomize{randomize},
m_stringLoss{1.0f - stringLoss},
m_choice{static_cast<int>(m_oversample * static_cast<float>(std::rand()) / RAND_MAX)},
m_state{0.1f},
m_outsamp{std::make_unique<sample_t[]>(m_oversample)}
{
int stringLength = static_cast<int>(m_oversample * sampleRate / pitch) + 1;
stringLength += static_cast<int>(stringLength * -detune);
const int pickInt = static_cast<int>(std::ceil(stringLength * pick));
if (!state)
{
m_impulse = std::make_unique<float[]>(stringLength);
resample(impulse, len, stringLength);
}
else
{
m_impulse = std::make_unique<float[]>(len);
std::copy_n(impulse, len, m_impulse.get());
}
m_toBridge = VibratingString::initDelayLine(stringLength);
m_fromBridge = VibratingString::initDelayLine(stringLength);
VibratingString::setDelayLine(m_toBridge.get(), pickInt, m_impulse.get(), len, 0.5f, state);
VibratingString::setDelayLine(m_fromBridge.get(), pickInt, m_impulse.get(), len, 0.5f, state);
m_pickupLoc = static_cast<int>(pickup * stringLength);
}
std::unique_ptr<VibratingString::DelayLine> VibratingString::initDelayLine(int len)
{
auto dl = std::make_unique<VibratingString::DelayLine>();
dl->length = len;
if (len > 0)
{
dl->data = std::make_unique<sample_t[]>(len);
for (int i = 0; i < dl->length; ++i)
{
float r = static_cast<float>(std::rand()) / RAND_MAX;
float offset = (m_randomize / 2.0f - m_randomize) * r;
dl->data[i] = offset;
}
}
else
{
dl->data = nullptr;
}
dl->pointer = dl->data.get();
dl->end = dl->data.get() + len - 1;
return dl;
}
void VibratingString::resample(const float* src, f_cnt_t srcFrames, f_cnt_t dstFrames)
{
for (f_cnt_t frame = 0; frame < dstFrames; ++frame)
{
const float srcFrameFloat = frame * static_cast<float>(srcFrames) / dstFrames;
const float fracPos = srcFrameFloat - static_cast<f_cnt_t>(srcFrameFloat);
const f_cnt_t srcFrame = std::clamp(static_cast<f_cnt_t>(srcFrameFloat), f_cnt_t{1}, srcFrames - 3);
m_impulse[frame] = cubicInterpolate(
src[srcFrame - 1],
src[srcFrame + 0],
src[srcFrame + 1],
src[srcFrame + 2],
fracPos);
}
}
} // namespace lmms
| 3,574
|
C++
|
.cpp
| 98
| 34.214286
| 105
| 0.721676
|
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,591
|
Vibed.cpp
|
LMMS_lmms/plugins/Vibed/Vibed.cpp
|
/*
* Vibed.cpp - combination of PluckedStringSynth and BitInvader
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/yahoo/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 "Vibed.h"
#include <array>
#include <cassert>
#include <QDomElement>
#include "AudioEngine.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "NotePlayHandle.h"
#include "VibratingString.h"
#include "base64.h"
#include "CaptionMenu.h"
#include "volume.h"
#include "Song.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT vibedstrings_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"Vibed",
QT_TRANSLATE_NOOP("PluginBrowser", "Vibrating string modeler"),
"Danny McRae <khjklujn/at/yahoo/com>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader("logo"),
nullptr,
nullptr
};
}
class Vibed::StringContainer
{
public:
StringContainer(float pitch, sample_rate_t sampleRate, int bufferLength) :
m_pitch(pitch), m_sampleRate(sampleRate), m_bufferLength(bufferLength) {}
~StringContainer() = default;
void addString(std::size_t harm, float pick, float pickup, const float* impulse, float randomize,
float stringLoss, float detune, int oversample, bool state, int id)
{
constexpr auto octave = std::array{0.25f, 0.5f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f};
assert(harm < octave.size());
m_strings[id] = VibratingString{m_pitch * octave[harm], pick, pickup, impulse, m_bufferLength,
m_sampleRate, oversample, randomize, stringLoss, detune, state};
m_exists[id] = true;
}
bool exists(int id) const { return m_exists[id]; }
sample_t getStringSample(int id) { return m_strings[id].nextSample(); }
private:
const float m_pitch;
const sample_rate_t m_sampleRate;
const int m_bufferLength;
std::array<VibratingString, s_stringCount> m_strings{};
std::array<bool, s_stringCount> m_exists{};
};
Vibed::Vibed(InstrumentTrack* instrumentTrack) :
Instrument(instrumentTrack, &vibedstrings_plugin_descriptor, nullptr, Flag::IsNotBendable)
{
for (int harm = 0; harm < s_stringCount; ++harm)
{
m_volumeModels[harm] = std::make_unique<FloatModel>(
DefaultVolume, MinVolume, MaxVolume, 1.0f, this, tr("String %1 volume").arg(harm + 1));
m_stiffnessModels[harm] = std::make_unique<FloatModel>(
0.0f, 0.0f, 0.05f, 0.001f, this, tr("String %1 stiffness").arg(harm + 1));
m_pickModels[harm] = std::make_unique<FloatModel>(
0.0f, 0.0f, 0.05f, 0.005f, this, tr("Pick %1 position").arg(harm + 1));
m_pickupModels[harm] = std::make_unique<FloatModel>(
0.05f, 0.0f, 0.05f, 0.005f, this, tr("Pickup %1 position").arg( harm + 1));
m_panModels[harm] = std::make_unique<FloatModel>(
0.0f, -1.0f, 1.0f, 0.01f, this, tr("String %1 panning").arg(harm + 1));
m_detuneModels[harm] = std::make_unique<FloatModel>(
0.0f, -0.1f, 0.1f, 0.001f, this, tr("String %1 detune").arg(harm + 1));
m_randomModels[harm] = std::make_unique<FloatModel>(
0.0f, 0.0f, 0.75f, 0.01f, this, tr("String %1 fuzziness").arg(harm + 1));
m_lengthModels[harm] = std::make_unique<FloatModel>(
1, 1, 16, 1, this, tr("String %1 length").arg(harm + 1));
m_impulseModels[harm] = std::make_unique<BoolModel>(false, this, tr("Impulse %1").arg(harm + 1));
m_powerModels[harm] = std::make_unique<BoolModel>(harm == 0, this, tr("String %1").arg(harm + 1));
m_harmonicModels[harm] = std::make_unique<NineButtonSelectorModel>(2, 0, 8, this);
m_graphModels[harm] = std::make_unique<graphModel>(-1.0, 1.0, s_sampleLength, this);
m_graphModels[harm]->setWaveToSine();
}
}
void Vibed::saveSettings(QDomDocument& doc, QDomElement& elem)
{
// Save plugin version
elem.setAttribute("version", "0.2");
for (int i = 0; i < s_stringCount; ++i)
{
const auto is = QString::number(i);
elem.setAttribute("active" + is, QString::number(m_powerModels[i]->value()));
m_volumeModels[i]->saveSettings(doc, elem, "volume" + is);
m_stiffnessModels[i]->saveSettings(doc, elem, "stiffness" + is);
m_pickModels[i]->saveSettings(doc, elem, "pick" + is);
m_pickupModels[i]->saveSettings(doc, elem, "pickup" + is);
m_harmonicModels[i]->saveSettings(doc, elem, "octave" + is);
m_lengthModels[i]->saveSettings(doc, elem, "length" + is);
m_panModels[i]->saveSettings(doc, elem, "pan" + is);
m_detuneModels[i]->saveSettings(doc, elem, "detune" + is);
m_randomModels[i]->saveSettings(doc, elem, "slap" + is);
m_impulseModels[i]->saveSettings(doc, elem, "impulse" + is);
QString sampleString;
base64::encode((const char*)m_graphModels[i]->samples(), s_sampleLength * sizeof(float), sampleString);
elem.setAttribute("graph" + is, sampleString);
}
}
void Vibed::loadSettings(const QDomElement& elem)
{
// Load plugin version
bool newVersion = false;
if (elem.hasAttribute("version"))
{
newVersion = elem.attribute("version").toFloat() >= 0.2f;
}
for (int i = 0; i < s_stringCount; ++i)
{
const auto is = QString::number(i);
m_powerModels[i]->setValue(elem.attribute("active" + is).toInt());
// Version 0.2 saves/loads all instrument data unconditionally
const bool hasVolumeAttr = elem.hasAttribute("volume" + is) || !elem.firstChildElement("volume" + is).isNull();
if (newVersion || (m_powerModels[i]->value() && hasVolumeAttr))
{
m_volumeModels[i]->loadSettings(elem, "volume" + is);
m_stiffnessModels[i]->loadSettings(elem, "stiffness" + is);
m_pickModels[i]->loadSettings(elem, "pick" + is);
m_pickupModels[i]->loadSettings(elem, "pickup" + is);
m_harmonicModels[i]->loadSettings(elem, "octave" + is);
m_lengthModels[i]->loadSettings(elem, "length" + is);
m_panModels[i]->loadSettings(elem, "pan" + is);
m_detuneModels[i]->loadSettings(elem, "detune" + is);
m_randomModels[i]->loadSettings(elem, "slap" + is);
m_impulseModels[i]->loadSettings(elem, "impulse" + is);
int size = 0;
float* shp = nullptr;
base64::decode(elem.attribute("graph" + is), &shp, &size);
assert(size == 128 * sizeof(float));
m_graphModels[i]->setSamples(shp);
delete[] shp;
}
}
}
QString Vibed::nodeName() const
{
return vibedstrings_plugin_descriptor.name;
}
void Vibed::playNote(NotePlayHandle* n, SampleFrame* workingBuffer)
{
if (!n->m_pluginData)
{
const auto newContainer = new StringContainer{n->frequency(),
Engine::audioEngine()->outputSampleRate(), s_sampleLength};
n->m_pluginData = newContainer;
for (int i = 0; i < s_stringCount; ++i)
{
if (m_powerModels[i]->value())
{
newContainer->addString(
m_harmonicModels[i]->value(),
m_pickModels[i]->value(),
m_pickupModels[i]->value(),
m_graphModels[i]->samples(),
m_randomModels[i]->value(),
m_stiffnessModels[i]->value(),
m_detuneModels[i]->value(),
static_cast<int>(m_lengthModels[i]->value()),
m_impulseModels[i]->value(),
i);
}
}
}
const fpp_t frames = n->framesLeftForCurrentPeriod();
const f_cnt_t offset = n->noteOffset();
auto ps = static_cast<StringContainer*>(n->m_pluginData);
for (fpp_t i = offset; i < frames + offset; ++i)
{
workingBuffer[i][0] = 0.0f;
workingBuffer[i][1] = 0.0f;
for (int str = 0; str < s_stringCount; ++str)
{
if (ps->exists(str))
{
// pan: 0 -> left, 1 -> right
const float pan = (m_panModels[str]->value() + 1) / 2.0f;
const sample_t sample = ps->getStringSample(str) * m_volumeModels[str]->value() / 100.0f;
workingBuffer[i][0] += (1.0f - pan) * sample;
workingBuffer[i][1] += pan * sample;
}
}
}
}
void Vibed::deleteNotePluginData(NotePlayHandle* n)
{
delete static_cast<StringContainer*>(n->m_pluginData);
}
gui::PluginView* Vibed::instantiateView(QWidget* parent)
{
return new gui::VibedView(this, parent);
}
namespace gui
{
VibedView::VibedView(Instrument* instrument, QWidget* parent) :
InstrumentViewFixedSize(instrument, parent),
m_volumeKnob(KnobType::Bright26, this),
m_stiffnessKnob(KnobType::Bright26, this),
m_pickKnob(KnobType::Bright26, this),
m_pickupKnob(KnobType::Bright26, this),
m_panKnob(KnobType::Bright26, this),
m_detuneKnob(KnobType::Bright26, this),
m_randomKnob(KnobType::Bright26, this),
m_lengthKnob(KnobType::Bright26, this),
m_graph(this),
m_impulse("", this),
m_power("", this, tr("Enable waveform")),
m_smoothBtn(this, tr("Smooth waveform")),
m_normalizeBtn(this, tr("Normalize waveform")),
m_sinWaveBtn(this, tr("Sine wave")),
m_triangleWaveBtn(this, tr("Triangle wave")),
m_sawWaveBtn(this, tr("Saw wave")),
m_sqrWaveBtn(this, tr("Square wave")),
m_whiteNoiseWaveBtn(this, tr("White noise")),
m_usrWaveBtn(this, tr("User-defined wave"))
{
setAutoFillBackground(true);
QPalette pal;
pal.setBrush(backgroundRole(), PLUGIN_NAME::getIconPixmap("artwork"));
setPalette(pal);
m_volumeKnob.setVolumeKnob(true);
m_volumeKnob.move(103, 142);
m_volumeKnob.setHintText(tr("String volume:"), "");
m_stiffnessKnob.move(129, 142);
m_stiffnessKnob.setHintText(tr("String stiffness:"), "");
m_pickKnob.move(153, 142);
m_pickKnob.setHintText(tr("Pick position:"), "");
m_pickupKnob.move(177, 142);
m_pickupKnob.setHintText(tr("Pickup position:"), "");
m_panKnob.move(105, 187);
m_panKnob.setHintText(tr("String panning:"), "");
m_detuneKnob.move(150, 187);
m_detuneKnob.setHintText(tr("String detune:"), "");
m_randomKnob.move(194, 187);
m_randomKnob.setHintText(tr("String fuzziness:"), "");
m_lengthKnob.move(23, 193);
m_lengthKnob.setHintText(tr("String length:"), "");
m_graph.setWindowTitle(tr("Impulse Editor"));
m_graph.setForeground(PLUGIN_NAME::getIconPixmap("wavegraph4"));
m_graph.move(76, 21);
m_graph.resize(132, 104);
m_impulse.move(23, 94);
m_impulse.setToolTip(tr("Impulse"));
m_power.move(212, 130);
m_power.setToolTip(tr("Enable/disable string"));
m_harmonic = std::make_unique<NineButtonSelector>(
std::array{
PLUGIN_NAME::getIconPixmap("button_-2_on"),
PLUGIN_NAME::getIconPixmap("button_-2_off"),
PLUGIN_NAME::getIconPixmap("button_-1_on"),
PLUGIN_NAME::getIconPixmap("button_-1_off"),
PLUGIN_NAME::getIconPixmap("button_f_on"),
PLUGIN_NAME::getIconPixmap("button_f_off"),
PLUGIN_NAME::getIconPixmap("button_2_on"),
PLUGIN_NAME::getIconPixmap("button_2_off"),
PLUGIN_NAME::getIconPixmap("button_3_on"),
PLUGIN_NAME::getIconPixmap("button_3_off"),
PLUGIN_NAME::getIconPixmap("button_4_on"),
PLUGIN_NAME::getIconPixmap("button_4_off"),
PLUGIN_NAME::getIconPixmap("button_5_on"),
PLUGIN_NAME::getIconPixmap("button_5_off"),
PLUGIN_NAME::getIconPixmap("button_6_on"),
PLUGIN_NAME::getIconPixmap("button_6_off"),
PLUGIN_NAME::getIconPixmap("button_7_on"),
PLUGIN_NAME::getIconPixmap("button_7_off")},
2,
21, 127,
this);
m_harmonic->setWindowTitle(tr("Octave"));
m_stringSelector = std::make_unique<NineButtonSelector>(
std::array{
PLUGIN_NAME::getIconPixmap("button_1_on"),
PLUGIN_NAME::getIconPixmap("button_1_off"),
PLUGIN_NAME::getIconPixmap("button_2_on"),
PLUGIN_NAME::getIconPixmap("button_2_off"),
PLUGIN_NAME::getIconPixmap("button_3_on"),
PLUGIN_NAME::getIconPixmap("button_3_off"),
PLUGIN_NAME::getIconPixmap("button_4_on"),
PLUGIN_NAME::getIconPixmap("button_4_off"),
PLUGIN_NAME::getIconPixmap("button_5_on"),
PLUGIN_NAME::getIconPixmap("button_5_off"),
PLUGIN_NAME::getIconPixmap("button_6_on"),
PLUGIN_NAME::getIconPixmap("button_6_off"),
PLUGIN_NAME::getIconPixmap("button_7_on"),
PLUGIN_NAME::getIconPixmap("button_7_off"),
PLUGIN_NAME::getIconPixmap("button_8_on"),
PLUGIN_NAME::getIconPixmap("button_8_off"),
PLUGIN_NAME::getIconPixmap("button_9_on"),
PLUGIN_NAME::getIconPixmap("button_9_off")},
0,
21, 39,
this);
// String selector is not a part of the model
m_stringSelector->setWindowTitle(tr("String"));
connect(m_stringSelector.get(), SIGNAL(NineButtonSelection(int)), this, SLOT(showString(int)));
showString(0);
m_smoothBtn.move(79, 129);
m_smoothBtn.setActiveGraphic(PLUGIN_NAME::getIconPixmap("smooth_active"));
m_smoothBtn.setInactiveGraphic(PLUGIN_NAME::getIconPixmap("smooth_inactive"));
m_smoothBtn.setChecked(false);
m_smoothBtn.setToolTip(tr("Smooth waveform"));
connect(&m_smoothBtn, SIGNAL(clicked()), this, SLOT(smoothClicked()));
m_normalizeBtn.move(96, 129);
m_normalizeBtn.setActiveGraphic(PLUGIN_NAME::getIconPixmap("normalize_active"));
m_normalizeBtn.setInactiveGraphic(PLUGIN_NAME::getIconPixmap("normalize_inactive"));
m_normalizeBtn.setChecked(false);
m_normalizeBtn.setToolTip(tr("Normalize waveform"));
connect(&m_normalizeBtn, SIGNAL(clicked()), this, SLOT(normalizeClicked()));
m_sinWaveBtn.move(212, 24);
m_sinWaveBtn.setActiveGraphic(embed::getIconPixmap("sin_wave_active"));
m_sinWaveBtn.setInactiveGraphic(embed::getIconPixmap("sin_wave_inactive"));
m_sinWaveBtn.setToolTip(tr("Sine wave"));
connect(&m_sinWaveBtn, SIGNAL(clicked()), this, SLOT(sinWaveClicked()));
m_triangleWaveBtn.move(212, 41);
m_triangleWaveBtn.setActiveGraphic(embed::getIconPixmap("triangle_wave_active"));
m_triangleWaveBtn.setInactiveGraphic(embed::getIconPixmap("triangle_wave_inactive"));
m_triangleWaveBtn.setToolTip(tr("Triangle wave"));
connect(&m_triangleWaveBtn, SIGNAL(clicked()), this, SLOT(triangleWaveClicked()));
m_sawWaveBtn.move(212, 58);
m_sawWaveBtn.setActiveGraphic(embed::getIconPixmap("saw_wave_active"));
m_sawWaveBtn.setInactiveGraphic(embed::getIconPixmap("saw_wave_inactive"));
m_sawWaveBtn.setToolTip(tr("Saw wave"));
connect(&m_sawWaveBtn, SIGNAL(clicked()), this, SLOT(sawWaveClicked()));
m_sqrWaveBtn.move(212, 75);
m_sqrWaveBtn.setActiveGraphic(embed::getIconPixmap("square_wave_active"));
m_sqrWaveBtn.setInactiveGraphic(embed::getIconPixmap("square_wave_inactive"));
m_sqrWaveBtn.setToolTip(tr("Square wave"));
connect(&m_sqrWaveBtn, SIGNAL(clicked()), this, SLOT(sqrWaveClicked()));
m_whiteNoiseWaveBtn.move(212, 92);
m_whiteNoiseWaveBtn.setActiveGraphic(embed::getIconPixmap("white_noise_wave_active"));
m_whiteNoiseWaveBtn.setInactiveGraphic(embed::getIconPixmap("white_noise_wave_inactive"));
m_whiteNoiseWaveBtn.setToolTip(tr("White noise"));
connect(&m_whiteNoiseWaveBtn, SIGNAL(clicked()), this, SLOT(noiseWaveClicked()));
m_usrWaveBtn.move(212, 109);
m_usrWaveBtn.setActiveGraphic(embed::getIconPixmap("usr_wave_active"));
m_usrWaveBtn.setInactiveGraphic(embed::getIconPixmap("usr_wave_inactive"));
m_usrWaveBtn.setToolTip(tr("User-defined wave"));
connect(&m_usrWaveBtn, SIGNAL(clicked()),this, SLOT(usrWaveClicked()));
}
void VibedView::modelChanged()
{
showString(0);
}
void VibedView::showString(int str)
{
auto v = castModel<Vibed>();
m_pickKnob.setModel(v->m_pickModels[str].get());
m_pickupKnob.setModel(v->m_pickupModels[str].get());
m_stiffnessKnob.setModel(v->m_stiffnessModels[str].get());
m_volumeKnob.setModel(v->m_volumeModels[str].get());
m_panKnob.setModel(v->m_panModels[str].get());
m_detuneKnob.setModel(v->m_detuneModels[str].get());
m_randomKnob.setModel(v->m_randomModels[str].get());
m_lengthKnob.setModel(v->m_lengthModels[str].get());
m_graph.setModel(v->m_graphModels[str].get());
m_impulse.setModel(v->m_impulseModels[str].get());
m_harmonic->setModel(v->m_harmonicModels[str].get());
m_power.setModel(v->m_powerModels[str].get());
}
void VibedView::sinWaveClicked()
{
m_graph.model()->setWaveToSine();
Engine::getSong()->setModified();
}
void VibedView::triangleWaveClicked()
{
m_graph.model()->setWaveToTriangle();
Engine::getSong()->setModified();
}
void VibedView::sawWaveClicked()
{
m_graph.model()->setWaveToSaw();
Engine::getSong()->setModified();
}
void VibedView::sqrWaveClicked()
{
m_graph.model()->setWaveToSquare();
Engine::getSong()->setModified();
}
void VibedView::noiseWaveClicked()
{
m_graph.model()->setWaveToNoise();
Engine::getSong()->setModified();
}
void VibedView::usrWaveClicked()
{
QString fileName = m_graph.model()->setWaveToUser();
m_usrWaveBtn.setToolTip(fileName);
Engine::getSong()->setModified();
}
void VibedView::smoothClicked()
{
m_graph.model()->smooth();
Engine::getSong()->setModified();
}
void VibedView::normalizeClicked()
{
m_graph.model()->normalize();
Engine::getSong()->setModified();
}
void VibedView::contextMenuEvent(QContextMenuEvent*)
{
CaptionMenu contextMenu(model()->displayName(), this);
contextMenu.exec(QCursor::pos());
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin* lmms_plugin_main(Model* m, void*)
{
return new Vibed(static_cast<InstrumentTrack*>(m));
}
}
} // namespace lmms
| 17,263
|
C++
|
.cpp
| 445
| 36.242697
| 113
| 0.722475
|
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,592
|
StereoMatrix.cpp
|
LMMS_lmms/plugins/StereoMatrix/StereoMatrix.cpp
|
/*
* StereoMatrix.cpp - stereo-matrix-effect-plugin
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "StereoMatrix.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT stereomatrix_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Stereo Matrix",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Plugin for freely manipulating stereo output" ),
"Paul Giblock <drfaygo/at/gmail.com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
StereoMatrixEffect::StereoMatrixEffect(
Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Effect( &stereomatrix_plugin_descriptor, _parent, _key ),
m_smControls( this )
{
}
Effect::ProcessStatus StereoMatrixEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
for (fpp_t f = 0; f < frames; ++f)
{
const float d = dryLevel();
const float w = wetLevel();
sample_t l = buf[f][0];
sample_t r = buf[f][1];
// Init with dry-mix
buf[f][0] = l * d;
buf[f][1] = r * d;
// Add it wet
buf[f][0] += ( m_smControls.m_llModel.value( f ) * l +
m_smControls.m_rlModel.value( f ) * r ) * w;
buf[f][1] += ( m_smControls.m_lrModel.value( f ) * l +
m_smControls.m_rrModel.value( f ) * r ) * w;
}
return ProcessStatus::ContinueIfNotQuiet;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * _parent, void * _data )
{
return( new StereoMatrixEffect( _parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(
_data ) ) );
}
}
} // namespace lmms
| 2,470
|
C++
|
.cpp
| 81
| 28.012346
| 91
| 0.711318
|
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,593
|
StereoMatrixControls.cpp
|
LMMS_lmms/plugins/StereoMatrix/StereoMatrixControls.cpp
|
/*
* StereoMatrixControls.cpp - controls for StereoMatrix effect
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "StereoMatrixControls.h"
#include "StereoMatrix.h"
namespace lmms
{
StereoMatrixControls::StereoMatrixControls( StereoMatrixEffect * _eff ) :
EffectControls( _eff ),
m_effect( _eff ),
m_llModel( 1.0f, -1.0f, 1.0f, 0.01f, this, tr( "Left to Left" ) ),
m_lrModel( 0.0f, -1.0f, 1.0f, 0.01f, this, tr( "Left to Right" ) ),
m_rlModel( 0.0f, -1.0f, 1.0f, 0.01f, this, tr( "Right to Left" ) ),
m_rrModel( 1.0f, -1.0f, 1.0f, 0.01f, this, tr( "Right to Right" ) )
{
m_llModel.setCenterValue( 0 );
m_lrModel.setCenterValue( 0 );
m_rlModel.setCenterValue( 0 );
m_rrModel.setCenterValue( 0 );
connect( &m_llModel, SIGNAL( dataChanged() ),
this, SLOT( changeMatrix() ) );
connect( &m_lrModel, SIGNAL( dataChanged() ),
this, SLOT( changeMatrix() ) );
connect( &m_rlModel, SIGNAL( dataChanged() ),
this, SLOT( changeMatrix() ) );
connect( &m_rrModel, SIGNAL( dataChanged() ),
this, SLOT( changeMatrix() ) );
changeMatrix();
}
void StereoMatrixControls::changeMatrix()
{
}
void StereoMatrixControls::loadSettings( const QDomElement & _this )
{
m_llModel.loadSettings( _this, "l-l" );
m_lrModel.loadSettings( _this, "l-r" );
m_rlModel.loadSettings( _this, "r-l" );
m_rrModel.loadSettings( _this, "r-r" );
}
void StereoMatrixControls::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
m_llModel.saveSettings( _doc, _this, "l-l" );
m_lrModel.saveSettings( _doc, _this, "l-r" );
m_rlModel.saveSettings( _doc, _this, "r-l" );
m_rrModel.saveSettings( _doc, _this, "r-r" );
}
} // namespace lmms
| 2,508
|
C++
|
.cpp
| 69
| 34.028986
| 73
| 0.703719
|
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,594
|
StereoMatrixControlDialog.cpp
|
LMMS_lmms/plugins/StereoMatrix/StereoMatrixControlDialog.cpp
|
/*
* StereoMatrixControlDialog.cpp - control dialog for StereoMatrix effect
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "StereoMatrixControlDialog.h"
#include "embed.h"
#include "Knob.h"
#include "StereoMatrixControls.h"
namespace lmms::gui
{
StereoMatrixControlDialog::StereoMatrixControlDialog(
StereoMatrixControls * _controls ) :
EffectControlDialog( _controls )
{
setFixedSize( 160, 185 );
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(),
PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
auto llKnob = new Knob(KnobType::Bright26, this);
llKnob->setModel( &_controls->m_llModel );
llKnob->setHintText( tr( "Left to Left Vol:" ) , "" );
llKnob->move( 10, 79 );
auto lrKnob = new Knob(KnobType::Bright26, this);
lrKnob->setModel( &_controls->m_lrModel );
lrKnob->setHintText( tr( "Left to Right Vol:" ) , "" );
lrKnob->move( 48, 79 );
auto rlKnob = new Knob(KnobType::Bright26, this);
rlKnob->setModel( &_controls->m_rlModel );
rlKnob->setHintText( tr( "Right to Left Vol:" ) , "" );
rlKnob->move( 85, 79 );
auto rrKnob = new Knob(KnobType::Bright26, this);
rrKnob->setModel( &_controls->m_rrModel );
rrKnob->setHintText( tr( "Right to Right Vol:" ) , "" );
rrKnob->move( 123, 79 );
}
} // namespace lmms::gui
| 2,123
|
C++
|
.cpp
| 57
| 35.087719
| 73
| 0.728293
|
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,595
|
AudioFileProcessorWaveView.cpp
|
LMMS_lmms/plugins/AudioFileProcessor/AudioFileProcessorWaveView.cpp
|
/*
* AudioFileProcessorWaveView.cpp - Wave renderer of the AFP
*
* 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 "AudioFileProcessorWaveView.h"
#include "ConfigManager.h"
#include "FontHelper.h"
#include "SampleWaveform.h"
#include <QPainter>
#include <QMouseEvent>
#include <algorithm>
namespace lmms
{
namespace gui
{
void AudioFileProcessorWaveView::updateSampleRange()
{
if (m_sample->sampleSize() > 1)
{
const auto marging = (m_sample->endFrame() - m_sample->startFrame()) * 0.1;
setFrom(m_sample->startFrame() - marging);
setTo(m_sample->endFrame() + marging);
}
}
void AudioFileProcessorWaveView::setTo(int to)
{
m_to = std::min(to, static_cast<int>(m_sample->sampleSize()));
}
void AudioFileProcessorWaveView::setFrom(int from)
{
m_from = std::max(from, 0);
}
int AudioFileProcessorWaveView::range() const
{
return m_to - m_from;
}
AudioFileProcessorWaveView::AudioFileProcessorWaveView(QWidget* parent, int w, int h, Sample const* buf,
knob* start, knob* end, knob* loop) :
QWidget(parent),
m_sample(buf),
m_graph(QPixmap(w - 2 * s_padding, h - 2 * s_padding)),
m_from(0),
m_to(m_sample->sampleSize()),
m_last_from(0),
m_last_to(0),
m_last_amp(0),
m_startKnob(start),
m_endKnob(end),
m_loopKnob(loop),
m_isDragging(false),
m_reversed(false),
m_framesPlayed(0),
m_animation(ConfigManager::inst()->value("ui", "animateafp").toInt())
{
setFixedSize(w, h);
setMouseTracking(true);
configureKnobRelationsAndWaveViews();
updateSampleRange();
m_graph.fill(Qt::transparent);
update();
updateCursor();
}
void AudioFileProcessorWaveView::isPlaying(f_cnt_t current_frame)
{
m_framesPlayed = current_frame;
update();
}
void AudioFileProcessorWaveView::enterEvent(QEvent * e)
{
updateCursor();
}
void AudioFileProcessorWaveView::leaveEvent(QEvent * e)
{
updateCursor();
}
void AudioFileProcessorWaveView::mousePressEvent(QMouseEvent * me)
{
m_isDragging = true;
m_draggingLastPoint = me->pos();
const int x = me->x();
const int start_dist = qAbs(m_startFrameX - x);
const int end_dist = qAbs(m_endFrameX - x);
const int loop_dist = qAbs(m_loopFrameX - x);
DraggingType dt = DraggingType::SampleLoop; int md = loop_dist;
if (start_dist < loop_dist) { dt = DraggingType::SampleStart; md = start_dist; }
else if (end_dist < loop_dist) { dt = DraggingType::SampleEnd; md = end_dist; }
if (md < 4)
{
m_draggingType = dt;
}
else
{
m_draggingType = DraggingType::Wave;
updateCursor(me);
}
}
void AudioFileProcessorWaveView::mouseReleaseEvent(QMouseEvent * me)
{
m_isDragging = false;
if (m_draggingType == DraggingType::Wave)
{
updateCursor(me);
}
}
void AudioFileProcessorWaveView::mouseMoveEvent(QMouseEvent * me)
{
if (! m_isDragging)
{
updateCursor(me);
return;
}
const int step = me->x() - m_draggingLastPoint.x();
switch(m_draggingType)
{
case DraggingType::SampleStart:
slideSamplePointByPx(Point::Start, step);
break;
case DraggingType::SampleEnd:
slideSamplePointByPx(Point::End, step);
break;
case DraggingType::SampleLoop:
slideSamplePointByPx(Point::Loop, step);
break;
case DraggingType::SlideWave:
slide(step);
break;
case DraggingType::ZoomWave:
zoom(me->y() < m_draggingLastPoint.y());
break;
case DraggingType::Wave:
default:
if (qAbs(me->y() - m_draggingLastPoint.y())
< 2 * qAbs(me->x() - m_draggingLastPoint.x()))
{
m_draggingType = DraggingType::SlideWave;
}
else
{
m_draggingType = DraggingType::ZoomWave;
}
}
m_draggingLastPoint = me->pos();
update();
}
void AudioFileProcessorWaveView::wheelEvent(QWheelEvent * we)
{
zoom(we->angleDelta().y() > 0);
update();
}
void AudioFileProcessorWaveView::paintEvent(QPaintEvent * pe)
{
QPainter p(this);
p.drawPixmap(s_padding, s_padding, m_graph);
const QRect graph_rect(s_padding, s_padding, width() - 2 * s_padding, height() - 2 * s_padding);
const auto frames = range();
m_startFrameX = graph_rect.x() + (m_sample->startFrame() - m_from) *
double(graph_rect.width()) / frames;
m_endFrameX = graph_rect.x() + (m_sample->endFrame() - m_from) *
double(graph_rect.width()) / frames;
m_loopFrameX = graph_rect.x() + (m_sample->loopStartFrame() - m_from) *
double(graph_rect.width()) / frames;
const int played_width_px = (m_framesPlayed - m_from) *
double(graph_rect.width()) / frames;
// loop point line
p.setPen(QColor(0x7F, 0xFF, 0xFF)); //TODO: put into a qproperty
p.drawLine(m_loopFrameX, graph_rect.y(),
m_loopFrameX,
graph_rect.height() + graph_rect.y());
// start/end lines
p.setPen(QColor(0xFF, 0xFF, 0xFF)); //TODO: put into a qproperty
p.drawLine(m_startFrameX, graph_rect.y(),
m_startFrameX,
graph_rect.height() + graph_rect.y());
p.drawLine(m_endFrameX, graph_rect.y(),
m_endFrameX,
graph_rect.height() + graph_rect.y());
if (m_endFrameX - m_startFrameX > 2)
{
p.fillRect(
m_startFrameX + 1,
graph_rect.y(),
m_endFrameX - m_startFrameX - 1,
graph_rect.height() + graph_rect.y(),
QColor(95, 175, 255, 50) //TODO: put into a qproperty
);
if (m_endFrameX - m_loopFrameX > 2)
p.fillRect(
m_loopFrameX + 1,
graph_rect.y(),
m_endFrameX - m_loopFrameX - 1,
graph_rect.height() + graph_rect.y(),
QColor(95, 205, 255, 65) //TODO: put into a qproperty
);
if (m_framesPlayed && m_animation)
{
QLinearGradient g(m_startFrameX, 0, played_width_px, 0);
const QColor c(0, 120, 255, 180); //TODO: put into a qproperty
g.setColorAt(0, Qt::transparent);
g.setColorAt(0.8, c);
g.setColorAt(1, c);
p.fillRect(
m_startFrameX + 1,
graph_rect.y(),
played_width_px - (m_startFrameX + 1),
graph_rect.height() + graph_rect.y(),
g
);
p.setPen(QColor(255, 255, 255)); //TODO: put into a qproperty
p.drawLine(
played_width_px,
graph_rect.y(),
played_width_px,
graph_rect.height() + graph_rect.y()
);
m_framesPlayed = 0;
}
}
QLinearGradient g(0, 0, width() * 0.7, 0);
const QColor c(16, 111, 170, 180);
g.setColorAt(0, c);
g.setColorAt(0.4, c);
g.setColorAt(1, Qt::transparent);
p.fillRect(s_padding, s_padding, m_graph.width(), 14, g);
p.setPen(QColor(255, 255, 255));
p.setFont(adjustedToPixelSize(font(), SMALL_FONT_SIZE));
QString length_text;
const int length = m_sample->sampleDuration().count();
if (length > 20000)
{
length_text = QString::number(length / 1000) + "s";
}
else if (length > 2000)
{
length_text = QString::number((length / 100) / 10.0) + "s";
}
else
{
length_text = QString::number(length) + "ms";
}
p.drawText(
s_padding + 2,
s_padding + 10,
tr("Sample length:") + " " + length_text
);
}
void AudioFileProcessorWaveView::updateGraph()
{
if (m_to == 1)
{
setTo(m_sample->sampleSize() * 0.7);
slideSamplePointToFrames(Point::End, m_to * 0.7);
}
if (m_from > m_sample->startFrame())
{
setFrom(m_sample->startFrame());
}
if (m_to < m_sample->endFrame())
{
setTo(m_sample->endFrame());
}
if (m_sample->reversed() != m_reversed)
{
reverse();
}
else if (m_last_from == m_from && m_last_to == m_to && m_sample->amplification() == m_last_amp)
{
return;
}
m_last_from = m_from;
m_last_to = m_to;
m_last_amp = m_sample->amplification();
m_graph.fill(Qt::transparent);
QPainter p(&m_graph);
p.setPen(QColor(255, 255, 255));
const auto dataOffset = m_reversed ? m_sample->sampleSize() - m_to : m_from;
const auto rect = QRect{0, 0, m_graph.width(), m_graph.height()};
const auto waveform = SampleWaveform::Parameters{
m_sample->data() + dataOffset, static_cast<size_t>(range()), m_sample->amplification(), m_sample->reversed()};
SampleWaveform::visualize(waveform, p, rect);
}
void AudioFileProcessorWaveView::zoom(const bool out)
{
const auto start = m_sample->startFrame();
const auto end = m_sample->endFrame();
const auto frames = m_sample->sampleSize();
const auto dFrom = start - m_from;
const auto dTo = m_to - end;
const auto step = std::max(1.0, std::max(dFrom, dTo) / 10.0);
const auto stepFrom = out ? -step : step;
const auto stepTo = out ? step : -step;
const auto boundedFrom = std::clamp(m_from + stepFrom, 0.0, static_cast<double>(start));
const auto boundedTo = std::clamp(m_to + stepTo, static_cast<double>(end), static_cast<double>(frames));
const auto compRatio = std::min(dFrom, dTo) / static_cast<double>(std::max(1, std::max(dFrom, dTo)));
const auto toStep = stepFrom * (boundedTo == m_to ? 1 : compRatio);
const auto newFrom = (out && dFrom < dTo) || (!out && dTo < dFrom)
? boundedFrom
: std::clamp(m_from + toStep, 0.0, static_cast<double>(start));
const auto fromStep = stepTo * (boundedFrom == m_from ? 1 : compRatio);
const auto newTo = (out && dFrom < dTo) || (!out && dTo < dFrom)
? std::clamp(m_to + fromStep, static_cast<double>(end), static_cast<double>(frames))
: boundedTo;
if ((newTo - newFrom) / m_sample->sampleRate() > 0.05)
{
setFrom(newFrom);
setTo(newTo);
}
}
void AudioFileProcessorWaveView::slide(int px)
{
const double fact = qAbs(double(px) / width());
auto step = range() * fact * (px > 0 ? 1 : -1);
const auto sampleStart = static_cast<double>(m_sample->startFrame());
const auto sampleEnd = static_cast<double>(m_sample->endFrame());
const auto stepFrom = std::clamp(sampleStart + step, 0.0, static_cast<double>(m_sample->sampleSize())) - sampleStart;
const auto stepTo = std::clamp(sampleEnd + step, sampleStart + 1.0, static_cast<double>(m_sample->sampleSize())) - sampleEnd;
step = std::abs(stepFrom) < std::abs(stepTo) ? stepFrom : stepTo;
slideSampleByFrames(step);
}
void AudioFileProcessorWaveView::slideSamplePointByPx(Point point, int px)
{
slideSamplePointByFrames(
point,
f_cnt_t((double(px) / width()) * range())
);
}
void AudioFileProcessorWaveView::slideSamplePointByFrames(Point point, long frameOffset, bool slideTo)
{
knob * a_knob = m_startKnob;
switch(point)
{
case Point::End:
a_knob = m_endKnob;
break;
case Point::Loop:
a_knob = m_loopKnob;
break;
case Point::Start:
break;
}
if (a_knob == nullptr)
{
return;
}
else
{
const double v = static_cast<double>(frameOffset) / m_sample->sampleSize();
if (slideTo)
{
a_knob->slideTo(v);
}
else
{
a_knob->slideBy(v);
}
}
}
void AudioFileProcessorWaveView::slideSampleByFrames(long frameOffset)
{
if (m_sample->sampleSize() <= 1)
{
return;
}
const double v = static_cast<double>(frameOffset) / m_sample->sampleSize();
// update knobs in the right order
// to avoid them clamping each other
if (v < 0)
{
m_startKnob->slideBy(v, false);
m_loopKnob->slideBy(v, false);
m_endKnob->slideBy(v, false);
}
else
{
m_endKnob->slideBy(v, false);
m_loopKnob->slideBy(v, false);
m_startKnob->slideBy(v, false);
}
}
void AudioFileProcessorWaveView::reverse()
{
slideSampleByFrames(
m_sample->sampleSize()
- m_sample->endFrame()
- m_sample->startFrame()
);
const int fromTmp = m_from;
setFrom(m_sample->sampleSize() - m_to);
setTo(m_sample->sampleSize() - fromTmp);
m_reversed = ! m_reversed;
}
void AudioFileProcessorWaveView::updateCursor(QMouseEvent * me)
{
bool const waveIsDragged = m_isDragging && (m_draggingType == DraggingType::Wave);
bool const pointerCloseToStartEndOrLoop = (me != nullptr) &&
(isCloseTo(me->x(), m_startFrameX) ||
isCloseTo(me->x(), m_endFrameX) ||
isCloseTo(me->x(), m_loopFrameX));
if (!m_isDragging && pointerCloseToStartEndOrLoop)
setCursor(Qt::SizeHorCursor);
else if (waveIsDragged)
setCursor(Qt::ClosedHandCursor);
else
setCursor(Qt::OpenHandCursor);
}
void AudioFileProcessorWaveView::configureKnobRelationsAndWaveViews()
{
m_startKnob->setWaveView(this);
m_startKnob->setRelatedKnob(m_endKnob);
m_endKnob->setWaveView(this);
m_endKnob->setRelatedKnob(m_startKnob);
m_loopKnob->setWaveView(this);
}
void AudioFileProcessorWaveView::knob::slideTo(double v, bool check_bound)
{
if (check_bound && ! checkBound(v))
{
return;
}
model()->setValue(v);
emit sliderMoved(model()->value());
}
float AudioFileProcessorWaveView::knob::getValue(const QPoint & p)
{
const double dec_fact = ! m_waveView ? 1 :
static_cast<double>(m_waveView->m_to - m_waveView->m_from) / m_waveView->m_sample->sampleSize();
const float inc = Knob::getValue(p) * dec_fact;
return inc;
}
bool AudioFileProcessorWaveView::knob::checkBound(double v) const
{
if (! m_relatedKnob || ! m_waveView)
{
return true;
}
if ((m_relatedKnob->model()->value() - v > 0) !=
(m_relatedKnob->model()->value() - model()->value() >= 0))
return false;
const double d1 = qAbs(m_relatedKnob->model()->value() - model()->value())
* (m_waveView->m_sample->sampleSize())
/ m_waveView->m_sample->sampleRate();
const double d2 = qAbs(m_relatedKnob->model()->value() - v)
* (m_waveView->m_sample->sampleSize())
/ m_waveView->m_sample->sampleRate();
return d1 < d2 || d2 > 0.005;
}
} // namespace gui
} // namespace lmms
| 13,786
|
C++
|
.cpp
| 466
| 27.023605
| 126
| 0.696161
|
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,596
|
AudioFileProcessor.cpp
|
LMMS_lmms/plugins/AudioFileProcessor/AudioFileProcessor.cpp
|
/*
* AudioFileProcessor.cpp - instrument for using audio files
*
* 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 "AudioFileProcessor.h"
#include "AudioFileProcessorView.h"
#include "InstrumentTrack.h"
#include "PathUtil.h"
#include "SampleLoader.h"
#include "Song.h"
#include "lmms_basics.h"
#include "plugin_export.h"
#include <QDomElement>
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT audiofileprocessor_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"AudioFileProcessor",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Simple sampler with various settings for "
"using samples (e.g. drums) in an "
"instrument-track" ),
"Tobias Doerffel <tobydox/at/users.sf.net>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
"wav,ogg,ds,spx,au,voc,aif,aiff,flac,raw"
#ifdef LMMS_HAVE_SNDFILE_MP3
",mp3"
#endif
,
nullptr,
} ;
}
AudioFileProcessor::AudioFileProcessor( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &audiofileprocessor_plugin_descriptor ),
m_ampModel( 100, 0, 500, 1, this, tr( "Amplify" ) ),
m_startPointModel( 0, 0, 1, 0.0000001f, this, tr( "Start of sample" ) ),
m_endPointModel( 1, 0, 1, 0.0000001f, this, tr( "End of sample" ) ),
m_loopPointModel( 0, 0, 1, 0.0000001f, this, tr( "Loopback point" ) ),
m_reverseModel( false, this, tr( "Reverse sample" ) ),
m_loopModel( 0, 0, 2, this, tr( "Loop mode" ) ),
m_stutterModel( false, this, tr( "Stutter" ) ),
m_interpolationModel( this, tr( "Interpolation mode" ) ),
m_nextPlayStartPoint( 0 ),
m_nextPlayBackwards( false )
{
connect( &m_reverseModel, SIGNAL( dataChanged() ),
this, SLOT( reverseModelChanged() ), Qt::DirectConnection );
connect( &m_ampModel, SIGNAL( dataChanged() ),
this, SLOT( ampModelChanged() ), Qt::DirectConnection );
connect( &m_startPointModel, SIGNAL( dataChanged() ),
this, SLOT( startPointChanged() ), Qt::DirectConnection );
connect( &m_endPointModel, SIGNAL( dataChanged() ),
this, SLOT( endPointChanged() ), Qt::DirectConnection );
connect( &m_loopPointModel, SIGNAL( dataChanged() ),
this, SLOT( loopPointChanged() ), Qt::DirectConnection );
connect( &m_stutterModel, SIGNAL( dataChanged() ),
this, SLOT( stutterModelChanged() ), Qt::DirectConnection );
//interpolation modes
m_interpolationModel.addItem( tr( "None" ) );
m_interpolationModel.addItem( tr( "Linear" ) );
m_interpolationModel.addItem( tr( "Sinc" ) );
m_interpolationModel.setValue( 1 );
pointChanged();
}
void AudioFileProcessor::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
// Magic key - a frequency < 20 (say, the bottom piano note if using
// a A4 base tuning) restarts the start point. The note is not actually
// played.
if( m_stutterModel.value() == true && _n->frequency() < 20.0 )
{
m_nextPlayStartPoint = m_sample.startFrame();
m_nextPlayBackwards = false;
return;
}
if( !_n->m_pluginData )
{
if (m_stutterModel.value() == true && m_nextPlayStartPoint >= static_cast<std::size_t>(m_sample.endFrame()))
{
// Restart playing the note if in stutter mode, not in loop mode,
// and we're at the end of the sample.
m_nextPlayStartPoint = m_sample.startFrame();
m_nextPlayBackwards = false;
}
// set interpolation mode for libsamplerate
int srcmode = SRC_LINEAR;
switch( m_interpolationModel.value() )
{
case 0:
srcmode = SRC_ZERO_ORDER_HOLD;
break;
case 1:
srcmode = SRC_LINEAR;
break;
case 2:
srcmode = SRC_SINC_MEDIUM_QUALITY;
break;
}
_n->m_pluginData = new Sample::PlaybackState(_n->hasDetuningInfo(), srcmode);
static_cast<Sample::PlaybackState*>(_n->m_pluginData)->setFrameIndex(m_nextPlayStartPoint);
static_cast<Sample::PlaybackState*>(_n->m_pluginData)->setBackwards(m_nextPlayBackwards);
// debug code
/* qDebug( "frames %d", m_sample->frames() );
qDebug( "startframe %d", m_sample->startFrame() );
qDebug( "nextPlayStartPoint %d", m_nextPlayStartPoint );*/
}
if( ! _n->isFinished() )
{
if (m_sample.play(_working_buffer + offset,
static_cast<Sample::PlaybackState*>(_n->m_pluginData),
frames, _n->frequency(),
static_cast<Sample::Loop>(m_loopModel.value())))
{
applyRelease( _working_buffer, _n );
emit isPlaying(static_cast<Sample::PlaybackState*>(_n->m_pluginData)->frameIndex());
}
else
{
zeroSampleFrames(_working_buffer, frames + offset);
emit isPlaying( 0 );
}
}
else
{
emit isPlaying( 0 );
}
if( m_stutterModel.value() == true )
{
m_nextPlayStartPoint = static_cast<Sample::PlaybackState*>(_n->m_pluginData)->frameIndex();
m_nextPlayBackwards = static_cast<Sample::PlaybackState*>(_n->m_pluginData)->backwards();
}
}
void AudioFileProcessor::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<Sample::PlaybackState*>(_n->m_pluginData);
}
void AudioFileProcessor::saveSettings(QDomDocument& doc, QDomElement& elem)
{
elem.setAttribute("src", m_sample.sampleFile());
if (m_sample.sampleFile().isEmpty())
{
elem.setAttribute("sampledata", m_sample.toBase64());
}
m_reverseModel.saveSettings(doc, elem, "reversed");
m_loopModel.saveSettings(doc, elem, "looped");
m_ampModel.saveSettings(doc, elem, "amp");
m_startPointModel.saveSettings(doc, elem, "sframe");
m_endPointModel.saveSettings(doc, elem, "eframe");
m_loopPointModel.saveSettings(doc, elem, "lframe");
m_stutterModel.saveSettings(doc, elem, "stutter");
m_interpolationModel.saveSettings(doc, elem, "interp");
}
void AudioFileProcessor::loadSettings(const QDomElement& elem)
{
if (auto srcFile = elem.attribute("src"); !srcFile.isEmpty())
{
if (QFileInfo(PathUtil::toAbsolute(srcFile)).exists())
{
setAudioFile(srcFile, false);
}
else { Engine::getSong()->collectError(QString("%1: %2").arg(tr("Sample not found"), srcFile)); }
}
else if (auto sampleData = elem.attribute("sampledata"); !sampleData.isEmpty())
{
m_sample = Sample(gui::SampleLoader::createBufferFromBase64(sampleData));
}
m_loopModel.loadSettings(elem, "looped");
m_ampModel.loadSettings(elem, "amp");
m_endPointModel.loadSettings(elem, "eframe");
m_startPointModel.loadSettings(elem, "sframe");
// compat code for not having a separate loopback point
if (elem.hasAttribute("lframe") || !elem.firstChildElement("lframe").isNull())
{
m_loopPointModel.loadSettings(elem, "lframe");
}
else
{
m_loopPointModel.loadSettings(elem, "sframe");
}
m_reverseModel.loadSettings(elem, "reversed");
m_stutterModel.loadSettings(elem, "stutter");
if (elem.hasAttribute("interp") || !elem.firstChildElement("interp").isNull())
{
m_interpolationModel.loadSettings(elem, "interp");
}
else
{
m_interpolationModel.setValue(1.0f); // linear by default
}
pointChanged();
emit sampleUpdated();
}
void AudioFileProcessor::loadFile( const QString & _file )
{
setAudioFile( _file );
}
QString AudioFileProcessor::nodeName() const
{
return audiofileprocessor_plugin_descriptor.name;
}
auto AudioFileProcessor::beatLen(NotePlayHandle* note) const -> f_cnt_t
{
// If we can play indefinitely, use the default beat note duration
if (static_cast<Sample::Loop>(m_loopModel.value()) != Sample::Loop::Off) { return 0; }
// Otherwise, use the remaining sample duration
const auto baseFreq = instrumentTrack()->baseFreq();
const auto freqFactor = baseFreq / note->frequency()
* Engine::audioEngine()->outputSampleRate()
/ Engine::audioEngine()->baseSampleRate();
const auto startFrame = m_nextPlayStartPoint >= static_cast<std::size_t>(m_sample.endFrame())
? m_sample.startFrame()
: m_nextPlayStartPoint;
const auto duration = m_sample.endFrame() - startFrame;
return static_cast<f_cnt_t>(std::floor(duration * freqFactor));
}
gui::PluginView* AudioFileProcessor::instantiateView( QWidget * _parent )
{
return new gui::AudioFileProcessorView( this, _parent );
}
void AudioFileProcessor::setAudioFile(const QString& _audio_file, bool _rename)
{
// is current channel-name equal to previous-filename??
if( _rename &&
( instrumentTrack()->name() ==
QFileInfo(m_sample.sampleFile()).fileName() ||
m_sample.sampleFile().isEmpty()))
{
// then set it to new one
instrumentTrack()->setName( PathUtil::cleanName( _audio_file ) );
}
// else we don't touch the track-name, because the user named it self
m_sample = Sample(gui::SampleLoader::createBufferFromFile(_audio_file));
loopPointChanged();
emit sampleUpdated();
}
void AudioFileProcessor::reverseModelChanged()
{
m_sample.setReversed(m_reverseModel.value());
m_nextPlayStartPoint = m_sample.startFrame();
m_nextPlayBackwards = false;
emit sampleUpdated();
}
void AudioFileProcessor::ampModelChanged()
{
m_sample.setAmplification(m_ampModel.value() / 100.0f);
emit sampleUpdated();
}
void AudioFileProcessor::stutterModelChanged()
{
m_nextPlayStartPoint = m_sample.startFrame();
m_nextPlayBackwards = false;
}
void AudioFileProcessor::startPointChanged()
{
// check if start is over end and swap values if so
if( m_startPointModel.value() > m_endPointModel.value() )
{
float tmp = m_endPointModel.value();
m_endPointModel.setValue( m_startPointModel.value() );
m_startPointModel.setValue( tmp );
}
// nudge loop point with end
if( m_loopPointModel.value() >= m_endPointModel.value() )
{
m_loopPointModel.setValue( qMax( m_endPointModel.value() - 0.001f, 0.0f ) );
}
// nudge loop point with start
if( m_loopPointModel.value() < m_startPointModel.value() )
{
m_loopPointModel.setValue( m_startPointModel.value() );
}
// check if start & end overlap and nudge end up if so
if( m_startPointModel.value() == m_endPointModel.value() )
{
m_endPointModel.setValue( qMin( m_endPointModel.value() + 0.001f, 1.0f ) );
}
pointChanged();
}
void AudioFileProcessor::endPointChanged()
{
// same as start, for now
startPointChanged();
}
void AudioFileProcessor::loopPointChanged()
{
// check that loop point is between start-end points and not overlapping with endpoint
// ...and move start/end points ahead if loop point is moved over them
if( m_loopPointModel.value() >= m_endPointModel.value() )
{
m_endPointModel.setValue( m_loopPointModel.value() + 0.001f );
if( m_endPointModel.value() == 1.0f )
{
m_loopPointModel.setValue( 1.0f - 0.001f );
}
}
// nudge start point with loop
if( m_loopPointModel.value() < m_startPointModel.value() )
{
m_startPointModel.setValue( m_loopPointModel.value() );
}
pointChanged();
}
void AudioFileProcessor::pointChanged()
{
const auto f_start = static_cast<f_cnt_t>(m_startPointModel.value() * m_sample.sampleSize());
const auto f_end = static_cast<f_cnt_t>(m_endPointModel.value() * m_sample.sampleSize());
const auto f_loop = static_cast<f_cnt_t>(m_loopPointModel.value() * m_sample.sampleSize());
m_nextPlayStartPoint = f_start;
m_nextPlayBackwards = false;
m_sample.setAllPointFrames(f_start, f_end, f_loop, f_end);
emit dataChanged();
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main(Model * model, void *)
{
return new AudioFileProcessor(static_cast<InstrumentTrack *>(model));
}
}
} // namespace lmms
| 12,102
|
C++
|
.cpp
| 348
| 32.313218
| 110
| 0.729674
|
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,597
|
AudioFileProcessorView.cpp
|
LMMS_lmms/plugins/AudioFileProcessor/AudioFileProcessorView.cpp
|
/*
* AudioFileProcessor.cpp - instrument for using audio files
*
* 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 "AudioFileProcessorView.h"
#include "AudioFileProcessor.h"
#include "AudioFileProcessorWaveView.h"
#include <QPainter>
#include "ComboBox.h"
#include "DataFile.h"
#include "FontHelper.h"
#include "PixmapButton.h"
#include "SampleLoader.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "Track.h"
#include "Clipboard.h"
namespace lmms
{
namespace gui
{
AudioFileProcessorView::AudioFileProcessorView(Instrument* instrument,
QWidget* parent) :
InstrumentViewFixedSize(instrument, parent)
{
m_openAudioFileButton = new PixmapButton(this);
m_openAudioFileButton->setCursor(QCursor(Qt::PointingHandCursor));
m_openAudioFileButton->move(227, 72);
m_openAudioFileButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap(
"select_file"));
m_openAudioFileButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap(
"select_file"));
connect(m_openAudioFileButton, SIGNAL(clicked()),
this, SLOT(openAudioFile()));
m_openAudioFileButton->setToolTip(tr("Open sample"));
m_reverseButton = new PixmapButton(this);
m_reverseButton->setCheckable(true);
m_reverseButton->move(164, 105);
m_reverseButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap(
"reverse_on"));
m_reverseButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap(
"reverse_off"));
m_reverseButton->setToolTip(tr("Reverse sample"));
// loop button group
auto m_loopOffButton = new PixmapButton(this);
m_loopOffButton->setCheckable(true);
m_loopOffButton->move(190, 105);
m_loopOffButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap(
"loop_off_on"));
m_loopOffButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap(
"loop_off_off"));
m_loopOffButton->setToolTip(tr("Disable loop"));
auto m_loopOnButton = new PixmapButton(this);
m_loopOnButton->setCheckable(true);
m_loopOnButton->move(190, 124);
m_loopOnButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap(
"loop_on_on"));
m_loopOnButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap(
"loop_on_off"));
m_loopOnButton->setToolTip(tr("Enable loop"));
auto m_loopPingPongButton = new PixmapButton(this);
m_loopPingPongButton->setCheckable(true);
m_loopPingPongButton->move(216, 124);
m_loopPingPongButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap(
"loop_pingpong_on"));
m_loopPingPongButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap(
"loop_pingpong_off"));
m_loopPingPongButton->setToolTip(tr("Enable ping-pong loop"));
m_loopGroup = new automatableButtonGroup(this);
m_loopGroup->addButton(m_loopOffButton);
m_loopGroup->addButton(m_loopOnButton);
m_loopGroup->addButton(m_loopPingPongButton);
m_stutterButton = new PixmapButton(this);
m_stutterButton->setCheckable(true);
m_stutterButton->move(164, 124);
m_stutterButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap(
"stutter_on"));
m_stutterButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap(
"stutter_off"));
m_stutterButton->setToolTip(
tr("Continue sample playback across notes"));
m_ampKnob = new Knob(KnobType::Bright26, this);
m_ampKnob->setVolumeKnob(true);
m_ampKnob->move(5, 108);
m_ampKnob->setHintText(tr("Amplify:"), "%");
m_startKnob = new AudioFileProcessorWaveView::knob(this);
m_startKnob->move(45, 108);
m_startKnob->setHintText(tr("Start point:"), "");
m_endKnob = new AudioFileProcessorWaveView::knob(this);
m_endKnob->move(125, 108);
m_endKnob->setHintText(tr("End point:"), "");
m_loopKnob = new AudioFileProcessorWaveView::knob(this);
m_loopKnob->move(85, 108);
m_loopKnob->setHintText(tr("Loopback point:"), "");
// interpolation selector
m_interpBox = new ComboBox(this);
m_interpBox->setGeometry(142, 62, 82, ComboBox::DEFAULT_HEIGHT);
// wavegraph
m_waveView = 0;
newWaveView();
connect(castModel<AudioFileProcessor>(), SIGNAL(isPlaying(lmms::f_cnt_t)),
m_waveView, SLOT(isPlaying(lmms::f_cnt_t)));
qRegisterMetaType<lmms::f_cnt_t>("lmms::f_cnt_t");
setAcceptDrops(true);
}
void AudioFileProcessorView::dragEnterEvent(QDragEnterEvent* dee)
{
// For mimeType() and MimeType enum class
using namespace Clipboard;
if (dee->mimeData()->hasFormat(mimeType(MimeType::StringPair)))
{
QString txt = dee->mimeData()->data(
mimeType(MimeType::StringPair));
if (txt.section(':', 0, 0) == QString("clip_%1").arg(
static_cast<int>(Track::Type::Sample)))
{
dee->acceptProposedAction();
}
else if (txt.section(':', 0, 0) == "samplefile")
{
dee->acceptProposedAction();
}
else
{
dee->ignore();
}
}
else
{
dee->ignore();
}
}
void AudioFileProcessorView::newWaveView()
{
if (m_waveView)
{
delete m_waveView;
m_waveView = 0;
}
m_waveView = new AudioFileProcessorWaveView(this, 245, 75, &castModel<AudioFileProcessor>()->sample(),
dynamic_cast<AudioFileProcessorWaveView::knob*>(m_startKnob),
dynamic_cast<AudioFileProcessorWaveView::knob*>(m_endKnob),
dynamic_cast<AudioFileProcessorWaveView::knob*>(m_loopKnob));
m_waveView->move(2, 172);
m_waveView->show();
}
void AudioFileProcessorView::dropEvent(QDropEvent* de)
{
const auto type = StringPairDrag::decodeKey(de);
const auto value = StringPairDrag::decodeValue(de);
if (type == "samplefile") { castModel<AudioFileProcessor>()->setAudioFile(value); }
else if (type == QString("clip_%1").arg(static_cast<int>(Track::Type::Sample)))
{
DataFile dataFile(value.toUtf8());
castModel<AudioFileProcessor>()->setAudioFile(dataFile.content().firstChild().toElement().attribute("src"));
}
else
{
de->ignore();
return;
}
m_waveView->updateSampleRange();
Engine::getSong()->setModified();
de->accept();
}
void AudioFileProcessorView::paintEvent(QPaintEvent*)
{
QPainter p(this);
static auto s_artwork = PLUGIN_NAME::getIconPixmap("artwork");
p.drawPixmap(0, 0, s_artwork);
auto a = castModel<AudioFileProcessor>();
QString file_name = "";
int idx = a->sample().sampleFile().length();
p.setFont(adjustedToPixelSize(font(), SMALL_FONT_SIZE));
QFontMetrics fm(p.font());
// simple algorithm for creating a text from the filename that
// matches in the white rectangle
while(idx > 0 &&
fm.size(Qt::TextSingleLine, file_name + "...").width() < 210)
{
file_name = a->sample().sampleFile()[--idx] + file_name;
}
if (idx > 0)
{
file_name = "..." + file_name;
}
p.setPen(QColor(255, 255, 255));
p.drawText(8, 99, file_name);
}
void AudioFileProcessorView::sampleUpdated()
{
m_waveView->updateSampleRange();
m_waveView->update();
update();
}
void AudioFileProcessorView::openAudioFile()
{
QString af = SampleLoader::openAudioFile();
if (af.isEmpty()) { return; }
castModel<AudioFileProcessor>()->setAudioFile(af);
Engine::getSong()->setModified();
m_waveView->updateSampleRange();
}
void AudioFileProcessorView::modelChanged()
{
auto a = castModel<AudioFileProcessor>();
connect(a, &AudioFileProcessor::sampleUpdated, this, &AudioFileProcessorView::sampleUpdated);
m_ampKnob->setModel(&a->ampModel());
m_startKnob->setModel(&a->startPointModel());
m_endKnob->setModel(&a->endPointModel());
m_loopKnob->setModel(&a->loopPointModel());
m_reverseButton->setModel(&a->reverseModel());
m_loopGroup->setModel(&a->loopModel());
m_stutterButton->setModel(&a->stutterModel());
m_interpBox->setModel(&a->interpolationModel());
sampleUpdated();
}
} // namespace gui
} // namespace lmms
| 8,260
|
C++
|
.cpp
| 238
| 32.168067
| 110
| 0.744294
|
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,598
|
PeakControllerEffectControls.cpp
|
LMMS_lmms/plugins/PeakControllerEffect/PeakControllerEffectControls.cpp
|
/*
* PeakControllerEffectControls.cpp - controls for peakController effect
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
* Copyright (c) 2009-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 "PeakControllerEffectControls.h"
#include "PeakControllerEffect.h"
#include "Song.h"
namespace lmms
{
PeakControllerEffectControls::
PeakControllerEffectControls( PeakControllerEffect * _eff ) :
EffectControls( _eff ),
m_effect( _eff ),
m_baseModel(0.5f, 0.f, 1.f, 0.001f, this, tr("Base value")),
m_amountModel(1.f, -1.f, 1.f, 0.005f, this, tr("Modulation amount")),
m_attackModel(0, 0, 0.999f, 0.001f, this, tr("Attack")),
m_decayModel(0, 0, 0.999f, 0.001f, this, tr("Release")),
m_tresholdModel(0, 0, 1.f, 0.001f, this, tr("Treshold")),
m_muteModel( false, this, tr( "Mute output" ) ),
m_absModel( true, this, tr("Absolute value") ),
m_amountMultModel(1.f, 0, 32, 0.2f, this, tr("Amount multiplicator"))
{
}
void PeakControllerEffectControls::loadSettings( const QDomElement & _this )
{
m_baseModel.loadSettings( _this, "base" );
m_effect->m_lastSample = m_baseModel.value(); //Set initial Peak Controller output to Base
m_amountModel.loadSettings( _this, "amount" );
m_muteModel.loadSettings( _this, "mute" );
m_attackModel.loadSettings( _this, "attack" );
m_decayModel.loadSettings( _this, "decay" );
m_absModel.loadSettings( _this, "abs" );
m_amountMultModel.loadSettings( _this, "amountmult" );
m_tresholdModel.loadSettings( _this, "treshold" );
/*If the peak controller effect is NOT loaded from project,
* m_effectId stored is useless.
* Reason to assign a random number to it:
* If the user clone the instrument, and m_effectId is cloned, and
* m_effectId is copied, then there would be two instruments
* having the same id.
*/
if( Engine::getSong()->isLoadingProject() == true )
{
m_effect->m_effectId = _this.attribute( "effectId" ).toInt();
}
else
{
// TODO: Fix possible collision
m_effect->m_effectId = rand();
}
}
void PeakControllerEffectControls::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
_this.setAttribute( "effectId", m_effect->m_effectId );
m_baseModel.saveSettings( _doc, _this, "base" );
m_amountModel.saveSettings( _doc, _this, "amount" );
m_muteModel.saveSettings( _doc, _this, "mute" );
m_attackModel.saveSettings( _doc, _this, "attack" );
m_decayModel.saveSettings( _doc, _this, "decay" );
m_absModel.saveSettings( _doc, _this, "abs" );
m_amountMultModel.saveSettings( _doc, _this, "amountmult" );
m_tresholdModel.saveSettings( _doc, _this, "treshold" );
}
} // namespace lmms
| 3,456
|
C++
|
.cpp
| 86
| 37.895349
| 91
| 0.725478
|
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,599
|
PeakControllerEffect.cpp
|
LMMS_lmms/plugins/PeakControllerEffect/PeakControllerEffect.cpp
|
/*
* PeakControllerEffect.cpp - PeakController effect plugin
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
* 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 "Song.h"
#include "PresetPreviewPlayHandle.h"
#include "PeakController.h"
#include "PeakControllerEffect.h"
#include "lmms_math.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT peakcontrollereffect_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Peak Controller",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Plugin for controlling knobs with sound peaks" ),
"Paul Giblock <drfaygo/at/gmail.com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
// We have to keep a list of all the PeakController effects so that we can save
// an peakEffect-ID to the project. This ID is referenced in the PeakController
// settings and is used to set the PeakControllerEffect pointer upon load
//QVector<PeakControllerEffect *> PeakControllerEffect::s_effects;
PeakControllerEffect::PeakControllerEffect(
Model * _parent,
const Descriptor::SubPluginFeatures::Key * _key ) :
Effect( &peakcontrollereffect_plugin_descriptor, _parent, _key ),
m_effectId( rand() ),
m_peakControls( this ),
m_lastSample( 0 ),
m_autoController( nullptr )
{
m_autoController = new PeakController( Engine::getSong(), this );
if( !Engine::getSong()->isLoadingProject() && !PresetPreviewPlayHandle::isPreviewing() )
{
Engine::getSong()->addController( m_autoController );
}
PeakController::s_effects.push_back(this);
}
PeakControllerEffect::~PeakControllerEffect()
{
auto it = std::find(PeakController::s_effects.begin(), PeakController::s_effects.end(), this);
if (it != PeakController::s_effects.end())
{
PeakController::s_effects.erase(it);
Engine::getSong()->removeController(m_autoController);
}
}
Effect::ProcessStatus PeakControllerEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
PeakControllerEffectControls & c = m_peakControls;
// RMS:
double sum = 0;
if( c.m_absModel.value() )
{
for (auto i = std::size_t{0}; i < frames; ++i)
{
// absolute value is achieved because the squares are > 0
sum += buf[i][0] * buf[i][0] + buf[i][1] * buf[i][1];
}
}
else
{
for (auto i = std::size_t{0}; i < frames; ++i)
{
// the value is absolute because of squaring,
// so we need to correct it
sum += buf[i][0] * buf[i][0] * sign(buf[i][0])
+ buf[i][1] * buf[i][1] * sign(buf[i][1]);
}
}
// TODO: flipping this might cause clipping
// this will mute the output after the values were measured
if( c.m_muteModel.value() )
{
for (auto i = std::size_t{0}; i < frames; ++i)
{
buf[i][0] = buf[i][1] = 0.0f;
}
}
float curRMS = sqrt_neg(sum / frames);
const float tres = c.m_tresholdModel.value();
const float amount = c.m_amountModel.value() * c.m_amountMultModel.value();
const float attack = 1.0f - c.m_attackModel.value();
const float decay = 1.0f - c.m_decayModel.value();
curRMS = qAbs( curRMS ) < tres ? 0.0f : curRMS;
float target = c.m_baseModel.value() + amount * curRMS;
// Use decay when the volume is decreasing, attack otherwise.
// Since direction can change as often as every sampleBuffer, it's difficult
// to witness attack/decay working in isolation unless using large buffer sizes.
const float t = target < m_lastSample ? decay : attack;
// Set m_lastSample to the interpolation between itself and target.
// When t is 1.0, m_lastSample snaps to target. When t is 0.0, m_lastSample shouldn't change.
m_lastSample = std::clamp(m_lastSample + t * (target - m_lastSample), 0.0f, 1.0f);
return ProcessStatus::Continue;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * _parent, void * _data )
{
return new PeakControllerEffect( _parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( _data ) );
}
}
} // namespace lmms
| 4,819
|
C++
|
.cpp
| 136
| 33.227941
| 95
| 0.725494
|
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,600
|
PeakControllerEffectControlDialog.cpp
|
LMMS_lmms/plugins/PeakControllerEffect/PeakControllerEffectControlDialog.cpp
|
/*
* PeakControllerEffectControlDialog.cpp - control dialog for
* PeakControllerEffect
*
* Copyright (c) 2008 Paul Giblock <drfaygo/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "PeakControllerEffectControlDialog.h"
#include "PeakControllerEffectControls.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "embed.h"
namespace lmms::gui
{
PeakControllerEffectControlDialog::PeakControllerEffectControlDialog(
PeakControllerEffectControls * _controls ) :
EffectControlDialog( _controls )
{
setWindowIcon( embed::getIconPixmap( "controller" ) );
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 240, 80 );
m_baseKnob = new Knob( KnobType::Bright26, this );
m_baseKnob->setLabel( tr( "BASE" ) );
m_baseKnob->setModel( &_controls->m_baseModel );
m_baseKnob->setHintText( tr( "Base:" ) , "" );
m_amountKnob = new Knob( KnobType::Bright26, this );
m_amountKnob->setLabel( tr( "AMNT" ) );
m_amountKnob->setModel( &_controls->m_amountModel );
m_amountKnob->setHintText( tr( "Modulation amount:" ) , "" );
m_amountMultKnob = new Knob( KnobType::Bright26, this );
m_amountMultKnob->setLabel( tr( "MULT" ) );
m_amountMultKnob->setModel( &_controls->m_amountMultModel );
m_amountMultKnob->setHintText( tr( "Amount multiplicator:" ) , "" );
m_attackKnob = new Knob( KnobType::Bright26, this );
m_attackKnob->setLabel( tr( "ATCK" ) );
m_attackKnob->setModel( &_controls->m_attackModel );
m_attackKnob->setHintText( tr( "Attack:" ) , "" );
m_decayKnob = new Knob( KnobType::Bright26, this );
m_decayKnob->setLabel( tr( "DCAY" ) );
m_decayKnob->setModel( &_controls->m_decayModel );
m_decayKnob->setHintText( tr( "Release:" ) , "" );
m_tresholdKnob = new Knob( KnobType::Bright26, this );
m_tresholdKnob->setLabel( tr( "TRSH" ) );
m_tresholdKnob->setModel( &_controls->m_tresholdModel );
m_tresholdKnob->setHintText( tr( "Treshold:" ) , "" );
m_muteLed = new LedCheckBox( tr( "Mute output" ), this );
m_muteLed->setModel( &_controls->m_muteModel );
m_absLed = new LedCheckBox( tr( "Absolute value" ), this );
m_absLed->setModel( &_controls->m_absModel );
auto mainLayout = new QVBoxLayout();
auto knobLayout = new QHBoxLayout();
auto ledLayout = new QHBoxLayout();
knobLayout->addWidget( m_baseKnob );
knobLayout->addWidget( m_amountKnob );
knobLayout->addWidget( m_amountMultKnob );
knobLayout->addWidget( m_attackKnob );
knobLayout->addWidget( m_decayKnob );
knobLayout->addWidget( m_tresholdKnob );
ledLayout->addWidget( m_muteLed );
ledLayout->addWidget( m_absLed );
mainLayout->setContentsMargins( 3, 10, 0, 0 );
mainLayout->addLayout( knobLayout );
mainLayout->addLayout( ledLayout );
setLayout( mainLayout );
}
} // namespace lmms::gui
| 3,681
|
C++
|
.cpp
| 88
| 39.681818
| 75
| 0.723249
|
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,601
|
BassBoosterControls.cpp
|
LMMS_lmms/plugins/BassBooster/BassBoosterControls.cpp
|
/*
* BassBoosterControls.cpp - controls for bassbooster effect
*
* Copyright (c) 2008-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "BassBoosterControls.h"
#include "BassBooster.h"
namespace lmms
{
BassBoosterControls::BassBoosterControls( BassBoosterEffect* effect ) :
EffectControls( effect ),
m_effect( effect ),
m_freqModel( 100.0f, 50.0f, 200.0f, 1.0f, this, tr( "Frequency" ) ),
m_gainModel( 1.0f, 0.1f, 5.0f, 0.05f, this, tr( "Gain" ) ),
m_ratioModel( 2.0f, 0.1f, 10.0f, 0.1f, this, tr( "Ratio" ) )
{
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( changeFrequency() ) );
}
void BassBoosterControls::changeFrequency()
{
m_effect->m_frequencyChangeNeeded = true;
}
void BassBoosterControls::loadSettings( const QDomElement& _this )
{
m_freqModel.loadSettings( _this, "freq" );
m_gainModel.loadSettings( _this, "gain" );
m_ratioModel.loadSettings( _this, "ratio");
}
void BassBoosterControls::saveSettings( QDomDocument& doc, QDomElement& _this )
{
m_freqModel.saveSettings( doc, _this, "freq" );
m_gainModel.saveSettings( doc, _this, "gain" );
m_ratioModel.saveSettings( doc, _this, "ratio");
}
} // namespace lmms
| 2,017
|
C++
|
.cpp
| 54
| 35.388889
| 98
| 0.741007
|
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,602
|
BassBooster.cpp
|
LMMS_lmms/plugins/BassBooster/BassBooster.cpp
|
/*
* BassBooster.cpp - bass booster effect plugin
*
* 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 "BassBooster.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT bassbooster_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"BassBooster",
QT_TRANSLATE_NOOP( "PluginBrowser", "Boost your bass the fast and simple way" ),
"Tobias Doerffel <tobydox/at/users.sf.net>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
BassBoosterEffect::BassBoosterEffect( Model* parent, const Descriptor::SubPluginFeatures::Key* key ) :
Effect( &bassbooster_plugin_descriptor, parent, key ),
m_frequencyChangeNeeded( false ),
m_bbFX( DspEffectLibrary::FastBassBoost( 70.0f, 1.0f, 2.8f ) ),
m_bbControls( this )
{
changeFrequency();
changeGain();
changeRatio();
}
Effect::ProcessStatus BassBoosterEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
// check out changed controls
if( m_frequencyChangeNeeded || m_bbControls.m_freqModel.isValueChanged() )
{
changeFrequency();
m_frequencyChangeNeeded = false;
}
if( m_bbControls.m_gainModel.isValueChanged() ) { changeGain(); }
if( m_bbControls.m_ratioModel.isValueChanged() ) { changeRatio(); }
const float const_gain = m_bbControls.m_gainModel.value();
const ValueBuffer *gainBuffer = m_bbControls.m_gainModel.valueBuffer();
const float d = dryLevel();
const float w = wetLevel();
for (fpp_t f = 0; f < frames; ++f)
{
auto& currentFrame = buf[f];
// Process copy of current sample frame
m_bbFX.setGain(gainBuffer ? gainBuffer->value(f) : const_gain);
auto s = currentFrame;
m_bbFX.nextSample(s);
// Dry/wet mix
currentFrame = currentFrame * d + s * w;
}
return ProcessStatus::ContinueIfNotQuiet;
}
inline void BassBoosterEffect::changeFrequency()
{
const sample_t fac = Engine::audioEngine()->outputSampleRate() / 44100.0f;
m_bbFX.leftFX().setFrequency( m_bbControls.m_freqModel.value() * fac );
m_bbFX.rightFX().setFrequency( m_bbControls.m_freqModel.value() * fac );
}
inline void BassBoosterEffect::changeGain()
{
m_bbFX.leftFX().setGain( m_bbControls.m_gainModel.value() );
m_bbFX.rightFX().setGain( m_bbControls.m_gainModel.value() );
}
inline void BassBoosterEffect::changeRatio()
{
m_bbFX.leftFX().setRatio( m_bbControls.m_ratioModel.value() );
m_bbFX.rightFX().setRatio( m_bbControls.m_ratioModel.value() );
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new BassBoosterEffect( parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( data ) );
}
}
} // namespace lmms
| 3,564
|
C++
|
.cpp
| 104
| 32.115385
| 113
| 0.748683
|
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,603
|
BassBoosterControlDialog.cpp
|
LMMS_lmms/plugins/BassBooster/BassBoosterControlDialog.cpp
|
/*
* BassBoosterControlDialog.cpp - control dialog for bassbooster effect
*
* Copyright (c) 2006-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "BassBoosterControlDialog.h"
#include "BassBoosterControls.h"
#include "embed.h"
#include "Knob.h"
namespace lmms::gui
{
BassBoosterControlDialog::BassBoosterControlDialog( BassBoosterControls* controls ) :
EffectControlDialog( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 120, 60 );
auto tl = new QVBoxLayout(this);
tl->addSpacing( 4 );
auto l = new QHBoxLayout;
auto freqKnob = new Knob(KnobType::Bright26, this);
freqKnob->setModel( &controls->m_freqModel );
freqKnob->setLabel( tr( "FREQ" ) );
freqKnob->setHintText( tr( "Frequency:" ) , "Hz" );
auto gainKnob = new Knob(KnobType::Bright26, this);
gainKnob->setModel( &controls->m_gainModel );
gainKnob->setLabel( tr( "GAIN" ) );
gainKnob->setHintText( tr( "Gain:" ) , "" );
auto ratioKnob = new Knob(KnobType::Bright26, this);
ratioKnob->setModel( &controls->m_ratioModel );
ratioKnob->setLabel( tr( "RATIO" ) );
ratioKnob->setHintText( tr( "Ratio:" ) , "" );
l->addWidget( freqKnob );
l->addWidget( gainKnob );
l->addWidget( ratioKnob );
tl->addLayout( l );
setLayout( tl );
}
} // namespace lmms::gui
| 2,226
|
C++
|
.cpp
| 61
| 34.442623
| 85
| 0.738483
|
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,604
|
Carla.cpp
|
LMMS_lmms/plugins/CarlaBase/Carla.cpp
|
/*
* carla.cpp - Carla for LMMS
*
* Copyright (C) 2014-2018 Filipe Coelho <falktx@falktx.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 "Carla.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "GuiApplication.h"
#include "InstrumentPlayHandle.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "MidiEventToByteSeq.h"
#include "MainWindow.h"
#include "FontHelper.h"
#include "Song.h"
#include <QApplication>
#include <QComboBox>
#include <QCompleter>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMdiArea>
#include <QPushButton>
#include <QScrollArea>
#include <QSizePolicy>
#include <QSpacerItem>
#include <QSplitter>
#include <QString>
#include <QStringList>
#include <QStringListModel>
#include <QTimerEvent>
#include <QVBoxLayout>
#include <cstring>
#include "embed.h"
namespace lmms
{
// this doesn't seem to be defined anywhere
static const double ticksPerBeat = 48.0;
/*
* Current TODO items:
* - get plugin instance name (to use in external window title)
* - offline mode change callback
* - midi output
*
* All other items are to be done in Carla itself.
*/
// -----------------------------------------------------------------------
#define handlePtr ((CarlaInstrument*)handle)
static uint32_t host_get_buffer_size(NativeHostHandle handle)
{
return handlePtr->handleGetBufferSize();
}
static double host_get_sample_rate(NativeHostHandle handle)
{
return handlePtr->handleGetSampleRate();
}
static bool host_is_offline(NativeHostHandle handle)
{
return handlePtr->handleIsOffline();
}
static const NativeTimeInfo* host_get_time_info(NativeHostHandle handle)
{
return handlePtr->handleGetTimeInfo();
}
static bool host_write_midi_event(NativeHostHandle, const NativeMidiEvent*)
{
return false; // unsupported?
}
static void host_ui_parameter_changed(NativeHostHandle handle, uint32_t index, float value)
{
handlePtr->handleUiParameterChanged(index, value);
}
static void host_ui_custom_data_changed(NativeHostHandle handle, const char* key, const char* value)
{
// unused
}
static void host_ui_closed(NativeHostHandle handle)
{
handlePtr->handleUiClosed();
}
static intptr_t host_dispatcher(NativeHostHandle handle, NativeHostDispatcherOpcode opcode, int32_t index, intptr_t value, void* ptr, float opt)
{
return handlePtr->handleDispatcher(opcode, index, value, ptr, opt);
}
#undef handlePtr
// -----------------------------------------------------------------------
static const char* host_ui_open_file(NativeHostHandle, bool isDir, const char* title, const char* filter)
{
static QByteArray retStr;
const QFileDialog::Options options(isDir ? QFileDialog::ShowDirsOnly : 0x0);
retStr = QFileDialog::getOpenFileName(QApplication::activeWindow(), title, "", filter, nullptr, options).toUtf8();
return retStr.isEmpty() ? nullptr : retStr.constData();
}
static const char* host_ui_save_file(NativeHostHandle, bool isDir, const char* title, const char* filter)
{
static QByteArray retStr;
const QFileDialog::Options options(isDir ? QFileDialog::ShowDirsOnly : 0x0);
retStr = QFileDialog::getSaveFileName(QApplication::activeWindow(), title, "", filter, nullptr, options).toUtf8();
return retStr.isEmpty() ? nullptr : retStr.constData();
}
// -----------------------------------------------------------------------
CarlaInstrument::CarlaInstrument(InstrumentTrack* const instrumentTrack, const Descriptor* const descriptor, const bool isPatchbay)
: Instrument(instrumentTrack, descriptor, nullptr, Flag::IsSingleStreamed | Flag::IsMidiBased | Flag::IsNotBendable),
kIsPatchbay(isPatchbay),
fHandle(nullptr),
fDescriptor(isPatchbay ? carla_get_native_patchbay_plugin() : carla_get_native_rack_plugin()),
fMidiEventCount(0),
m_paramModels()
{
fHost.handle = this;
fHost.uiName = nullptr;
fHost.uiParentId = 0;
// carla/resources contains PyQt scripts required for launch
QDir path(carla_get_library_folder());
#if defined(CARLA_OS_LINUX)
path.cdUp();
path.cdUp();
QString resourcesPath = path.absolutePath() + "/share/carla/resources";
#else
// parse prefix from dll filename
QString resourcesPath = path.absolutePath() + "/resources";
#endif
fHost.resourceDir = strdup(resourcesPath.toUtf8().constData());
fHost.get_buffer_size = host_get_buffer_size;
fHost.get_sample_rate = host_get_sample_rate;
fHost.is_offline = host_is_offline;
fHost.get_time_info = host_get_time_info;
fHost.write_midi_event = host_write_midi_event;
fHost.ui_parameter_changed = host_ui_parameter_changed;
fHost.ui_custom_data_changed = host_ui_custom_data_changed;
fHost.ui_closed = host_ui_closed;
fHost.ui_open_file = host_ui_open_file;
fHost.ui_save_file = host_ui_save_file;
fHost.dispatcher = host_dispatcher;
std::memset(&fTimeInfo, 0, sizeof(NativeTimeInfo));
fTimeInfo.bbt.valid = true; // always valid
fHandle = fDescriptor->instantiate(&fHost);
Q_ASSERT(fHandle != nullptr);
if (fHandle != nullptr && fDescriptor->activate != nullptr)
fDescriptor->activate(fHandle);
// we need a play-handle which cares for calling play()
auto iph = new InstrumentPlayHandle(this, instrumentTrack);
Engine::audioEngine()->addPlayHandle( iph );
#if CARLA_VERSION_HEX >= CARLA_MIN_PARAM_VERSION
// text filter completion
m_completerModel = new QStringListModel(this);
m_paramsCompleter = new QCompleter(m_completerModel, this);
m_paramsCompleter->setCaseSensitivity(Qt::CaseInsensitive);
m_paramsCompleter->setCompletionMode(QCompleter::PopupCompletion);
// Add static amount of CarlaParamFloatModel's.
const auto paramCount = fDescriptor->get_parameter_count(fHandle);
m_paramModels.reserve(paramCount);
for (auto i = std::size_t{0}; i < paramCount; ++i)
{
m_paramModels.push_back(new CarlaParamFloatModel(this));
connect(m_paramModels[i], &CarlaParamFloatModel::dataChanged,
this, [this, i]() {paramModelChanged(i);}, Qt::DirectConnection);
}
#endif
connect(Engine::audioEngine(), SIGNAL(sampleRateChanged()), this, SLOT(sampleRateChanged()));
}
CarlaInstrument::~CarlaInstrument()
{
Engine::audioEngine()->removePlayHandlesOfTypes(instrumentTrack(), PlayHandle::Type::NotePlayHandle | PlayHandle::Type::InstrumentPlayHandle);
if (fHost.resourceDir != nullptr)
{
std::free((char*)fHost.resourceDir);
fHost.resourceDir = nullptr;
}
if (fHost.uiName != nullptr)
{
std::free((char*)fHost.uiName);
fHost.uiName = nullptr;
}
if (fHandle == nullptr)
return;
if (fDescriptor->deactivate != nullptr)
fDescriptor->deactivate(fHandle);
if (fDescriptor->cleanup != nullptr)
fDescriptor->cleanup(fHandle);
fHandle = nullptr;
#if CARLA_VERSION_HEX >= CARLA_MIN_PARAM_VERSION
clearParamModels();
#endif
}
// -------------------------------------------------------------------
uint32_t CarlaInstrument::handleGetBufferSize() const
{
return Engine::audioEngine()->framesPerPeriod();
}
double CarlaInstrument::handleGetSampleRate() const
{
return Engine::audioEngine()->outputSampleRate();
}
bool CarlaInstrument::handleIsOffline() const
{
return false; // TODO
}
const NativeTimeInfo* CarlaInstrument::handleGetTimeInfo() const
{
return &fTimeInfo;
}
void CarlaInstrument::handleUiParameterChanged(const uint32_t index, const float value) const
{
if (m_paramModels.size() > index)
{
m_paramModels[index]->setValue(value);
}
}
void CarlaInstrument::handleUiClosed()
{
emit uiClosed();
}
intptr_t CarlaInstrument::handleDispatcher(const NativeHostDispatcherOpcode opcode, const int32_t index,
const intptr_t value, void* const ptr, const float opt)
{
intptr_t ret = 0;
// source/includes/CarlaNative.h
// NATIVE_HOST_OPCODE_NULL = 0, nothing
// NATIVE_HOST_OPCODE_UPDATE_PARAMETER = 1, uses index, -1 for all
// NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM = 2, uses index, -1 for all; may use value for channel
// NATIVE_HOST_OPCODE_RELOAD_PARAMETERS = 3, nothing
// NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS = 4, nothing
// NATIVE_HOST_OPCODE_RELOAD_ALL = 5, nothing
// NATIVE_HOST_OPCODE_UI_UNAVAILABLE = 6, nothing
// NATIVE_HOST_OPCODE_HOST_IDLE = 7, nothing
// NATIVE_HOST_OPCODE_INTERNAL_PLUGIN = 8, nothing
// NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY = 9, nothing
// NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER = 10 uses index, value as bool
switch (opcode)
{
case NATIVE_HOST_OPCODE_UI_UNAVAILABLE:
handleUiClosed();
break;
case NATIVE_HOST_OPCODE_HOST_IDLE:
qApp->processEvents();
break;
#if CARLA_VERSION_HEX >= CARLA_MIN_PARAM_VERSION
case NATIVE_HOST_OPCODE_UI_TOUCH_PARAMETER:
// param index, value as bool
// true = mousePress
// false = mouseRelease
if (!value) {
updateParamModel(index);
}
break;
case NATIVE_HOST_OPCODE_RELOAD_ALL:
refreshParams();
break;
case NATIVE_HOST_OPCODE_UPDATE_PARAMETER:
break;
case NATIVE_HOST_OPCODE_RELOAD_PARAMETERS:
refreshParams();
break;
case NATIVE_HOST_OPCODE_UPDATE_MIDI_PROGRAM:
case NATIVE_HOST_OPCODE_RELOAD_MIDI_PROGRAMS:
case NATIVE_HOST_OPCODE_INTERNAL_PLUGIN:
case NATIVE_HOST_OPCODE_QUEUE_INLINE_DISPLAY:
break;
#endif
default:
break;
}
return ret;
}
// -------------------------------------------------------------------
QString CarlaInstrument::nodeName() const
{
return descriptor()->name;
}
void CarlaInstrument::saveSettings(QDomDocument& doc, QDomElement& parent)
{
if (fHandle == nullptr || fDescriptor->get_state == nullptr)
return;
char* const state = fDescriptor->get_state(fHandle);
if (state == nullptr)
return;
QDomDocument carlaDoc("carla");
if (carlaDoc.setContent(QString(state)))
{
QDomNode n = doc.importNode(carlaDoc.documentElement(), true);
parent.appendChild(n);
}
std::free(state);
#if CARLA_VERSION_HEX >= CARLA_MIN_PARAM_VERSION
for (uint32_t index = 0; index < m_paramModels.size(); ++index)
{
QString idStr = CARLA_SETTING_PREFIX + QString::number(index);
m_paramModels[index]->saveSettings(doc, parent, idStr);
}
#endif
}
void CarlaInstrument::refreshParams(bool init)
{
m_paramGroupCount = 0;
if (fDescriptor->get_parameter_count != nullptr &&
fDescriptor->get_parameter_info != nullptr &&
fDescriptor->get_parameter_value != nullptr &&
fDescriptor->set_parameter_value != nullptr)
{
QList<QString> completerData;
QList<QString> groups; // used to count no. groups.
uint32_t paramCount = fDescriptor->get_parameter_count(fHandle);
for (uint32_t i=0; i < paramCount; ++i)
{
const NativeParameter* paramInfo(fDescriptor->get_parameter_info(fHandle, i));
m_paramModels[i]->setOutput((paramInfo->hints & NATIVE_PARAMETER_IS_OUTPUT));
m_paramModels[i]->setEnabled((paramInfo->hints & NATIVE_PARAMETER_IS_ENABLED));
m_paramModels[i]->setValue(fDescriptor->get_parameter_value(fHandle, i));
// Get parameter name
QString name = "_NO_NAME_";
if (paramInfo->name != nullptr)
{
name = paramInfo->name;
}
if (paramInfo->groupName != nullptr)
{
m_paramModels[i]->setGroupName(paramInfo->groupName);
if (m_paramModels[i]->enabled() && !groups.contains(paramInfo->groupName))
{
groups.push_back(paramInfo->groupName);
m_paramGroupCount++;
}
m_paramModels[i]->setGroupId(groups.indexOf(paramInfo->groupName));
}
completerData.push_back(name);
m_paramModels[i]->setDisplayName(name);
m_paramModels[i]->setRange(paramInfo->ranges.min,
paramInfo->ranges.max,
paramInfo->ranges.step);
// Load settings into model.
if (init)
{
QString idStr = CARLA_SETTING_PREFIX + QString::number(i);
m_paramModels[i]->loadSettings(m_settingsElem, idStr);
}
}
// Set completer data
m_completerModel->setStringList(completerData);
}
emit paramsUpdated();
}
void CarlaInstrument::clearParamModels()
{
//Delete the models, this also disconnects all connections (automation and controller connections)
for (uint32_t index = 0; index < m_paramModels.size(); ++index)
{
delete m_paramModels[index];
}
//Clear the list
m_paramModels.clear();
m_paramGroupCount = 0;
}
void CarlaInstrument::paramModelChanged(uint32_t index)
{ // Update Carla param (LMMS -> Carla)
if (!m_paramModels[index]->isOutput())
{
if (fDescriptor->set_parameter_value != nullptr)
{
fDescriptor->set_parameter_value(fHandle, index, m_paramModels[index]->value());
}
// TODO? Shouldn't Carla be doing this?
if (fDescriptor->ui_set_parameter_value != nullptr)
{
fDescriptor->ui_set_parameter_value(fHandle, index, m_paramModels[index]->value());
}
}
}
void CarlaInstrument::updateParamModel(uint32_t index)
{ // Called on param changed (Carla -> LMMS)
if (fDescriptor->get_parameter_value != nullptr)
{
m_paramModels[index]->setValue(
fDescriptor->get_parameter_value(fHandle, index)
);
}
}
void CarlaInstrument::loadSettings(const QDomElement& elem)
{
if (fHandle == nullptr || fDescriptor->set_state == nullptr)
return;
QDomDocument carlaDoc("carla");
carlaDoc.appendChild(carlaDoc.importNode(elem.firstChildElement(), true ));
fDescriptor->set_state(fHandle, carlaDoc.toString(0).toUtf8().constData());
#if CARLA_VERSION_HEX >= CARLA_MIN_PARAM_VERSION
// Store to load parameter knobs settings when added.
m_settingsElem = const_cast<QDomElement&>(elem);
refreshParams(true);
#endif
}
void CarlaInstrument::play(SampleFrame* workingBuffer)
{
const uint bufsize = Engine::audioEngine()->framesPerPeriod();
zeroSampleFrames(workingBuffer, bufsize);
if (fHandle == nullptr)
{
return;
}
// set time info
Song * const s = Engine::getSong();
fTimeInfo.playing = s->isPlaying();
fTimeInfo.frame = s->getPlayPos(s->playMode()).frames(Engine::framesPerTick());
fTimeInfo.usecs = s->getMilliseconds()*1000;
fTimeInfo.bbt.bar = s->getBars() + 1;
fTimeInfo.bbt.beat = s->getBeat() + 1;
fTimeInfo.bbt.tick = s->getBeatTicks();
fTimeInfo.bbt.barStartTick = ticksPerBeat*s->getTimeSigModel().getNumerator()*s->getBars();
fTimeInfo.bbt.beatsPerBar = s->getTimeSigModel().getNumerator();
fTimeInfo.bbt.beatType = s->getTimeSigModel().getDenominator();
fTimeInfo.bbt.ticksPerBeat = ticksPerBeat;
fTimeInfo.bbt.beatsPerMinute = s->getTempo();
#ifndef _MSC_VER
float buf1[bufsize];
float buf2[bufsize];
#else
float *buf1 = static_cast<float *>(_alloca(bufsize * sizeof(float)));
float *buf2 = static_cast<float *>(_alloca(bufsize * sizeof(float)));
#endif
float* rBuf[] = { buf1, buf2 };
std::memset(buf1, 0, sizeof(float)*bufsize);
std::memset(buf2, 0, sizeof(float)*bufsize);
{
const QMutexLocker ml(&fMutex);
// TODO FIXME this is just here so it compiles.
// https://github.com/falkTX/Carla/blob/8bceb9ed173a10b29038f8abb4383710c0e497c1/source/includes/CarlaNative.h
// FIXME for v3.0, use const for the input buffer
#if CARLA_VERSION_HEX >= CARLA_VERSION_HEX_3
fDescriptor->process(fHandle, (const float**)rBuf, rBuf, bufsize, fMidiEvents, fMidiEventCount);
#else
fDescriptor->process(fHandle, rBuf, rBuf, bufsize, fMidiEvents, fMidiEventCount);
#endif
fMidiEventCount = 0;
}
for (uint i=0; i < bufsize; ++i)
{
workingBuffer[i][0] = buf1[i];
workingBuffer[i][1] = buf2[i];
}
}
bool CarlaInstrument::handleMidiEvent(const MidiEvent& event, const TimePos&, f_cnt_t offset)
{
const QMutexLocker ml(&fMutex);
if (fMidiEventCount >= kMaxMidiEvents)
return false;
NativeMidiEvent& nEvent(fMidiEvents[fMidiEventCount++]);
std::memset(&nEvent, 0, sizeof(NativeMidiEvent));
nEvent.port = 0;
nEvent.time = offset;
std::size_t written = writeToByteSeq(event, nEvent.data, sizeof(NativeMidiEvent::data));
if(written) { nEvent.size = written; }
else { --fMidiEventCount; }
return true;
}
gui::PluginView* CarlaInstrument::instantiateView(QWidget* parent)
{
// Disable plugin focus per https://bugreports.qt.io/browse/QTBUG-30181
#ifndef CARLA_OS_MAC
if (QWidget* const window = parent->window())
// TODO: Remove cast; Only needed for Qt4
fHost.uiParentId = (uintptr_t)window->winId();
else
#endif
fHost.uiParentId = 0;
std::free((char*)fHost.uiName);
// TODO - get plugin instance name
//fHost.uiName = strdup(parent->windowTitle().toUtf8().constData());
fHost.uiName = strdup(kIsPatchbay ? "CarlaPatchbay-LMMS" : "CarlaRack-LMMS");
return new gui::CarlaInstrumentView(this, parent);
}
void CarlaInstrument::sampleRateChanged()
{
fDescriptor->dispatcher(fHandle, NATIVE_PLUGIN_OPCODE_SAMPLE_RATE_CHANGED, 0, 0, nullptr, handleGetSampleRate());
}
// -------------------------------------------------------------------
namespace gui
{
CarlaInstrumentView::CarlaInstrumentView(CarlaInstrument* const instrument, QWidget* const parent)
: InstrumentViewFixedSize(instrument, parent),
fHandle(instrument->fHandle),
fDescriptor(instrument->fDescriptor),
fTimerId(fHandle != nullptr && fDescriptor->ui_idle != nullptr ? startTimer(30) : 0),
m_carlaInstrument(instrument),
m_parent(parent),
m_paramsSubWindow(nullptr),
m_paramsView(nullptr)
{
setAutoFillBackground(true);
QPalette pal;
pal.setBrush(backgroundRole(), instrument->kIsPatchbay ? PLUGIN_NAME::getIconPixmap("artwork-patchbay") : PLUGIN_NAME::getIconPixmap("artwork-rack"));
setPalette(pal);
auto l = new QHBoxLayout(this);
l->setContentsMargins( 20, 180, 10, 10 );
l->setSpacing(3);
l->setAlignment(Qt::AlignTop);
// Show GUI button
m_toggleUIButton = new QPushButton( tr( "Show GUI" ), this );
m_toggleUIButton->setCheckable( true );
m_toggleUIButton->setChecked( false );
m_toggleUIButton->setIcon( embed::getIconPixmap( "zoom" ) );
m_toggleUIButton->setFont(adjustedToPixelSize(m_toggleUIButton->font(), SMALL_FONT_SIZE));
connect( m_toggleUIButton, SIGNAL( clicked(bool) ), this, SLOT( toggleUI( bool ) ) );
m_toggleUIButton->setToolTip(
tr("Click here to show or hide the graphical user interface (GUI) of Carla."));
// Open params sub window button
m_toggleParamsWindowButton = new QPushButton(tr("Params"), this);
m_toggleParamsWindowButton->setIcon(embed::getIconPixmap("controller"));
m_toggleParamsWindowButton->setCheckable(true);
m_toggleParamsWindowButton->setFont(adjustedToPixelSize(m_toggleParamsWindowButton->font(), SMALL_FONT_SIZE));
#if CARLA_VERSION_HEX < CARLA_MIN_PARAM_VERSION
m_toggleParamsWindowButton->setEnabled(false);
m_toggleParamsWindowButton->setToolTip(tr("Available from Carla version 2.1 and up."));
#else
connect(m_toggleParamsWindowButton, SIGNAL(clicked(bool)), this, SLOT(toggleParamsWindow()));
#endif
// Add widgets to layout
l->addWidget( m_toggleUIButton );
l->addWidget(m_toggleParamsWindowButton);
// Connect signals
connect(m_toggleUIButton, SIGNAL(clicked(bool)), this, SLOT(toggleUI(bool)));
connect(instrument, SIGNAL(uiClosed()), this, SLOT(uiClosed()));
}
CarlaInstrumentView::~CarlaInstrumentView()
{
if (m_toggleUIButton->isChecked())
{
toggleUI(false);
}
#if CARLA_VERSION_HEX >= CARLA_MIN_PARAM_VERSION
if (m_paramsView)
{
delete m_paramsView;
m_paramsView = nullptr;
}
#endif
}
void CarlaInstrumentView::toggleUI(bool visible)
{
if (fHandle != nullptr && fDescriptor->ui_show != nullptr) {
// TODO: remove when fixed upstream
// change working path to location of carla.dll to avoid conflict with lmms
#if defined(CARLA_OS_WIN32) || defined(CARLA_OS_WIN64)
if (visible) {
QString backupDir = QDir::currentPath();
QDir::setCurrent(carla_get_library_folder());
fDescriptor->ui_show(fHandle, true);
QDir::setCurrent(backupDir);
return;
}
#endif
fDescriptor->ui_show(fHandle, visible);
}
}
void CarlaInstrumentView::uiClosed()
{
m_toggleUIButton->setChecked(false);
}
void CarlaInstrumentView::modelChanged()
{
}
void CarlaInstrumentView::timerEvent(QTimerEvent* event)
{
if (event->timerId() == fTimerId)
fDescriptor->ui_idle(fHandle);
InstrumentView::timerEvent(event);
}
void CarlaInstrumentView::toggleParamsWindow()
{
if (!m_paramsSubWindow)
{
m_paramsView = new CarlaParamsView(this, m_parent);
connect(m_paramsSubWindow, SIGNAL(uiClosed()), this, SLOT(paramsUiClosed()));
}
else
{
if (m_paramsSubWindow->isVisible())
{
m_paramsSubWindow->hide();
}
else
{
m_paramsSubWindow->show();
}
}
}
void CarlaInstrumentView::paramsUiClosed()
{
m_toggleParamsWindowButton->setChecked(false);
}
// -------------------------------------------------------------------
CarlaParamsView::CarlaParamsView(CarlaInstrumentView* const instrumentView, QWidget* const parent)
: InstrumentView(instrumentView->m_carlaInstrument, parent),
m_carlaInstrument(instrumentView->m_carlaInstrument),
m_carlaInstrumentView(instrumentView),
m_maxColumns(6),
m_curColumn(0),
m_curRow(0),
m_curOutColumn(0),
m_curOutRow(0)
{
auto centralWidget = new QWidget(this);
auto verticalLayout = new QVBoxLayout(centralWidget);
// -- Toolbar
m_toolBarLayout = new QHBoxLayout();
// Toolbar widgets
QSizePolicy sizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
// Params filter line edit
m_paramsFilterLineEdit = new QLineEdit(this);
m_paramsFilterLineEdit->setPlaceholderText(tr("Search.."));
m_paramsFilterLineEdit->setCompleter(m_carlaInstrument->m_paramsCompleter);
// Clear filter line edit button
m_clearFilterButton = new QPushButton(tr(""), this);
m_clearFilterButton->setIcon(embed::getIconPixmap("edit_erase"));
m_clearFilterButton->setToolTip(tr("Clear filter text"));
sizePolicy.setHeightForWidth(m_clearFilterButton->sizePolicy().hasHeightForWidth());
m_clearFilterButton->setSizePolicy(sizePolicy);
// Show automated only button
m_automatedOnlyButton = new QPushButton(tr(""), this);
m_automatedOnlyButton->setIcon(embed::getIconPixmap("automation"));
m_automatedOnlyButton->setToolTip(
tr("Only show knobs with a connection."));
m_automatedOnlyButton->setCheckable(true);
sizePolicy.setHeightForWidth(m_automatedOnlyButton->sizePolicy().hasHeightForWidth());
m_automatedOnlyButton->setSizePolicy(sizePolicy);
// Group name combobox
m_groupFilterCombo = new QComboBox(this);
m_groupFilterModel = new QStringListModel(this);
m_groupFilterCombo->setModel(m_groupFilterModel);
// Add stuff to toolbar
m_toolBarLayout->addWidget(m_paramsFilterLineEdit);
m_toolBarLayout->addWidget(m_clearFilterButton);
m_toolBarLayout->addWidget(m_automatedOnlyButton);
m_toolBarLayout->addWidget(m_groupFilterCombo);
// -- Input params
auto inputFrame = new QFrame(this);
auto inputLayout = new QVBoxLayout(inputFrame);
auto inputLabel = new QLabel("Input parameters", inputFrame);
m_inputScrollArea = new QScrollArea(inputFrame);
m_inputScrollAreaWidgetContent = new QWidget();
m_inputScrollAreaLayout = new QGridLayout(m_inputScrollAreaWidgetContent);
m_inputScrollAreaWidgetContent->setLayout(m_inputScrollAreaLayout);
m_inputScrollAreaWidgetContent->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_inputScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
m_inputScrollArea->setWidget(m_inputScrollAreaWidgetContent);
m_inputScrollArea->setWidgetResizable(true);
m_inputScrollArea->setFrameShadow(QFrame::Plain);
m_inputScrollArea->setFrameShape(QFrame::NoFrame);
m_inputScrollAreaLayout->setContentsMargins(3, 3, 3, 3);
m_inputScrollAreaLayout->setVerticalSpacing(12);
m_inputScrollAreaLayout->setHorizontalSpacing(6);
m_inputScrollAreaLayout->setColumnStretch(m_maxColumns, 1);
inputLayout->addWidget(inputLabel);
inputLayout->addWidget(m_inputScrollArea);
// -- Output params
auto outputFrame = new QFrame(this);
auto outputLayout = new QVBoxLayout(outputFrame);
auto outputLabel = new QLabel("Output parameters", outputFrame);
m_outputScrollArea = new QScrollArea(outputFrame);
m_outputScrollAreaWidgetContent = new QWidget();
m_outputScrollAreaLayout = new QGridLayout(m_outputScrollAreaWidgetContent);
m_outputScrollAreaWidgetContent->setLayout(m_outputScrollAreaLayout);
m_outputScrollAreaWidgetContent->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
m_outputScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
m_outputScrollArea->setWidget(m_outputScrollAreaWidgetContent);
m_outputScrollArea->setWidgetResizable(true);
m_outputScrollArea->setFrameShadow(QFrame::Plain);
m_outputScrollArea->setFrameShape(QFrame::NoFrame);
m_outputScrollAreaLayout->setContentsMargins(3, 28, 3, 3);
m_outputScrollAreaLayout->setVerticalSpacing(12);
m_outputScrollAreaLayout->setHorizontalSpacing(6);
m_outputScrollAreaLayout->setColumnStretch(m_maxColumns, 1);
outputLayout->addWidget(outputLabel);
outputLayout->addWidget(m_outputScrollArea);
// -- QSplitter
auto splitter = new QSplitter(Qt::Vertical, this);
// -- Add layout and widgets.
verticalLayout->addLayout(m_toolBarLayout);
splitter->addWidget(inputFrame);
splitter->addWidget(outputFrame);
verticalLayout->addWidget(splitter);
#if QT_VERSION < 0x50C00
// Workaround for a bug in Qt versions below 5.12,
// where argument-dependent-lookup fails for QFlags operators
// declared inside a namepsace.
// This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h
// See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348
using ::operator|;
#endif
// -- Sub window
auto win = new CarlaParamsSubWindow(getGUI()->mainWindow()->workspace()->viewport(),
Qt::SubWindow | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint);
m_carlaInstrumentView->m_paramsSubWindow = getGUI()->mainWindow()->workspace()->addSubWindow(win);
m_carlaInstrumentView->m_paramsSubWindow->setSizePolicy(
QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
m_carlaInstrumentView->m_paramsSubWindow->setMinimumHeight(200);
m_carlaInstrumentView->m_paramsSubWindow->setMinimumWidth(200);
m_carlaInstrumentView->m_paramsSubWindow->resize(600, 400);
m_carlaInstrumentView->m_paramsSubWindow->setWidget(centralWidget);
centralWidget->setWindowTitle(m_carlaInstrument->instrumentTrack()->name() + tr(" - Parameters"));
// -- Connect signals
connect(m_carlaInstrumentView->m_paramsSubWindow, SIGNAL(resized()), this, SLOT(windowResized()));
connect(m_paramsFilterLineEdit, SIGNAL(textChanged(const QString)), this, SLOT(filterKnobs()));
connect(m_clearFilterButton, SIGNAL(clicked(bool)), this, SLOT(clearFilterText()));
connect(m_automatedOnlyButton, SIGNAL(toggled(bool)), this, SLOT(filterKnobs()));
connect(m_groupFilterCombo, SIGNAL(currentTextChanged(const QString)), this, SLOT(filterKnobs()));
connect(m_carlaInstrument, SIGNAL(paramsUpdated()), this, SLOT(refreshKnobs()));
m_carlaInstrumentView->m_paramsSubWindow->show(); // Show the subwindow
// Add knobs if there are any already.
// Call this after show() so the m_inputScrollArea->width() is set properly.
refreshKnobs(); // Will trigger filterKnobs() due m_groupFilterCombo->setCurrentIndex(0)
}
CarlaParamsView::~CarlaParamsView()
{
// Close and delete m_paramsSubWindow
if (m_carlaInstrumentView->m_paramsSubWindow)
{
m_carlaInstrumentView->m_paramsSubWindow->setAttribute(Qt::WA_DeleteOnClose);
m_carlaInstrumentView->m_paramsSubWindow->close();
delete m_carlaInstrumentView->m_paramsSubWindow;
m_carlaInstrumentView->m_paramsSubWindow = nullptr;
}
m_carlaInstrumentView->m_paramsView = nullptr;
// Clear models
if (!m_carlaInstrument->m_paramModels.empty())
{
m_carlaInstrument->clearParamModels();
}
}
void CarlaParamsView::clearFilterText()
{
m_paramsFilterLineEdit->setText("");
}
void CarlaParamsView::filterKnobs()
{
clearKnobs(); // Remove all knobs from the layout.
if (!m_carlaInstrument->m_paramGroupCount)
{
return;
}
// Calc how many knobs will fit horizontal in the params window.
uint16_t maxKnobWidth = m_maxKnobWidthPerGroup[m_groupFilterCombo->currentIndex()];
maxKnobWidth += m_inputScrollAreaLayout->spacing();
if (!maxKnobWidth)
{
// Prevent possible division by zero.
return;
}
m_maxColumns = m_inputScrollArea->width() / maxKnobWidth;
QString text = m_paramsFilterLineEdit->text();
for (uint32_t i = 0; i < m_knobs.size(); ++i)
{
// Don't show disabled (unused) knobs.
if (!m_carlaInstrument->m_paramModels[i]->enabled())
{
continue;
}
// Filter on automation only
if (m_automatedOnlyButton->isChecked())
{
if (! m_carlaInstrument->m_paramModels[i]->isAutomatedOrControlled())
{
continue;
}
}
// Filter on group name
if (m_groupFilterCombo->currentText() != m_carlaInstrument->m_paramModels[i]->groupName())
{
continue;
}
// Filter on text
if (text != "")
{
if (m_knobs[i]->objectName().contains(text, Qt::CaseInsensitive))
{
addKnob(i);
}
}
else
{
addKnob(i);
}
}
// Add spacer so all knobs go to top
auto verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
m_inputScrollAreaLayout->addItem(verticalSpacer, m_curRow+1, 0, 1, 1);
}
void CarlaParamsView::refreshKnobs()
{
// Make sure all the knobs are deleted.
for (uint32_t i = 0; i < m_knobs.size(); ++i)
{
delete m_knobs[i]; // Delete knob widgets itself.
}
m_knobs.clear(); // Clear the pointer list.
// Reset position data.
m_curColumn = 0;
m_curRow = 0;
m_curOutColumn = 0;
m_curOutRow = 0;
// Clear max knob width per group
m_maxKnobWidthPerGroup.clear();
m_maxKnobWidthPerGroup.reserve(m_carlaInstrument->m_paramGroupCount);
for (uint8_t i = 0; i < m_carlaInstrument->m_paramGroupCount; i++)
{
m_maxKnobWidthPerGroup[i] = 0;
}
if (m_carlaInstrument->m_paramModels.empty()) { return; }
// Make room in QList m_knobs
m_knobs.reserve(m_carlaInstrument->m_paramModels.size());
QStringList groupNameList;
groupNameList.reserve(m_carlaInstrument->m_paramGroupCount);
for (uint32_t i = 0; i < m_carlaInstrument->m_paramModels.size(); ++i)
{
bool enabled = m_carlaInstrument->m_paramModels[i]->enabled();
m_knobs.push_back(new Knob(KnobType::Dark28, m_inputScrollAreaWidgetContent));
QString name = (*m_carlaInstrument->m_paramModels[i]).displayName();
m_knobs[i]->setHintText(name, "");
m_knobs[i]->setLabel(name);
m_knobs[i]->setObjectName(name); // this is being used for filtering the knobs.
// Set the newly created model to the knob.
m_knobs[i]->setModel(m_carlaInstrument->m_paramModels[i]);
m_knobs[i]->setEnabled(enabled);
if (enabled)
{
// Collect group names
if (!groupNameList.contains(m_carlaInstrument->m_paramModels[i]->groupName()))
{
groupNameList.append(m_carlaInstrument->m_paramModels[i]->groupName());
}
// Store biggest knob width per group (so we can calc how many
// knobs we can horizontaly fit)
uint8_t groupId = m_carlaInstrument->m_paramModels[i]->groupId();
if (m_maxKnobWidthPerGroup[groupId] < m_knobs[i]->width())
{
m_maxKnobWidthPerGroup[groupId] = m_knobs[i]->width();
}
}
}
// Set new list with group names to the model
if (!groupNameList.count())
{
groupNameList.append("No params");
}
m_groupFilterModel->setStringList(groupNameList);
m_groupFilterCombo->setCurrentIndex(0);
}
void CarlaParamsView::windowResized()
{
filterKnobs();
}
void CarlaParamsView::addKnob(uint32_t index)
{
#if QT_VERSION < 0x50C00
// Workaround for a bug in Qt versions below 5.12,
// where argument-dependent-lookup fails for QFlags operators
// declared inside a namepsace.
// This affects the Q_DECLARE_OPERATORS_FOR_FLAGS macro in Instrument.h
// See also: https://codereview.qt-project.org/c/qt/qtbase/+/225348
using ::operator|;
#endif
bool output = m_carlaInstrument->m_paramModels[index]->isOutput();
if (output)
{
m_outputScrollAreaLayout->addWidget(
m_knobs[index], m_curOutRow, m_curOutColumn, Qt::AlignHCenter | Qt::AlignTop);
m_knobs[index]->setEnabled(false); // We should not be able to adjust output.
m_knobs[index]->show();
if (m_curOutColumn < m_maxColumns - 1)
{
m_curOutColumn++;
}
else
{
m_curOutColumn = 0;
m_curOutRow++;
}
}
else
{
// Add the new knob to layout
m_inputScrollAreaLayout->addWidget(m_knobs[index], m_curRow, m_curColumn, Qt::AlignHCenter | Qt::AlignTop);
m_inputScrollAreaLayout->setColumnStretch(m_curColumn, 1);
// Chances that we did close() on the widget is big, so show it.
m_knobs[index]->show();
// Keep track of current column and row index.
if (m_curColumn < m_maxColumns - 1)
{
m_curColumn++;
}
else
{
m_curColumn = 0;
m_curRow++;
}
}
}
void CarlaParamsView::clearKnobs()
{
// Remove knobs from layout.
for (uint16_t i = 0; i < m_knobs.size(); ++i)
{
m_knobs[i]->close();
}
// Remove spacers
for (int16_t i=m_inputScrollAreaLayout->count() - 1; i > 0; i--)
{
auto item = m_inputScrollAreaLayout->takeAt(i);
if (item->widget()) {continue;}
delete item;
}
for (int16_t i=m_outputScrollAreaLayout->count() - 1; i > 0; i--)
{
auto item = m_outputScrollAreaLayout->takeAt(i);
if (item->widget()) {continue;}
delete item;
}
// Reset position data.
m_curColumn = 0;
m_curRow = 0;
m_curOutColumn = 0;
m_curOutRow = 0;
}
} // namespace gui
} // namespace lmms
| 34,874
|
C++
|
.cpp
| 945
| 33.453968
| 154
| 0.720129
|
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,605
|
DummyCarla.cpp
|
LMMS_lmms/plugins/CarlaBase/DummyCarla.cpp
|
// A dummy Carla interface
#define BUILDING_CARLA
#include <CarlaNativePlugin.h>
#ifndef CARLA_PLUGIN_EXPORT
#define CARLA_PLUGIN_EXPORT CARLA_EXPORT
#endif
CARLA_PLUGIN_EXPORT const char* carla_get_library_filename() { return nullptr; }
CARLA_PLUGIN_EXPORT const char* carla_get_library_folder() { return nullptr; }
CARLA_PLUGIN_EXPORT const NativePluginDescriptor* carla_get_native_rack_plugin() { return nullptr; }
CARLA_PLUGIN_EXPORT const NativePluginDescriptor* carla_get_native_patchbay_plugin() { return nullptr; }
CARLA_PLUGIN_EXPORT const NativePluginDescriptor* carla_get_native_patchbay16_plugin() { return nullptr; }
CARLA_PLUGIN_EXPORT const NativePluginDescriptor* carla_get_native_patchbay32_plugin() { return nullptr; }
CARLA_PLUGIN_EXPORT const NativePluginDescriptor* carla_get_native_patchbay64_plugin() { return nullptr; }
CARLA_PLUGIN_EXPORT const NativePluginDescriptor* carla_get_native_patchbay_cv_plugin() { return nullptr; }
CARLA_PLUGIN_EXPORT CarlaBackend::CarlaEngine* carla_get_native_plugin_engine(const NativePluginDescriptor* desc, NativePluginHandle handle) { return nullptr; }
| 1,115
|
C++
|
.cpp
| 15
| 73.2
| 160
| 0.816029
|
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,606
|
Mallets.cpp
|
LMMS_lmms/plugins/Stk/Mallets/Mallets.cpp
|
/*
* Mallets.cpp - tuned instruments that one would bang upon
*
* Copyright (c) 2006-2008 Danny McRae <khjklujn/at/users.sourceforge.net>
* Copyright (c) 2009-2015 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2016 Oskar Wallgren <oskarwallgren13/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 "Mallets.h"
#include <QDir>
#include <QDomElement>
#include <QMessageBox>
#include <stk/BandedWG.h>
#include <stk/ModalBar.h>
#include <stk/TubeBell.h>
#include "AudioEngine.h"
#include "ConfigManager.h"
#include "Engine.h"
#include "GuiApplication.h"
#include "InstrumentTrack.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT malletsstk_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Mallets",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Tuneful things to bang on" ),
"Danny McRae <khjklujn/at/users.sf.net>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
MalletsInstrument::MalletsInstrument( InstrumentTrack * _instrument_track ):
Instrument( _instrument_track, &malletsstk_plugin_descriptor ),
m_hardnessModel(64.0f, 0.0f, 128.0f, 0.1f, this, tr( "Hardness" )),
m_positionModel(64.0f, 0.0f, 64.0f, 0.1f, this, tr( "Position" )),
m_vibratoGainModel(0.0f, 0.0f, 128.0f, 0.1f, this, tr( "Vibrato gain" )),
m_vibratoFreqModel(0.0f, 0.0f, 128.0f, 0.1f, this, tr( "Vibrato frequency" )),
m_stickModel(0.0f, 0.0f, 128.0f, 0.1f, this, tr( "Stick mix" )),
m_modulatorModel(64.0f, 0.0f, 128.0f, 0.1f, this, tr( "Modulator" )),
m_crossfadeModel(64.0f, 0.0f, 128.0f, 0.1f, this, tr( "Crossfade" )),
m_lfoSpeedModel(64.0f, 0.0f, 128.0f, 0.1f, this, tr( "LFO speed" )),
m_lfoDepthModel(64.0f, 0.0f, 128.0f, 0.1f, this, tr( "LFO depth" )),
m_adsrModel(64.0f, 0.0f, 128.0f, 0.1f, this, tr( "ADSR" )),
m_pressureModel(64.0f, 0.1f, 128.0f, 0.1f, this, tr( "Pressure" )),
m_motionModel(64.0f, 0.0f, 128.0f, 0.1f, this, tr( "Motion" )),
// TODO: m_vibratoModel
m_velocityModel(64.0f, 0.1f, 128.0f, 0.1f, this, tr( "Speed" )),
m_strikeModel( true, this, tr( "Bowed" ) ),
m_presetsModel(this, tr("Instrument")),
m_spreadModel(0, 0, 255, 1, this, tr( "Spread" )),
m_randomModel(0.0f, 0.0f, 1.0f, 0.01f, this, tr("Randomness")),
m_versionModel( MALLETS_PRESET_VERSION, 0, MALLETS_PRESET_VERSION, this, "" ),
m_isOldVersionModel( false, this, "" ),
m_filesMissing( !QDir( ConfigManager::inst()->stkDir() ).exists() ||
!QFileInfo( ConfigManager::inst()->stkDir() + "/sinewave.raw" ).exists() )
{
// ModalBar
m_presetsModel.addItem( tr( "Marimba" ) );
m_scalers.append( 4.0 );
m_presetsModel.addItem( tr( "Vibraphone" ) );
m_scalers.append( 4.0 );
m_presetsModel.addItem( tr( "Agogo" ) );
m_scalers.append( 5.0 );
m_presetsModel.addItem( tr( "Wood 1" ) );
m_scalers.append( 4.0 );
m_presetsModel.addItem( tr( "Reso" ) );
m_scalers.append( 2.5 );
m_presetsModel.addItem( tr( "Wood 2" ) );
m_scalers.append( 5.0 );
m_presetsModel.addItem( tr( "Beats" ) );
m_scalers.append( 20.0 );
m_presetsModel.addItem( tr( "Two fixed" ) );
m_scalers.append( 5.0 );
m_presetsModel.addItem( tr( "Clump" ) );
m_scalers.append( 4.0 );
// TubeBell
m_presetsModel.addItem( tr( "Tubular bells" ) );
m_scalers.append(1.8f);
// BandedWG
m_presetsModel.addItem( tr( "Uniform bar" ) );
m_scalers.append( 25.0 );
m_presetsModel.addItem( tr( "Tuned bar" ) );
m_scalers.append( 10.0 );
m_presetsModel.addItem( tr( "Glass" ) );
m_scalers.append( 16.0 );
m_presetsModel.addItem( tr( "Tibetan bowl" ) );
m_scalers.append( 7.0 );
}
void MalletsInstrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
// ModalBar
m_hardnessModel.saveSettings( _doc, _this, "hardness" );
m_positionModel.saveSettings( _doc, _this, "position" );
m_vibratoGainModel.saveSettings( _doc, _this, "vib_gain" );
m_vibratoFreqModel.saveSettings( _doc, _this, "vib_freq" );
m_stickModel.saveSettings( _doc, _this, "stick_mix" );
// TubeBell
m_modulatorModel.saveSettings( _doc, _this, "modulator" );
m_crossfadeModel.saveSettings( _doc, _this, "crossfade" );
m_lfoSpeedModel.saveSettings( _doc, _this, "lfo_speed" );
m_lfoDepthModel.saveSettings( _doc, _this, "lfo_depth" );
m_adsrModel.saveSettings( _doc, _this, "adsr" );
// BandedWG
m_pressureModel.saveSettings( _doc, _this, "pressure" );
// m_motionModel.saveSettings( _doc, _this, "motion" );
// m_vibratoModel.saveSettings( _doc, _this, "vibrato" );
m_velocityModel.saveSettings( _doc, _this, "velocity" );
m_strikeModel.saveSettings( _doc, _this, "strike" );
m_presetsModel.saveSettings( _doc, _this, "preset" );
m_spreadModel.saveSettings( _doc, _this, "spread" );
m_randomModel.saveSettings(_doc, _this, "randomness");
m_versionModel.saveSettings( _doc, _this, "version" );
m_isOldVersionModel.saveSettings( _doc, _this, "oldversion" );
}
void MalletsInstrument::loadSettings( const QDomElement & _this )
{
m_versionModel.loadSettings( _this, "version" );
// ModalBar
m_hardnessModel.loadSettings( _this, "hardness" );
m_positionModel.loadSettings( _this, "position" );
m_vibratoGainModel.loadSettings( _this, "vib_gain" );
m_vibratoFreqModel.loadSettings( _this, "vib_freq" );
m_stickModel.loadSettings( _this, "stick_mix" );
// TubeBell
m_modulatorModel.loadSettings( _this, "modulator" );
m_crossfadeModel.loadSettings( _this, "crossfade" );
m_lfoSpeedModel.loadSettings( _this, "lfo_speed" );
m_lfoDepthModel.loadSettings( _this, "lfo_depth" );
m_adsrModel.loadSettings( _this, "adsr" );
// BandedWG
m_pressureModel.loadSettings( _this, "pressure" );
// m_motionModel.loadSettings( _this, "motion" );
// m_vibratoModel.loadSettings( _this, "vibrato" );
m_velocityModel.loadSettings( _this, "velocity" );
m_strikeModel.loadSettings( _this, "strike" );
m_presetsModel.loadSettings( _this, "preset" );
m_spreadModel.loadSettings( _this, "spread" );
m_randomModel.loadSettings(_this, "randomness");
m_isOldVersionModel.loadSettings( _this, "oldversion" );
// To maintain backward compatibility
if( !_this.hasAttribute( "version" ) )
{
m_isOldVersionModel.setValue( true );
m_vibratoGainModel.setValue( 0.0f );
if( m_presetsModel.value() == 1 )
{
/* Earlier mallets used the stk internal
default of 0.2. 0.2 * 128.0 = 25.6 */
m_vibratoGainModel.setValue( 25.6f );
}
if( m_presetsModel.value() != 1 )
{
// Frequency actually worked for Vibraphone!
m_vibratoFreqModel.setValue( 0.0f );
}
/* Modalbar preset values, see stk, ModalBar.cpp
void ModalBar :: setPreset( int preset )
Stick Mix * 128.0
m_positionModel values over 64 is formatted to the
new knob by 128 - x */
switch( m_presetsModel.value() )
{
case 0:
m_hardnessModel.setValue( 55.0f );
m_positionModel.setValue( 57.0f );
m_stickModel.setValue( 12.0f );
break;
case 1:
m_hardnessModel.setValue( 50.0f );
m_positionModel.setValue( 55.0f );// 128 - 73!
m_stickModel.setValue( 10.0f );
break;
case 2:
m_hardnessModel.setValue( 78.0f );
m_positionModel.setValue( 46.0f );
m_stickModel.setValue( 18.0f );
break;
case 3:
m_hardnessModel.setValue( 59.0f );
m_positionModel.setValue( 48.0f );
m_stickModel.setValue( 6.0f );
break;
case 4:
m_hardnessModel.setValue( 58.0f );
m_positionModel.setValue( 32.0f );
m_stickModel.setValue( 13.0f );
break;
case 5:
m_hardnessModel.setValue( 40.0f );
m_positionModel.setValue( 57.0f );
m_stickModel.setValue( 14.0f );
break;
case 6:
m_hardnessModel.setValue( 51.0f );
m_positionModel.setValue( 38.0f );
m_stickModel.setValue( 9.0f );
break;
case 7:
m_hardnessModel.setValue( 58.0f );
m_positionModel.setValue( 58.0f );
m_stickModel.setValue( 9.0f );
break;
case 8:
m_hardnessModel.setValue( 50.0f );
m_positionModel.setValue( 55.0f );// 128 - 73!
m_stickModel.setValue( 10.0f );
break;
}
}
}
QString MalletsInstrument::nodeName() const
{
return( malletsstk_plugin_descriptor.name );
}
void MalletsInstrument::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
if( m_filesMissing )
{
return;
}
int p = m_presetsModel.value();
const float freq = _n->frequency();
if (!_n->m_pluginData)
{
// If newer projects, adjust velocity to within stk's limits
float velocityAdjust =
m_isOldVersionModel.value() ? 100.0 : 200.0;
const float vel = _n->getVolume() / velocityAdjust;
const float random = m_randomModel.value();
float hardness = m_hardnessModel.value();
float position = m_positionModel.value();
float modulator = m_modulatorModel.value();
float crossfade = m_crossfadeModel.value();
float pressure = m_pressureModel.value();
float speed = m_velocityModel.value();
if (p < 9)
{
hardness += random * (static_cast<float>(fast_rand() % 128) - 64.0);
hardness = std::clamp(hardness, 0.0f, 128.0f);
position += random * (static_cast<float>(fast_rand() % 64) - 32.0);
position = std::clamp(position, 0.0f, 64.0f);
}
else if (p == 9)
{
modulator += random * (static_cast<float>(fast_rand() % 128) - 64.0);
modulator = std::clamp(modulator, 0.0f, 128.0f);
crossfade += random * (static_cast<float>(fast_rand() % 128) - 64.0);
crossfade = std::clamp(crossfade, 0.0f, 128.0f);
}
else
{
pressure += random * (static_cast<float>(fast_rand() % 128) - 64.0);
pressure = std::clamp(pressure, 0.0f, 128.0f);
speed += random * (static_cast<float>(fast_rand() % 128) - 64.0);
speed = std::clamp(speed, 0.0f, 128.0f);
}
// critical section as STK is not thread-safe
static QMutex m;
m.lock();
if( p < 9 )
{
_n->m_pluginData = new MalletsSynth( freq,
vel,
m_stickModel.value(),
hardness,
position,
m_vibratoGainModel.value(),
m_vibratoFreqModel.value(),
p,
(uint8_t) m_spreadModel.value(),
Engine::audioEngine()->outputSampleRate() );
}
else if( p == 9 )
{
_n->m_pluginData = new MalletsSynth( freq,
vel,
p,
m_lfoDepthModel.value(),
modulator,
crossfade,
m_lfoSpeedModel.value(),
m_adsrModel.value(),
(uint8_t) m_spreadModel.value(),
Engine::audioEngine()->outputSampleRate() );
}
else
{
_n->m_pluginData = new MalletsSynth( freq,
vel,
pressure,
m_motionModel.value(),
m_vibratoModel.value(),
p - 10,
m_strikeModel.value() * 128.0,
speed,
(uint8_t) m_spreadModel.value(),
Engine::audioEngine()->outputSampleRate() );
}
m.unlock();
static_cast<MalletsSynth *>(_n->m_pluginData)->setPresetIndex(p);
}
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
auto ps = static_cast<MalletsSynth*>(_n->m_pluginData);
ps->setFrequency(freq);
p = ps->presetIndex();
if (p < 9) // ModalBar updates
{
ps->setVibratoGain(m_vibratoGainModel.value());
ps->setVibratoFreq(m_vibratoFreqModel.value());
}
else if (p == 9) // Tubular Bells updates
{
ps->setADSR(m_adsrModel.value());
ps->setLFODepth(m_lfoDepthModel.value());
ps->setLFOSpeed(m_lfoSpeedModel.value());
}
sample_t add_scale = 0.0f;
if( p == 10 && m_isOldVersionModel.value() == true )
{
add_scale = static_cast<sample_t>( m_strikeModel.value() ) * freq * 2.5f;
}
for( fpp_t frame = offset; frame < frames + offset; ++frame )
{
_working_buffer[frame][0] = ps->nextSampleLeft() *
( m_scalers[p] + add_scale );
_working_buffer[frame][1] = ps->nextSampleRight() *
( m_scalers[p] + add_scale );
}
}
void MalletsInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<MalletsSynth *>( _n->m_pluginData );
}
gui::PluginView * MalletsInstrument::instantiateView( QWidget * _parent )
{
return( new gui::MalletsInstrumentView( this, _parent ) );
}
namespace gui
{
MalletsInstrumentView::MalletsInstrumentView( MalletsInstrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
m_modalBarWidget = setupModalBarControls( this );
setWidgetBackground( m_modalBarWidget, "artwork" );
m_modalBarWidget->move( 0,0 );
m_tubeBellWidget = setupTubeBellControls( this );
setWidgetBackground( m_tubeBellWidget, "artwork" );
m_tubeBellWidget->move( 0,0 );
m_bandedWGWidget = setupBandedWGControls( this );
setWidgetBackground( m_bandedWGWidget, "artwork" );
m_bandedWGWidget->move( 0,0 );
changePreset(); // Show widget
m_presetsCombo = new ComboBox( this, tr( "Instrument" ) );
m_presetsCombo->setGeometry( 140, 50, 99, ComboBox::DEFAULT_HEIGHT );
connect( &_instrument->m_presetsModel, SIGNAL( dataChanged() ),
this, SLOT( changePreset() ) );
m_spreadKnob = new Knob( KnobType::Vintage32, this );
m_spreadKnob->setLabel( tr( "Spread" ) );
m_spreadKnob->move( 190, 140 );
m_spreadKnob->setHintText( tr( "Spread:" ), "" );
m_randomKnob = new Knob(KnobType::Vintage32, this);
m_randomKnob->setLabel(tr("Random"));
m_randomKnob->move(190, 190);
m_randomKnob->setHintText(tr("Random:"), "");
// try to inform user about missing Stk-installation
if( _instrument->m_filesMissing && getGUI() != nullptr )
{
QMessageBox::information( 0, tr( "Missing files" ),
tr( "Your Stk-installation seems to be "
"incomplete. Please make sure "
"the full Stk-package is installed!" ),
QMessageBox::Ok );
}
}
void MalletsInstrumentView::setWidgetBackground( QWidget * _widget, const QString & _pic )
{
_widget->setAutoFillBackground( true );
QPalette pal;
pal.setBrush( _widget->backgroundRole(),
PLUGIN_NAME::getIconPixmap( _pic.toLatin1().constData() ) );
_widget->setPalette( pal );
}
QWidget * MalletsInstrumentView::setupModalBarControls( QWidget * _parent )
{
auto widget = new QWidget(_parent);
widget->setFixedSize( 250, 250 );
m_hardnessKnob = new Knob( KnobType::Vintage32, widget );
m_hardnessKnob->setLabel( tr( "Hardness" ) );
m_hardnessKnob->move( 30, 90 );
m_hardnessKnob->setHintText( tr( "Hardness:" ), "" );
m_positionKnob = new Knob( KnobType::Vintage32, widget );
m_positionKnob->setLabel( tr( "Position" ) );
m_positionKnob->move( 110, 90 );
m_positionKnob->setHintText( tr( "Position:" ), "" );
m_vibratoGainKnob = new Knob( KnobType::Vintage32, widget );
m_vibratoGainKnob->setLabel( tr( "Vibrato gain" ) );
m_vibratoGainKnob->move( 30, 140 );
m_vibratoGainKnob->setHintText( tr( "Vibrato gain:" ), "" );
m_vibratoFreqKnob = new Knob( KnobType::Vintage32, widget );
m_vibratoFreqKnob->setLabel( tr( "Vibrato frequency" ) );
m_vibratoFreqKnob->move( 110, 140 );
m_vibratoFreqKnob->setHintText( tr( "Vibrato frequency:" ), "" );
m_stickKnob = new Knob( KnobType::Vintage32, widget );
m_stickKnob->setLabel( tr( "Stick mix" ) );
m_stickKnob->move( 190, 90 );
m_stickKnob->setHintText( tr( "Stick mix:" ), "" );
return( widget );
}
QWidget * MalletsInstrumentView::setupTubeBellControls( QWidget * _parent )
{
auto widget = new QWidget(_parent);
widget->setFixedSize( 250, 250 );
m_modulatorKnob = new Knob( KnobType::Vintage32, widget );
m_modulatorKnob->setLabel( tr( "Modulator" ) );
m_modulatorKnob->move( 30, 90 );
m_modulatorKnob->setHintText( tr( "Modulator:" ), "" );
m_crossfadeKnob = new Knob( KnobType::Vintage32, widget );
m_crossfadeKnob->setLabel( tr( "Crossfade" ) );
m_crossfadeKnob->move( 110, 90 );
m_crossfadeKnob->setHintText( tr( "Crossfade:" ), "" );
m_lfoSpeedKnob = new Knob( KnobType::Vintage32, widget );
m_lfoSpeedKnob->setLabel( tr( "LFO speed" ) );
m_lfoSpeedKnob->move( 30, 140 );
m_lfoSpeedKnob->setHintText( tr( "LFO speed:" ), "" );
m_lfoDepthKnob = new Knob( KnobType::Vintage32, widget );
m_lfoDepthKnob->setLabel( tr( "LFO depth" ) );
m_lfoDepthKnob->move( 110, 140 );
m_lfoDepthKnob->setHintText( tr( "LFO depth:" ), "" );
m_adsrKnob = new Knob( KnobType::Vintage32, widget );
m_adsrKnob->setLabel( tr( "ADSR" ) );
m_adsrKnob->move( 190, 90 );
m_adsrKnob->setHintText( tr( "ADSR:" ), "" );
return( widget );
}
QWidget * MalletsInstrumentView::setupBandedWGControls( QWidget * _parent )
{
// BandedWG
auto widget = new QWidget(_parent);
widget->setFixedSize( 250, 250 );
/* m_strikeLED = new LedCheckBox( tr( "Bowed" ), widget );
m_strikeLED->move( 138, 25 );*/
m_pressureKnob = new Knob( KnobType::Vintage32, widget );
m_pressureKnob->setLabel( tr( "Pressure" ) );
m_pressureKnob->move( 30, 90 );
m_pressureKnob->setHintText( tr( "Pressure:" ), "" );
/* m_motionKnob = new Knob( KnobType::Vintage32, widget );
m_motionKnob->setLabel( tr( "Motion" ) );
m_motionKnob->move( 110, 90 );
m_motionKnob->setHintText( tr( "Motion:" ), "" );*/
m_velocityKnob = new Knob( KnobType::Vintage32, widget );
m_velocityKnob->setLabel( tr( "Speed" ) );
m_velocityKnob->move( 30, 140 );
m_velocityKnob->setHintText( tr( "Speed:" ), "" );
/* m_vibratoKnob = new Knob( KnobType::Vintage32, widget, tr( "Vibrato" ) );
m_vibratoKnob->setLabel( tr( "Vibrato" ) );
m_vibratoKnob->move( 110, 140 );
m_vibratoKnob->setHintText( tr( "Vibrato:" ), "" );*/
return( widget );
}
void MalletsInstrumentView::modelChanged()
{
auto inst = castModel<MalletsInstrument>();
m_hardnessKnob->setModel( &inst->m_hardnessModel );
m_positionKnob->setModel( &inst->m_positionModel );
m_vibratoGainKnob->setModel( &inst->m_vibratoGainModel );
m_vibratoFreqKnob->setModel( &inst->m_vibratoFreqModel );
m_stickKnob->setModel( &inst->m_stickModel );
m_modulatorKnob->setModel( &inst->m_modulatorModel );
m_crossfadeKnob->setModel( &inst->m_crossfadeModel );
m_lfoSpeedKnob->setModel( &inst->m_lfoSpeedModel );
m_lfoDepthKnob->setModel( &inst->m_lfoDepthModel );
m_adsrKnob->setModel( &inst->m_adsrModel );
m_pressureKnob->setModel( &inst->m_pressureModel );
// m_motionKnob->setModel( &inst->m_motionModel );
// m_vibratoKnob->setModel( &inst->m_vibratoModel );
m_velocityKnob->setModel( &inst->m_velocityModel );
// m_strikeLED->setModel( &inst->m_strikeModel );
m_presetsCombo->setModel( &inst->m_presetsModel );
m_spreadKnob->setModel( &inst->m_spreadModel );
m_randomKnob->setModel(&inst->m_randomModel);
}
void MalletsInstrumentView::changePreset()
{
auto inst = castModel<MalletsInstrument>();
int _preset = inst->m_presetsModel.value();
if( _preset < 9 )
{
m_tubeBellWidget->hide();
m_bandedWGWidget->hide();
m_modalBarWidget->show();
}
else if( _preset == 9 )
{
m_modalBarWidget->hide();
m_bandedWGWidget->hide();
m_tubeBellWidget->show();
}
else
{
m_modalBarWidget->hide();
m_tubeBellWidget->hide();
m_bandedWGWidget->show();
}
}
} // namespace gui
// ModalBar
MalletsSynth::MalletsSynth( const StkFloat _pitch,
const StkFloat _velocity,
const StkFloat _control1,
const StkFloat _control2,
const StkFloat _control4,
const StkFloat _control8,
const StkFloat _control11,
const int _control16,
const uint8_t _delay,
const sample_rate_t _sample_rate ) :
m_presetIndex(0)
{
try
{
Stk::setSampleRate( _sample_rate );
Stk::setRawwavePath( QDir( ConfigManager::inst()->stkDir() ).absolutePath()
.toLocal8Bit().constData() );
#ifndef LMMS_DEBUG
Stk::showWarnings( false );
#endif
m_voice = new ModalBar();
m_voice->controlChange( 16, _control16 );
m_voice->controlChange( 1, _control1 );
m_voice->controlChange( 2, _control2 );
m_voice->controlChange( 4, _control4 );
m_voice->controlChange( 8, _control8 );
m_voice->controlChange( 11, _control11 );
m_voice->controlChange( 128, 128.0f );
m_voice->noteOn( _pitch, _velocity );
}
catch( ... )
{
m_voice = nullptr;
}
m_delay = new StkFloat[256];
m_delayRead = 0;
m_delayWrite = _delay;
for( int i = 0; i < 256; i++ )
{
m_delay[i] = 0.0;
}
}
// TubeBell
MalletsSynth::MalletsSynth( const StkFloat _pitch,
const StkFloat _velocity,
const int _preset,
const StkFloat _control1,
const StkFloat _control2,
const StkFloat _control4,
const StkFloat _control11,
const StkFloat _control128,
const uint8_t _delay,
const sample_rate_t _sample_rate ) :
m_presetIndex(0)
{
try
{
Stk::setSampleRate( _sample_rate );
Stk::setRawwavePath( QDir( ConfigManager::inst()->stkDir() ).absolutePath()
.toLocal8Bit().constData() );
#ifndef LMMS_DEBUG
Stk::showWarnings( false );
#endif
m_voice = new TubeBell();
m_voice->controlChange( 1, _control1 );
m_voice->controlChange( 2, _control2 );
m_voice->controlChange( 4, _control4 );
m_voice->controlChange( 11, _control11 );
m_voice->controlChange( 128, _control128 );
m_voice->noteOn( _pitch, _velocity );
}
catch( ... )
{
m_voice = nullptr;
}
m_delay = new StkFloat[256];
m_delayRead = 0;
m_delayWrite = _delay;
for( int i = 0; i < 256; i++ )
{
m_delay[i] = 0.0;
}
}
// BandedWG
MalletsSynth::MalletsSynth( const StkFloat _pitch,
const StkFloat _velocity,
const StkFloat _control2,
const StkFloat _control4,
const StkFloat _control11,
const int _control16,
const StkFloat _control64,
const StkFloat _control128,
const uint8_t _delay,
const sample_rate_t _sample_rate ) :
m_presetIndex(0)
{
try
{
Stk::setSampleRate( _sample_rate );
Stk::setRawwavePath( QDir( ConfigManager::inst()->stkDir() ).absolutePath()
.toLocal8Bit().constData() );
#ifndef LMMS_DEBUG
Stk::showWarnings( false );
#endif
m_voice = new BandedWG();
m_voice->controlChange( 1, 128.0 );
m_voice->controlChange( 2, _control2 );
m_voice->controlChange( 4, _control4 );
m_voice->controlChange( 11, _control11 );
m_voice->controlChange( 16, _control16 );
m_voice->controlChange( 64, _control64 );
m_voice->controlChange( 128, _control128 );
m_voice->noteOn( _pitch, _velocity );
}
catch( ... )
{
m_voice = nullptr;
}
m_delay = new StkFloat[256];
m_delayRead = 0;
m_delayWrite = _delay;
for( int i = 0; i < 256; i++ )
{
m_delay[i] = 0.0;
}
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * m, void * )
{
return new MalletsInstrument( static_cast<InstrumentTrack *>( m ) );
}
}
} // namespace lmms
| 22,952
|
C++
|
.cpp
| 670
| 31.332836
| 90
| 0.688696
|
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,607
|
OpulenZ.cpp
|
LMMS_lmms/plugins/OpulenZ/OpulenZ.cpp
|
/*
* OpulenZ.cpp - AdLib OPL2 FM synth based instrument
*
* Copyright (c) 2014 Raine M. Ekman <raine/at/iki/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.
*
*/
// TODO:
// - Better voice allocation: long releases get cut short :(
// - RT safety = get rid of mutex = make emulator code thread-safe
// - Extras:
// - double release: first release is in effect until noteoff (heard if percussive sound),
// second is switched in just before key bit cleared (is this useful???)
// - Unison: 2,3,4, or 9 voices with configurable spread?
// - Portamento (needs mono mode?)
// - Pre-bend/post-bend in poly mode could use portamento speed?
#include "OpulenZ.h"
#include "Instrument.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "InstrumentPlayHandle.h"
#include "InstrumentTrack.h"
#include <QFile>
#include <QFileInfo>
#include <QByteArray>
#include <cassert>
#include <cmath>
#include <opl.h>
#include <temuopl.h>
#include <mididata.h>
#include "embed.h"
#include "debug.h"
#include "Knob.h"
#include "PixmapButton.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT opulenz_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"OpulenZ",
QT_TRANSLATE_NOOP( "PluginBrowser",
"2-operator FM Synth" ),
"Raine M. Ekman <raine/at/iki/fi>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
"sbi",
nullptr,
};
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return( new OpulenzInstrument( static_cast<InstrumentTrack *>( m ) ) );
}
}
// I'd much rather do without a mutex, but it looks like
// the emulator code isn't really ready for threads
QMutex OpulenzInstrument::emulatorMutex;
// Weird ordering of voice parameters
const auto adlib_opadd = std::array<unsigned int, OPL2_VOICES>{0x00, 0x01, 0x02, 0x08, 0x09, 0x0A, 0x10, 0x11, 0x12};
OpulenzInstrument::OpulenzInstrument( InstrumentTrack * _instrument_track ) :
Instrument(_instrument_track, &opulenz_plugin_descriptor, nullptr, Flag::IsSingleStreamed | Flag::IsMidiBased),
m_patchModel( 0, 0, 127, this, tr( "Patch" ) ),
op1_a_mdl(14.0, 0.0, 15.0, 1.0, this, tr( "Op 1 attack" ) ),
op1_d_mdl(14.0, 0.0, 15.0, 1.0, this, tr( "Op 1 decay" ) ),
op1_s_mdl(3.0, 0.0, 15.0, 1.0, this, tr( "Op 1 sustain" ) ),
op1_r_mdl(10.0, 0.0, 15.0, 1.0, this, tr( "Op 1 release" ) ),
op1_lvl_mdl(62.0, 0.0, 63.0, 1.0, this, tr( "Op 1 level" ) ),
op1_scale_mdl(0.0, 0.0, 3.0, 1.0, this, tr( "Op 1 level scaling" ) ),
op1_mul_mdl(0.0, 0.0, 15.0, 1.0, this, tr( "Op 1 frequency multiplier" ) ),
feedback_mdl(0.0, 0.0, 7.0, 1.0, this, tr( "Op 1 feedback" ) ),
op1_ksr_mdl(false, this, tr( "Op 1 key scaling rate" ) ),
op1_perc_mdl(false, this, tr( "Op 1 percussive envelope" ) ),
op1_trem_mdl(true, this, tr( "Op 1 tremolo" ) ),
op1_vib_mdl(false, this, tr( "Op 1 vibrato" ) ),
op1_w0_mdl( ),
op1_w1_mdl( ),
op1_w2_mdl( ),
op1_w3_mdl( ),
op1_waveform_mdl(0,0,3,this, tr( "Op 1 waveform" ) ),
op2_a_mdl(1.0, 0.0, 15.0, 1.0, this, tr( "Op 2 attack" ) ),
op2_d_mdl(3.0, 0.0, 15.0, 1.0, this, tr( "Op 2 decay" ) ),
op2_s_mdl(14.0, 0.0, 15.0, 1.0, this, tr( "Op 2 sustain" ) ),
op2_r_mdl(12.0, 0.0, 15.0, 1.0, this, tr( "Op 2 release" ) ),
op2_lvl_mdl(63.0, 0.0, 63.0, 1.0, this, tr( "Op 2 level" ) ),
op2_scale_mdl(0.0, 0.0, 3.0, 1.0, this, tr( "Op 2 level scaling" ) ),
op2_mul_mdl(1.0, 0.0, 15.0, 1.0, this, tr( "Op 2 frequency multiplier" ) ),
op2_ksr_mdl(false, this, tr( "Op 2 key scaling rate" ) ),
op2_perc_mdl(false, this, tr( "Op 2 percussive envelope" ) ),
op2_trem_mdl(false, this, tr( "Op 2 tremolo" ) ),
op2_vib_mdl(true, this, tr( "Op 2 vibrato" ) ),
op2_w0_mdl( ),
op2_w1_mdl( ),
op2_w2_mdl( ),
op2_w3_mdl( ),
op2_waveform_mdl(0,0,3,this, tr( "Op 2 waveform" ) ),
fm_mdl(true, this, tr( "FM" ) ),
vib_depth_mdl(false, this, tr( "Vibrato depth" ) ),
trem_depth_mdl(false, this, tr( "Tremolo depth" ) )
{
// Create an emulator - samplerate, 16 bit, mono
emulatorMutex.lock();
theEmulator = new CTemuopl(Engine::audioEngine()->outputSampleRate(), true, false);
theEmulator->init();
// Enable waveform selection
theEmulator->write(0x01,0x20);
emulatorMutex.unlock();
//Initialize voice values
// voiceNote[0] = 0;
// voiceLRU[0] = 0;
for(int i=0; i<OPL2_VOICES; ++i) {
voiceNote[i] = OPL2_VOICE_FREE;
voiceLRU[i] = i;
}
storedname = displayName();
updatePatch();
// Can the buffer size change suddenly? I bet that would break lots of stuff
frameCount = Engine::audioEngine()->framesPerPeriod();
renderbuffer = new short[frameCount];
// Some kind of sane defaults
pitchbend = 0;
pitchBendRange = 100; // cents
RPNcoarse = RPNfine = 255;
tuneEqual(69, 440);
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ),
this, SLOT( reloadEmulator() ) );
// Connect knobs
// This one's for testing...
connect( &m_patchModel, SIGNAL( dataChanged() ), this, SLOT( loadGMPatch() ) );
#define MOD_CON( model ) connect( &model, SIGNAL( dataChanged() ), this, SLOT( updatePatch() ) );
MOD_CON( op1_a_mdl );
MOD_CON( op1_d_mdl );
MOD_CON( op1_s_mdl );
MOD_CON( op1_r_mdl );
MOD_CON( op1_lvl_mdl );
MOD_CON( op1_scale_mdl );
MOD_CON( op1_mul_mdl );
MOD_CON( feedback_mdl );
MOD_CON( op1_ksr_mdl );
MOD_CON( op1_perc_mdl );
MOD_CON( op1_trem_mdl );
MOD_CON( op1_vib_mdl );
MOD_CON( op1_w0_mdl );
MOD_CON( op1_w1_mdl );
MOD_CON( op1_w2_mdl );
MOD_CON( op1_w3_mdl );
MOD_CON( op1_waveform_mdl );
MOD_CON( op2_a_mdl );
MOD_CON( op2_d_mdl );
MOD_CON( op2_s_mdl );
MOD_CON( op2_r_mdl );
MOD_CON( op2_lvl_mdl );
MOD_CON( op2_scale_mdl );
MOD_CON( op2_mul_mdl );
MOD_CON( op2_ksr_mdl );
MOD_CON( op2_perc_mdl );
MOD_CON( op2_trem_mdl );
MOD_CON( op2_vib_mdl );
MOD_CON( op2_w0_mdl );
MOD_CON( op2_w1_mdl );
MOD_CON( op2_w2_mdl );
MOD_CON( op2_w3_mdl );
MOD_CON( op2_waveform_mdl );
MOD_CON( fm_mdl );
MOD_CON( vib_depth_mdl );
MOD_CON( trem_depth_mdl );
// Connect the plugin to the audio engine...
auto iph = new InstrumentPlayHandle(this, _instrument_track);
Engine::audioEngine()->addPlayHandle( iph );
}
OpulenzInstrument::~OpulenzInstrument() {
delete theEmulator;
Engine::audioEngine()->removePlayHandlesOfTypes( instrumentTrack(),
PlayHandle::Type::NotePlayHandle
| PlayHandle::Type::InstrumentPlayHandle );
delete [] renderbuffer;
}
// Samplerate changes when choosing oversampling, so this is more or less mandatory
void OpulenzInstrument::reloadEmulator() {
delete theEmulator;
emulatorMutex.lock();
theEmulator = new CTemuopl(Engine::audioEngine()->outputSampleRate(), true, false);
theEmulator->init();
theEmulator->write(0x01,0x20);
emulatorMutex.unlock();
for(int i=0; i<OPL2_VOICES; ++i) {
voiceNote[i] = OPL2_VOICE_FREE;
voiceLRU[i] = i;
}
updatePatch();
}
// This shall only be called from code protected by the holy Mutex!
void OpulenzInstrument::setVoiceVelocity(int voice, int vel) {
int vel_adjusted = !fm_mdl.value()
? 63 - (op1_lvl_mdl.value() * vel / 127.0)
: 63 - op1_lvl_mdl.value();
// Velocity calculation, some kind of approximation
// Only calculate for operator 1 if in adding mode, don't want to change timbre
theEmulator->write(0x40+adlib_opadd[voice],
( (int)op1_scale_mdl.value() & 0x03 << 6) +
( vel_adjusted & 0x3f ) );
vel_adjusted = 63 - ( op2_lvl_mdl.value() * vel/127.0 );
// vel_adjusted = 63 - op2_lvl_mdl.value();
theEmulator->write(0x43+adlib_opadd[voice],
( (int)op2_scale_mdl.value() & 0x03 << 6) +
( vel_adjusted & 0x3f ) );
}
// Pop least recently used voice
int OpulenzInstrument::popVoice() {
int tmp = voiceLRU[0];
for( int i=0; i<OPL2_VOICES-1; ++i) {
voiceLRU[i] = voiceLRU[i+1];
}
voiceLRU[OPL2_VOICES-1] = OPL2_NO_VOICE;
#ifdef false
printf("<-- %d %d %d %d %d %d %d %d %d \n", voiceLRU[0],voiceLRU[1],voiceLRU[2],
voiceLRU[3],voiceLRU[4],voiceLRU[5],voiceLRU[6],voiceLRU[7],voiceLRU[8]);
#endif
return tmp;
}
// Push voice into first free slot
int OpulenzInstrument::pushVoice(int v) {
int i;
assert(voiceLRU[OPL2_VOICES-1]==OPL2_NO_VOICE);
for(i=OPL2_VOICES-1; i>0; --i) {
if( voiceLRU[i-1] != OPL2_NO_VOICE ) {
break;
}
}
voiceLRU[i] = v;
#ifdef false
printf("%d %d %d %d %d %d %d %d %d <-- \n", voiceLRU[0],voiceLRU[1],voiceLRU[2],
voiceLRU[3],voiceLRU[4],voiceLRU[5],voiceLRU[6],voiceLRU[7],voiceLRU[8]);
#endif
return i;
}
bool OpulenzInstrument::handleMidiEvent( const MidiEvent& event, const TimePos& time, f_cnt_t offset )
{
emulatorMutex.lock();
int key = event.key();
int vel = event.velocity();
switch (event.type())
{
case MidiNoteOn:
if (int voice = popVoice(); voice != OPL2_NO_VOICE)
{
// Turn voice on, NB! the frequencies are straight by voice number,
// not by the adlib_opadd table!
theEmulator->write(0xA0 + voice, fnums[key] & 0xff);
theEmulator->write(0xB0 + voice, 32 + ((fnums[key] & 0x1f00) >> 8));
setVoiceVelocity(voice, vel);
voiceNote[voice] = key;
velocities[key] = vel;
}
break;
case MidiNoteOff:
for (int voice = 0; voice < OPL2_VOICES; ++voice)
{
if (voiceNote[voice] == key)
{
theEmulator->write(0xA0 + voice, fnums[key] & 0xff);
theEmulator->write(0xB0 + voice, (fnums[key] & 0x1f00) >> 8);
voiceNote[voice] |= OPL2_VOICE_FREE;
pushVoice(voice);
}
}
velocities[key] = 0;
break;
case MidiKeyPressure:
if (velocities[key] != 0) { velocities[key] = vel; }
for (int voice = 0; voice < OPL2_VOICES; ++voice)
{
if (voiceNote[voice] == key) { setVoiceVelocity(voice, vel); }
}
break;
case MidiPitchBend:
// Update fnumber table
// Neutral = 8192, full downbend = 0, full upbend = 16383
if (int tmp_pb = (event.pitchBend() - 8192) * pitchBendRange / 8192; tmp_pb != pitchbend)
{
pitchbend = tmp_pb;
tuneEqual(69, 440.0);
}
// Update pitch of all voices (also released ones)
for (int v = 0; v < OPL2_VOICES; ++v)
{
int vn = (voiceNote[v] & ~OPL2_VOICE_FREE); // remove the flag bit
int playing = (voiceNote[v] & OPL2_VOICE_FREE) == 0; // just the flag bit
theEmulator->write(0xA0 + v, fnums[vn] & 0xff);
theEmulator->write(0xB0 + v, (playing ? 32 : 0) + ((fnums[vn] & 0x1f00) >> 8));
}
break;
case MidiControlChange:
switch (event.controllerNumber()) {
case MidiControllerRegisteredParameterNumberLSB:
RPNfine = event.controllerValue();
break;
case MidiControllerRegisteredParameterNumberMSB:
RPNcoarse = event.controllerValue();
break;
case MidiControllerDataEntry:
if( (RPNcoarse << 8) + RPNfine == MidiPitchBendSensitivityRPN) {
pitchBendRange = event.controllerValue() * 100;
}
break;
default:
#ifdef LMMS_DEBUG
printf("Midi CC %02x %02x\n", event.controllerNumber(), event.controllerValue() );
#endif
break;
}
break;
default:
#ifdef LMMS_DEBUG
printf("Midi event type %d\n",event.type());
#endif
break;
}
emulatorMutex.unlock();
return true;
}
QString OpulenzInstrument::nodeName() const
{
return( opulenz_plugin_descriptor.name );
}
gui::PluginView* OpulenzInstrument::instantiateView( QWidget * _parent )
{
return( new gui::OpulenzInstrumentView( this, _parent ) );
}
void OpulenzInstrument::play( SampleFrame* _working_buffer )
{
emulatorMutex.lock();
theEmulator->update(renderbuffer, frameCount);
for( fpp_t frame = 0; frame < frameCount; ++frame )
{
sample_t s = float(renderbuffer[frame]) / 8192.0;
for( ch_cnt_t ch = 0; ch < DEFAULT_CHANNELS; ++ch )
{
_working_buffer[frame][ch] = s;
}
}
emulatorMutex.unlock();
}
void OpulenzInstrument::saveSettings( QDomDocument & _doc, QDomElement & _this )
{
op1_a_mdl.saveSettings( _doc, _this, "op1_a" );
op1_d_mdl.saveSettings( _doc, _this, "op1_d" );
op1_s_mdl.saveSettings( _doc, _this, "op1_s" );
op1_r_mdl.saveSettings( _doc, _this, "op1_r" );
op1_lvl_mdl.saveSettings( _doc, _this, "op1_lvl" );
op1_scale_mdl.saveSettings( _doc, _this, "op1_scale" );
op1_mul_mdl.saveSettings( _doc, _this, "op1_mul" );
feedback_mdl.saveSettings( _doc, _this, "feedback" );
op1_ksr_mdl.saveSettings( _doc, _this, "op1_ksr" );
op1_perc_mdl.saveSettings( _doc, _this, "op1_perc" );
op1_trem_mdl.saveSettings( _doc, _this, "op1_trem" );
op1_vib_mdl.saveSettings( _doc, _this, "op1_vib" );
op1_waveform_mdl.saveSettings( _doc, _this, "op1_waveform" );
op2_a_mdl.saveSettings( _doc, _this, "op2_a" );
op2_d_mdl.saveSettings( _doc, _this, "op2_d" );
op2_s_mdl.saveSettings( _doc, _this, "op2_s" );
op2_r_mdl.saveSettings( _doc, _this, "op2_r" );
op2_lvl_mdl.saveSettings( _doc, _this, "op2_lvl" );
op2_scale_mdl.saveSettings( _doc, _this, "op2_scale" );
op2_mul_mdl.saveSettings( _doc, _this, "op2_mul" );
op2_ksr_mdl.saveSettings( _doc, _this, "op2_ksr" );
op2_perc_mdl.saveSettings( _doc, _this, "op2_perc" );
op2_trem_mdl.saveSettings( _doc, _this, "op2_trem" );
op2_vib_mdl.saveSettings( _doc, _this, "op2_vib" );
op2_waveform_mdl.saveSettings( _doc, _this, "op2_waveform" );
fm_mdl.saveSettings( _doc, _this, "fm" );
vib_depth_mdl.saveSettings( _doc, _this, "vib_depth" );
trem_depth_mdl.saveSettings( _doc, _this, "trem_depth" );
}
void OpulenzInstrument::loadSettings( const QDomElement & _this )
{
op1_a_mdl.loadSettings( _this, "op1_a" );
op1_d_mdl.loadSettings( _this, "op1_d" );
op1_s_mdl.loadSettings( _this, "op1_s" );
op1_r_mdl.loadSettings( _this, "op1_r" );
op1_lvl_mdl.loadSettings( _this, "op1_lvl" );
op1_scale_mdl.loadSettings( _this, "op1_scale" );
op1_mul_mdl.loadSettings( _this, "op1_mul" );
feedback_mdl.loadSettings( _this, "feedback" );
op1_ksr_mdl.loadSettings( _this, "op1_ksr" );
op1_perc_mdl.loadSettings( _this, "op1_perc" );
op1_trem_mdl.loadSettings( _this, "op1_trem" );
op1_vib_mdl.loadSettings( _this, "op1_vib" );
op1_waveform_mdl.loadSettings( _this, "op1_waveform" );
op2_a_mdl.loadSettings( _this, "op2_a" );
op2_d_mdl.loadSettings( _this, "op2_d" );
op2_s_mdl.loadSettings( _this, "op2_s" );
op2_r_mdl.loadSettings( _this, "op2_r" );
op2_lvl_mdl.loadSettings( _this, "op2_lvl" );
op2_scale_mdl.loadSettings( _this, "op2_scale" );
op2_mul_mdl.loadSettings( _this, "op2_mul" );
op2_ksr_mdl.loadSettings( _this, "op2_ksr" );
op2_perc_mdl.loadSettings( _this, "op2_perc" );
op2_trem_mdl.loadSettings( _this, "op2_trem" );
op2_vib_mdl.loadSettings( _this, "op2_vib" );
op2_waveform_mdl.loadSettings( _this, "op2_waveform" );
fm_mdl.loadSettings( _this, "fm" );
vib_depth_mdl.loadSettings( _this, "vib_depth" );
trem_depth_mdl.loadSettings( _this, "trem_depth" );
}
// Load a patch into the emulator
void OpulenzInstrument::loadPatch(const unsigned char inst[14]) {
emulatorMutex.lock();
for(int v=0; v<OPL2_VOICES; ++v) {
theEmulator->write(0x20+adlib_opadd[v],inst[0]); // op1 AM/VIB/EG/KSR/Multiplier
theEmulator->write(0x23+adlib_opadd[v],inst[1]); // op2
// theEmulator->write(0x40+adlib_opadd[v],inst[2]); // op1 KSL/Output Level - these are handled by noteon/aftertouch code
// theEmulator->write(0x43+adlib_opadd[v],inst[3]); // op2
theEmulator->write(0x60+adlib_opadd[v],inst[4]); // op1 A/D
theEmulator->write(0x63+adlib_opadd[v],inst[5]); // op2
theEmulator->write(0x80+adlib_opadd[v],inst[6]); // op1 S/R
theEmulator->write(0x83+adlib_opadd[v],inst[7]); // op2
theEmulator->write(0xe0+adlib_opadd[v],inst[8]); // op1 waveform
theEmulator->write(0xe3+adlib_opadd[v],inst[9]); // op2
theEmulator->write(0xc0+v,inst[10]); // feedback/algorithm
}
emulatorMutex.unlock();
}
void OpulenzInstrument::tuneEqual(int center, float Hz) {
for(int n=0; n<128; ++n) {
float tmp = Hz * pow(2.0, (n - center) * (1.0 / 12.0) + pitchbend * (1.0 / 1200.0));
fnums[n] = Hz2fnum( tmp );
}
}
// Find suitable F number in lowest possible block
int OpulenzInstrument::Hz2fnum(float Hz) {
for(int block=0; block<8; ++block) {
unsigned int fnum = Hz * pow( 2.0, 20.0 - (double)block ) * ( 1.0 / 49716.0 );
if(fnum<1023) {
return fnum + (block << 10);
}
}
return 0;
}
// Load one of the default patches
void OpulenzInstrument::loadGMPatch() {
unsigned char *inst = midi_fm_instruments[m_patchModel.value()];
loadPatch(inst);
}
// Update patch from the models to the chip emulation
void OpulenzInstrument::updatePatch() {
auto inst = std::array<unsigned char, 14>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
inst[0] = ( op1_trem_mdl.value() ? 128 : 0 ) +
( op1_vib_mdl.value() ? 64 : 0 ) +
( op1_perc_mdl.value() ? 0 : 32 ) + // NB. This envelope mode is "perc", not "sus"
( op1_ksr_mdl.value() ? 16 : 0 ) +
((int)op1_mul_mdl.value() & 0x0f);
inst[1] = ( op2_trem_mdl.value() ? 128 : 0 ) +
( op2_vib_mdl.value() ? 64 : 0 ) +
( op2_perc_mdl.value() ? 0 : 32 ) + // NB. This envelope mode is "perc", not "sus"
( op2_ksr_mdl.value() ? 16 : 0 ) +
((int)op2_mul_mdl.value() & 0x0f);
inst[2] = ( ((int)op1_scale_mdl.value() & 0x03) << 6 ) +
(63 - ( (int)op1_lvl_mdl.value() & 0x3f ) );
inst[3] = ( ((int)op2_scale_mdl.value() & 0x03) << 6 ) +
(63 - ( (int)op2_lvl_mdl.value() & 0x3f ) );
inst[4] = ((15 - ((int)op1_a_mdl.value() & 0x0f ) ) << 4 )+
(15 - ( (int)op1_d_mdl.value() & 0x0f ) );
inst[5] = ((15 - ( (int)op2_a_mdl.value() & 0x0f ) ) << 4 )+
(15 - ( (int)op2_d_mdl.value() & 0x0f ) );
inst[6] = ((15 - ( (int)op1_s_mdl.value() & 0x0f ) ) << 4 ) +
(15 - ( (int)op1_r_mdl.value() & 0x0f ) );
inst[7] = ((15 - ( (int)op2_s_mdl.value() & 0x0f ) ) << 4 ) +
(15 - ( (int)op2_r_mdl.value() & 0x0f ) );
inst[8] = (int)op1_waveform_mdl.value() & 0x03;
inst[9] = (int)op2_waveform_mdl.value() & 0x03;
inst[10] = (fm_mdl.value() ? 0 : 1 ) +
(((int)feedback_mdl.value() & 0x07 )<< 1);
// These are always 0 in the list I had?
inst[11] = 0;
inst[12] = 0;
inst[13] = 0;
// Not part of the per-voice patch info
theEmulator->write(0xBD, (trem_depth_mdl.value() ? 128 : 0 ) +
(vib_depth_mdl.value() ? 64 : 0 ));
// have to do this, as the level knobs might've changed
for( int voice = 0; voice < OPL2_VOICES ; ++voice) {
if(voiceNote[voice] && OPL2_VOICE_FREE == 0) {
setVoiceVelocity(voice, velocities[voiceNote[voice]] );
}
}
#ifdef false
printf("UPD: %02x %02x %02x %02x %02x -- %02x %02x %02x %02x %02x %02x\n",
inst[0], inst[1], inst[2], inst[3], inst[4],
inst[5], inst[6], inst[7], inst[8], inst[9], inst[10]);
#endif
loadPatch(inst.data());
}
// Load an SBI file into the knob models
void OpulenzInstrument::loadFile( const QString& file ) {
// http://cd.textfiles.com/soundsensations/SYNTH/SBINS/
// http://cd.textfiles.com/soundsensations/SYNTH/SBI1198/1198SBI.ZIP
if( !file.isEmpty() && QFileInfo( file ).exists() )
{
QFile sbifile(file);
if (!sbifile.open(QIODevice::ReadOnly )) {
printf("Can't open file\n");
return;
}
QByteArray sbidata = sbifile.read(52);
if( !sbidata.startsWith("SBI\0x1a") ) {
printf("No SBI signature\n");
return;
}
if( sbidata.size() != 52 ) {
printf("SBI size error: expected 52, got %d\n",sbidata.size() );
}
// Minimum size of SBI if we ignore "reserved" bytes at end
// https://courses.engr.illinois.edu/ece390/resources/sound/cmf.txt.html
if( sbidata.size() < 47 ) {
return;
}
QString sbiname = sbidata.mid(4, 32);
// If user has changed track name... let's hope my logic is valid.
if( sbiname.size() > 0 && instrumentTrack()->displayName() == storedname ) {
instrumentTrack()->setName(sbiname);
storedname = sbiname;
}
#ifdef false
printf("SBI: %02x %02x %02x %02x %02x -- %02x %02x %02x %02x %02x %02x\n",
(unsigned char)sbidata[36], (unsigned char)sbidata[37], (unsigned char)sbidata[38], (unsigned char)sbidata[39], (unsigned char)sbidata[40],
(unsigned char)sbidata[41], (unsigned char)sbidata[42], (unsigned char)sbidata[43], (unsigned char)sbidata[44], (unsigned char)sbidata[45], (unsigned char)sbidata[46]);
#endif
// Modulator Sound Characteristic (Mult, KSR, EG, VIB, AM)
op1_trem_mdl.setValue( (sbidata[36] & 0x80 ) == 0x80 ? true : false );
op1_vib_mdl.setValue( (sbidata[36] & 0x40 ) == 0x40 ? true : false );
op1_perc_mdl.setValue( (sbidata[36] & 0x20 ) == 0x20 ? false : true );
op1_ksr_mdl.setValue( (sbidata[36] & 0x10 ) == 0x10 ? true : false );
op1_mul_mdl.setValue( sbidata[36] & 0x0f );
// Carrier Sound Characteristic
op2_trem_mdl.setValue( (sbidata[37] & 0x80 ) == 0x80 ? true : false );
op2_vib_mdl.setValue( (sbidata[37] & 0x40 ) == 0x40 ? true : false );
op2_perc_mdl.setValue( (sbidata[37] & 0x20 ) == 0x20 ? false : true );
op2_ksr_mdl.setValue( (sbidata[37] & 0x10 ) == 0x10 ? true : false );
op2_mul_mdl.setValue( sbidata[37] & 0x0f );
// Modulator Scaling/Output Level
op1_scale_mdl.setValue( (sbidata[38] & 0xc0 ) >> 6 );
op1_lvl_mdl.setValue( 63 - (sbidata[38] & 0x3f) );
// Carrier Scaling/Output Level
op2_scale_mdl.setValue( (sbidata[39] & 0xc0) >> 6 );
op2_lvl_mdl.setValue( 63 - (sbidata[39] & 0x3f) );
// Modulator Attack/Decay
op1_a_mdl.setValue( 15 - ( ( sbidata[40] & 0xf0 ) >> 4 ) );
op1_d_mdl.setValue( 15 - ( sbidata[40] & 0x0f ) );
// Carrier Attack/Decay
op2_a_mdl.setValue( 15 - ( ( sbidata[41] & 0xf0 ) >> 4 ) );
op2_d_mdl.setValue( 15 - ( sbidata[41] & 0x0f ) );
// Modulator Sustain/Release
op1_s_mdl.setValue( 15 - ( ( sbidata[42] & 0xf0 ) >> 4 ) );
op1_r_mdl.setValue( 15 - ( sbidata[42] & 0x0f ) );
// Carrier Sustain/Release
op2_s_mdl.setValue( 15 - ( ( sbidata[43] & 0xf0 ) >> 4 ) );
op2_r_mdl.setValue( 15 - ( sbidata[43] & 0x0f ) );
// Modulator Wave Select
op1_waveform_mdl.setValue( sbidata[44] & 0x03 );
// Carrier Wave Select
op2_waveform_mdl.setValue( sbidata[45] & 0x03 );
// Feedback/Connection
fm_mdl.setValue( (sbidata[46] & 0x01) == 0x01 ? false : true );
feedback_mdl.setValue( ( (sbidata[46] & 0x0e ) >> 1 ) );
}
}
namespace gui
{
OpulenzInstrumentView::OpulenzInstrumentView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
#define KNOB_GEN(knobname, hinttext, hintunit,xpos,ypos) \
knobname = new Knob( KnobType::Styled, this );\
knobname->setHintText( tr(hinttext), hintunit );\
knobname->setFixedSize(22,22);\
knobname->setCenterPointX(11.0);\
knobname->setCenterPointY(11.0);\
knobname->setTotalAngle(270.0);\
knobname->move(xpos,ypos);
#define BUTTON_GEN(buttname, tooltip, xpos, ypos) \
buttname = new PixmapButton( this, nullptr );\
buttname->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "led_on" ) );\
buttname->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "led_off" ) );\
buttname->setCheckable( true );\
buttname->setToolTip(tr(tooltip));\
buttname->move( xpos, ypos );
#define WAVEBUTTON_GEN(buttname, tooltip, xpos, ypos, icon_on, icon_off, buttgroup) \
buttname = new PixmapButton( this, nullptr );\
buttname->setActiveGraphic( PLUGIN_NAME::getIconPixmap( icon_on ) ); \
buttname->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( icon_off ) ); \
buttname->setToolTip(tr(tooltip));\
buttname->move( xpos, ypos );\
buttgroup->addButton(buttname);
// OP1 knobs & buttons...
KNOB_GEN(op1_a_kn, "Attack", "", 6, 48);
KNOB_GEN(op1_d_kn, "Decay", "", 34, 48);
KNOB_GEN(op1_s_kn, "Sustain", "", 62, 48);
KNOB_GEN(op1_r_kn, "Release", "", 90, 48);
KNOB_GEN(op1_lvl_kn, "Level", "", 166, 48);
KNOB_GEN(op1_scale_kn, "Scale", "", 194, 48);
KNOB_GEN(op1_mul_kn, "Frequency multiplier", "", 222, 48);
BUTTON_GEN(op1_ksr_btn, "Keyboard scaling rate", 9, 87);
BUTTON_GEN(op1_perc_btn, "Percussive envelope", 36, 87);
BUTTON_GEN(op1_trem_btn, "Tremolo", 65, 87);
BUTTON_GEN(op1_vib_btn, "Vibrato", 93, 87);
KNOB_GEN(feedback_kn, "Feedback", "", 128, 48);
op1_waveform = new automatableButtonGroup( this );
WAVEBUTTON_GEN(op1_w0_btn,"Sine", 154, 86, "wave1_on", "wave1_off", op1_waveform);
WAVEBUTTON_GEN(op1_w1_btn,"Half sine", 178, 86, "wave2_on", "wave2_off", op1_waveform);
WAVEBUTTON_GEN(op1_w2_btn,"Absolute sine", 199, 86, "wave3_on", "wave3_off", op1_waveform);
WAVEBUTTON_GEN(op1_w3_btn,"Quarter sine", 220, 86, "wave4_on", "wave4_off", op1_waveform);
// And the same for OP2
KNOB_GEN(op2_a_kn, "Attack", "", 6, 138);
KNOB_GEN(op2_d_kn, "Decay", "", 34, 138);
KNOB_GEN(op2_s_kn, "Sustain", "", 62, 138);
KNOB_GEN(op2_r_kn, "Release", "", 90, 138);
KNOB_GEN(op2_lvl_kn, "Level", "", 166, 138);
KNOB_GEN(op2_scale_kn, "Scale", "", 194, 138);
KNOB_GEN(op2_mul_kn, "Frequency multiplier", "", 222, 138);
BUTTON_GEN(op2_ksr_btn, "Keyboard scaling rate", 9, 177);
BUTTON_GEN(op2_perc_btn, "Percussive envelope", 36, 177);
BUTTON_GEN(op2_trem_btn, "Tremolo", 65, 177);
BUTTON_GEN(op2_vib_btn, "Vibrato", 93, 177);
op2_waveform = new automatableButtonGroup( this );
WAVEBUTTON_GEN(op2_w0_btn,"Sine", 154, 176, "wave1_on", "wave1_off", op2_waveform);
WAVEBUTTON_GEN(op2_w1_btn,"Half sine", 178, 176, "wave2_on", "wave2_off", op2_waveform);
WAVEBUTTON_GEN(op2_w2_btn,"Absolute sine", 199, 176, "wave3_on", "wave3_off", op2_waveform);
WAVEBUTTON_GEN(op2_w3_btn,"Quarter Sine", 220, 176, "wave4_on", "wave4_off", op2_waveform);
BUTTON_GEN(fm_btn, "FM", 9, 220);
BUTTON_GEN(vib_depth_btn, "Vibrato depth", 65, 220);
BUTTON_GEN(trem_depth_btn, "Tremolo depth", 93, 220);
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap(
"artwork" ) );
setPalette( pal );
}
OpulenzInstrumentView::~OpulenzInstrumentView() {
// Knobs are QWidgets and our children, so they're
// destroyed automagically
}
// Returns text for time knob formatted nicely
inline QString OpulenzInstrumentView::knobHintHelper(float n) {
if(n>1000) {
return QString::number(n/1000, 'f', 0)+ " s";
} else if(n>10) {
return QString::number(n, 'f', 0)+ " ms";
} else {
return QString::number(n, 'f', 1)+ " ms";
}
}
void OpulenzInstrumentView::updateKnobHints()
{
// Envelope times in ms: t[0] = 0, t[n] = ( 1<<n ) * X, X = 0.11597 for A, 0.6311 for D/R
// Here some rounding has been applied.
const auto attack_times = std::array<float, 16>{
0.f, 0.2f, 0.4f, 0.9f, 1.8f, 3.7f, 7.4f,
15.f, 30.f, 60.f, 120.f, 240.f, 480.f,
950.f, 1900.f, 3800.f
};
const auto dr_times = std::array<float, 16>{
0.f, 1.2f, 2.5f, 5.f, 10.f, 20.f, 40.f,
80.f, 160.f, 320.f, 640.f, 1300.f, 2600.f,
5200.f, 10000.f, 20000.f
};
const auto fmultipliers = std::array<int, 16>{
-12, 0, 12, 19, 24, 28, 31, 34, 36, 38, 40, 40, 43, 43, 47, 47
};
auto m = castModel<OpulenzInstrument>();
op1_a_kn->setHintText( tr( "Attack" ),
" (" + knobHintHelper(attack_times[(int)m->op1_a_mdl.value()]) + ")");
op2_a_kn->setHintText( tr( "Attack" ),
" (" + knobHintHelper(attack_times[(int)m->op2_a_mdl.value()]) + ")");
op1_d_kn->setHintText( tr( "Decay" ),
" (" + knobHintHelper(dr_times[(int)m->op1_d_mdl.value()]) + ")");
op2_d_kn->setHintText( tr( "Decay" ),
" (" + knobHintHelper(dr_times[(int)m->op2_d_mdl.value()]) + ")");
op1_r_kn->setHintText( tr( "Release" ),
" (" + knobHintHelper(dr_times[(int)m->op1_r_mdl.value()]) + ")");
op2_r_kn->setHintText( tr( "Release" ),
" (" + knobHintHelper(dr_times[(int)m->op2_r_mdl.value()]) + ")");
op1_mul_kn->setHintText( tr( "Frequency multiplier" ),
" (" + QString::number(fmultipliers[(int)m->op1_mul_mdl.value()]) + " semitones)");
op2_mul_kn->setHintText( tr( "Frequency multiplier" ),
" (" + QString::number(fmultipliers[(int)m->op2_mul_mdl.value()]) + " semitones)");
}
void OpulenzInstrumentView::modelChanged()
{
auto m = castModel<OpulenzInstrument>();
// m_patch->setModel( &m->m_patchModel );
op1_a_kn->setModel( &m->op1_a_mdl );
op1_d_kn->setModel( &m->op1_d_mdl );
op1_s_kn->setModel( &m->op1_s_mdl );
op1_r_kn->setModel( &m->op1_r_mdl );
op1_lvl_kn->setModel( &m->op1_lvl_mdl );
op1_scale_kn->setModel( &m->op1_scale_mdl );
op1_mul_kn->setModel( &m->op1_mul_mdl );
feedback_kn->setModel( &m->feedback_mdl );
op1_ksr_btn->setModel( &m->op1_ksr_mdl );
op1_perc_btn->setModel( &m->op1_perc_mdl );
op1_trem_btn->setModel( &m->op1_trem_mdl );
op1_vib_btn->setModel( &m->op1_vib_mdl );
op1_waveform->setModel( &m->op1_waveform_mdl );
op2_a_kn->setModel( &m->op2_a_mdl );
op2_d_kn->setModel( &m->op2_d_mdl );
op2_s_kn->setModel( &m->op2_s_mdl );
op2_r_kn->setModel( &m->op2_r_mdl );
op2_lvl_kn->setModel( &m->op2_lvl_mdl );
op2_scale_kn->setModel( &m->op2_scale_mdl );
op2_mul_kn->setModel( &m->op2_mul_mdl );
op2_ksr_btn->setModel( &m->op2_ksr_mdl );
op2_perc_btn->setModel( &m->op2_perc_mdl );
op2_trem_btn->setModel( &m->op2_trem_mdl );
op2_vib_btn->setModel( &m->op2_vib_mdl );
op2_waveform->setModel( &m->op2_waveform_mdl );
fm_btn->setModel( &m->fm_mdl );
vib_depth_btn->setModel( &m->vib_depth_mdl );
trem_depth_btn->setModel( &m->trem_depth_mdl );
// All knobs needing a user friendly unit
connect( &m->op1_a_mdl, SIGNAL( dataChanged() ), this, SLOT( updateKnobHints() ) );
connect( &m->op2_a_mdl, SIGNAL( dataChanged() ), this, SLOT( updateKnobHints() ) );
connect( &m->op1_d_mdl, SIGNAL( dataChanged() ), this, SLOT( updateKnobHints() ) );
connect( &m->op2_d_mdl, SIGNAL( dataChanged() ), this, SLOT( updateKnobHints() ) );
connect( &m->op1_r_mdl, SIGNAL( dataChanged() ), this, SLOT( updateKnobHints() ) );
connect( &m->op2_r_mdl, SIGNAL( dataChanged() ), this, SLOT( updateKnobHints() ) );
connect( &m->op1_mul_mdl, SIGNAL( dataChanged() ), this, SLOT( updateKnobHints() ) );
connect( &m->op2_mul_mdl, SIGNAL( dataChanged() ), this, SLOT( updateKnobHints() ) );
updateKnobHints();
}
} // namespace gui
} // namespace lmms
| 30,703
|
C++
|
.cpp
| 752
| 37.828457
| 177
| 0.652411
|
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,608
|
EqParameterWidget.cpp
|
LMMS_lmms/plugins/Eq/EqParameterWidget.cpp
|
/*
* eqparameterwidget.cpp - defination of EqParameterWidget class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
* Copyright (c) 2015 Steffen Baranowsky <BaraMGB/at/freenet/dot/de>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "EqParameterWidget.h"
#include <cmath>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPainter>
#include <QPen>
#include <QWidget>
#include "AutomatableModel.h"
#include "EqCurve.h"
#include "EqParameterWidget.h"
#include "lmms_constants.h"
namespace lmms::gui
{
EqParameterWidget::EqParameterWidget( QWidget *parent, EqControls * controls ) :
QWidget( parent ),
m_displayWidth ( 450 ),
m_displayHeigth ( 200 ),
m_controls ( controls )
{
m_bands = new EqBand[8];
resize( m_displayWidth, m_displayHeigth );
float totalHeight = 36; // gain range from -18 to +18
m_pixelsPerUnitHeight = m_displayHeigth / totalHeight;
m_pixelsPerOctave = EqHandle::freqToXPixel( 10000, m_displayWidth ) - EqHandle::freqToXPixel( 5000, m_displayWidth );
//GraphicsScene and GraphicsView stuff
auto scene = new QGraphicsScene(this);
scene->setSceneRect( 0, 0, m_displayWidth, m_displayHeigth );
auto view = new QGraphicsView(this);
view->setStyleSheet( "border-style: none; background: transparent;" );
view->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
view->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
view->setScene( scene );
//adds the handles
m_handleList.reserve(bandCount());
for ( int i = 0; i < bandCount(); i++ )
{
m_handle = new EqHandle ( i, m_displayWidth, m_displayHeigth );
m_handleList.append(m_handle);
m_handle->setZValue( 1 );
scene->addItem( m_handle );
}
//adds the curve widget
m_eqcurve = new EqCurve(&m_handleList, m_displayWidth, m_displayHeigth);
scene->addItem( m_eqcurve );
for ( int i = 0; i < bandCount(); i++ )
{
// if the data of handle position has changed update the models
QObject::connect(m_handleList.at(i), SIGNAL(positionChanged()), this, SLOT(updateModels()));
}
}
EqParameterWidget::~EqParameterWidget()
{
if( m_bands )
{
delete[] m_bands;
m_bands = 0;
}
}
EqBand *EqParameterWidget::getBandModels( int i )
{
return &m_bands[i];
}
void EqParameterWidget::updateHandle()
{
m_eqcurve->setModelChanged( true );
for( int i = 0 ; i < bandCount(); i++ )
{
if (!m_handleList.at(i)->mousePressed()) // prevents a short circuit between handle and data model
{
//sets the band on active if a fader or a knob is moved
bool hover = false; // prevents an action if handle is moved
for ( int j = 0; j < bandCount(); j++ )
{
if (m_handleList.at(j)->isMouseHover()) { hover = true; }
}
if ( !hover )
{
if ( sender() == m_bands[i].gain ) m_bands[i].active->setValue( true );
if ( sender() == m_bands[i].freq ) m_bands[i].active->setValue( true );
if ( sender() == m_bands[i].res ) m_bands[i].active->setValue( true );
}
changeHandle( i );
}
else { m_handleList.at(i)->setHandleActive(m_bands[i].active->value()); }
}
if (m_bands[0].hp12->value()) m_handleList.at(0)->sethp12();
if (m_bands[0].hp24->value()) m_handleList.at(0)->sethp24();
if (m_bands[0].hp48->value()) m_handleList.at(0)->sethp48();
if (m_bands[7].lp12->value()) m_handleList.at(7)->setlp12();
if (m_bands[7].lp24->value()) m_handleList.at(7)->setlp24();
if (m_bands[7].lp48->value()) m_handleList.at(7)->setlp48();
}
void EqParameterWidget::changeHandle( int i )
{
//fill x, y, and bw with data from model
float x = EqHandle::freqToXPixel( m_bands[i].freq->value(), m_displayWidth );
float y = m_handleList.at(i)->y();
//for pass filters there is no gain model
if( m_bands[i].gain )
{
float gain = m_bands[i].gain->value();
y = EqHandle::gainToYPixel( gain, m_displayHeigth, m_pixelsPerUnitHeight );
}
float bw = m_bands[i].res->value();
// set the handle position, filter type for each handle
switch ( i )
{
case 0 :
m_handleList.at(i)->setType(EqHandleType::HighPass);
m_handleList.at(i)->setPos(x, m_displayHeigth / 2);
break;
case 1:
m_handleList.at(i)->setType(EqHandleType::LowShelf);
m_handleList.at(i)->setPos(x, y);
break;
case 2:
m_handleList.at(i)->setType(EqHandleType::Para);
m_handleList.at(i)->setPos(x, y);
break;
case 3:
m_handleList.at(i)->setType(EqHandleType::Para);
m_handleList.at(i)->setPos(x, y);
break;
case 4:
m_handleList.at(i)->setType(EqHandleType::Para);
m_handleList.at(i)->setPos(x, y);
break;
case 5:
m_handleList.at(i)->setType(EqHandleType::Para);
m_handleList.at(i)->setPos(x, y);
break;
case 6:
m_handleList.at(i)->setType(EqHandleType::HighShelf);
m_handleList.at(i)->setPos(x, y);
break;
case 7:
m_handleList.at(i)->setType(EqHandleType::LowPass);
m_handleList.at(i)->setPos(QPointF(x, m_displayHeigth / 2));
break;
}
// set resonance/bandwidth for each handle
if (m_handleList.at(i)->getResonance() != bw) { m_handleList.at(i)->setResonance(bw); }
// and the active status
m_handleList.at(i)->setHandleActive(m_bands[i].active->value());
m_handleList.at(i)->update();
m_eqcurve->update();
}
//this is called if a handle is moved
void EqParameterWidget::updateModels()
{
for ( int i=0 ; i < bandCount(); i++ )
{
m_bands[i].freq->setValue(EqHandle::xPixelToFreq(m_handleList.at(i)->x(), m_displayWidth));
if( m_bands[i].gain )
{
m_bands[i].gain->setValue(
EqHandle::yPixelToGain(m_handleList.at(i)->y(), m_displayHeigth, m_pixelsPerUnitHeight));
}
m_bands[i].res->setValue(m_handleList.at(i)->getResonance());
//identifies the handle which is moved and set the band active
if (sender() == m_handleList.at(i)) { m_bands[i].active->setValue(true); }
}
m_eqcurve->update();
}
EqBand::EqBand() :
gain ( 0 ),
res ( 0 ),
freq ( 0 ),
color ( QColor( 255, 255, 255 ) ),
x( 0 ),
y( 0 ),
name ( QString( "" ) ),
peakL( 0 ),
peakR( 0 )
{
}
} // namespace lmms::gui
| 6,678
|
C++
|
.cpp
| 201
| 30.810945
| 118
| 0.698462
|
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,609
|
EqControls.cpp
|
LMMS_lmms/plugins/Eq/EqControls.cpp
|
/*
* eqcontrols.cpp - defination of EqControls class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "EqControls.h"
#include <QDomElement>
#include "EqControlsDialog.h"
#include "EqEffect.h"
namespace lmms
{
EqControls::EqControls( EqEffect *effect ) :
EffectControls( effect ),
m_effect( effect ),
m_inGainModel(0.f, -60.f, 20.f, 0.01f, this, tr("Input gain")),
m_outGainModel(-0.f, -60.f, 20.f, 0.01f, this, tr("Output gain")),
m_lowShelfGainModel( 0.f, -18, 18, 0.001f, this, tr("Low-shelf gain")),
m_para1GainModel(0.f, -18, 18, 0.001f, this, tr("Peak 1 gain")),
m_para2GainModel(0.f, -18, 18, 0.001f, this, tr("Peak 2 gain")),
m_para3GainModel(0.f, -18, 18, 0.001f, this, tr("Peak 3 gain")),
m_para4GainModel(0.f, -18, 18, 0.001f, this, tr("Peak 4 gain")),
m_highShelfGainModel(0.f, -18, 18, 0.001f, this, tr("High-shelf gain")),
m_hpResModel(0.707f,0.003f, 10.f, 0.001f, this, tr("HP res")),
m_lowShelfResModel(0.707f, 0.55f, 10.f, 0.001f, this, tr("Low-shelf res")),
m_para1BwModel(0.3f, 0.1f, 4, 0.001f, this, tr("Peak 1 BW")),
m_para2BwModel(0.3f, 0.1f, 4, 0.001f, this, tr("Peak 2 BW")),
m_para3BwModel(0.3f, 0.1f, 4, 0.001f, this, tr("Peak 3 BW")),
m_para4BwModel(0.3f, 0.1f, 4, 0.001f, this, tr("Peak 4 BW")),
m_highShelfResModel(0.707f, 0.55f, 10.f, 0.001f, this, tr("High-shelf res")),
m_lpResModel(0.707f,0.003f, 10.f, 0.001f, this, tr("LP res")),
m_hpFeqModel(31.f, 20.f, 20000, 0.001f, this, tr("HP freq")),
m_lowShelfFreqModel(80.f, 20.f, 20000, 0.001f, this, tr("Low-shelf freq")),
m_para1FreqModel(120.f, 20.f, 20000, 0.001f, this, tr("Peak 1 freq")),
m_para2FreqModel(250.f, 20.f, 20000, 0.001f, this, tr("Peak 2 freq")),
m_para3FreqModel(2000.f, 20.f, 20000, 0.001f, this, tr("Peak 3 freq")),
m_para4FreqModel(4000.f, 20.f, 20000, 0.001f, this, tr("Peak 4 freq")),
m_highShelfFreqModel(12000.f, 20.f, 20000, 0.001f, this, tr("High-shelf freq")),
m_lpFreqModel(18000.f, 20.f, 20000, 0.001f, this, tr("LP freq")),
m_hpActiveModel( false, this , tr( "HP active" ) ),
m_lowShelfActiveModel( false, this , tr( "Low-shelf active" ) ),
m_para1ActiveModel( false, this , tr( "Peak 1 active" ) ),
m_para2ActiveModel( false, this , tr( "Peak 2 active" ) ),
m_para3ActiveModel( false, this , tr( "Peak 3 active" ) ),
m_para4ActiveModel( false, this , tr( "Peak 4 active" ) ),
m_highShelfActiveModel( false, this , tr( "High-shelf active" ) ),
m_lpActiveModel( false, this , tr( "LP active" ) ),
m_lp12Model( false, this , tr( "LP 12" ) ),
m_lp24Model( false, this , tr( "LP 24" ) ),
m_lp48Model( false, this , tr( "LP 48" ) ),
m_hp12Model( false, this , tr( "HP 12" ) ),
m_hp24Model( false, this , tr( "HP 24" ) ),
m_hp48Model( false, this , tr( "HP 48" ) ),
m_lpTypeModel( 0,0,2, this, tr( "Low-pass type" ) ) ,
m_hpTypeModel( 0,0,2, this, tr( "High-pass type" ) ),
m_analyseInModel( true, this , tr( "Analyse IN" ) ),
m_analyseOutModel( true, this, tr( "Analyse OUT" ) )
{
m_hpFeqModel.setScaleLogarithmic( true );
m_lowShelfFreqModel.setScaleLogarithmic( true );
m_para1FreqModel.setScaleLogarithmic( true );
m_para2FreqModel.setScaleLogarithmic( true );
m_para3FreqModel.setScaleLogarithmic( true );
m_para4FreqModel.setScaleLogarithmic( true );
m_highShelfFreqModel.setScaleLogarithmic( true );
m_lpFreqModel.setScaleLogarithmic( true );
m_para1GainModel.setScaleLogarithmic( true );
m_inPeakL = 0;
m_inPeakR = 0;
m_outPeakL = 0;
m_outPeakR = 0;
m_lowShelfPeakL = 0; m_lowShelfPeakR = 0;
m_para1PeakL = 0; m_para1PeakR = 0;
m_para2PeakL = 0; m_para2PeakR = 0;
m_para3PeakL = 0; m_para3PeakR = 0;
m_para4PeakL = 0; m_para4PeakR = 0;
m_highShelfPeakL = 0; m_highShelfPeakR = 0;
m_inProgress = false;
m_inGainModel.setScaleLogarithmic( true );
}
void EqControls::loadSettings( const QDomElement &_this )
{
m_inGainModel.loadSettings( _this, "Inputgain" );
m_outGainModel.loadSettings( _this, "Outputgain" );
m_lowShelfGainModel.loadSettings( _this , "Lowshelfgain" );
m_para1GainModel.loadSettings( _this, "Peak1gain" );
m_para2GainModel.loadSettings( _this, "Peak2gain" );
m_para3GainModel.loadSettings( _this, "Peak3gain" );
m_para4GainModel.loadSettings( _this, "Peak4gain" );
m_highShelfGainModel.loadSettings( _this , "HighShelfgain" );
m_hpResModel.loadSettings( _this ,"HPres" );
m_lowShelfResModel.loadSettings( _this, "LowShelfres" );
m_para1BwModel.loadSettings( _this ,"Peak1bw" );
m_para2BwModel.loadSettings( _this ,"Peak2bw" );
m_para3BwModel.loadSettings( _this ,"Peak3bw" );
m_para4BwModel.loadSettings( _this ,"Peak4bw" );
m_highShelfResModel.loadSettings( _this, "HighShelfres" );
m_lpResModel.loadSettings( _this, "LPres" );
m_hpFeqModel.loadSettings( _this, "HPfreq" );
m_lowShelfFreqModel.loadSettings( _this, "LowShelffreq" );
m_para1FreqModel.loadSettings( _this, "Peak1freq" );
m_para2FreqModel.loadSettings( _this, "Peak2freq" );
m_para3FreqModel.loadSettings( _this, "Peak3freq" );
m_para4FreqModel.loadSettings( _this, "Peak4freq" );
m_highShelfFreqModel.loadSettings( _this, "Highshelffreq" );
m_lpFreqModel.loadSettings( _this, "LPfreq" );
m_hpActiveModel.loadSettings( _this, "HPactive" );
m_lowShelfActiveModel.loadSettings( _this, "Lowshelfactive" );
m_para1ActiveModel.loadSettings( _this, "Peak1active" );
m_para2ActiveModel.loadSettings( _this, "Peak2active" );
m_para3ActiveModel.loadSettings( _this, "Peak3active" );
m_para4ActiveModel.loadSettings( _this, "Peak4active" );
m_highShelfActiveModel.loadSettings( _this, "Highshelfactive" );
m_lpActiveModel.loadSettings( _this, "LPactive" );
m_lp12Model.loadSettings( _this , "LP12" );
m_lp24Model.loadSettings( _this , "LP24" );
m_lp48Model.loadSettings( _this , "LP48" );
m_hp12Model.loadSettings( _this , "HP12" );
m_hp24Model.loadSettings( _this , "HP24" );
m_hp48Model.loadSettings( _this , "HP48" );
m_lpTypeModel.loadSettings( _this, "LP" );
m_hpTypeModel.loadSettings( _this, "HP" );
m_analyseInModel.loadSettings( _this, "AnalyseIn" );
m_analyseOutModel.loadSettings( _this, "AnalyseOut" );
}
gui::EffectControlDialog* EqControls::createView()
{
return new gui::EqControlsDialog( this );
}
void EqControls::saveSettings( QDomDocument &doc, QDomElement &parent )
{
m_inGainModel.saveSettings( doc, parent, "Inputgain" );
m_outGainModel.saveSettings( doc, parent, "Outputgain");
m_lowShelfGainModel.saveSettings( doc, parent , "Lowshelfgain" );
m_para1GainModel.saveSettings( doc, parent, "Peak1gain" );
m_para2GainModel.saveSettings( doc, parent, "Peak2gain" );
m_para3GainModel.saveSettings( doc, parent, "Peak3gain" );
m_para4GainModel.saveSettings( doc, parent, "Peak4gain" );
m_highShelfGainModel.saveSettings( doc, parent, "HighShelfgain" );
m_hpResModel.saveSettings( doc, parent ,"HPres" );
m_lowShelfResModel.saveSettings( doc, parent, "LowShelfres" );
m_para1BwModel.saveSettings( doc, parent,"Peak1bw" );
m_para2BwModel.saveSettings( doc, parent,"Peak2bw" );
m_para3BwModel.saveSettings( doc, parent,"Peak3bw" );
m_para4BwModel.saveSettings( doc, parent,"Peak4bw" );
m_highShelfResModel.saveSettings( doc, parent, "HighShelfres" );
m_lpResModel.saveSettings( doc, parent, "LPres" );
m_hpFeqModel.saveSettings( doc, parent, "HPfreq" );
m_lowShelfFreqModel.saveSettings( doc, parent, "LowShelffreq" );
m_para1FreqModel.saveSettings( doc, parent, "Peak1freq" );
m_para2FreqModel.saveSettings( doc, parent, "Peak2freq" );
m_para3FreqModel.saveSettings( doc, parent, "Peak3freq" );
m_para4FreqModel.saveSettings( doc, parent, "Peak4freq" );
m_highShelfFreqModel.saveSettings( doc, parent, "Highshelffreq" );
m_lpFreqModel.saveSettings( doc, parent, "LPfreq" );
m_hpActiveModel.saveSettings( doc, parent, "HPactive" );
m_lowShelfActiveModel.saveSettings( doc, parent, "Lowshelfactive" );
m_para1ActiveModel.saveSettings( doc, parent, "Peak1active" );
m_para2ActiveModel.saveSettings( doc, parent, "Peak2active" );
m_para3ActiveModel.saveSettings( doc, parent, "Peak3active" );
m_para4ActiveModel.saveSettings( doc, parent, "Peak4active" );
m_highShelfActiveModel.saveSettings( doc, parent, "Highshelfactive" );
m_lpActiveModel.saveSettings( doc, parent, "LPactive" );
m_lp12Model.saveSettings( doc, parent, "LP12" );
m_lp24Model.saveSettings( doc, parent, "LP24" );
m_lp48Model.saveSettings( doc, parent, "LP48" );
m_hp12Model.saveSettings( doc, parent, "HP12" );
m_hp24Model.saveSettings( doc, parent, "HP24" );
m_hp48Model.saveSettings( doc, parent, "HP48" );
m_lpTypeModel.saveSettings( doc, parent, "LP" );
m_hpTypeModel.saveSettings( doc, parent, "HP" );
m_analyseInModel.saveSettings( doc, parent, "AnalyseIn" );
m_analyseOutModel.saveSettings( doc, parent, "AnalyseOut" );
}
} // namespace lmms
| 9,516
|
C++
|
.cpp
| 192
| 47.572917
| 81
| 0.723512
|
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,610
|
EqCurve.cpp
|
LMMS_lmms/plugins/Eq/EqCurve.cpp
|
/*
* EqCurve.cpp - declaration of EqCurve and EqHandle classes.
*
* Copyright (c) 2015 Steffen Baranowsky <BaraMGB/at/freenet/dot/de>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "EqCurve.h"
#include <cmath>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include "AudioEngine.h"
#include "embed.h"
#include "Engine.h"
#include "FontHelper.h"
#include "lmms_constants.h"
#include "lmms_math.h"
namespace lmms::gui
{
EqHandle::EqHandle( int num, int x, int y ):
m_numb( num ),
m_width( x ),
m_heigth( y ),
m_mousePressed( false ),
m_active( false )
{
setFlag( ItemIsMovable );
setFlag( ItemSendsGeometryChanges );
setAcceptHoverEvents( true );
float totalHeight = 36;
m_pixelsPerUnitHeight = ( m_heigth ) / ( totalHeight );
setMouseHover( false );
}
QRectF EqHandle::boundingRect() const
{
return QRectF( - m_circlePixmap.width() / 2, - m_circlePixmap.height() / 2, m_circlePixmap.width(), m_circlePixmap.height() );
}
float EqHandle::freqToXPixel( float freq , int w )
{
if (approximatelyEqual(freq, 0.0f)) { return 0.0f; }
float min = log10f( 20 );
float max = log10f( 20000 );
float range = max - min;
return ( log10f( freq ) - min ) / range * w;
}
float EqHandle::xPixelToFreq( float x , int w )
{
float min = log10f( 20 );
float max = log10f( 20000 );
float range = max - min;
return powf( 10 , x * ( range / w ) + min );
}
float EqHandle::gainToYPixel(float gain , int h, float pixelPerUnitHeight )
{
return h * 0.5 - gain * pixelPerUnitHeight;
}
float EqHandle::yPixelToGain(float y , int h, float pixelPerUnitHeight )
{
return ( ( h * 0.5 ) - y ) / pixelPerUnitHeight;
}
void EqHandle::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget )
{
painter->setRenderHint( QPainter::Antialiasing, true );
if ( m_mousePressed )
{
emit positionChanged();
}
// graphics for the handles
loadPixmap();
painter->drawPixmap( - ( m_circlePixmap.width() / 2 ) - 1 , - ( m_circlePixmap.height() / 2 ), m_circlePixmap );
// on mouse hover draw an info box and change the pixmap of the handle
if ( isMouseHover() )
{
// keeps the info box in view
float rectX = -40;
float rectY = -40;
if ( EqHandle::y() < 40 )
{
rectY = rectY + 40 - EqHandle::y();
}
if ( EqHandle::x() < 40 )
{
rectX = rectX + 40 - EqHandle::x();
}
if ( EqHandle::x() > m_width - 40 )
{
rectX = rectX - ( 40 - ( m_width - EqHandle::x() ) );
}
QPixmap hover = PLUGIN_NAME::getIconPixmap( "handlehover" );
painter->drawPixmap( - ( hover.width() / 2) - 1, - ( hover.height() / 2 ), hover );
QRectF textRect = QRectF ( rectX, rectY, 80, 30 );
QRectF textRect2 = QRectF ( rectX+1, rectY+1, 80, 30 );
QString freq = QString::number( xPixelToFreq( EqHandle::x(), m_width ) );
QString res;
if ( getType() != EqHandleType::Para )
{
res = tr( "Reso: ") + QString::number( getResonance() );
}
else
{
res = tr( "BW: " ) + QString::number( getResonance() );
}
painter->setFont(adjustedToPixelSize(painter->font(), SMALL_FONT_SIZE));
painter->setPen( Qt::black );
painter->drawRect( textRect );
painter->fillRect( textRect, QBrush( QColor( 6, 106, 43, 180 ) ) );
painter->setPen ( QColor( 0, 0, 0 ) );
painter->drawText( textRect2, Qt::AlignCenter,
QString( tr( "Freq: " ) + freq + "\n" + res ) );
painter->setPen( QColor( 255, 255, 255 ) );
painter->drawText( textRect, Qt::AlignCenter,
QString( tr( "Freq: " ) + freq + "\n" + res ) );
}
}
QPainterPath EqHandle::getCurvePath()
{
QPainterPath path;
float y = m_heigth * 0.5;
for ( float x = 0 ; x < m_width; x++ )
{
if ( m_type == EqHandleType::HighPass ) y = getLowCutCurve( x );
if ( m_type == EqHandleType::LowShelf ) y = getLowShelfCurve( x );
if ( m_type == EqHandleType::Para ) y = getPeakCurve( x );
if ( m_type == EqHandleType::HighShelf ) y = getHighShelfCurve( x );
if ( m_type == EqHandleType::LowPass ) y = getHighCutCurve( x );
if ( x == 0 ) path.moveTo( x, y ); // sets the begin of Path
path.lineTo( x, y );
}
return path;
}
void EqHandle::loadPixmap()
{
auto fileName = "handle" + std::to_string(m_numb + 1);
if (!isActiveHandle()) { fileName += "inactive"; }
m_circlePixmap = PLUGIN_NAME::getIconPixmap(fileName);
}
bool EqHandle::mousePressed() const
{
return m_mousePressed;
}
float EqHandle::getPeakCurve( float x )
{
double freqZ = xPixelToFreq( EqHandle::x(), m_width );
const int SR = Engine::audioEngine()->outputSampleRate();
double w0 = 2 * LD_PI * freqZ / SR ;
double c = cosf( w0 );
double s = sinf( w0 );
double Q = getResonance();
double A = pow( 10, yPixelToGain( EqHandle::y(), m_heigth, m_pixelsPerUnitHeight ) / 40 );
double alpha = s * sinh( log( 2 ) / 2 * Q * w0 / sinf( w0 ) );
//calc coefficents
double b0 = 1 + alpha * A;
double b1 = -2 * c;
double b2 = 1 - alpha * A;
double a0 = 1 + alpha / A;
double a1 = -2 * c;
double a2 = 1 - alpha / A;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
double freq = xPixelToFreq( x, m_width );
double gain = calculateGain( freq, a1, a2, b0, b1, b2 );
float y = gainToYPixel( gain, m_heigth, m_pixelsPerUnitHeight );
return y;
}
float EqHandle::getHighShelfCurve( float x )
{
double freqZ = xPixelToFreq( EqHandle::x(), m_width );
const int SR = Engine::audioEngine()->outputSampleRate();
double w0 = 2 * LD_PI * freqZ / SR;
double c = cosf( w0 );
double s = sinf( w0 );
double A = pow( 10, yPixelToGain( EqHandle::y(), m_heigth, m_pixelsPerUnitHeight ) * 0.025 );
double beta = sqrt( A ) / m_resonance;
//calc coefficents
double b0 = A * ((A + 1) + (A - 1) * c + beta * s);
double b1 = -2 * A * ((A - 1) + (A + 1) * c);
double b2 = A * ((A + 1) + (A - 1) * c - beta * s);
double a0 = (A + 1) - (A - 1) * c + beta * s;
double a1 = 2 * ((A - 1) - (A + 1) * c);
double a2 = (A + 1) - (A - 1) * c - beta * s;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
double freq = xPixelToFreq( x, m_width );
double gain = calculateGain( freq, a1, a2, b0, b1, b2 );
float y = gainToYPixel( gain, m_heigth, m_pixelsPerUnitHeight );
return y;
}
float EqHandle::getLowShelfCurve( float x )
{
double freqZ = xPixelToFreq( EqHandle::x(), m_width );
const int SR = Engine::audioEngine()->outputSampleRate();
double w0 = 2 * LD_PI * freqZ / SR ;
double c = cosf( w0 );
double s = sinf( w0 );
double A = pow( 10, yPixelToGain( EqHandle::y(), m_heigth, m_pixelsPerUnitHeight ) / 40 );
double beta = sqrt( A ) / m_resonance;
//calc coefficents
double b0 = A * ((A + 1) - (A - 1) * c + beta * s);
double b1 = 2 * A * ((A - 1) - (A + 1) * c);
double b2 = A * ((A + 1) - (A - 1) * c - beta * s);
double a0 = (A + 1) + (A - 1) * c + beta * s;
double a1 = -2 * ((A - 1) + (A + 1) * c);
double a2 = (A + 1) + (A - 1) * c - beta * s;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
double freq = xPixelToFreq( x, m_width );
double gain = calculateGain( freq, a1, a2, b0, b1, b2 );
float y = gainToYPixel( gain, m_heigth, m_pixelsPerUnitHeight );
return y;
}
float EqHandle::getLowCutCurve( float x )
{
double freqZ = xPixelToFreq( EqHandle::x(), m_width );
const int SR = Engine::audioEngine()->outputSampleRate();
double w0 = 2 * LD_PI * freqZ / SR ;
double c = cosf( w0 );
double s = sinf( w0 );
double resonance = getResonance();
double alpha = s / (2 * resonance);
double b0 = (1 + c) * 0.5;
double b1 = (-(1 + c));
double b2 = (1 + c) * 0.5;
double a0 = 1 + alpha;
double a1 = (-2 * c);
double a2 = 1 - alpha;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
double freq = xPixelToFreq( x, m_width );
double gain = calculateGain( freq, a1, a2, b0, b1, b2 );
if ( m_hp24 )
{
gain = gain * 2;
}
if ( m_hp48 )
{
gain = gain * 3;
}
float y = gainToYPixel( gain, m_heigth, m_pixelsPerUnitHeight );
return y;
}
float EqHandle::getHighCutCurve( float x )
{
double freqZ = xPixelToFreq( EqHandle::x(), m_width );
const int SR = Engine::audioEngine()->outputSampleRate();
double w0 = 2 * LD_PI * freqZ / SR ;
double c = cosf( w0 );
double s = sinf( w0 );
double resonance = getResonance();
double alpha = s / (2 * resonance);
double b0 = (1 - c) * 0.5;
double b1 = 1 - c;
double b2 = (1 - c) * 0.5;
double a0 = 1 + alpha;
double a1 = -2 * c;
double a2 = 1 - alpha;
//normalise
b0 /= a0;
b1 /= a0;
b2 /= a0;
a1 /= a0;
a2 /= a0;
a0 = 1;
double freq = xPixelToFreq( x, m_width );
double gain = calculateGain( freq, a1, a2, b0, b1, b2 );
if ( m_lp24 )
{
gain = gain * 2;
}
if ( m_lp48 )
{
gain = gain * 3;
}
float y = gainToYPixel( gain, m_heigth, m_pixelsPerUnitHeight );
return y;
}
float EqHandle::getResonance()
{
return m_resonance;
}
int EqHandle::getNum()
{
return m_numb;
}
void EqHandle::setType( EqHandleType t )
{
EqHandle::m_type = t;
}
void EqHandle::setResonance( float r )
{
EqHandle::m_resonance = r;
}
bool EqHandle::isMouseHover()
{
return m_mouseHover;
}
void EqHandle::setMouseHover( bool d )
{
m_mouseHover = d;
}
EqHandleType EqHandle::getType()
{
return m_type;
}
bool EqHandle::isActiveHandle()
{
return m_active;
}
void EqHandle::setHandleActive( bool a )
{
EqHandle::m_active = a;
}
void EqHandle::sethp12()
{
m_hp12 = true;
m_hp24 = false;
m_hp48 = false;
}
void EqHandle::sethp24()
{
m_hp12 = false;
m_hp24 = true;
m_hp48 = false;
}
void EqHandle::sethp48()
{
m_hp12 = false;
m_hp24 = false;
m_hp48 = true;
}
void EqHandle::setlp12()
{
m_lp12 = true;
m_lp24 = false;
m_lp48 = false;
}
void EqHandle::setlp24()
{
m_lp12 = false;
m_lp24 = true;
m_lp48 = false;
}
void EqHandle::setlp48()
{
m_lp12 = false;
m_lp24 = false;
m_lp48 = true;
}
double EqHandle::calculateGain(const double freq, const double a1, const double a2, const double b0, const double b1, const double b2 )
{
const int SR = Engine::audioEngine()->outputSampleRate();
const double w = 2 * LD_PI * freq / SR ;
const double PHI = pow( sin( w / 2 ), 2 ) * 4;
double gain = 10 * log10( pow( b0 + b1 + b2 , 2 ) + ( b0 * b2 * PHI - ( b1 * ( b0 + b2 )
+ 4 * b0 * b2 ) ) * PHI ) - 10 * log10( pow( 1 + a1 + a2, 2 )
+ ( 1 * a2 * PHI - ( a1 * ( 1 + a2 ) + 4 * 1 * a2 ) ) * PHI );
return gain;
}
void EqHandle::mousePressEvent( QGraphicsSceneMouseEvent *event )
{
if( event->button() == Qt::LeftButton )
{
m_mousePressed = true;
QGraphicsItem::mousePressEvent( event );
}
}
void EqHandle::mouseReleaseEvent( QGraphicsSceneMouseEvent *event )
{
if( event->button() == Qt::LeftButton )
{
m_mousePressed = false;
QGraphicsItem::mouseReleaseEvent( event );
}
}
void EqHandle::wheelEvent( QGraphicsSceneWheelEvent *wevent )
{
float highestBandwich = m_type != EqHandleType::Para ? 10 : 4;
int numDegrees = wevent->delta() / 120;
float numSteps = 0;
if( wevent->modifiers() == Qt::ControlModifier )
{
numSteps = numDegrees * 0.01;
}
else
{
numSteps = numDegrees * 0.15;
}
if( wevent->orientation() == Qt::Vertical )
{
m_resonance = std::clamp(m_resonance + numSteps, 0.1f, highestBandwich);
emit positionChanged();
}
wevent->accept();
}
void EqHandle::hoverEnterEvent( QGraphicsSceneHoverEvent *hevent )
{
setMouseHover( true );
}
void EqHandle::hoverLeaveEvent( QGraphicsSceneHoverEvent *hevent )
{
setMouseHover( false );
}
QVariant EqHandle::itemChange( QGraphicsItem::GraphicsItemChange change, const QVariant &value )
{
if( change == ItemPositionChange )
{
// pass filter don't move in y direction
if ( m_type == EqHandleType::HighPass || m_type == EqHandleType::LowPass )
{
float newX = value.toPointF().x();
if( newX < 0 )
{
newX = 0;
}
if( newX > m_width )
{
newX = m_width;
}
return QPointF(newX, m_heigth/2);
}
}
QPointF newPos = value.toPointF();
QRectF rect = QRectF( 0, 0, m_width, m_heigth );
if( !rect.contains( newPos ) )
{
// Keep the item inside the scene rect.
newPos.setX( qMin( rect.right(), qMax( newPos.x(), rect.left() ) ) );
newPos.setY( qMin( rect.bottom(), qMax( newPos.y(), rect.top() ) ) );
return newPos;
}
return QGraphicsItem::itemChange( change, value );
}
// ----------------------------------------------------------------------
//
// Class EqCurve
//
// Every Handle calculates its own curve.
// But EqCurve generates an average curve.
//
// ----------------------------------------------------------------------
EqCurve::EqCurve( QList<EqHandle*> *handle, int x, int y ) :
m_handle( handle ),
m_width( x ),
m_heigth( y ),
m_alpha( 0 ),
m_modelChanged( false )
{
}
QRectF EqCurve::boundingRect() const
{
return QRect( 0, 0, m_width, m_heigth );
}
void EqCurve::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget )
{
painter->setRenderHint( QPainter::Antialiasing, true );
if( m_modelChanged )
{
setModelChanged( false );
//counts the active bands
int activeHandles=0;
for ( int thatHandle = 0; thatHandle<m_handle->count(); thatHandle++ )
{
if ( m_handle->at(thatHandle)->isActiveHandle() == true )
{
activeHandles++;
}
}
//Computes the main curve
//if a band is active the curve will be computed by averaging the curves of each band
QMap<float,float> mainCurve;
for ( int thatHandle = 0; thatHandle<m_handle->count(); thatHandle++ )
{
if ( m_handle->at(thatHandle)->isActiveHandle() == true )
{
for ( int x = 0; x < m_width ; x=x+1 )
{
if ( m_handle->at( thatHandle )->getType() == EqHandleType::HighPass )
{
mainCurve[x]= ( mainCurve[x] + ( m_handle->at( thatHandle )->getLowCutCurve( x ) * ( activeHandles ) ) - ( ( activeHandles * ( m_heigth/2 ) ) - m_heigth ) );
}
if ( m_handle->at(thatHandle)->getType() == EqHandleType::LowShelf )
{
mainCurve[x]= ( mainCurve[x] + ( m_handle->at( thatHandle )->getLowShelfCurve( x ) * ( activeHandles ) ) - ( ( activeHandles * ( m_heigth/2 ) ) - m_heigth ) );
}
if ( m_handle->at( thatHandle )->getType() == EqHandleType::Para )
{
mainCurve[x]= ( mainCurve[x] + ( m_handle->at( thatHandle )->getPeakCurve( x ) * ( activeHandles ) ) - ( ( activeHandles * ( m_heigth/2 ) ) - m_heigth ) );
}
if ( m_handle->at( thatHandle )->getType() == EqHandleType::HighShelf )
{
mainCurve[x]= ( mainCurve[x] + ( m_handle->at( thatHandle )->getHighShelfCurve( x ) * ( activeHandles ) ) - ( ( activeHandles * ( m_heigth/2 ) ) - m_heigth ) );
}
if ( m_handle->at(thatHandle)->getType() == EqHandleType::LowPass )
{
mainCurve[x]= ( mainCurve[x] + ( m_handle->at( thatHandle )->getHighCutCurve( x ) * ( activeHandles ) ) - ( ( activeHandles * ( m_heigth/2 ) ) - m_heigth ) );
}
}
}
}
//compute a QPainterPath
m_curve = QPainterPath();
//only draw the EQ curve if there are any activeHandles
if (activeHandles != 0)
{
for (int x = 0; x < m_width; x++)
{
mainCurve[x] = ((mainCurve[x] / activeHandles)) - (m_heigth / 2);
if (x == 0)
{
m_curve.moveTo(x, mainCurve[x]);
}
m_curve.lineTo(x, mainCurve[x]);
}
}
//we cache the curve painting in a pixmap for saving cpu
QPixmap cacheMap( boundingRect().size().toSize() );
cacheMap.fill( QColor( 0, 0, 0, 0 ) );
QPainter cachePainter( &cacheMap );
cachePainter.setRenderHint( QPainter::Antialiasing, true );
QPen pen;
pen.setWidth( 2 );
pen.setColor( Qt::white );
cachePainter.setPen( pen );
cachePainter.drawPath( m_curve );
cachePainter.end();
m_curvePixmapCache.fill( QColor( 0, 0, 0, 0 ) );
m_curvePixmapCache.swap( cacheMap );
}
//we paint our cached curve pixmap
painter->drawPixmap( 0, 0, m_width, m_heigth, m_curvePixmapCache );
// if mouse hover a handle, m_alpha counts up slow for blend in the filled EQ curve
// todo: a smarter way of this "if-monster"
QColor curveColor;
if( m_handle->at( 0 )->isMouseHover()
|| m_handle->at( 1 )->isMouseHover()
|| m_handle->at( 2 )->isMouseHover()
|| m_handle->at( 3 )->isMouseHover()
|| m_handle->at( 4 )->isMouseHover()
|| m_handle->at( 5 )->isMouseHover()
|| m_handle->at( 6 )->isMouseHover()
|| m_handle->at( 7 )->isMouseHover()
)
{
if ( m_alpha < 40 )
{
m_alpha = m_alpha + 10;
}
}
else
{
if ( m_alpha > 0 )
{
m_alpha = m_alpha - 10;
}
}
//draw on mouse hover the curve of hovered filter in different colors
for ( int i = 0; i < m_handle->count(); i++ )
{
if ( m_handle->at(i)->isMouseHover() )
{
curveColor = QColor( qRgba( 6, 106, 43, 242 ));
QPen pen ( curveColor);
pen.setWidth( 2 );
painter->setPen( pen );
painter->drawPath( m_handle->at( i )->getCurvePath() );
}
}
//draw on mouse hover the EQ curve filled. with m_alpha it blends in and out smooth
QPainterPath cPath;
cPath.addPath( m_curve );
cPath.lineTo( cPath.currentPosition().x(), m_heigth );
cPath.lineTo( cPath.elementAt( 0 ).x , m_heigth );
painter->fillPath( cPath, QBrush ( QColor( 255,255,255, m_alpha ) ) );
}
void EqCurve::setModelChanged( bool mc )
{
m_modelChanged = mc;
}
} // namespace lmms::gui
| 17,912
|
C++
|
.cpp
| 614
| 26.574919
| 166
| 0.638527
|
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,611
|
EqSpectrumView.cpp
|
LMMS_lmms/plugins/Eq/EqSpectrumView.cpp
|
/* eqspectrumview.cpp - implementation of EqSpectrumView class.
*
* Copyright (c) 2014-2017, David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "EqSpectrumView.h"
#include <cmath>
#include <QPainter>
#include <QPen>
#include "AudioEngine.h"
#include "Engine.h"
#include "EqCurve.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "lmms_constants.h"
namespace lmms
{
EqAnalyser::EqAnalyser() :
m_framesFilledUp ( 0 ),
m_energy ( 0 ),
m_sampleRate ( 1 ),
m_active ( true )
{
m_inProgress=false;
m_specBuf = ( fftwf_complex * ) fftwf_malloc( ( FFT_BUFFER_SIZE + 1 ) * sizeof( fftwf_complex ) );
m_fftPlan = fftwf_plan_dft_r2c_1d( FFT_BUFFER_SIZE*2, m_buffer, m_specBuf, FFTW_MEASURE );
//initialize Blackman-Harris window, constants taken from
//https://en.wikipedia.org/wiki/Window_function#A_list_of_window_functions
const float a0 = 0.35875f;
const float a1 = 0.48829f;
const float a2 = 0.14128f;
const float a3 = 0.01168f;
for (auto i = std::size_t{0}; i < FFT_BUFFER_SIZE; i++)
{
m_fftWindow[i] = (a0 - a1 * cos(2 * F_PI * i / ((float)FFT_BUFFER_SIZE - 1.0))
+ a2 * cos(4 * F_PI * i / ((float)FFT_BUFFER_SIZE - 1.0))
- a3 * cos(6 * F_PI * i / ((float)FFT_BUFFER_SIZE - 1.0)));
}
clear();
}
EqAnalyser::~EqAnalyser()
{
fftwf_destroy_plan( m_fftPlan );
fftwf_free( m_specBuf );
}
void EqAnalyser::analyze( SampleFrame* buf, const fpp_t frames )
{
//only analyse if the view is visible
if ( m_active )
{
m_inProgress=true;
const int FFT_BUFFER_SIZE = 2048;
fpp_t f = 0;
if( frames > FFT_BUFFER_SIZE )
{
m_framesFilledUp = 0;
f = frames - FFT_BUFFER_SIZE;
}
// meger channels
for( ; f < frames; ++f )
{
m_buffer[m_framesFilledUp] =
( buf[f][0] + buf[f][1] ) * 0.5;
++m_framesFilledUp;
}
if( m_framesFilledUp < FFT_BUFFER_SIZE )
{
m_inProgress = false;
return;
}
m_sampleRate = Engine::audioEngine()->outputSampleRate();
const int LOWEST_FREQ = 0;
const int HIGHEST_FREQ = m_sampleRate / 2;
//apply FFT window
for( int i = 0; i < FFT_BUFFER_SIZE; i++ )
{
m_buffer[i] = m_buffer[i] * m_fftWindow[i];
}
fftwf_execute( m_fftPlan );
absspec( m_specBuf, m_absSpecBuf, FFT_BUFFER_SIZE+1 );
compressbands( m_absSpecBuf, m_bands, FFT_BUFFER_SIZE+1,
MAX_BANDS,
( int )( LOWEST_FREQ * ( FFT_BUFFER_SIZE + 1 ) / ( float )( m_sampleRate / 2 ) ),
( int )( HIGHEST_FREQ * ( FFT_BUFFER_SIZE + 1) / ( float )( m_sampleRate / 2 ) ) );
m_energy = maximum( m_bands, MAX_BANDS ) / maximum( m_buffer, FFT_BUFFER_SIZE );
m_framesFilledUp = 0;
m_inProgress = false;
m_active = false;
}
}
float EqAnalyser::getEnergy() const
{
return m_energy;
}
int EqAnalyser::getSampleRate() const
{
return m_sampleRate;
}
bool EqAnalyser::getActive() const
{
return m_active;
}
void EqAnalyser::setActive(bool active)
{
m_active = active;
}
bool EqAnalyser::getInProgress()
{
return m_inProgress;
}
void EqAnalyser::clear()
{
m_framesFilledUp = 0;
m_energy = 0;
memset( m_buffer, 0, sizeof( m_buffer ) );
memset( m_bands, 0, sizeof( m_bands ) );
}
namespace gui
{
EqSpectrumView::EqSpectrumView(EqAnalyser *b, QWidget *_parent) :
QWidget( _parent ),
m_analyser( b ),
m_peakSum(0.),
m_periodicalUpdate( false )
{
setFixedSize( 450, 200 );
connect( getGUI()->mainWindow(), SIGNAL( periodicUpdate() ), this, SLOT( periodicalUpdate() ) );
setAttribute( Qt::WA_TranslucentBackground, true );
m_skipBands = MAX_BANDS * 0.5;
float totalLength = log10( 20000 );
m_pixelsPerUnitWidth = width() / totalLength ;
m_scale = 1.5;
m_color = QColor( 255, 255, 255, 255 );
for ( int i = 0 ; i < MAX_BANDS ; i++ )
{
m_bandHeight.append( 0 );
}
}
void EqSpectrumView::paintEvent(QPaintEvent *event)
{
const float energy = m_analyser->getEnergy();
if (energy <= 0. && m_peakSum <= 0) { return; }
const int fh = height();
const int LOWER_Y = -36; // dB
QPainter painter( this );
painter.setPen( QPen( m_color, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin ) );
painter.setRenderHint(QPainter::Antialiasing, true);
if( m_analyser->getInProgress() || m_periodicalUpdate == false )
{
//only paint the cached path
painter.fillPath( m_path, QBrush( m_color ) );
return;
}
m_periodicalUpdate = false;
//Now we calculate the path
m_path = QPainterPath();
float *bands = m_analyser->m_bands;
m_path.moveTo( 0, height() );
m_peakSum = 0;
const float fallOff = 1.07f;
for( int x = 0; x < MAX_BANDS; ++x, ++bands )
{
float peak = *bands != 0. ? (fh * 2.0 / 3.0 * (20. * log10(*bands / energy) - LOWER_Y) / (-LOWER_Y)) : 0.;
if( peak < 0 )
{
peak = 0;
}
else if( peak >= fh )
{
continue;
}
if ( peak > m_bandHeight[x] )
{
m_bandHeight[x] = peak;
}
else
{
m_bandHeight[x] = m_bandHeight[x] / fallOff;
}
if( m_bandHeight[x] < 0 )
{
m_bandHeight[x] = 0;
}
m_path.lineTo( EqHandle::freqToXPixel( bandToFreq( x ), width() ), fh - m_bandHeight[x] );
m_peakSum += m_bandHeight[x];
}
m_path.lineTo( width(), height() );
m_path.closeSubpath();
painter.fillPath( m_path, QBrush( m_color ) );
painter.drawPath( m_path );
}
QColor EqSpectrumView::getColor() const
{
return m_color;
}
void EqSpectrumView::setColor( const QColor &value )
{
m_color = value;
}
float EqSpectrumView::bandToFreq( int index )
{
return index * m_analyser->getSampleRate() / ( MAX_BANDS * 2 );
}
void EqSpectrumView::periodicalUpdate()
{
m_periodicalUpdate = true;
m_analyser->setActive( isVisible() );
update();
}
} // namespace gui
} // namespace lmms
| 6,383
|
C++
|
.cpp
| 227
| 25.625551
| 108
| 0.677695
|
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,612
|
EqEffect.cpp
|
LMMS_lmms/plugins/Eq/EqEffect.cpp
|
/*
* eqeffect.cpp - defination of EqEffect class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "EqEffect.h"
#include "Engine.h"
#include "lmms_math.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT eq_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Equalizer",
QT_TRANSLATE_NOOP( "PluginBrowser", "A native eq plugin" ),
"Dave French <contact/dot/dave/dot/french3/at/googlemail/dot/com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
EqEffect::EqEffect( Model *parent, const Plugin::Descriptor::SubPluginFeatures::Key *key) :
Effect( &eq_plugin_descriptor, parent, key ),
m_eqControls( this ),
m_inGain( 1.0 ),
m_outGain( 1.0 )
{
}
Effect::ProcessStatus EqEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const int sampleRate = Engine::audioEngine()->outputSampleRate();
//wet/dry controls
const float dry = dryLevel();
const float wet = wetLevel();
auto dryS = std::array<sample_t, 2>{};
// setup sample exact controls
float hpRes = m_eqControls.m_hpResModel.value();
float lowShelfRes = m_eqControls.m_lowShelfResModel.value();
float para1Bw = m_eqControls.m_para1BwModel.value();
float para2Bw = m_eqControls.m_para2BwModel.value();
float para3Bw = m_eqControls.m_para3BwModel.value();
float para4Bw = m_eqControls.m_para4BwModel.value();
float highShelfRes = m_eqControls.m_highShelfResModel.value();
float lpRes = m_eqControls.m_lpResModel.value();
float hpFreq = m_eqControls.m_hpFeqModel.value();
float lowShelfFreq = m_eqControls.m_lowShelfFreqModel.value();
float para1Freq = m_eqControls.m_para1FreqModel.value();
float para2Freq = m_eqControls.m_para2FreqModel.value();
float para3Freq = m_eqControls.m_para3FreqModel.value();
float para4Freq = m_eqControls.m_para4FreqModel.value();
float highShelfFreq = m_eqControls.m_highShelfFreqModel.value();
float lpFreq = m_eqControls.m_lpFreqModel.value();
bool hpActive = m_eqControls.m_hpActiveModel.value();
bool hp24Active = m_eqControls.m_hp24Model.value();
bool hp48Active = m_eqControls.m_hp48Model.value();
bool lowShelfActive = m_eqControls.m_lowShelfActiveModel.value();
bool para1Active = m_eqControls.m_para1ActiveModel.value();
bool para2Active = m_eqControls.m_para2ActiveModel.value();
bool para3Active = m_eqControls.m_para3ActiveModel.value();
bool para4Active = m_eqControls.m_para4ActiveModel.value();
bool highShelfActive = m_eqControls.m_highShelfActiveModel.value();
bool lpActive = m_eqControls.m_lpActiveModel.value();
bool lp24Active = m_eqControls.m_lp24Model.value();
bool lp48Active = m_eqControls.m_lp48Model.value();
float lowShelfGain = m_eqControls.m_lowShelfGainModel.value();
float para1Gain = m_eqControls.m_para1GainModel.value();
float para2Gain = m_eqControls.m_para2GainModel.value();
float para3Gain = m_eqControls.m_para3GainModel.value();
float para4Gain = m_eqControls.m_para4GainModel.value();
float highShelfGain = m_eqControls.m_highShelfGainModel.value();
//set all filter parameters once per frame, EqFilter handles
//smooth xfading, reducing pops clicks and dc bias offsets
m_hp12.setParameters( sampleRate, hpFreq, hpRes, 1 );
m_hp24.setParameters( sampleRate, hpFreq, hpRes, 1 );
m_hp480.setParameters( sampleRate, hpFreq, hpRes, 1 );
m_hp481.setParameters( sampleRate, hpFreq, hpRes, 1 );
m_lowShelf.setParameters( sampleRate, lowShelfFreq, lowShelfRes, lowShelfGain );
m_para1.setParameters( sampleRate, para1Freq, para1Bw, para1Gain );
m_para2.setParameters( sampleRate, para2Freq, para2Bw, para2Gain );
m_para3.setParameters( sampleRate, para3Freq, para3Bw, para3Gain );
m_para4.setParameters( sampleRate, para4Freq, para4Bw, para4Gain );
m_highShelf.setParameters( sampleRate, highShelfFreq, highShelfRes, highShelfGain );
m_lp12.setParameters( sampleRate, lpFreq, lpRes, 1 );
m_lp24.setParameters( sampleRate, lpFreq, lpRes, 1 );
m_lp480.setParameters( sampleRate, lpFreq, lpRes, 1 );
m_lp481.setParameters( sampleRate, lpFreq, lpRes, 1 );
if( m_eqControls.m_outGainModel.isValueChanged() )
{
m_outGain = dbfsToAmp(m_eqControls.m_outGainModel.value());
}
if( m_eqControls.m_inGainModel.isValueChanged() )
{
m_inGain = dbfsToAmp(m_eqControls.m_inGainModel.value());
}
m_eqControls.m_inProgress = true;
double outSum = 0.0;
for (fpp_t f = 0; f < frames; ++f)
{
outSum += buf[f][0] * buf[f][0] + buf[f][1] * buf[f][1];
}
const float outGain = m_outGain;
SampleFrame m_inPeak = { 0, 0 };
if(m_eqControls.m_analyseInModel.value( true ) && outSum > 0 && m_eqControls.isViewVisible() )
{
m_eqControls.m_inFftBands.analyze( buf, frames );
}
else
{
m_eqControls.m_inFftBands.clear();
}
gain( buf, frames, m_inGain, &m_inPeak );
m_eqControls.m_inPeakL = m_eqControls.m_inPeakL < m_inPeak[0] ? m_inPeak[0] : m_eqControls.m_inPeakL;
m_eqControls.m_inPeakR = m_eqControls.m_inPeakR < m_inPeak[1] ? m_inPeak[1] : m_eqControls.m_inPeakR;
float periodProgress = 0.0f; // percentage of period processed
for( fpp_t f = 0; f < frames; ++f)
{
periodProgress = (float)f / (float)(frames-1);
//wet dry buffer
dryS[0] = buf[f][0];
dryS[1] = buf[f][1];
if( hpActive )
{
buf[f][0] = m_hp12.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_hp12.update( buf[f][1], 1, periodProgress );
if( hp24Active || hp48Active )
{
buf[f][0] = m_hp24.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_hp24.update( buf[f][1], 1, periodProgress );
}
if( hp48Active )
{
buf[f][0] = m_hp480.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_hp480.update( buf[f][1], 1, periodProgress );
buf[f][0] = m_hp481.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_hp481.update( buf[f][1], 1, periodProgress );
}
}
if( lowShelfActive )
{
buf[f][0] = m_lowShelf.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_lowShelf.update( buf[f][1], 1, periodProgress );
}
if( para1Active )
{
buf[f][0] = m_para1.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_para1.update( buf[f][1], 1, periodProgress );
}
if( para2Active )
{
buf[f][0] = m_para2.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_para2.update( buf[f][1], 1, periodProgress );
}
if( para3Active )
{
buf[f][0] = m_para3.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_para3.update( buf[f][1], 1, periodProgress );
}
if( para4Active )
{
buf[f][0] = m_para4.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_para4.update( buf[f][1], 1, periodProgress );
}
if( highShelfActive )
{
buf[f][0] = m_highShelf.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_highShelf.update( buf[f][1], 1, periodProgress );
}
if( lpActive ){
buf[f][0] = m_lp12.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_lp12.update( buf[f][1], 1, periodProgress );
if( lp24Active || lp48Active )
{
buf[f][0] = m_lp24.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_lp24.update( buf[f][1], 1, periodProgress );
}
if( lp48Active )
{
buf[f][0] = m_lp480.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_lp480.update( buf[f][1], 1, periodProgress );
buf[f][0] = m_lp481.update( buf[f][0], 0, periodProgress );
buf[f][1] = m_lp481.update( buf[f][1], 1, periodProgress );
}
}
//apply wet / dry levels
buf[f][1] = ( dry * dryS[1] ) + ( wet * buf[f][1] );
buf[f][0] = ( dry * dryS[0] ) + ( wet * buf[f][0] );
}
SampleFrame outPeak = { 0, 0 };
gain( buf, frames, outGain, &outPeak );
m_eqControls.m_outPeakL = m_eqControls.m_outPeakL < outPeak[0] ? outPeak[0] : m_eqControls.m_outPeakL;
m_eqControls.m_outPeakR = m_eqControls.m_outPeakR < outPeak[1] ? outPeak[1] : m_eqControls.m_outPeakR;
if(m_eqControls.m_analyseOutModel.value( true ) && outSum > 0 && m_eqControls.isViewVisible() )
{
m_eqControls.m_outFftBands.analyze( buf, frames );
setBandPeaks( &m_eqControls.m_outFftBands , ( int )( sampleRate ) );
}
else
{
m_eqControls.m_outFftBands.clear();
}
m_eqControls.m_inProgress = false;
return Effect::ProcessStatus::ContinueIfNotQuiet;
}
float EqEffect::linearPeakBand(float minF, float maxF, EqAnalyser* fft, int sr)
{
auto const fftEnergy = fft->getEnergy();
if (fftEnergy == 0.) { return 0.; }
float peakLinear = 0.;
for (int i = 0; i < MAX_BANDS; ++i)
{
if (bandToFreq(i, sr) >= minF && bandToFreq(i, sr) <= maxF)
{
peakLinear = std::max(peakLinear, fft->m_bands[i] / fftEnergy);
}
}
return peakLinear;
}
void EqEffect::setBandPeaks( EqAnalyser *fft, int samplerate )
{
auto computePeakBand = [&](const FloatModel& freqModel, const FloatModel& bwModel)
{
float const freq = freqModel.value();
float const bw = bwModel.value();
return linearPeakBand(freq * (1 - bw * 0.5), freq * (1 + bw * 0.5), fft, samplerate);
};
m_eqControls.m_lowShelfPeakR = m_eqControls.m_lowShelfPeakL =
linearPeakBand(m_eqControls.m_lowShelfFreqModel.value() * (1 - m_eqControls.m_lowShelfResModel.value() * 0.5),
m_eqControls.m_lowShelfFreqModel.value(), fft , samplerate);
m_eqControls.m_para1PeakL = m_eqControls.m_para1PeakR =
computePeakBand(m_eqControls.m_para1FreqModel, m_eqControls.m_para1BwModel);
m_eqControls.m_para2PeakL = m_eqControls.m_para2PeakR =
computePeakBand(m_eqControls.m_para2FreqModel, m_eqControls.m_para2BwModel);
m_eqControls.m_para3PeakL = m_eqControls.m_para3PeakR =
computePeakBand(m_eqControls.m_para3FreqModel, m_eqControls.m_para3BwModel);
m_eqControls.m_para4PeakL = m_eqControls.m_para4PeakR =
computePeakBand(m_eqControls.m_para4FreqModel, m_eqControls.m_para4BwModel);
m_eqControls.m_highShelfPeakL = m_eqControls.m_highShelfPeakR =
linearPeakBand(m_eqControls.m_highShelfFreqModel.value(),
m_eqControls.m_highShelfFreqModel.value() * (1 + m_eqControls.m_highShelfResModel.value() * 0.5),
fft, samplerate);
}
extern "C"
{
//needed for getting plugin out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new EqEffect( parent , static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( data ) );
}
}
} // namespace lmms
| 11,026
|
C++
|
.cpp
| 274
| 37.551095
| 112
| 0.710741
|
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,613
|
EqControlsDialog.cpp
|
LMMS_lmms/plugins/Eq/EqControlsDialog.cpp
|
/*
* eqcontrolsdialog.cpp - defination of EqControlsDialog class.
*
* Copyright (c) 2014 David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "EqControlsDialog.h"
#include <QWidget>
#include "AutomatableButton.h"
#include "embed.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "PixmapButton.h"
#include "EqControls.h"
#include "EqFader.h"
#include "EqParameterWidget.h"
#include "EqSpectrumView.h"
namespace lmms::gui
{
EqControlsDialog::EqControlsDialog( EqControls *controls ) :
EffectControlDialog( controls ),
m_controls( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 500, 500 );
auto inSpec = new EqSpectrumView(&controls->m_inFftBands, this);
inSpec->move( 26, 17 );
inSpec->setColor( QColor( 77, 101, 242, 150 ) );
auto outSpec = new EqSpectrumView(&controls->m_outFftBands, this);
outSpec->setColor( QColor( 0, 255, 239, 150 ) );
outSpec->move( 26, 17 );
m_parameterWidget = new EqParameterWidget( this , controls );
m_parameterWidget->move( 26, 17 );
setBand( 0, &controls->m_hpActiveModel, &controls->m_hpFeqModel, &controls->m_hpResModel, 0, QColor(255 ,255, 255), tr( "HP" ) ,0,0, &controls->m_hp12Model, &controls->m_hp24Model, &controls->m_hp48Model,0,0,0);
setBand( 1, &controls->m_lowShelfActiveModel, &controls->m_lowShelfFreqModel, &controls->m_lowShelfResModel, &controls->m_lowShelfGainModel, QColor(255 ,255, 255), tr( "Low-shelf" ), &controls->m_lowShelfPeakL , &controls->m_lowShelfPeakR,0,0,0,0,0,0 );
setBand( 2, &controls->m_para1ActiveModel, &controls->m_para1FreqModel, &controls->m_para1BwModel, &controls->m_para1GainModel, QColor(255 ,255, 255), tr( "Peak 1" ), &controls->m_para1PeakL, &controls->m_para1PeakR,0,0,0,0,0,0 );
setBand( 3, &controls->m_para2ActiveModel, &controls->m_para2FreqModel, &controls->m_para2BwModel, &controls->m_para2GainModel, QColor(255 ,255, 255), tr( "Peak 2" ), &controls->m_para2PeakL, &controls->m_para2PeakR,0,0,0,0,0,0 );
setBand( 4, &controls->m_para3ActiveModel, &controls->m_para3FreqModel, &controls->m_para3BwModel, &controls->m_para3GainModel, QColor(255 ,255, 255), tr( "Peak 3" ), &controls->m_para3PeakL, &controls->m_para3PeakR,0,0,0,0,0,0 );
setBand( 5, &controls->m_para4ActiveModel, &controls->m_para4FreqModel, &controls->m_para4BwModel, &controls->m_para4GainModel, QColor(255 ,255, 255), tr( "Peak 4" ), &controls->m_para4PeakL, &controls->m_para4PeakR,0,0,0,0,0,0 );
setBand( 6, &controls->m_highShelfActiveModel, &controls->m_highShelfFreqModel, &controls->m_highShelfResModel, &controls->m_highShelfGainModel, QColor(255 ,255, 255), tr( "High-shelf" ), &controls->m_highShelfPeakL, &controls->m_highShelfPeakR,0,0,0,0,0,0 );
setBand( 7, &controls->m_lpActiveModel, &controls->m_lpFreqModel, &controls->m_lpResModel, 0, QColor(255 ,255, 255), tr( "LP" ) ,0,0,0,0,0, &controls->m_lp12Model, &controls->m_lp24Model, &controls->m_lp48Model);
QSize const faderSize(23, 80);
auto GainFaderIn = new EqFader(&controls->m_inGainModel, tr("Input gain"), this, &controls->m_inPeakL, &controls->m_inPeakR);
GainFaderIn->setFixedSize(faderSize);
GainFaderIn->move( 23, 295 );
GainFaderIn->setDisplayConversion( false );
GainFaderIn->setHintText( tr( "Gain" ), "dBv");
auto GainFaderOut = new EqFader(&controls->m_outGainModel, tr("Output gain"), this, &controls->m_outPeakL, &controls->m_outPeakR);
GainFaderOut->setFixedSize(faderSize);
GainFaderOut->move( 453, 295);
GainFaderOut->setDisplayConversion( false );
GainFaderOut->setHintText( tr( "Gain" ), "dBv" );
// Gain Fader for each Filter exepts the pass filter
int distance = 126;
for( int i = 1; i < m_parameterWidget->bandCount() - 1; i++ )
{
auto gainFader = new EqFader(m_parameterWidget->getBandModels(i)->gain, tr(""), this,
m_parameterWidget->getBandModels(i)->peakL, m_parameterWidget->getBandModels(i)->peakR);
gainFader->setFixedSize(faderSize);
gainFader->move( distance, 295 );
distance += 44;
gainFader->setMinimumHeight(80);
gainFader->resize(gainFader->width() , 80);
gainFader->setDisplayConversion( false );
gainFader->setHintText( tr( "Gain") , "dB");
}
//Control Button and Knobs for each Band
distance = 81;
for( int i = 0; i < m_parameterWidget->bandCount() ; i++ )
{
auto resKnob = new Knob(KnobType::Bright26, this);
resKnob->move( distance, 440 );
resKnob->setVolumeKnob(false);
resKnob->setModel( m_parameterWidget->getBandModels( i )->res );
if(i > 1 && i < 6) { resKnob->setHintText( tr( "Bandwidth: " ) , tr( " Octave" ) ); }
else { resKnob->setHintText(tr("Resonance: "), ""); }
auto freqKnob = new Knob(KnobType::Bright26, this);
freqKnob->move( distance, 396 );
freqKnob->setVolumeKnob( false );
freqKnob->setModel( m_parameterWidget->getBandModels( i )->freq );
freqKnob->setHintText( tr( "Frequency:" ), "Hz" );
// adds the Number Active buttons
auto activeButton = new PixmapButton(this, nullptr);
activeButton->setCheckable(true);
activeButton->setModel( m_parameterWidget->getBandModels( i )->active );
const auto iconActiveFileName = "bandLabel" + std::to_string(i + 1);
const auto iconInactiveFileName = iconActiveFileName + "off";
activeButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap(iconActiveFileName));
activeButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap(iconInactiveFileName));
activeButton->move( distance - 2, 276 );
activeButton->setModel( m_parameterWidget->getBandModels( i )->active );
// Connects the knobs, Faders and buttons with the curve graphic
QObject::connect( m_parameterWidget->getBandModels( i )->freq , SIGNAL( dataChanged() ), m_parameterWidget, SLOT ( updateHandle() ) );
if ( m_parameterWidget->getBandModels( i )->gain ) QObject::connect( m_parameterWidget->getBandModels( i )->gain, SIGNAL( dataChanged() ), m_parameterWidget, SLOT ( updateHandle() ));
QObject::connect( m_parameterWidget->getBandModels( i )->res, SIGNAL( dataChanged() ), m_parameterWidget , SLOT ( updateHandle() ) );
QObject::connect( m_parameterWidget->getBandModels( i )->active, SIGNAL( dataChanged() ), m_parameterWidget , SLOT ( updateHandle() ) );
m_parameterWidget->changeHandle( i );
distance += 44;
}
// adds the buttons for Spectrum analyser on/off
auto inSpecButton = new LedCheckBox(this);
inSpecButton->setCheckable(true);
inSpecButton->setModel( &controls->m_analyseInModel );
inSpecButton->move( 172, 240 );
auto outSpecButton = new LedCheckBox(this);
outSpecButton->setCheckable(true);
outSpecButton->setModel( &controls->m_analyseOutModel );
outSpecButton->move( 302, 240 );
//hp filter type
auto hp12Button = new PixmapButton(this, nullptr);
hp12Button->setModel( m_parameterWidget->getBandModels( 0 )->hp12 );
hp12Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "12dB" ) );
hp12Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "12dBoff" ) );
hp12Button->move( 79, 298 );
auto hp24Button = new PixmapButton(this, nullptr);
hp24Button->setModel(m_parameterWidget->getBandModels( 0 )->hp24 );
hp24Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "24dB" ) );
hp24Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "24dBoff" ) );
hp24Button->move( 79 , 328 );
auto hp48Button = new PixmapButton(this, nullptr);
hp48Button->setModel( m_parameterWidget->getBandModels(0)->hp48 );
hp48Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "48dB" ) );
hp48Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "48dBoff" ) );
hp48Button->move( 79, 358 );
//LP filter type
auto lp12Button = new PixmapButton(this, nullptr);
lp12Button->setModel( m_parameterWidget->getBandModels( 7 )->lp12 );
lp12Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "12dB" ) );
lp12Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "12dBoff" ) );
lp12Button->move( 387, 298 );
auto lp24Button = new PixmapButton(this, nullptr);
lp24Button->setModel( m_parameterWidget->getBandModels( 7 )->lp24 );
lp24Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "24dB" ) );
lp24Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "24dBoff" ) );
lp24Button->move( 387, 328 );
auto lp48Button = new PixmapButton(this, nullptr);
lp48Button->setModel( m_parameterWidget->getBandModels( 7 )->lp48 );
lp48Button->setActiveGraphic( PLUGIN_NAME::getIconPixmap( "48dB" ) );
lp48Button->setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "48dBoff" ) );
lp48Button->move( 387, 358 );
// the curve has to change its appearance
QObject::connect( m_parameterWidget->getBandModels( 0 )->hp12 , SIGNAL ( dataChanged() ), m_parameterWidget, SLOT( updateHandle()));
QObject::connect( m_parameterWidget->getBandModels( 0 )->hp24 , SIGNAL ( dataChanged() ), m_parameterWidget, SLOT( updateHandle()));
QObject::connect( m_parameterWidget->getBandModels( 0 )->hp48 , SIGNAL ( dataChanged() ), m_parameterWidget, SLOT( updateHandle()));
QObject::connect( m_parameterWidget->getBandModels( 7 )->lp12 , SIGNAL ( dataChanged() ), m_parameterWidget, SLOT( updateHandle()));
QObject::connect( m_parameterWidget->getBandModels( 7 )->lp24 , SIGNAL ( dataChanged() ), m_parameterWidget, SLOT( updateHandle()));
QObject::connect( m_parameterWidget->getBandModels( 7 )->lp48 , SIGNAL ( dataChanged() ), m_parameterWidget, SLOT( updateHandle()));
auto lpBtnGrp = new automatableButtonGroup(this, tr("LP group"));
lpBtnGrp->addButton( lp12Button );
lpBtnGrp->addButton( lp24Button );
lpBtnGrp->addButton( lp48Button );
lpBtnGrp->setModel(&m_controls->m_lpTypeModel);
auto hpBtnGrp = new automatableButtonGroup(this, tr("HP group"));
hpBtnGrp->addButton( hp12Button );
hpBtnGrp->addButton( hp24Button );
hpBtnGrp->addButton( hp48Button );
hpBtnGrp->setModel(&m_controls->m_hpTypeModel);
}
void EqControlsDialog::mouseDoubleClickEvent(QMouseEvent *event)
{
m_originalHeight = parentWidget()->height() == 283 ? m_originalHeight : parentWidget()->height() ;
parentWidget()->setFixedHeight( parentWidget()->height() == m_originalHeight ? 283 : m_originalHeight );
update();
}
EqBand* EqControlsDialog::setBand(int index, BoolModel* active, FloatModel* freq, FloatModel* res, FloatModel* gain, QColor color, QString name, float* peakL, float* peakR, BoolModel* hp12, BoolModel* hp24, BoolModel* hp48, BoolModel* lp12, BoolModel* lp24, BoolModel* lp48)
{
EqBand *filterModels = m_parameterWidget->getBandModels( index );
filterModels->active = active;
filterModels->freq = freq;
filterModels->res = res;
filterModels->color = color;
filterModels->gain = gain;
filterModels->peakL = peakL;
filterModels->peakR = peakR;
filterModels->hp12 = hp12;
filterModels->hp24 = hp24;
filterModels->hp48 = hp48;
filterModels->lp12 = lp12;
filterModels->lp24 = lp24;
filterModels->lp48 = lp48;
return filterModels;
}
} // namespace lmms::gui
| 11,658
|
C++
|
.cpp
| 203
| 55.157635
| 274
| 0.738742
|
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,614
|
Kicker.cpp
|
LMMS_lmms/plugins/Kicker/Kicker.cpp
|
/*
* Kicker.cpp - drum synthesizer
*
* Copyright (c) 2006-2009 Tobias Doerffel <tobydox/at/users.sourceforge.net>
* Copyright (c) 2014 grejppi <grejppi/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 "Kicker.h"
#include <QDomElement>
#include "AudioEngine.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "NotePlayHandle.h"
#include "KickerOsc.h"
#include "TempoSyncKnob.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT kicker_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Kicker",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Versatile drum synthesizer" ),
"Tobias Doerffel <tobydox/at/users.sf.net>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
KickerInstrument::KickerInstrument( InstrumentTrack * _instrument_track ) :
Instrument(_instrument_track, &kicker_plugin_descriptor, nullptr, Flag::IsNotBendable),
m_startFreqModel( 150.0f, 5.0f, 1000.0f, 1.0f, this, tr( "Start frequency" ) ),
m_endFreqModel( 40.0f, 5.0f, 1000.0f, 1.0f, this, tr( "End frequency" ) ),
m_decayModel( 440.0f, 5.0f, 5000.0f, 1.0f, 5000.0f, this, tr( "Length" ) ),
m_distModel( 0.8f, 0.0f, 100.0f, 0.1f, this, tr( "Start distortion" ) ),
m_distEndModel( 0.8f, 0.0f, 100.0f, 0.1f, this, tr( "End distortion" ) ),
m_gainModel( 1.0f, 0.1f, 5.0f, 0.05f, this, tr( "Gain" ) ),
m_envModel( 0.163f, 0.01f, 1.0f, 0.001f, this, tr( "Envelope slope" ) ),
m_noiseModel( 0.0f, 0.0f, 1.0f, 0.01f, this, tr( "Noise" ) ),
m_clickModel( 0.4f, 0.0f, 1.0f, 0.05f, this, tr( "Click" ) ),
m_slopeModel( 0.06f, 0.001f, 1.0f, 0.001f, this, tr( "Frequency slope" ) ),
m_startNoteModel( true, this, tr( "Start from note" ) ),
m_endNoteModel( false, this, tr( "End to note" ) ),
m_versionModel( KICKER_PRESET_VERSION, 0, KICKER_PRESET_VERSION, this, "" )
{
}
void KickerInstrument::saveSettings(QDomDocument& doc, QDomElement& elem)
{
m_startFreqModel.saveSettings(doc, elem, "startfreq");
m_endFreqModel.saveSettings(doc, elem, "endfreq");
m_decayModel.saveSettings(doc, elem, "decay");
m_distModel.saveSettings(doc, elem, "dist");
m_distEndModel.saveSettings(doc, elem, "distend");
m_gainModel.saveSettings(doc, elem, "gain");
m_envModel.saveSettings(doc, elem, "env");
m_noiseModel.saveSettings(doc, elem, "noise");
m_clickModel.saveSettings(doc, elem, "click");
m_slopeModel.saveSettings(doc, elem, "slope");
m_startNoteModel.saveSettings(doc, elem, "startnote");
m_endNoteModel.saveSettings(doc, elem, "endnote");
m_versionModel.saveSettings(doc, elem, "version");
}
void KickerInstrument::loadSettings(const QDomElement& elem)
{
m_versionModel.loadSettings(elem, "version");
m_startFreqModel.loadSettings(elem, "startfreq");
m_endFreqModel.loadSettings(elem, "endfreq");
m_decayModel.loadSettings(elem, "decay");
m_distModel.loadSettings(elem, "dist");
if (elem.hasAttribute("distend") || !elem.firstChildElement("distend").isNull())
{
m_distEndModel.loadSettings(elem, "distend");
}
else
{
m_distEndModel.setValue(m_distModel.value());
}
m_gainModel.loadSettings(elem, "gain");
m_envModel.loadSettings(elem, "env");
m_noiseModel.loadSettings(elem, "noise");
m_clickModel.loadSettings(elem, "click");
m_slopeModel.loadSettings(elem, "slope");
m_startNoteModel.loadSettings(elem, "startnote");
if (m_versionModel.value() < 1)
{
m_startNoteModel.setValue(false);
}
m_endNoteModel.loadSettings(elem, "endnote");
// Try to maintain backwards compatibility
if (!elem.hasAttribute("version"))
{
m_startNoteModel.setValue(false);
m_decayModel.setValue(m_decayModel.value() * 1.33f);
m_envModel.setValue(1.0f);
m_slopeModel.setValue(1.0f);
m_clickModel.setValue(0.0f);
}
m_versionModel.setValue(KICKER_PRESET_VERSION);
}
QString KickerInstrument::nodeName() const
{
return kicker_plugin_descriptor.name;
}
using DistFX = DspEffectLibrary::Distortion;
using SweepOsc = KickerOsc<DspEffectLibrary::MonoToStereoAdaptor<DistFX>>;
void KickerInstrument::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
const float decfr = m_decayModel.value() * Engine::audioEngine()->outputSampleRate() / 1000.0f;
const f_cnt_t tfp = _n->totalFramesPlayed();
if (!_n->m_pluginData)
{
_n->m_pluginData = new SweepOsc(
DistFX( m_distModel.value(),
m_gainModel.value() ),
m_startNoteModel.value() ? _n->frequency() : m_startFreqModel.value(),
m_endNoteModel.value() ? _n->frequency() : m_endFreqModel.value(),
m_noiseModel.value() * m_noiseModel.value(),
m_clickModel.value() * 0.25f,
m_slopeModel.value(),
m_envModel.value(),
m_distModel.value(),
m_distEndModel.value(),
decfr );
}
else if( tfp > decfr && !_n->isReleased() )
{
_n->noteOff();
}
auto so = static_cast<SweepOsc*>(_n->m_pluginData);
so->update( _working_buffer + offset, frames, Engine::audioEngine()->outputSampleRate() );
if( _n->isReleased() )
{
// We need this to check if the release has ended
const float desired = desiredReleaseFrames();
// This can be considered the current release frame in the "global" context of the release.
// We need it with the desired number of release frames to compute the linear decay.
fpp_t currentReleaseFrame = _n->releaseFramesDone();
// Start applying the release at the correct frame
const float framesBeforeRelease = _n->framesBeforeRelease();
for (fpp_t f = framesBeforeRelease; f < frames; ++f, ++currentReleaseFrame)
{
const bool releaseStillActive = currentReleaseFrame < desired;
const float attenuation = releaseStillActive ? (1.0f - (currentReleaseFrame / desired)) : 0.f;
_working_buffer[f + offset][0] *= attenuation;
_working_buffer[f + offset][1] *= attenuation;
}
}
}
void KickerInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<SweepOsc *>( _n->m_pluginData );
}
gui::PluginView * KickerInstrument::instantiateView( QWidget * _parent )
{
return new gui::KickerInstrumentView( this, _parent );
}
namespace gui
{
class KickerKnob : public Knob
{
public:
KickerKnob( QWidget * _parent ) :
Knob( KnobType::Styled, _parent )
{
setFixedSize( 29, 29 );
setObjectName( "smallKnob" );
}
};
class KickerEnvKnob : public TempoSyncKnob
{
public:
KickerEnvKnob( QWidget * _parent ) :
TempoSyncKnob( KnobType::Styled, _parent )
{
setFixedSize( 29, 29 );
setObjectName( "smallKnob" );
}
};
class KickerLargeKnob : public Knob
{
public:
KickerLargeKnob( QWidget * _parent ) :
Knob( KnobType::Styled, _parent )
{
setFixedSize( 34, 34 );
setObjectName( "largeKnob" );
}
};
KickerInstrumentView::KickerInstrumentView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
const int ROW1 = 14;
const int ROW2 = ROW1 + 56;
const int ROW3 = ROW2 + 56;
const int LED_ROW = 63;
const int COL1 = 14;
const int COL2 = COL1 + 56;
const int COL3 = COL2 + 56;
const int COL4 = COL3 + 41;
const int COL5 = COL4 + 41;
const int END_COL = COL1 + 48;
m_startFreqKnob = new KickerLargeKnob( this );
m_startFreqKnob->setHintText( tr( "Start frequency:" ), "Hz" );
m_startFreqKnob->move( COL1, ROW1 );
m_endFreqKnob = new KickerLargeKnob( this );
m_endFreqKnob->setHintText( tr( "End frequency:" ), "Hz" );
m_endFreqKnob->move( END_COL, ROW1 );
m_slopeKnob = new KickerKnob( this );
m_slopeKnob->setHintText( tr( "Frequency slope:" ), "" );
m_slopeKnob->move( COL3, ROW1 );
m_gainKnob = new KickerKnob( this );
m_gainKnob->setHintText( tr( "Gain:" ), "" );
m_gainKnob->move( COL1, ROW3 );
m_decayKnob = new KickerEnvKnob( this );
m_decayKnob->setHintText( tr( "Envelope length:" ), "ms" );
m_decayKnob->move( COL2, ROW3 );
m_envKnob = new KickerKnob( this );
m_envKnob->setHintText( tr( "Envelope slope:" ), "" );
m_envKnob->move( COL3, ROW3 );
m_clickKnob = new KickerKnob( this );
m_clickKnob->setHintText( tr( "Click:" ), "" );
m_clickKnob->move( COL5, ROW1 );
m_noiseKnob = new KickerKnob( this );
m_noiseKnob->setHintText( tr( "Noise:" ), "" );
m_noiseKnob->move( COL5, ROW3 );
m_distKnob = new KickerKnob( this );
m_distKnob->setHintText( tr( "Start distortion:" ), "" );
m_distKnob->move( COL4, ROW2 );
m_distEndKnob = new KickerKnob( this );
m_distEndKnob->setHintText( tr( "End distortion:" ), "" );
m_distEndKnob->move( COL5, ROW2 );
m_startNoteToggle = new LedCheckBox( "", this, "", LedCheckBox::LedColor::Green );
m_startNoteToggle->move( COL1 + 8, LED_ROW );
m_endNoteToggle = new LedCheckBox( "", this, "", LedCheckBox::LedColor::Green );
m_endNoteToggle->move( END_COL + 8, LED_ROW );
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
}
void KickerInstrumentView::modelChanged()
{
auto k = castModel<KickerInstrument>();
m_startFreqKnob->setModel( &k->m_startFreqModel );
m_endFreqKnob->setModel( &k->m_endFreqModel );
m_decayKnob->setModel( &k->m_decayModel );
m_distKnob->setModel( &k->m_distModel );
m_distEndKnob->setModel( &k->m_distEndModel );
m_gainKnob->setModel( &k->m_gainModel );
m_envKnob->setModel( &k->m_envModel );
m_noiseKnob->setModel( &k->m_noiseModel );
m_clickKnob->setModel( &k->m_clickModel );
m_slopeKnob->setModel( &k->m_slopeModel );
m_startNoteToggle->setModel( &k->m_startNoteModel );
m_endNoteToggle->setModel( &k->m_endNoteModel );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model * m, void * )
{
return new KickerInstrument( static_cast<InstrumentTrack *>( m ) );
}
}
} // namespace lmms
| 10,619
|
C++
|
.cpp
| 295
| 33.633898
| 97
| 0.714662
|
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,615
|
BitcrushControls.cpp
|
LMMS_lmms/plugins/Bitcrush/BitcrushControls.cpp
|
/*
* BitcrushControls.cpp - A native bitcrusher
*
* 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 <QDomElement>
#include "BitcrushControls.h"
#include "Bitcrush.h"
namespace lmms
{
BitcrushControls::BitcrushControls( BitcrushEffect * eff ) :
EffectControls( eff ),
m_effect( eff ),
m_inGain( 0.0f, -20.0f, 20.0f, 0.1f, this, tr( "Input gain" ) ),
m_inNoise( 0.0f, 0.0f, 100.0f, 0.1f, this, tr( "Input noise" ) ),
m_outGain( 0.0f, -20.0f, 20.0f, 0.1f, this, tr( "Output gain" ) ),
m_outClip( 0.0f, -20.0f, 20.0f, 0.1f, this, tr( "Output clip" ) ),
m_rate( 44100.f, 20.f, 44100.f, 1.0f, this, tr( "Sample rate" ) ),
m_stereoDiff( 0.f, -50.f, 50.f, 0.1f, this, tr( "Stereo difference" ) ),
m_levels( 256.f, 1.f, 256.f, 0.01f, this, tr( "Levels" ) ),
m_rateEnabled( true, this, tr( "Rate enabled" ) ),
m_depthEnabled( true, this, tr( "Depth enabled" ) )
{
m_rate.setStrictStepSize( true );
m_levels.setStrictStepSize( true );
connect( Engine::audioEngine(), SIGNAL( sampleRateChanged() ), this, SLOT( sampleRateChanged() ) );
}
void BitcrushControls::saveSettings( QDomDocument & doc, QDomElement & elem )
{
m_inGain.saveSettings( doc, elem, "ingain" );
m_inNoise.saveSettings( doc, elem, "innoise" );
m_outGain.saveSettings( doc, elem, "outgain" );
m_outClip.saveSettings( doc, elem, "outclip" );
m_rate.saveSettings( doc, elem, "rate" );
m_stereoDiff.saveSettings( doc, elem, "stereodiff" );
m_levels.saveSettings( doc, elem, "levels" );
m_rateEnabled.saveSettings( doc, elem, "rateon" );
m_depthEnabled.saveSettings( doc, elem, "depthon" );
}
void BitcrushControls::loadSettings( const QDomElement & elem )
{
m_inGain.loadSettings( elem, "ingain" );
m_inNoise.loadSettings( elem, "innoise" );
m_outGain.loadSettings( elem, "outgain" );
m_outClip.loadSettings( elem, "outclip" );
m_rate.loadSettings( elem, "rate" );
m_stereoDiff.loadSettings( elem, "stereodiff" );
m_levels.loadSettings( elem, "levels" );
m_rateEnabled.loadSettings( elem, "rateon" );
m_depthEnabled.loadSettings( elem, "depthon" );
m_effect->m_needsUpdate = true;
}
void BitcrushControls::sampleRateChanged()
{
m_effect->sampleRateChanged();
}
} // namespace lmms
| 3,097
|
C++
|
.cpp
| 76
| 38.776316
| 100
| 0.712716
|
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,616
|
Bitcrush.cpp
|
LMMS_lmms/plugins/Bitcrush/Bitcrush.cpp
|
/*
* Bitcrush.cpp - A native bitcrusher
*
* 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 "Bitcrush.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
const int OS_RATE = 5;
const float OS_RATIO = 1.0f / OS_RATE;
const float CUTOFF_RATIO = 0.353553391f;
const int SILENCEFRAMES = 10;
const auto OS_RESAMPLE = std::array{0.0001490062883964112f, 0.1645978376763992f, 0.6705063120704088f,
0.1645978376763992f, 0.0001490062883964112f };
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT bitcrush_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Bitcrush",
QT_TRANSLATE_NOOP( "PluginBrowser", "An oversampling bitcrusher" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
};
}
BitcrushEffect::BitcrushEffect( Model * parent, const Descriptor::SubPluginFeatures::Key * key ) :
Effect( &bitcrush_plugin_descriptor, parent, key ),
m_controls( this ),
m_sampleRate( Engine::audioEngine()->outputSampleRate() ),
m_filter( m_sampleRate )
{
m_buffer = new SampleFrame[Engine::audioEngine()->framesPerPeriod() * OS_RATE];
m_filter.setLowpass( m_sampleRate * ( CUTOFF_RATIO * OS_RATIO ) );
m_needsUpdate = true;
m_bitCounterL = 0.0f;
m_bitCounterR = 0.0f;
m_left = 0.0f;
m_right = 0.0f;
m_silenceCounter = 0;
}
BitcrushEffect::~BitcrushEffect()
{
delete[] m_buffer;
}
void BitcrushEffect::sampleRateChanged()
{
m_sampleRate = Engine::audioEngine()->outputSampleRate();
m_filter.setSampleRate( m_sampleRate );
m_filter.setLowpass( m_sampleRate * ( CUTOFF_RATIO * OS_RATIO ) );
m_needsUpdate = true;
}
inline float BitcrushEffect::depthCrush( float in )
{
return roundf( in * (float) m_levels ) * m_levelsRatio;
}
inline float BitcrushEffect::noise( float amt )
{
return fastRandf( amt * 2.0f ) - amt;
}
Effect::ProcessStatus BitcrushEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
// update values
if( m_needsUpdate || m_controls.m_rateEnabled.isValueChanged() )
{
m_rateEnabled = m_controls.m_rateEnabled.value();
m_bitCounterL = 0.0f;
m_bitCounterR = 0.0f;
}
if( m_needsUpdate || m_controls.m_depthEnabled.isValueChanged() )
{
m_depthEnabled = m_controls.m_depthEnabled.value();
}
if( m_needsUpdate || m_controls.m_rate.isValueChanged() || m_controls.m_stereoDiff.isValueChanged() )
{
const float rate = m_controls.m_rate.value();
const float diff = m_controls.m_stereoDiff.value() * 0.005 * rate;
m_rateCoeffL = ( m_sampleRate * OS_RATE ) / ( rate - diff );
m_rateCoeffR = ( m_sampleRate * OS_RATE ) / ( rate + diff );
m_bitCounterL = 0.0f;
m_bitCounterR = 0.0f;
}
if( m_needsUpdate || m_controls.m_levels.isValueChanged() )
{
m_levels = m_controls.m_levels.value();
m_levelsRatio = 1.0f / (float) m_levels;
}
if( m_needsUpdate || m_controls.m_inGain.isValueChanged() )
{
m_inGain = dbfsToAmp( m_controls.m_inGain.value() );
}
if( m_needsUpdate || m_controls.m_outGain.isValueChanged() )
{
m_outGain = dbfsToAmp( m_controls.m_outGain.value() );
}
if( m_needsUpdate || m_controls.m_outClip.isValueChanged() )
{
m_outClip = dbfsToAmp( m_controls.m_outClip.value() );
}
m_needsUpdate = false;
const float noiseAmt = m_controls.m_inNoise.value() * 0.01f;
// read input buffer and write it to oversampled buffer
if( m_rateEnabled ) // rate crushing enabled so do that
{
for (auto f = std::size_t{0}; f < frames; ++f)
{
for( int o = 0; o < OS_RATE; ++o )
{
m_buffer[f * OS_RATE + o][0] = m_left;
m_buffer[f * OS_RATE + o][1] = m_right;
m_bitCounterL += 1.0f;
m_bitCounterR += 1.0f;
if( m_bitCounterL > m_rateCoeffL )
{
m_bitCounterL -= m_rateCoeffL;
m_left = m_depthEnabled
? depthCrush( buf[f][0] * m_inGain + noise( buf[f][0] * noiseAmt ) )
: buf[f][0] * m_inGain + noise( buf[f][0] * noiseAmt );
}
if( m_bitCounterR > m_rateCoeffR )
{
m_bitCounterR -= m_rateCoeffR;
m_right = m_depthEnabled
? depthCrush( buf[f][1] * m_inGain + noise( buf[f][1] * noiseAmt ) )
: buf[f][1] * m_inGain + noise( buf[f][1] * noiseAmt );
}
}
}
}
else // rate crushing disabled: simply oversample with zero-order hold
{
for (auto f = std::size_t{0}; f < frames; ++f)
{
for( int o = 0; o < OS_RATE; ++o )
{
m_buffer[f * OS_RATE + o][0] = m_depthEnabled
? depthCrush( buf[f][0] * m_inGain + noise( buf[f][0] * noiseAmt ) )
: buf[f][0] * m_inGain + noise( buf[f][0] * noiseAmt );
m_buffer[f * OS_RATE + o][1] = m_depthEnabled
? depthCrush( buf[f][1] * m_inGain + noise( buf[f][1] * noiseAmt ) )
: buf[f][1] * m_inGain + noise( buf[f][1] * noiseAmt );
}
}
}
// the oversampled buffer is now written, so filter it to reduce aliasing
for (auto f = std::size_t{0}; f < frames * OS_RATE; ++f)
{
if( qMax( qAbs( m_buffer[f][0] ), qAbs( m_buffer[f][1] ) ) >= 1.0e-10f )
{
m_silenceCounter = 0;
m_buffer[f][0] = m_filter.update( m_buffer[f][0], 0 );
m_buffer[f][1] = m_filter.update( m_buffer[f][1], 1 );
}
else
{
if( m_silenceCounter > SILENCEFRAMES )
{
m_buffer[f][0] = m_buffer[f][1] = 0.0f;
}
else
{
++m_silenceCounter;
m_buffer[f][0] = m_filter.update( m_buffer[f][0], 0 );
m_buffer[f][1] = m_filter.update( m_buffer[f][1], 1 );
}
}
}
// now downsample and write it back to main buffer
const float d = dryLevel();
const float w = wetLevel();
for (auto f = std::size_t{0}; f < frames; ++f)
{
float lsum = 0.0f;
float rsum = 0.0f;
for( int o = 0; o < OS_RATE; ++o )
{
lsum += m_buffer[f * OS_RATE + o][0] * OS_RESAMPLE[o];
rsum += m_buffer[f * OS_RATE + o][1] * OS_RESAMPLE[o];
}
buf[f][0] = d * buf[f][0] + w * qBound( -m_outClip, lsum, m_outClip ) * m_outGain;
buf[f][1] = d * buf[f][1] + w * qBound( -m_outClip, rsum, m_outClip ) * m_outGain;
}
return ProcessStatus::ContinueIfNotQuiet;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new BitcrushEffect( parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>( data ) );
}
}
} // namespace lmms
| 7,090
|
C++
|
.cpp
| 217
| 29.930876
| 110
| 0.669055
|
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,617
|
BitcrushControlDialog.cpp
|
LMMS_lmms/plugins/Bitcrush/BitcrushControlDialog.cpp
|
/*
* BitcrushControlDialog.cpp - A native bitcrusher
*
* 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 <QLabel>
#include "embed.h"
#include "BitcrushControlDialog.h"
#include "BitcrushControls.h"
#include "LedCheckBox.h"
#include "Knob.h"
namespace lmms::gui
{
BitcrushControlDialog::BitcrushControlDialog( BitcrushControls * controls ) :
EffectControlDialog( controls )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
setFixedSize( 181, 128 );
// labels
auto inLabel = new QLabel(tr("IN"), this);
inLabel->move( 24, 15 );
auto outLabel = new QLabel(tr("OUT"), this);
outLabel->move( 139, 15 );
// input knobs
auto inGain = new Knob(KnobType::Bright26, this);
inGain->move( 16, 32 );
inGain->setModel( & controls->m_inGain );
inGain->setLabel( tr( "GAIN" ) );
inGain->setHintText( tr( "Input gain:" ) , " dBFS" );
auto inNoise = new Knob(KnobType::Bright26, this);
inNoise->move( 14, 76 );
inNoise->setModel( & controls->m_inNoise );
inNoise->setLabel( tr( "NOISE" ) );
inNoise->setHintText( tr( "Input noise:" ) , "%" );
// output knobs
auto outGain = new Knob(KnobType::Bright26, this);
outGain->move( 138, 32 );
outGain->setModel( & controls->m_outGain );
outGain->setLabel( tr( "GAIN" ) );
outGain->setHintText( tr( "Output gain:" ) , " dBFS" );
auto outClip = new Knob(KnobType::Bright26, this);
outClip->move( 138, 76 );
outClip->setModel( & controls->m_outClip );
outClip->setLabel( tr( "CLIP" ) );
outClip->setHintText( tr( "Output clip:" ) , " dBFS");
// leds
auto rateEnabled = new LedCheckBox("", this, tr("Rate enabled"), LedCheckBox::LedColor::Green);
rateEnabled->move( 64, 14 );
rateEnabled->setModel( & controls->m_rateEnabled );
rateEnabled->setToolTip(tr("Enable sample-rate crushing"));
auto depthEnabled = new LedCheckBox("", this, tr("Depth enabled"), LedCheckBox::LedColor::Green);
depthEnabled->move( 101, 14 );
depthEnabled->setModel( & controls->m_depthEnabled );
depthEnabled->setToolTip(tr("Enable bit-depth crushing"));
// rate crushing knobs
auto rate = new Knob(KnobType::Bright26, this);
rate->move( 59, 32 );
rate->setModel( & controls->m_rate );
rate->setLabel( tr( "FREQ" ) );
rate->setHintText( tr( "Sample rate:" ) , " Hz" );
auto stereoDiff = new Knob(KnobType::Bright26, this);
stereoDiff->move( 72, 76 );
stereoDiff->setModel( & controls->m_stereoDiff );
stereoDiff->setLabel( tr( "STEREO" ) );
stereoDiff->setHintText( tr( "Stereo difference:" ) , "%" );
// depth crushing knob
auto levels = new Knob(KnobType::Bright26, this);
levels->move( 92, 32 );
levels->setModel( & controls->m_levels );
levels->setLabel( tr( "QUANT" ) );
levels->setHintText( tr( "Levels:" ) , "" );
}
} // namespace lmms::gui
| 3,735
|
C++
|
.cpp
| 95
| 37.073684
| 98
| 0.708622
|
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,618
|
Watsyn.cpp
|
LMMS_lmms/plugins/Watsyn/Watsyn.cpp
|
/*
* Watsyn.cpp - a 4-oscillator modulating wavetable synth
*
* Copyright (c) 2014 Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "Watsyn.h"
#include "base64.h"
#include "AudioEngine.h"
#include "Engine.h"
#include "InstrumentTrack.h"
#include "PixmapButton.h"
#include "Song.h"
#include "lmms_math.h"
#include "interpolation.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT watsyn_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Watsyn",
QT_TRANSLATE_NOOP( "PluginBrowser",
"4-oscillator modulatable wavetable synth" ),
"Vesa Kivimäki <contact/dot/diizy/at/nbl/dot/fi>",
0x0100,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
}
WatsynObject::WatsynObject( float * _A1wave, float * _A2wave,
float * _B1wave, float * _B2wave,
int _amod, int _bmod, const sample_rate_t _samplerate, NotePlayHandle * _nph, fpp_t _frames,
WatsynInstrument * _w ) :
m_amod( _amod ),
m_bmod( _bmod ),
m_samplerate( _samplerate ),
m_nph( _nph ),
m_fpp( _frames ),
m_parent( _w )
{
m_abuf = new SampleFrame[_frames];
m_bbuf = new SampleFrame[_frames];
m_lphase[A1_OSC] = 0.0f;
m_lphase[A2_OSC] = 0.0f;
m_lphase[B1_OSC] = 0.0f;
m_lphase[B2_OSC] = 0.0f;
m_rphase[A1_OSC] = 0.0f;
m_rphase[A2_OSC] = 0.0f;
m_rphase[B1_OSC] = 0.0f;
m_rphase[B2_OSC] = 0.0f;
// copy wavegraphs to the synth object to prevent race conditions
memcpy( &m_A1wave, _A1wave, sizeof( m_A1wave ) );
memcpy( &m_A2wave, _A2wave, sizeof( m_A2wave ) );
memcpy( &m_B1wave, _B1wave, sizeof( m_B1wave ) );
memcpy( &m_B2wave, _B2wave, sizeof( m_B2wave ) );
}
WatsynObject::~WatsynObject()
{
delete[] m_abuf;
delete[] m_bbuf;
}
void WatsynObject::renderOutput( fpp_t _frames )
{
if( m_abuf == nullptr )
m_abuf = new SampleFrame[m_fpp];
if( m_bbuf == nullptr )
m_bbuf = new SampleFrame[m_fpp];
for( fpp_t frame = 0; frame < _frames; frame++ )
{
// put phases of 1-series oscs into variables because phase modulation might happen
float A1_lphase = m_lphase[A1_OSC];
float A1_rphase = m_rphase[A1_OSC];
float B1_lphase = m_lphase[B1_OSC];
float B1_rphase = m_rphase[B1_OSC];
///////////// A-series /////////////////
// A2
sample_t A2_L = linearInterpolate( m_A2wave[ static_cast<int>( m_lphase[A2_OSC] ) ],
m_A2wave[ static_cast<int>( m_lphase[A2_OSC] + 1 ) % WAVELEN ],
fraction( m_lphase[A2_OSC] ) ) * m_parent->m_lvol[A2_OSC];
sample_t A2_R = linearInterpolate( m_A2wave[ static_cast<int>( m_rphase[A2_OSC] ) ],
m_A2wave[ static_cast<int>( m_rphase[A2_OSC] + 1 ) % WAVELEN ],
fraction( m_rphase[A2_OSC] ) ) * m_parent->m_rvol[A2_OSC];
// if phase mod, add to phases
if( m_amod == MOD_PM )
{
A1_lphase = fmodf( A1_lphase + A2_L * PMOD_AMT, WAVELEN );
if( A1_lphase < 0 ) A1_lphase += WAVELEN;
A1_rphase = fmodf( A1_rphase + A2_R * PMOD_AMT, WAVELEN );
if( A1_rphase < 0 ) A1_rphase += WAVELEN;
}
// A1
sample_t A1_L = linearInterpolate( m_A1wave[ static_cast<int>( A1_lphase ) ],
m_A1wave[ static_cast<int>( A1_lphase + 1 ) % WAVELEN ],
fraction( A1_lphase ) ) * m_parent->m_lvol[A1_OSC];
sample_t A1_R = linearInterpolate( m_A1wave[ static_cast<int>( A1_rphase ) ],
m_A1wave[ static_cast<int>( A1_rphase + 1 ) % WAVELEN ],
fraction( A1_rphase ) ) * m_parent->m_rvol[A1_OSC];
///////////// B-series /////////////////
// B2
sample_t B2_L = linearInterpolate( m_B2wave[ static_cast<int>( m_lphase[B2_OSC] ) ],
m_B2wave[ static_cast<int>( m_lphase[B2_OSC] + 1 ) % WAVELEN ],
fraction( m_lphase[B2_OSC] ) ) * m_parent->m_lvol[B2_OSC];
sample_t B2_R = linearInterpolate( m_B2wave[ static_cast<int>( m_rphase[B2_OSC] ) ],
m_B2wave[ static_cast<int>( m_rphase[B2_OSC] + 1 ) % WAVELEN ],
fraction( m_rphase[B2_OSC] ) ) * m_parent->m_rvol[B2_OSC];
// if crosstalk active, add a1
const float xt = m_parent->m_xtalk.value();
if( xt > 0.0 )
{
B2_L += ( A1_L * xt ) * 0.01f;
B2_R += ( A1_R * xt ) * 0.01f;
}
// if phase mod, add to phases
if( m_bmod == MOD_PM )
{
B1_lphase = fmodf( B1_lphase + B2_L * PMOD_AMT, WAVELEN );
if( B1_lphase < 0 ) B1_lphase += WAVELEN;
B1_rphase = fmodf( B1_rphase + B2_R * PMOD_AMT, WAVELEN );
if( B1_rphase < 0 ) B1_rphase += WAVELEN;
}
// B1
sample_t B1_L = linearInterpolate( m_B1wave[ static_cast<int>( B1_lphase ) % WAVELEN ],
m_B1wave[ static_cast<int>( B1_lphase + 1 ) % WAVELEN ],
fraction( B1_lphase ) ) * m_parent->m_lvol[B1_OSC];
sample_t B1_R = linearInterpolate( m_B1wave[ static_cast<int>( B1_rphase ) % WAVELEN ],
m_B1wave[ static_cast<int>( B1_rphase + 1 ) % WAVELEN ],
fraction( B1_rphase ) ) * m_parent->m_rvol[B1_OSC];
// A-series modulation)
switch( m_amod )
{
case MOD_MIX:
A1_L = ( A1_L + A2_L ) / 2.0;
A1_R = ( A1_R + A2_R ) / 2.0;
break;
case MOD_AM:
A1_L *= qMax( 0.0f, A2_L + 1.0f );
A1_R *= qMax( 0.0f, A2_R + 1.0f );
break;
case MOD_RM:
A1_L *= A2_L;
A1_R *= A2_R;
break;
}
m_abuf[frame][0] = A1_L;
m_abuf[frame][1] = A1_R;
// B-series modulation (other than phase mod)
switch( m_bmod )
{
case MOD_MIX:
B1_L = ( B1_L + B2_L ) / 2.0;
B1_R = ( B1_R + B2_R ) / 2.0;
break;
case MOD_AM:
B1_L *= qMax( 0.0f, B2_L + 1.0f );
B1_R *= qMax( 0.0f, B2_R + 1.0f );
break;
case MOD_RM:
B1_L *= B2_L;
B1_R *= B2_R;
break;
}
m_bbuf[frame][0] = B1_L;
m_bbuf[frame][1] = B1_R;
// update phases
for( int i = 0; i < NUM_OSCS; i++ )
{
m_lphase[i] += ( static_cast<float>( WAVELEN ) / ( m_samplerate / ( m_nph->frequency() * m_parent->m_lfreq[i] ) ) );
m_lphase[i] = fmodf( m_lphase[i], WAVELEN );
m_rphase[i] += ( static_cast<float>( WAVELEN ) / ( m_samplerate / ( m_nph->frequency() * m_parent->m_rfreq[i] ) ) );
m_rphase[i] = fmodf( m_rphase[i], WAVELEN );
}
}
}
WatsynInstrument::WatsynInstrument( InstrumentTrack * _instrument_track ) :
Instrument( _instrument_track, &watsyn_plugin_descriptor ),
a1_vol( 100.0f, 0.0f, 200.0f, 0.1f, this, tr( "Volume A1" ) ),
a2_vol( 100.0f, 0.0f, 200.0f, 0.1f, this, tr( "Volume A2" ) ),
b1_vol( 100.0f, 0.0f, 200.0f, 0.1f, this, tr( "Volume B1" ) ),
b2_vol( 100.0f, 0.0f, 200.0f, 0.1f, this, tr( "Volume B2" ) ),
a1_pan( 0.0f, -100.0f, 100.0f, 0.1f, this, tr( "Panning A1" ) ),
a2_pan( 0.0f, -100.0f, 100.0f, 0.1f, this, tr( "Panning A2" ) ),
b1_pan( 0.0f, -100.0f, 100.0f, 0.1f, this, tr( "Panning B1" ) ),
b2_pan( 0.0f, -100.0f, 100.0f, 0.1f, this, tr( "Panning B2" ) ),
a1_mult( 8.0f, 1.0, 24.0, 1.0, this, tr( "Freq. multiplier A1" ) ),
a2_mult( 8.0f, 1.0, 24.0, 1.0, this, tr( "Freq. multiplier A2" ) ),
b1_mult( 8.0f, 1.0, 24.0, 1.0, this, tr( "Freq. multiplier B1" ) ),
b2_mult( 8.0f, 1.0, 24.0, 1.0, this, tr( "Freq. multiplier B2" ) ),
a1_ltune( 0.0f, -600.0f, 600.0f, 1.0f, this, tr( "Left detune A1" ) ),
a2_ltune( 0.0f, -600.0f, 600.0f, 1.0f, this, tr( "Left detune A2" ) ),
b1_ltune( 0.0f, -600.0f, 600.0f, 1.0f, this, tr( "Left detune B1" ) ),
b2_ltune( 0.0f, -600.0f, 600.0f, 1.0f, this, tr( "Left detune B2" ) ),
a1_rtune( 0.0f, -600.0f, 600.0f, 1.0f, this, tr( "Right detune A1" ) ),
a2_rtune( 0.0f, -600.0f, 600.0f, 1.0f, this, tr( "Right detune A2" ) ),
b1_rtune( 0.0f, -600.0f, 600.0f, 1.0f, this, tr( "Right detune B1" ) ),
b2_rtune( 0.0f, -600.0f, 600.0f, 1.0f, this, tr( "Right detune B2" ) ),
a1_graph( -1.0f, 1.0f, GRAPHLEN, this ),
a2_graph( -1.0f, 1.0f, GRAPHLEN, this ),
b1_graph( -1.0f, 1.0f, GRAPHLEN, this ),
b2_graph( -1.0f, 1.0f, GRAPHLEN, this ),
m_abmix( 0.0f, -100.0f, 100.0f, 0.1f, this, tr( "A-B Mix" ) ),
m_envAmt( 0.0f, -200.0f, 200.0f, 1.0f, this, tr( "A-B Mix envelope amount" ) ),
m_envAtt( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "A-B Mix envelope attack" ) ),
m_envHold( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "A-B Mix envelope hold" ) ),
m_envDec( 0.0f, 0.0f, 2000.0f, 1.0f, 2000.0f, this, tr( "A-B Mix envelope decay" ) ),
m_xtalk( 0.0f, 0.0f, 100.0f, 0.1f, this, tr( "A1-B2 Crosstalk" ) ),
m_amod( 0, 0, 3, this, tr( "A2-A1 modulation" ) ),
m_bmod( 0, 0, 3, this, tr( "B2-B1 modulation" ) ),
m_selectedGraph( 0, 0, 3, this, tr( "Selected graph" ) )
{
connect( &a1_vol, SIGNAL( dataChanged() ), this, SLOT( updateVolumes() ) );
connect( &a2_vol, SIGNAL( dataChanged() ), this, SLOT( updateVolumes() ) );
connect( &b1_vol, SIGNAL( dataChanged() ), this, SLOT( updateVolumes() ) );
connect( &b2_vol, SIGNAL( dataChanged() ), this, SLOT( updateVolumes() ) );
connect( &a1_pan, SIGNAL( dataChanged() ), this, SLOT( updateVolumes() ) );
connect( &a2_pan, SIGNAL( dataChanged() ), this, SLOT( updateVolumes() ) );
connect( &b1_pan, SIGNAL( dataChanged() ), this, SLOT( updateVolumes() ) );
connect( &b2_pan, SIGNAL( dataChanged() ), this, SLOT( updateVolumes() ) );
connect( &a1_mult, SIGNAL( dataChanged() ), this, SLOT( updateFreqA1() ) );
connect( &a2_mult, SIGNAL( dataChanged() ), this, SLOT( updateFreqA2() ) );
connect( &b1_mult, SIGNAL( dataChanged() ), this, SLOT( updateFreqB1() ) );
connect( &b2_mult, SIGNAL( dataChanged() ), this, SLOT( updateFreqB2() ) );
connect( &a1_ltune, SIGNAL( dataChanged() ), this, SLOT( updateFreqA1() ) );
connect( &a2_ltune, SIGNAL( dataChanged() ), this, SLOT( updateFreqA2() ) );
connect( &b1_ltune, SIGNAL( dataChanged() ), this, SLOT( updateFreqB1() ) );
connect( &b2_ltune, SIGNAL( dataChanged() ), this, SLOT( updateFreqB2() ) );
connect( &a1_rtune, SIGNAL( dataChanged() ), this, SLOT( updateFreqA1() ) );
connect( &a2_rtune, SIGNAL( dataChanged() ), this, SLOT( updateFreqA2() ) );
connect( &b1_rtune, SIGNAL( dataChanged() ), this, SLOT( updateFreqB1() ) );
connect( &b2_rtune, SIGNAL( dataChanged() ), this, SLOT( updateFreqB2() ) );
connect( &a1_graph, SIGNAL( samplesChanged( int, int ) ), this, SLOT( updateWaveA1() ) );
connect( &a2_graph, SIGNAL( samplesChanged( int, int ) ), this, SLOT( updateWaveA2() ) );
connect( &b1_graph, SIGNAL( samplesChanged( int, int ) ), this, SLOT( updateWaveB1() ) );
connect( &b2_graph, SIGNAL( samplesChanged( int, int ) ), this, SLOT( updateWaveB2() ) );
a1_graph.setWaveToSine();
a2_graph.setWaveToSine();
b1_graph.setWaveToSine();
b2_graph.setWaveToSine();
updateVolumes();
updateFreqA1();
updateFreqA2();
updateFreqB1();
updateFreqB2();
updateWaveA1();
updateWaveA2();
updateWaveB1();
updateWaveB2();
}
void WatsynInstrument::playNote( NotePlayHandle * _n,
SampleFrame* _working_buffer )
{
if (!_n->m_pluginData)
{
auto w = new WatsynObject(&A1_wave[0], &A2_wave[0], &B1_wave[0], &B2_wave[0], m_amod.value(), m_bmod.value(),
Engine::audioEngine()->outputSampleRate(), _n, Engine::audioEngine()->framesPerPeriod(), this);
_n->m_pluginData = w;
}
const fpp_t frames = _n->framesLeftForCurrentPeriod();
const f_cnt_t offset = _n->noteOffset();
SampleFrame* buffer = _working_buffer + offset;
auto w = static_cast<WatsynObject*>(_n->m_pluginData);
SampleFrame* abuf = w->abuf();
SampleFrame* bbuf = w->bbuf();
w-> renderOutput( frames );
// envelope parameters
const float envAmt = m_envAmt.value();
const float envAtt = ( m_envAtt.value() * w->samplerate() ) / 1000.0f;
const float envHold = ( m_envHold.value() * w->samplerate() ) / 1000.0f;
const float envDec = ( m_envDec.value() * w->samplerate() ) / 1000.0f;
const float envLen = envAtt + envDec + envHold;
const auto tfp_ = static_cast<float>(_n->totalFramesPlayed());
// if sample-exact is enabled, use sample-exact calculations...
// disabled pending proper implementation of sample-exactness
/* if( engine::audioEngine()->currentQualitySettings().sampleExactControllers )
{
for( fpp_t f=0; f < frames; f++ )
{
const float tfp = tfp_ + f;
// handle mixing envelope
float mixvalue = m_abmix.value( f );
if( envAmt != 0.0f && tfp < envLen )
{
if( tfp < envAtt )
{
mixvalue = qBound( -100.0f, mixvalue + ( tfp / envAtt * envAmt ), 100.0f );
}
else if ( tfp >= envAtt && tfp < envAtt + envHold )
{
mixvalue = qBound( -100.0f, mixvalue + envAmt, 100.0f );
}
else
{
mixvalue = qBound( -100.0f, mixvalue + envAmt - ( ( tfp - ( envAtt + envHold ) ) / envDec * envAmt ), 100.0f );
}
}
// get knob values in sample-exact way
const float bmix = ( ( mixvalue + 100.0 ) / 200.0 );
const float amix = 1.0 - bmix;
// mix a/b streams according to mixing knob
_working_buffer[f][0] = ( abuf[f][0] * amix ) +
( bbuf[f][0] * bmix );
_working_buffer[f][1] = ( abuf[f][1] * amix ) +
( bbuf[f][1] * bmix );
}
}
else*/
// if sample-exact is not enabled, use simpler calculations:
// if mix envelope is active, and we haven't gone past the envelope end, use envelope-aware calculation...
if( envAmt != 0.0f && tfp_ < envLen )
{
const float mixvalue_ = m_abmix.value();
for( fpp_t f=0; f < frames; f++ )
{
float mixvalue = mixvalue_;
const float tfp = tfp_ + f;
// handle mixing envelope
if( tfp < envAtt )
{
mixvalue = qBound( -100.0f, mixvalue + ( tfp / envAtt * envAmt ), 100.0f );
}
else if ( tfp >= envAtt && tfp < envAtt + envHold )
{
mixvalue = qBound( -100.0f, mixvalue + envAmt, 100.0f );
}
else
{
mixvalue = qBound( -100.0f, mixvalue + envAmt - ( ( tfp - ( envAtt + envHold ) ) / envDec * envAmt ), 100.0f );
}
// get knob values
const float bmix = ( ( mixvalue + 100.0 ) / 200.0 );
const float amix = 1.0 - bmix;
// mix a/b streams according to mixing knob
buffer[f][0] = ( abuf[f][0] * amix ) +
( bbuf[f][0] * bmix );
buffer[f][1] = ( abuf[f][1] * amix ) +
( bbuf[f][1] * bmix );
}
}
// ... mix envelope is inactive or we've past the end of envelope, so use a faster calculation to save cpu
else
{
// get knob values
const float bmix = ( ( m_abmix.value() + 100.0 ) / 200.0 );
const float amix = 1.0 - bmix;
for( fpp_t f=0; f < frames; f++ )
{
// mix a/b streams according to mixing knob
buffer[f][0] = ( abuf[f][0] * amix ) +
( bbuf[f][0] * bmix );
buffer[f][1] = ( abuf[f][1] * amix ) +
( bbuf[f][1] * bmix );
}
}
applyRelease( _working_buffer, _n );
}
void WatsynInstrument::deleteNotePluginData( NotePlayHandle * _n )
{
delete static_cast<WatsynObject *>( _n->m_pluginData );
}
void WatsynInstrument::saveSettings( QDomDocument & _doc,
QDomElement & _this )
{
a1_vol.saveSettings( _doc, _this, "a1_vol" );
a2_vol.saveSettings( _doc, _this, "a2_vol" );
b1_vol.saveSettings( _doc, _this, "b1_vol" );
b2_vol.saveSettings( _doc, _this, "b2_vol" );
a1_pan.saveSettings( _doc, _this, "a1_pan" );
a2_pan.saveSettings( _doc, _this, "a2_pan" );
b1_pan.saveSettings( _doc, _this, "b1_pan" );
b2_pan.saveSettings( _doc, _this, "b2_pan" );
a1_mult.saveSettings( _doc, _this, "a1_mult" );
a2_mult.saveSettings( _doc, _this, "a2_mult" );
b1_mult.saveSettings( _doc, _this, "b1_mult" );
b2_mult.saveSettings( _doc, _this, "b2_mult" );
a1_ltune.saveSettings( _doc, _this, "a1_ltune" );
a2_ltune.saveSettings( _doc, _this, "a2_ltune" );
b1_ltune.saveSettings( _doc, _this, "b1_ltune" );
b2_ltune.saveSettings( _doc, _this, "b2_ltune" );
a1_rtune.saveSettings( _doc, _this, "a1_rtune" );
a2_rtune.saveSettings( _doc, _this, "a2_rtune" );
b1_rtune.saveSettings( _doc, _this, "b1_rtune" );
b2_rtune.saveSettings( _doc, _this, "b2_rtune" );
// save graphs
QString sampleString;
base64::encode( (const char *)a1_graph.samples(), a1_graph.length() * sizeof(float), sampleString );
_this.setAttribute( "a1_wave", sampleString );
base64::encode( (const char *)a2_graph.samples(), a2_graph.length() * sizeof(float), sampleString );
_this.setAttribute( "a2_wave", sampleString );
base64::encode( (const char *)b1_graph.samples(), b1_graph.length() * sizeof(float), sampleString );
_this.setAttribute( "b1_wave", sampleString );
base64::encode( (const char *)b2_graph.samples(), b2_graph.length() * sizeof(float), sampleString );
_this.setAttribute( "b2_wave", sampleString );
m_abmix.saveSettings( _doc, _this, "abmix" );
m_envAmt.saveSettings( _doc, _this, "envAmt" );
m_envAtt.saveSettings( _doc, _this, "envAtt" );
m_envHold.saveSettings( _doc, _this, "envHold" );
m_envDec.saveSettings( _doc, _this, "envDec" );
m_xtalk.saveSettings( _doc, _this, "xtalk" );
m_amod.saveSettings( _doc, _this, "amod" );
m_bmod.saveSettings( _doc, _this, "bmod" );
/* m_selectedGraph.saveSettings( _doc, _this, "selgraph" );*/
}
void WatsynInstrument::loadSettings( const QDomElement & _this )
{
a1_vol.loadSettings( _this, "a1_vol" );
a2_vol.loadSettings( _this, "a2_vol" );
b1_vol.loadSettings( _this, "b1_vol" );
b2_vol.loadSettings( _this, "b2_vol" );
a1_pan.loadSettings( _this, "a1_pan" );
a2_pan.loadSettings( _this, "a2_pan" );
b1_pan.loadSettings( _this, "b1_pan" );
b2_pan.loadSettings( _this, "b2_pan" );
a1_mult.loadSettings( _this, "a1_mult" );
a2_mult.loadSettings( _this, "a2_mult" );
b1_mult.loadSettings( _this, "b1_mult" );
b2_mult.loadSettings( _this, "b2_mult" );
a1_ltune.loadSettings( _this, "a1_ltune" );
a2_ltune.loadSettings( _this, "a2_ltune" );
b1_ltune.loadSettings( _this, "b1_ltune" );
b2_ltune.loadSettings( _this, "b2_ltune" );
a1_rtune.loadSettings( _this, "a1_rtune" );
a2_rtune.loadSettings( _this, "a2_rtune" );
b1_rtune.loadSettings( _this, "b1_rtune" );
b2_rtune.loadSettings( _this, "b2_rtune" );
// load graphs
int size = 0;
char * dst = 0;
base64::decode( _this.attribute( "a1_wave"), &dst, &size );
a1_graph.setSamples( (float*) dst );
base64::decode( _this.attribute( "a2_wave"), &dst, &size );
a2_graph.setSamples( (float*) dst );
base64::decode( _this.attribute( "b1_wave"), &dst, &size );
b1_graph.setSamples( (float*) dst );
base64::decode( _this.attribute( "b2_wave"), &dst, &size );
b2_graph.setSamples( (float*) dst );
delete[] dst;
m_abmix.loadSettings( _this, "abmix" );
m_envAmt.loadSettings( _this, "envAmt" );
m_envAtt.loadSettings( _this, "envAtt" );
m_envHold.loadSettings( _this, "envHold" );
m_envDec.loadSettings( _this, "envDec" );
m_xtalk.loadSettings( _this, "xtalk" );
m_amod.loadSettings( _this, "amod" );
m_bmod.loadSettings( _this, "bmod" );
/* m_selectedGraph.loadSettings( _this, "selgraph" );*/
}
QString WatsynInstrument::nodeName() const
{
return( watsyn_plugin_descriptor.name );
}
gui::PluginView* WatsynInstrument::instantiateView( QWidget * _parent )
{
return( new gui::WatsynView( this, _parent ) );
}
void WatsynInstrument::updateVolumes()
{
m_lvol[A1_OSC] = leftCh( a1_vol.value(), a1_pan.value() );
m_rvol[A1_OSC] = rightCh( a1_vol.value(), a1_pan.value() );
m_lvol[A2_OSC] = leftCh( a2_vol.value(), a2_pan.value() );
m_rvol[A2_OSC] = rightCh( a2_vol.value(), a2_pan.value() );
m_lvol[B1_OSC] = leftCh( b1_vol.value(), b1_pan.value() );
m_rvol[B1_OSC] = rightCh( b1_vol.value(), b1_pan.value() );
m_lvol[B2_OSC] = leftCh( b2_vol.value(), b2_pan.value() );
m_rvol[B2_OSC] = rightCh( b2_vol.value(), b2_pan.value() );
}
void WatsynInstrument::updateFreqA1()
{
// calculate frequencies
m_lfreq[A1_OSC] = ( a1_mult.value() / 8 ) * powf( 2, a1_ltune.value() / 1200 );
m_rfreq[A1_OSC] = ( a1_mult.value() / 8 ) * powf( 2, a1_rtune.value() / 1200 );
}
void WatsynInstrument::updateFreqA2()
{
// calculate frequencies
m_lfreq[A2_OSC] = ( a2_mult.value() / 8 ) * powf( 2, a2_ltune.value() / 1200 );
m_rfreq[A2_OSC] = ( a2_mult.value() / 8 ) * powf( 2, a2_rtune.value() / 1200 );
}
void WatsynInstrument::updateFreqB1()
{
// calculate frequencies
m_lfreq[B1_OSC] = ( b1_mult.value() / 8 ) * powf( 2, b1_ltune.value() / 1200 );
m_rfreq[B1_OSC] = ( b1_mult.value() / 8 ) * powf( 2, b1_rtune.value() / 1200 );
}
void WatsynInstrument::updateFreqB2()
{
// calculate frequencies
m_lfreq[B2_OSC] = ( b2_mult.value() / 8 ) * powf( 2, b2_ltune.value() / 1200 );
m_rfreq[B2_OSC] = ( b2_mult.value() / 8 ) * powf( 2, b2_rtune.value() / 1200 );
}
void WatsynInstrument::updateWaveA1()
{
// do sinc+oversampling on the wavetables to improve quality
srccpy( &A1_wave[0], const_cast<float*>( a1_graph.samples() ) );
}
void WatsynInstrument::updateWaveA2()
{
// do sinc+oversampling on the wavetables to improve quality
srccpy( &A2_wave[0], const_cast<float*>( a2_graph.samples() ) );
}
void WatsynInstrument::updateWaveB1()
{
// do sinc+oversampling on the wavetables to improve quality
srccpy( &B1_wave[0], const_cast<float*>( b1_graph.samples() ) );
}
void WatsynInstrument::updateWaveB2()
{
// do sinc+oversampling on the wavetables to improve quality
srccpy( &B2_wave[0], const_cast<float*>( b2_graph.samples() ) );
}
namespace gui
{
WatsynView::WatsynView( Instrument * _instrument,
QWidget * _parent ) :
InstrumentViewFixedSize( _instrument, _parent )
{
setAutoFillBackground( true );
QPalette pal;
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap( "artwork" ) );
setPalette( pal );
// knobs... lots of em
makeknob( a1_volKnob, 130, A1ROW, tr( "Volume" ), "%", "aKnob" )
makeknob( a2_volKnob, 130, A2ROW, tr( "Volume" ), "%", "aKnob" )
makeknob( b1_volKnob, 130, B1ROW, tr( "Volume" ), "%", "bKnob" )
makeknob( b2_volKnob, 130, B2ROW, tr( "Volume" ), "%", "bKnob" )
makeknob( a1_panKnob, 154, A1ROW, tr( "Panning" ), "", "aKnob" )
makeknob( a2_panKnob, 154, A2ROW, tr( "Panning" ), "", "aKnob" )
makeknob( b1_panKnob, 154, B1ROW, tr( "Panning" ), "", "bKnob" )
makeknob( b2_panKnob, 154, B2ROW, tr( "Panning" ), "", "bKnob" )
makeknob( a1_multKnob, 178, A1ROW, tr( "Freq. multiplier" ), "/8", "aKnob" )
makeknob( a2_multKnob, 178, A2ROW, tr( "Freq. multiplier" ), "/8", "aKnob" )
makeknob( b1_multKnob, 178, B1ROW, tr( "Freq. multiplier" ), "/8", "bKnob" )
makeknob( b2_multKnob, 178, B2ROW, tr( "Freq. multiplier" ), "/8", "bKnob" )
makeknob( a1_ltuneKnob, 202, A1ROW, tr( "Left detune" ), tr( " cents" ), "aKnob" )
makeknob( a2_ltuneKnob, 202, A2ROW, tr( "Left detune" ), tr( " cents" ), "aKnob" )
makeknob( b1_ltuneKnob, 202, B1ROW, tr( "Left detune" ), tr( " cents" ), "bKnob" )
makeknob( b2_ltuneKnob, 202, B2ROW, tr( "Left detune" ), tr( " cents" ), "bKnob" )
makeknob( a1_rtuneKnob, 226, A1ROW, tr( "Right detune" ), tr( " cents" ), "aKnob" )
makeknob( a2_rtuneKnob, 226, A2ROW, tr( "Right detune" ), tr( " cents" ), "aKnob" )
makeknob( b1_rtuneKnob, 226, B1ROW, tr( "Right detune" ), tr( " cents" ), "bKnob" )
makeknob( b2_rtuneKnob, 226, B2ROW, tr( "Right detune" ), tr( " cents" ), "bKnob" )
makeknob( m_abmixKnob, 4, 3, tr( "A-B Mix" ), "", "mixKnob" )
makeknob( m_envAmtKnob, 88, 3, tr( "Mix envelope amount" ), "", "mixenvKnob" )
maketsknob( m_envAttKnob, 88, A1ROW, tr( "Mix envelope attack" ), " ms", "mixenvKnob" )
maketsknob( m_envHoldKnob, 88, A2ROW, tr( "Mix envelope hold" ), " ms", "mixenvKnob" )
maketsknob( m_envDecKnob, 88, B1ROW, tr( "Mix envelope decay" ), " ms", "mixenvKnob" )
makeknob( m_xtalkKnob, 88, B2ROW, tr( "Crosstalk" ), "", "xtalkKnob" )
// let's set volume knobs
a1_volKnob -> setVolumeKnob( true );
a2_volKnob -> setVolumeKnob( true );
b1_volKnob -> setVolumeKnob( true );
b2_volKnob -> setVolumeKnob( true );
m_abmixKnob -> setFixedSize( 31, 31 );
// button groups next.
// graph select buttons
auto a1_selectButton = new PixmapButton(this, nullptr);
a1_selectButton -> move( 4, 121 );
a1_selectButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "a1_active" ) );
a1_selectButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "a1_inactive" ) );
a1_selectButton->setToolTip(tr("Select oscillator A1"));
auto a2_selectButton = new PixmapButton(this, nullptr);
a2_selectButton -> move( 44, 121 );
a2_selectButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "a2_active" ) );
a2_selectButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "a2_inactive" ) );
a2_selectButton->setToolTip(tr("Select oscillator A2"));
auto b1_selectButton = new PixmapButton(this, nullptr);
b1_selectButton -> move( 84, 121 );
b1_selectButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "b1_active" ) );
b1_selectButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "b1_inactive" ) );
b1_selectButton->setToolTip(tr("Select oscillator B1"));
auto b2_selectButton = new PixmapButton(this, nullptr);
b2_selectButton -> move( 124, 121 );
b2_selectButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "b2_active" ) );
b2_selectButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "b2_inactive" ) );
b2_selectButton->setToolTip(tr("Select oscillator B2"));
m_selectedGraphGroup = new automatableButtonGroup( this );
m_selectedGraphGroup -> addButton( a1_selectButton );
m_selectedGraphGroup -> addButton( a2_selectButton );
m_selectedGraphGroup -> addButton( b1_selectButton );
m_selectedGraphGroup -> addButton( b2_selectButton );
auto w = castModel<WatsynInstrument>();
m_selectedGraphGroup -> setModel( &w -> m_selectedGraph);
// A-modulation button group
auto amod_mixButton = new PixmapButton(this, nullptr);
amod_mixButton -> move( 4, 50 );
amod_mixButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "amix_active" ) );
amod_mixButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "amix_inactive" ) );
amod_mixButton->setToolTip(tr("Mix output of A2 to A1"));
auto amod_amButton = new PixmapButton(this, nullptr);
amod_amButton -> move( 4, 66 );
amod_amButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "aam_active" ) );
amod_amButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "aam_inactive" ) );
amod_amButton->setToolTip(tr("Modulate amplitude of A1 by output of A2"));
auto amod_rmButton = new PixmapButton(this, nullptr);
amod_rmButton -> move( 4, 82 );
amod_rmButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "arm_active" ) );
amod_rmButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "arm_inactive" ) );
amod_rmButton->setToolTip(tr("Ring modulate A1 and A2"));
auto amod_pmButton = new PixmapButton(this, nullptr);
amod_pmButton -> move( 4, 98 );
amod_pmButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "apm_active" ) );
amod_pmButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "apm_inactive" ) );
amod_pmButton->setToolTip(tr("Modulate phase of A1 by output of A2"));
m_aModGroup = new automatableButtonGroup( this );
m_aModGroup -> addButton( amod_mixButton );
m_aModGroup -> addButton( amod_amButton );
m_aModGroup -> addButton( amod_rmButton );
m_aModGroup -> addButton( amod_pmButton );
// B-modulation button group
auto bmod_mixButton = new PixmapButton(this, nullptr);
bmod_mixButton -> move( 44, 50 );
bmod_mixButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "bmix_active" ) );
bmod_mixButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "bmix_inactive" ) );
bmod_mixButton->setToolTip(tr("Mix output of B2 to B1"));
auto bmod_amButton = new PixmapButton(this, nullptr);
bmod_amButton -> move( 44, 66 );
bmod_amButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "bam_active" ) );
bmod_amButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "bam_inactive" ) );
bmod_amButton->setToolTip(tr("Modulate amplitude of B1 by output of B2"));
auto bmod_rmButton = new PixmapButton(this, nullptr);
bmod_rmButton -> move( 44, 82 );
bmod_rmButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "brm_active" ) );
bmod_rmButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "brm_inactive" ) );
bmod_rmButton->setToolTip(tr("Ring modulate B1 and B2"));
auto bmod_pmButton = new PixmapButton(this, nullptr);
bmod_pmButton -> move( 44, 98 );
bmod_pmButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "bpm_active" ) );
bmod_pmButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "bpm_inactive" ) );
bmod_pmButton->setToolTip(tr("Modulate phase of B1 by output of B2"));
m_bModGroup = new automatableButtonGroup( this );
m_bModGroup -> addButton( bmod_mixButton );
m_bModGroup -> addButton( bmod_amButton );
m_bModGroup -> addButton( bmod_rmButton );
m_bModGroup -> addButton( bmod_pmButton );
// graph widgets
pal = QPalette();
pal.setBrush( backgroundRole(), PLUGIN_NAME::getIconPixmap("wavegraph") );
// a1 graph
a1_graph = new Graph( this, Graph::Style::Linear, 224, 105 );
a1_graph->move( 4, 141 );
a1_graph->setAutoFillBackground( true );
a1_graph->setGraphColor( QColor( 0x43, 0xb2, 0xff ) );
a1_graph->setToolTip(tr("Draw your own waveform here by dragging your mouse on this graph."));
a1_graph->setPalette( pal );
// a2 graph
a2_graph = new Graph( this, Graph::Style::Linear, 224, 105 );
a2_graph->move( 4, 141 );
a2_graph->setAutoFillBackground( true );
a2_graph->setGraphColor( QColor( 0x43, 0xb2, 0xff ) );
a2_graph->setToolTip(tr("Draw your own waveform here by dragging your mouse on this graph."));
a2_graph->setPalette( pal );
// b1 graph
b1_graph = new Graph( this, Graph::Style::Linear, 224, 105 );
b1_graph->move( 4, 141 );
b1_graph->setAutoFillBackground( true );
b1_graph->setGraphColor( QColor( 0xfc, 0x54, 0x31 ) );
b1_graph->setToolTip(tr("Draw your own waveform here by dragging your mouse on this graph."));
b1_graph->setPalette( pal );
// b2 graph
b2_graph = new Graph( this, Graph::Style::Linear, 224, 105 );
b2_graph->move( 4, 141 );
b2_graph->setAutoFillBackground( true );
b2_graph->setGraphColor( QColor( 0xfc, 0x54, 0x31 ) );
b2_graph->setToolTip(tr("Draw your own waveform here by dragging your mouse on this graph."));
b2_graph->setPalette( pal );
// misc pushbuttons
// waveform modifications
m_loadButton = new PixmapButton( this, tr( "Load waveform" ) );
m_loadButton -> move ( 173, 121 );
m_loadButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "load_active" ) );
m_loadButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "load_inactive" ) );
m_loadButton->setToolTip(tr("Load a waveform from a sample file"));
m_phaseLeftButton = new PixmapButton( this, tr( "Phase left" ) );
m_phaseLeftButton -> move ( 193, 121 );
m_phaseLeftButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "phl_active" ) );
m_phaseLeftButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "phl_inactive" ) );
m_phaseLeftButton->setToolTip(tr("Shift phase by -15 degrees"));
m_phaseRightButton = new PixmapButton( this, tr( "Phase right" ) );
m_phaseRightButton -> move ( 210, 121 );
m_phaseRightButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "phr_active" ) );
m_phaseRightButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "phr_inactive" ) );
m_phaseRightButton->setToolTip(tr("Shift phase by +15 degrees"));
m_normalizeButton = new PixmapButton( this, tr( "Normalize" ) );
m_normalizeButton -> move ( 230, 121 );
m_normalizeButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "norm_active" ) );
m_normalizeButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "norm_inactive" ) );
m_normalizeButton->setToolTip(tr("Normalize"));
m_invertButton = new PixmapButton( this, tr( "Invert" ) );
m_invertButton -> move ( 230, 138 );
m_invertButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "inv_active" ) );
m_invertButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "inv_inactive" ) );
m_invertButton->setToolTip(tr("Invert"));
m_smoothButton = new PixmapButton( this, tr( "Smooth" ) );
m_smoothButton -> move ( 230, 155 );
m_smoothButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "smooth_active" ) );
m_smoothButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "smooth_inactive" ) );
m_smoothButton->setToolTip(tr("Smooth"));
// waveforms
m_sinWaveButton = new PixmapButton( this, tr( "Sine wave" ) );
m_sinWaveButton -> move ( 230, 176 );
m_sinWaveButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "sin_active" ) );
m_sinWaveButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "sin_inactive" ) );
m_sinWaveButton->setToolTip(tr("Sine wave"));
m_triWaveButton = new PixmapButton( this, tr( "Triangle wave" ) );
m_triWaveButton -> move ( 230, 194 );
m_triWaveButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "tri_active" ) );
m_triWaveButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "tri_inactive" ) );
m_triWaveButton->setToolTip(tr("Triangle wave"));
m_sawWaveButton = new PixmapButton( this, tr( "Triangle wave" ) );
m_sawWaveButton -> move ( 230, 212 );
m_sawWaveButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "saw_active" ) );
m_sawWaveButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "saw_inactive" ) );
m_sawWaveButton->setToolTip(tr("Saw wave"));
m_sqrWaveButton = new PixmapButton( this, tr( "Square wave" ) );
m_sqrWaveButton -> move ( 230, 230 );
m_sqrWaveButton -> setActiveGraphic( PLUGIN_NAME::getIconPixmap( "sqr_active" ) );
m_sqrWaveButton -> setInactiveGraphic( PLUGIN_NAME::getIconPixmap( "sqr_inactive" ) );
m_sqrWaveButton->setToolTip(tr("Square wave"));
connect( m_sinWaveButton, SIGNAL( clicked() ), this, SLOT( sinWaveClicked() ) );
connect( m_triWaveButton, SIGNAL( clicked() ), this, SLOT( triWaveClicked() ) );
connect( m_sawWaveButton, SIGNAL( clicked() ), this, SLOT( sawWaveClicked() ) );
connect( m_sqrWaveButton, SIGNAL( clicked() ), this, SLOT( sqrWaveClicked() ) );
connect( m_normalizeButton, SIGNAL( clicked() ), this, SLOT( normalizeClicked() ) );
connect( m_invertButton, SIGNAL( clicked() ), this, SLOT( invertClicked() ) );
connect( m_smoothButton, SIGNAL( clicked() ), this, SLOT( smoothClicked() ) );
connect( m_phaseLeftButton, SIGNAL( clicked() ), this, SLOT( phaseLeftClicked() ) );
connect( m_phaseRightButton, SIGNAL( clicked() ), this, SLOT( phaseRightClicked() ) );
connect( m_loadButton, SIGNAL( clicked() ), this, SLOT( loadClicked() ) );
connect( a1_selectButton, SIGNAL( clicked() ), this, SLOT( updateLayout() ) );
connect( a2_selectButton, SIGNAL( clicked() ), this, SLOT( updateLayout() ) );
connect( b1_selectButton, SIGNAL( clicked() ), this, SLOT( updateLayout() ) );
connect( b2_selectButton, SIGNAL( clicked() ), this, SLOT( updateLayout() ) );
updateLayout();
}
void WatsynView::updateLayout()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->show();
a2_graph->hide();
b1_graph->hide();
b2_graph->hide();
break;
case A2_OSC:
a1_graph->hide();
a2_graph->show();
b1_graph->hide();
b2_graph->hide();
break;
case B1_OSC:
a1_graph->hide();
a2_graph->hide();
b1_graph->show();
b2_graph->hide();
break;
case B2_OSC:
a1_graph->hide();
a2_graph->hide();
b1_graph->hide();
b2_graph->show();
break;
}
}
void WatsynView::sinWaveClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->setWaveToSine();
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->setWaveToSine();
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->setWaveToSine();
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->setWaveToSine();
Engine::getSong()->setModified();
break;
}
}
void WatsynView::triWaveClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->setWaveToTriangle();
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->setWaveToTriangle();
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->setWaveToTriangle();
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->setWaveToTriangle();
Engine::getSong()->setModified();
break;
}
}
void WatsynView::sawWaveClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->setWaveToSaw();
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->setWaveToSaw();
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->setWaveToSaw();
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->setWaveToSaw();
Engine::getSong()->setModified();
break;
}
}
void WatsynView::sqrWaveClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->setWaveToSquare();
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->setWaveToSquare();
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->setWaveToSquare();
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->setWaveToSquare();
Engine::getSong()->setModified();
break;
}
}
void WatsynView::normalizeClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->normalize();
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->normalize();
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->normalize();
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->normalize();
Engine::getSong()->setModified();
break;
}
}
void WatsynView::invertClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->invert();
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->invert();
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->invert();
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->invert();
Engine::getSong()->setModified();
break;
}
}
void WatsynView::smoothClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->smooth();
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->smooth();
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->smooth();
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->smooth();
Engine::getSong()->setModified();
break;
}
}
void WatsynView::phaseLeftClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->shiftPhase( -15 );
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->shiftPhase( -15 );
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->shiftPhase( -15 );
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->shiftPhase( -15 );
Engine::getSong()->setModified();
break;
}
}
void WatsynView::phaseRightClicked()
{
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->shiftPhase( 15 );
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->shiftPhase( 15 );
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->shiftPhase( 15 );
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->shiftPhase( 15 );
Engine::getSong()->setModified();
break;
}
}
void WatsynView::loadClicked()
{
QString fileName;
switch( m_selectedGraphGroup->model()->value() )
{
case A1_OSC:
a1_graph->model()->setWaveToUser();
Engine::getSong()->setModified();
break;
case A2_OSC:
a2_graph->model()->setWaveToUser();
Engine::getSong()->setModified();
break;
case B1_OSC:
b1_graph->model()->setWaveToUser();
Engine::getSong()->setModified();
break;
case B2_OSC:
b2_graph->model()->setWaveToUser();
Engine::getSong()->setModified();
break;
}
}
void WatsynView::modelChanged()
{
auto w = castModel<WatsynInstrument>();
a1_volKnob -> setModel( &w -> a1_vol );
a2_volKnob -> setModel( &w -> a2_vol );
b1_volKnob -> setModel( &w -> b1_vol );
b2_volKnob -> setModel( &w -> b2_vol );
a1_panKnob -> setModel( &w -> a1_pan );
a2_panKnob -> setModel( &w -> a2_pan );
b1_panKnob -> setModel( &w -> b1_pan );
b2_panKnob -> setModel( &w -> b2_pan );
a1_multKnob -> setModel( &w -> a1_mult );
a2_multKnob -> setModel( &w -> a2_mult );
b1_multKnob -> setModel( &w -> b1_mult );
b2_multKnob -> setModel( &w -> b2_mult );
a1_ltuneKnob -> setModel( &w -> a1_ltune );
a2_ltuneKnob -> setModel( &w -> a2_ltune );
b1_ltuneKnob -> setModel( &w -> b1_ltune );
b2_ltuneKnob -> setModel( &w -> b2_ltune );
a1_rtuneKnob -> setModel( &w -> a1_rtune );
a2_rtuneKnob -> setModel( &w -> a2_rtune );
b1_rtuneKnob -> setModel( &w -> b1_rtune );
b2_rtuneKnob -> setModel( &w -> b2_rtune );
m_abmixKnob -> setModel( &w -> m_abmix );
m_selectedGraphGroup -> setModel( &w -> m_selectedGraph );
m_aModGroup -> setModel( &w -> m_amod );
m_bModGroup -> setModel( &w -> m_bmod );
a1_graph -> setModel( &w -> a1_graph );
a2_graph -> setModel( &w -> a2_graph );
b1_graph -> setModel( &w -> b1_graph );
b2_graph -> setModel( &w -> b2_graph );
m_envAmtKnob -> setModel( &w -> m_envAmt );
m_envAttKnob -> setModel( &w -> m_envAtt );
m_envHoldKnob -> setModel( &w -> m_envHold );
m_envDecKnob -> setModel( &w -> m_envDec );
m_xtalkKnob -> setModel( &w -> m_xtalk );
}
} // namespace gui
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *m, void * )
{
return( new WatsynInstrument( static_cast<InstrumentTrack *>( m ) ) );
}
}
} // namespace lmms
| 42,276
|
C++
|
.cpp
| 1,054
| 37.246679
| 119
| 0.660975
|
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,619
|
LocalFileMng.cpp
|
LMMS_lmms/plugins/HydrogenImport/LocalFileMng.cpp
|
#include "LocalFileMng.h"
#include <cctype>
#include <QDomDocument>
#include <QFile>
#include <QLocale>
namespace lmms
{
/* New QtXml based methods */
QString LocalFileMng::readXmlString( QDomNode node , const QString& nodeName, const QString& defaultValue, bool bCanBeEmpty, bool bShouldExists, bool tinyXmlCompatMode)
{
QDomElement element = node.firstChildElement( nodeName );
if( !node.isNull() && !element.isNull() ){
if( !element.text().isEmpty() ){
return element.text();
} else {
if ( !bCanBeEmpty ) {
//_WARNINGLOG( "Using default value in " + nodeName );
}
return defaultValue;
}
} else {
if( bShouldExists ){
//_WARNINGLOG( "'" + nodeName + "' node not found" );
}
return defaultValue;
}
}
float LocalFileMng::readXmlFloat( QDomNode node , const QString& nodeName, float defaultValue, bool bCanBeEmpty, bool bShouldExists, bool tinyXmlCompatMode)
{
QLocale c_locale = QLocale::c();
QDomElement element = node.firstChildElement( nodeName );
if( !node.isNull() && !element.isNull() ){
if( !element.text().isEmpty() ){
return c_locale.toFloat(element.text());
} else {
if ( !bCanBeEmpty ) {
//_WARNINGLOG( "Using default value in " + nodeName );
}
return defaultValue;
}
} else {
if( bShouldExists ){
//_WARNINGLOG( "'" + nodeName + "' node not found" );
}
return defaultValue;
}
}
int LocalFileMng::readXmlInt( QDomNode node , const QString& nodeName, int defaultValue, bool bCanBeEmpty, bool bShouldExists, bool tinyXmlCompatMode)
{
QLocale c_locale = QLocale::c();
QDomElement element = node.firstChildElement( nodeName );
if( !node.isNull() && !element.isNull() ){
if( !element.text().isEmpty() ){
return c_locale.toInt( element.text() );
} else {
if ( !bCanBeEmpty ) {
//_WARNINGLOG( "Using default value in " + nodeName );
}
return defaultValue;
}
} else {
if( bShouldExists ){
//_WARNINGLOG( "'" + nodeName + "' node not found" );
}
return defaultValue;
}
}
bool LocalFileMng::readXmlBool( QDomNode node , const QString& nodeName, bool defaultValue, bool bShouldExists, bool tinyXmlCompatMode)
{
QDomElement element = node.firstChildElement( nodeName );
if( !node.isNull() && !element.isNull() ){
if( !element.text().isEmpty() ){
if( element.text() == "true"){
return true;
} else {
return false;
}
} else {
//_WARNINGLOG( "Using default value in " + nodeName );
return defaultValue;
}
} else {
if( bShouldExists ){
//_WARNINGLOG( "'" + nodeName + "' node not found" );
}
return defaultValue;
}
}
/* Convert (in-place) an XML escape sequence into a literal byte,
* rather than the character it actually refers to.
*/
void LocalFileMng::convertFromTinyXMLString( QByteArray* str )
{
/* When TinyXML encountered a non-ASCII character, it would
* simply write the character as "&#xx;" -- where "xx" is
* the hex character code. However, this doesn't respect
* any encodings (e.g. UTF-8, UTF-16). In XML, &#xx; literally
* means "the Unicode character # xx." However, in a UTF-8
* sequence, this could be an escape character that tells
* whether we have a 2, 3, or 4-byte UTF-8 sequence.
*
* For example, the UTF-8 sequence 0xD184 was being written
* by TinyXML as "Ñ„". However, this is the UTF-8
* sequence for the cyrillic small letter EF (which looks
* kind of like a thorn or a greek phi). This letter, in
* XML, should be saved as ф, or even literally
* (no escaping). As a consequence, when Ñ is read
* by an XML parser, it will be interpreted as capital N
* with a tilde (~). Then „ will be interpreted as
* an unknown or control character.
*
* So, when we know that TinyXML wrote the file, we can
* simply exchange these hex sequences to literal bytes.
*/
int pos = 0;
pos = str->indexOf("&#x");
while( pos != -1 ) {
if( isxdigit(str->at(pos+3))
&& isxdigit(str->at(pos+4))
&& (str->at(pos+5) == ';') ) {
char w1 = str->at(pos+3);
char w2 = str->at(pos+4);
w1 = tolower(w1) - 0x30; // '0' = 0x30
if( w1 > 9 ) w1 -= 0x27; // '9' = 0x39, 'a' = 0x61
w1 = (w1 & 0xF);
w2 = tolower(w2) - 0x30; // '0' = 0x30
if( w2 > 9 ) w2 -= 0x27; // '9' = 0x39, 'a' = 0x61
w2 = (w2 & 0xF);
char ch = (w1 << 4) | w2;
(*str)[pos] = ch;
++pos;
str->remove(pos, 5);
}
pos = str->indexOf("&#x");
}
}
bool LocalFileMng::checkTinyXMLCompatMode( const QString& filename )
{
/*
Check if filename was created with TinyXml or QtXml
TinyXML: return true
QtXml: return false
*/
QFile file( filename );
if ( !file.open(QIODevice::ReadOnly) )
return false;
QString line = file.readLine();
file.close();
if ( line.startsWith( "<?xml" )){
return false;
} else {
//_WARNINGLOG( QString("File '%1' is being read in "
// "TinyXML compatability mode")
// .arg(filename) );
return true;
}
}
QDomDocument LocalFileMng::openXmlDocument( const QString& filename )
{
bool TinyXMLCompat = LocalFileMng::checkTinyXMLCompatMode( filename );
QDomDocument doc;
QFile file( filename );
if ( !file.open(QIODevice::ReadOnly) )
return QDomDocument();
if( TinyXMLCompat ) {
const QString enc = "UTF-8"; // unknown encoding, so assume utf-8 and call it a day
QByteArray line;
QByteArray buf = QString("<?xml version='1.0' encoding='%1' ?>\n")
.arg( enc )
.toLocal8Bit();
//_INFOLOG( QString("Using '%1' encoding for TinyXML file").arg(enc) );
while( !file.atEnd() ) {
line = file.readLine();
LocalFileMng::convertFromTinyXMLString( &line );
buf += line;
}
if( ! doc.setContent( buf ) ) {
file.close();
return QDomDocument();
}
} else {
if( ! doc.setContent( &file ) ) {
file.close();
return QDomDocument();
}
}
file.close();
return doc;
}
} // namespace lmms
| 5,899
|
C++
|
.cpp
| 190
| 27.857895
| 168
| 0.659954
|
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,620
|
HydrogenImport.cpp
|
LMMS_lmms/plugins/HydrogenImport/HydrogenImport.cpp
|
#include "HydrogenImport.h"
#include <QDomDocument>
#include "LocalFileMng.h"
#include "Song.h"
#include "Engine.h"
#include "Instrument.h"
#include "InstrumentTrack.h"
#include "Note.h"
#include "MidiClip.h"
#include "PatternStore.h"
#include "Track.h"
#include "plugin_export.h"
#define MAX_LAYERS 4
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT hydrogenimport_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Hydrogen Import",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Filter for importing Hydrogen files into LMMS" ),
"frank mather",
0x0100,
Plugin::Type::ImportFilter,
nullptr,
nullptr,
nullptr,
} ;
}
QString filename;
class NoteKey
{
public:
enum class Key {
C = 0,
Cs,
D,
Ef,
E,
F,
Fs,
G,
Af,
A,
Bf,
B,
};
static int stringToNoteKey( const QString& str )
{
auto m_key = Key::C;
QString sKey = str.left( str.length() - 1 );
QString sOct = str.mid( str.length() - 1, str.length() );
if ( sKey.endsWith( "-" ) )
{
sKey.replace( "-", "" );
sOct.insert( 0, "-" );
}
int nOctave = sOct.toInt();
if ( sKey == "C" )
{
m_key = Key::C;
}
else if ( sKey == "Cs" )
{
m_key = Key::Cs;
}
else if ( sKey == "D" )
{
m_key = Key::D;
}
else if ( sKey == "Ef" )
{
m_key = Key::Ef;
}
else if ( sKey == "E" )
{
m_key = Key::E;
}
else if ( sKey == "F" )
{
m_key = Key::F;
}
else if ( sKey == "Fs" )
{
m_key = Key::Fs;
}
else if ( sKey == "G" )
{
m_key = Key::G;
}
else if ( sKey == "Af" )
{
m_key = Key::Af;
}
else if ( sKey == "A" )
{
m_key = Key::A;
}
else if ( sKey == "Bf" )
{
m_key = Key::Bf;
}
else if ( sKey == "B" ) {
m_key = Key::B;
}
// Hydrogen records MIDI notes from C-1 to B5, and exports them as a number ranging from -3 to 3
return static_cast<int>(m_key) + ((nOctave + 3) * 12);
}
};
HydrogenImport::HydrogenImport( const QString & _file ) :
ImportFilter( _file, &hydrogenimport_plugin_descriptor )
{
filename = _file;
}
Instrument * ins;
bool HydrogenImport::readSong()
{
QHash<QString, InstrumentTrack *> drum_track;
QHash<QString, int> pattern_length;
QHash<QString, int> pattern_id;
Song *s = Engine::getSong();
int song_num_tracks = s->tracks().size();
if ( QFile( filename ).exists() == false )
{
printf( "Song file not found \n" );
return false;
}
QDomDocument doc = LocalFileMng::openXmlDocument( filename );
QDomNodeList nodeList = doc.elementsByTagName( "song" );
if( nodeList.isEmpty() )
{
printf( "Error reading song: song node not found\n" );
return false;
}
QDomNode songNode = nodeList.at( 0 );
QString m_sSongVersion = LocalFileMng::readXmlString( songNode , "version", "Unknown version" );
QString sName( LocalFileMng::readXmlString( songNode, "name", "Untitled Song" ) );
QString sAuthor( LocalFileMng::readXmlString( songNode, "author", "Unknown Author" ) );
QString sNotes( LocalFileMng::readXmlString( songNode, "notes", "..." ) );
QString sLicense( LocalFileMng::readXmlString( songNode, "license", "Unknown license" ) );
QString sMode = LocalFileMng::readXmlString( songNode, "mode", "pattern" );
QDomNode instrumentListNode = songNode.firstChildElement( "instrumentList" );
if ( ( ! instrumentListNode.isNull() ) )
{
int instrumentList_count = 0;
QDomNode instrumentNode;
instrumentNode = instrumentListNode.firstChildElement( "instrument" );
while ( ! instrumentNode.isNull() )
{
instrumentList_count++;
QString sId = LocalFileMng::readXmlString( instrumentNode, "id", "" ); // instrument id
QString sDrumkit = LocalFileMng::readXmlString( instrumentNode, "drumkit", "" ); // drumkit
QString sName = LocalFileMng::readXmlString( instrumentNode, "name", "" ); // name
float fVolume = LocalFileMng::readXmlFloat( instrumentNode, "volume", 1.0 ); // volume
float fPan_L = LocalFileMng::readXmlFloat( instrumentNode, "pan_L", 0.5 ); // pan L
float fPan_R = LocalFileMng::readXmlFloat( instrumentNode, "pan_R", 0.5 ); // pan R
if ( sId.isEmpty() ) {
printf( "Empty ID for instrument. skipping \n" );
instrumentNode = (QDomNode) instrumentNode.nextSiblingElement( "instrument" );
continue;
}
QDomNode filenameNode = instrumentNode.firstChildElement( "filename" );
if ( ! filenameNode.isNull() )
{
return false;
}
else
{
unsigned nLayer = 0;
QDomNode instrumentComponentNode = instrumentNode.firstChildElement("instrumentComponent");
if (instrumentComponentNode.isNull())
{
instrumentComponentNode = instrumentNode;
}
QDomNode layerNode = instrumentComponentNode.firstChildElement( "layer" );
while ( ! layerNode.isNull() )
{
if ( nLayer >= MAX_LAYERS )
{
printf("nLayer >= MAX_LAYERS\n");
break;
}
QString sFilename = LocalFileMng::readXmlString( layerNode, "filename", "" );
QString sMode = LocalFileMng::readXmlString( layerNode, "smode", "forward" );
if ( nLayer == 0 )
{
drum_track[sId] = static_cast<InstrumentTrack*>(
Track::create(Track::Type::Instrument, Engine::patternStore())
);
drum_track[sId]->volumeModel()->setValue( fVolume * 100 );
drum_track[sId]->panningModel()->setValue( ( fPan_R - fPan_L ) * 100 );
ins = drum_track[sId]->loadInstrument( "audiofileprocessor" );
ins->loadFile( sFilename );
}
nLayer++;
layerNode = ( QDomNode ) layerNode.nextSiblingElement( "layer" );
}
}
instrumentNode = (QDomNode) instrumentNode.nextSiblingElement( "instrument" );
}
if ( instrumentList_count == 0 )
{
return false;
}
}
else
{
return false;
}
QDomNode patterns = songNode.firstChildElement( "patternList" );
int pattern_count = 0;
int existing_patterns = Engine::patternStore()->numOfPatterns();
QDomNode patternNode = patterns.firstChildElement( "pattern" );
int pn = 1;
while ( !patternNode.isNull() )
{
if ( pn > 0 )
{
pattern_count++;
s->addPatternTrack();
pn = 0;
}
QString sName; // name
sName = LocalFileMng::readXmlString( patternNode, "name", sName );
QString sCategory = ""; // category
sCategory = LocalFileMng::readXmlString( patternNode, "category", sCategory ,false ,false );
int nSize = -1;
nSize = LocalFileMng::readXmlInt( patternNode, "size", nSize, false, false );
pattern_length[sName] = nSize;
QDomNode pNoteListNode = patternNode.firstChildElement( "noteList" );
if ( ! pNoteListNode.isNull() ) {
QDomNode noteNode = pNoteListNode.firstChildElement( "note" );
while ( ! noteNode.isNull() ) {
int nPosition = LocalFileMng::readXmlInt( noteNode, "position", 0 );
float fVelocity = LocalFileMng::readXmlFloat( noteNode, "velocity", 0.8f );
float fPan_L = LocalFileMng::readXmlFloat( noteNode, "pan_L", 0.5 );
float fPan_R = LocalFileMng::readXmlFloat( noteNode, "pan_R", 0.5 );
QString sKey = LocalFileMng::readXmlString( noteNode, "key", "C0", false, false );
QString nNoteOff = LocalFileMng::readXmlString( noteNode, "note_off", "false", false, false );
QString instrId = LocalFileMng::readXmlString( noteNode, "instrument", 0,false, false );
int i = pattern_count - 1 + existing_patterns;
pattern_id[sName] = pattern_count - 1;
auto p = dynamic_cast<MidiClip*>(drum_track[instrId]->getClip(i));
Note n;
n.setPos( nPosition );
if ( (nPosition + 48) <= nSize )
{
n.setLength( 48 );
}
else
{
n.setLength( nSize - nPosition );
}
n.setVolume( fVelocity * 100 );
n.setPanning( ( fPan_R - fPan_L ) * 100 );
n.setKey( NoteKey::stringToNoteKey( sKey ) );
p->addNote( n,false );
pn = pn + 1;
noteNode = ( QDomNode ) noteNode.nextSiblingElement( "note" );
}
}
patternNode = ( QDomNode ) patternNode.nextSiblingElement( "pattern" );
}
// MidiClip sequence
QDomNode patternSequenceNode = songNode.firstChildElement( "patternSequence" );
QDomNode groupNode = patternSequenceNode.firstChildElement( "group" );
int pos = 0;
while ( !groupNode.isNull() )
{
int best_length = 0;
QDomNode patternId = groupNode.firstChildElement( "patternID" );
while ( !patternId.isNull() )
{
QString patId = patternId.firstChild().nodeValue();
patternId = ( QDomNode ) patternId.nextSiblingElement( "patternID" );
int i = pattern_id[patId]+song_num_tracks;
Track* t = s->tracks().at(i);
t->createClip(pos);
if ( pattern_length[patId] > best_length )
{
best_length = pattern_length[patId];
}
}
pos = pos + best_length;
groupNode = groupNode.nextSiblingElement( "group" );
}
if ( pattern_count == 0 )
{
return false;
}
return true;
}
bool HydrogenImport::tryImport( TrackContainer* tc )
{
if( openFile() == false )
{
return false;
}
return readSong();
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *, void * _data )
{
return new HydrogenImport( QString::fromUtf8(
static_cast<const char *>( _data ) ) );
}
}
} // namespace lmms
| 9,138
|
C++
|
.cpp
| 312
| 25.74359
| 104
| 0.66139
|
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,621
|
MidiExport.cpp
|
LMMS_lmms/plugins/MidiExport/MidiExport.cpp
|
/*
* MidiExport.cpp - support for Exporting MIDI files
*
* Copyright (c) 2015 Mohamed Abdel Maksoud <mohamed at amaksoud.com>
* Copyright (c) 2017 Hyunjin Song <tteu.ingog/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 "MidiExport.h"
#include "Engine.h"
#include "TrackContainer.h"
#include "DataFile.h"
#include "InstrumentTrack.h"
#include "LocaleHelper.h"
#include "PatternTrack.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT midiexport_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"MIDI Export",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Filter for exporting MIDI-files from LMMS" ),
"Mohamed Abdel Maksoud <mohamed at amaksoud.com> and "
"Hyunjin Song <tteu.ingog/at/gmail.com>",
0x0100,
Plugin::Type::ExportFilter,
nullptr,
nullptr,
nullptr,
} ;
}
MidiExport::MidiExport() : ExportFilter( &midiexport_plugin_descriptor)
{
}
bool MidiExport::tryExport(const TrackContainer::TrackList &tracks,
const TrackContainer::TrackList &patternStoreTracks,
int tempo, int masterPitch, const QString &filename)
{
QFile f(filename);
f.open(QIODevice::WriteOnly);
QDataStream midiout(&f);
QDomElement element;
int nTracks = 0;
auto buffer = std::array<uint8_t, BUFFER_SIZE>{};
for (const Track* track : tracks) if (track->type() == Track::Type::Instrument) nTracks++;
for (const Track* track : patternStoreTracks) if (track->type() == Track::Type::Instrument) nTracks++;
// midi header
MidiFile::MIDIHeader header(nTracks);
uint32_t size = header.writeToBuffer(buffer.data());
midiout.writeRawData((char *)buffer.data(), size);
std::vector<std::vector<std::pair<int,int>>> plists;
// midi tracks
for (Track* track : tracks)
{
DataFile dataFile(DataFile::Type::SongProject);
MTrack mtrack;
if (track->type() == Track::Type::Instrument)
{
mtrack.addName(track->name().toStdString(), 0);
//mtrack.addProgramChange(0, 0);
mtrack.addTempo(tempo, 0);
auto instTrack = dynamic_cast<InstrumentTrack *>(track);
element = instTrack->saveState(dataFile, dataFile.content());
int base_pitch = 0;
double base_volume = 1.0;
int base_time = 0;
MidiNoteVector midiClip;
for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
{
if (n.nodeName() == "instrumenttrack")
{
QDomElement it = n.toElement();
base_pitch = (69 - it.attribute("basenote", "69").toInt());
if (it.attribute("usemasterpitch", "1").toInt())
{
base_pitch += masterPitch;
}
base_volume = LocaleHelper::toDouble(it.attribute("volume", "100"))/100.0;
}
if (n.nodeName() == "midiclip")
{
base_time = n.toElement().attribute("pos", "0").toInt();
writeMidiClip(midiClip, n, base_pitch, base_volume, base_time);
}
}
processPatternNotes(midiClip, INT_MAX);
writeMidiClipToTrack(mtrack, midiClip);
size = mtrack.writeToBuffer(buffer.data());
midiout.writeRawData((char *)buffer.data(), size);
}
if (track->type() == Track::Type::Pattern)
{
auto patternTrack = dynamic_cast<PatternTrack*>(track);
element = patternTrack->saveState(dataFile, dataFile.content());
std::vector<std::pair<int,int>> plist;
for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
{
if (n.nodeName() == "patternclip")
{
QDomElement it = n.toElement();
int pos = it.attribute("pos", "0").toInt();
int len = it.attribute("len", "0").toInt();
plist.emplace_back(pos, pos+len);
}
}
std::sort(plist.begin(), plist.end());
plists.push_back(plist);
}
} // for each track
// for each instrument in the pattern editor
for (Track* track : patternStoreTracks)
{
DataFile dataFile(DataFile::Type::SongProject);
MTrack mtrack;
// begin at the first pattern track (first pattern)
auto itr = plists.begin();
std::vector<std::pair<int,int>> st;
if (track->type() != Track::Type::Instrument) continue;
mtrack.addName(track->name().toStdString(), 0);
//mtrack.addProgramChange(0, 0);
mtrack.addTempo(tempo, 0);
auto instTrack = dynamic_cast<InstrumentTrack *>(track);
element = instTrack->saveState(dataFile, dataFile.content());
int base_pitch = 0;
double base_volume = 1.0;
// for each pattern in the pattern editor
for (QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling())
{
if (n.nodeName() == "instrumenttrack")
{
QDomElement it = n.toElement();
base_pitch = (69 - it.attribute("basenote", "69").toInt());
if (it.attribute("usemasterpitch", "1").toInt())
{
base_pitch += masterPitch;
}
base_volume = LocaleHelper::toDouble(it.attribute("volume", "100")) / 100.0;
}
if (n.nodeName() == "midiclip")
{
std::vector<std::pair<int,int>> &plist = *itr;
MidiNoteVector nv, midiClip;
writeMidiClip(midiClip, n, base_pitch, base_volume, 0);
// FIXME better variable names and comments
int pos = 0;
int len = n.toElement().attribute("steps", "1").toInt() * 12;
// for each pattern clip of the current pattern track (in song editor)
for (const auto& position : plist)
{
const auto& [start, end] = position;
while (!st.empty() && st.back().second <= start)
{
writePatternClip(midiClip, nv, len, st.back().first, pos, st.back().second);
pos = st.back().second;
st.pop_back();
}
if (!st.empty() && st.back().second <= end)
{
writePatternClip(midiClip, nv, len, st.back().first, pos, start);
pos = start;
while (!st.empty() && st.back().second <= end)
{
st.pop_back();
}
}
st.push_back(position);
pos = start;
}
while (!st.empty())
{
writePatternClip(midiClip, nv, len, st.back().first, pos, st.back().second);
pos = st.back().second;
st.pop_back();
}
processPatternNotes(nv, pos);
writeMidiClipToTrack(mtrack, nv);
// next pattern track
++itr;
}
}
size = mtrack.writeToBuffer(buffer.data());
midiout.writeRawData((char *)buffer.data(), size);
}
return true;
}
void MidiExport::writeMidiClip(MidiNoteVector &midiClip, const QDomNode& n,
int base_pitch, double base_volume, int base_time)
{
// TODO interpret steps="12" muted="0" type="1" name="Piano1" len="2592"
for (QDomNode nn = n.firstChild(); !nn.isNull(); nn = nn.nextSibling())
{
QDomElement note = nn.toElement();
if (note.attribute("len", "0") == "0") continue;
// TODO interpret pan="0" mixch="0" pitchrange="1"
MidiNote mnote;
mnote.pitch = qMax(0, qMin(127, note.attribute("key", "0").toInt() + base_pitch));
// Map from LMMS volume to MIDI velocity
mnote.volume = qMin(qRound(base_volume * LocaleHelper::toDouble(note.attribute("vol", "100")) * (127.0 / 200.0)), 127);
mnote.time = base_time + note.attribute("pos", "0").toInt();
mnote.duration = note.attribute("len", "0").toInt();
mnote.type = static_cast<Note::Type>(note.attribute("type", "0").toInt());
midiClip.push_back(mnote);
}
}
void MidiExport::writeMidiClipToTrack(MTrack &mtrack, MidiNoteVector &nv)
{
for (const auto& note : nv)
{
mtrack.addNote(note.pitch, note.volume, note.time / 48.0, note.duration / 48.0);
}
}
void MidiExport::writePatternClip(MidiNoteVector& src, MidiNoteVector& dst,
int len, int base, int start, int end)
{
if (start >= end) { return; }
start -= base;
end -= base;
std::sort(src.begin(), src.end());
for (const auto& srcNote : src)
{
for (int time = srcNote.time + ceil((start - srcNote.time) / len) * len; time < end; time += len)
{
MidiNote note;
note.duration = srcNote.duration;
note.pitch = srcNote.pitch;
note.time = base + time;
note.volume = srcNote.volume;
note.type = srcNote.type;
dst.push_back(note);
}
}
}
void MidiExport::processPatternNotes(MidiNoteVector& nv, int cutPos)
{
std::sort(nv.begin(), nv.end());
int cur = INT_MAX, next = INT_MAX;
for (auto it = nv.rbegin(); it != nv.rend(); ++it)
{
if (it->time < cur)
{
next = cur;
cur = it->time;
}
if (it->type == Note::Type::Step)
{
it->duration = qMin(qMin(DefaultBeatLength, next - cur), cutPos - it->time);
}
}
}
void MidiExport::error()
{
//qDebug() << "MidiExport error: " << m_error ;
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model *, void * _data )
{
return new MidiExport();
}
}
} // namespace lmms
| 9,230
|
C++
|
.cpp
| 282
| 29.234043
| 121
| 0.675048
|
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,622
|
DispersionControlDialog.cpp
|
LMMS_lmms/plugins/Dispersion/DispersionControlDialog.cpp
|
/*
* DispersionControlDialog.cpp
*
* Copyright (c) 2023 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "DispersionControlDialog.h"
#include "DispersionControls.h"
#include "embed.h"
#include "Knob.h"
#include "LcdSpinBox.h"
#include "PixmapButton.h"
namespace lmms::gui
{
DispersionControlDialog::DispersionControlDialog(DispersionControls* controls) :
EffectControlDialog(controls)
{
setAutoFillBackground(true);
QPalette pal;
pal.setBrush(backgroundRole(), PLUGIN_NAME::getIconPixmap("artwork"));
setPalette(pal);
setFixedSize(207, 50);
LcdSpinBox * m_amountBox = new LcdSpinBox(3, this, "Amount");
m_amountBox->setModel(&controls->m_amountModel);
m_amountBox->move(5, 10);
m_amountBox->setLabel(tr("AMOUNT"));
m_amountBox->setToolTip(tr("Number of all-pass filters"));
Knob * freqKnob = new Knob(KnobType::Bright26, this);
freqKnob->move(59, 8);
freqKnob->setModel(&controls->m_freqModel);
freqKnob->setLabel(tr("FREQ"));
freqKnob->setHintText(tr("Frequency:") , " Hz");
Knob * resoKnob = new Knob(KnobType::Bright26, this);
resoKnob->move(99, 8);
resoKnob->setModel(&controls->m_resoModel);
resoKnob->setLabel(tr("RESO"));
resoKnob->setHintText(tr("Resonance:") , " octaves");
Knob * feedbackKnob = new Knob(KnobType::Bright26, this);
feedbackKnob->move(139, 8);
feedbackKnob->setModel(&controls->m_feedbackModel);
feedbackKnob->setLabel(tr("FEED"));
feedbackKnob->setHintText(tr("Feedback:") , "");
PixmapButton * dcButton = new PixmapButton(this, tr("DC Offset Removal"));
dcButton->move(176, 16);
dcButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("dc_active"));
dcButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("dc_inactive"));
dcButton->setCheckable(true);
dcButton->setModel(&controls->m_dcModel);
dcButton->setToolTip(tr("Remove DC Offset"));
}
} // namespace lmms::gui
| 2,638
|
C++
|
.cpp
| 68
| 36.720588
| 80
| 0.753527
|
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,623
|
Dispersion.cpp
|
LMMS_lmms/plugins/Dispersion/Dispersion.cpp
|
/*
* Dispersion.cpp
*
* Copyright (c) 2023 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Dispersion.h"
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT dispersion_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"Dispersion",
QT_TRANSLATE_NOOP("PluginBrowser", "An all-pass filter allowing for extremely high orders."),
"Lost Robot <r94231/at/gmail/dot/com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr
};
}
DispersionEffect::DispersionEffect(Model* parent, const Descriptor::SubPluginFeatures::Key* key) :
Effect(&dispersion_plugin_descriptor, parent, key),
m_dispersionControls(this),
m_sampleRate(Engine::audioEngine()->outputSampleRate()),
m_amountVal(0)
{
}
Effect::ProcessStatus DispersionEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const float d = dryLevel();
const float w = wetLevel();
const int amount = m_dispersionControls.m_amountModel.value();
const float freq = m_dispersionControls.m_freqModel.value();
const float reso = m_dispersionControls.m_resoModel.value();
float feedback = m_dispersionControls.m_feedbackModel.value();
const bool dc = m_dispersionControls.m_dcModel.value();
// All-pass coefficient calculation
const float w0 = (F_2PI / m_sampleRate) * freq;
const float a0 = 1 + (std::sin(w0) / (reso * 2.f));
float apCoeff1 = (1 - (a0 - 1)) / a0;
float apCoeff2 = (-2 * std::cos(w0)) / a0;
float dcCoeff = 0.001 * (44100.f / m_sampleRate);
if (amount != m_amountVal)
{
if (amount < m_amountVal)
{
// Flush filter buffers when they're no longer in use
for (int i = amount * 2; i < m_amountVal * 2; ++i)
{
m_state.x0[i] = m_state.x1[i] = m_state.y0[i] = m_state.y1[i] = 0;
}
}
m_amountVal = amount;
}
if (amount == 0)
{
feedback = 0;
m_feedbackVal[0] = m_feedbackVal[1] = 0;
}
for (fpp_t f = 0; f < frames; ++f)
{
std::array<sample_t, 2> s = { buf[f][0] + m_feedbackVal[0], buf[f][1] + m_feedbackVal[1] };
runDispersionAP(m_amountVal, apCoeff1, apCoeff2, s);
m_feedbackVal[0] = s[0] * feedback;
m_feedbackVal[1] = s[1] * feedback;
if (dc)
{
// DC offset removal
for (int i = 0; i < 2; ++i)
{
m_integrator[i] = m_integrator[i] * (1.f - dcCoeff) + s[i] * dcCoeff;
s[i] -= m_integrator[i];
}
}
buf[f][0] = d * buf[f][0] + w * s[0];
buf[f][1] = d * buf[f][1] + w * s[1];
}
return ProcessStatus::ContinueIfNotQuiet;
}
void DispersionEffect::runDispersionAP(const int filtNum, const float apCoeff1, const float apCoeff2, std::array<sample_t, 2> &put)
{
for (int i = 0; i < filtNum * 2; ++i)
{
const int channel = i % 2;
const sample_t currentInput = put[channel];
const sample_t filterOutput = apCoeff1 * (currentInput - m_state.y1[i])
+ apCoeff2 * (m_state.x0[i] - m_state.y0[i]) + m_state.x1[i];
m_state.x1[i] = m_state.x0[i];
m_state.x0[i] = currentInput;
m_state.y1[i] = m_state.y0[i];
m_state.y0[i] = filterOutput;
put[channel] = filterOutput;
}
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main(Model* parent, void* data)
{
return new DispersionEffect(parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(data));
}
}
} // namespace lmms
| 4,111
|
C++
|
.cpp
| 126
| 30.166667
| 131
| 0.695542
|
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,624
|
DispersionControls.cpp
|
LMMS_lmms/plugins/Dispersion/DispersionControls.cpp
|
/*
* DispersionControls.cpp
*
* Copyright (c) 2023 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "DispersionControls.h"
#include "Dispersion.h"
#include <QDomElement>
namespace lmms
{
DispersionControls::DispersionControls(DispersionEffect* effect) :
EffectControls(effect),
m_effect(effect),
m_amountModel(0, 0, MAX_DISPERSION_FILTERS, this, tr("Amount")),
m_freqModel(200, 20, 20000, 0.001f, this, tr("Frequency")),
m_resoModel(0.707f, 0.01f, 8, 0.0001f, this, tr("Resonance")),
m_feedbackModel(0.f, -1.f, 1.f, 0.0001f, this, tr("Feedback")),
m_dcModel(false, this, tr("DC Offset Removal"))
{
m_freqModel.setScaleLogarithmic(true);
m_resoModel.setScaleLogarithmic(true);
}
void DispersionControls::loadSettings(const QDomElement& parent)
{
m_amountModel.loadSettings(parent, "amount");
m_freqModel.loadSettings(parent, "freq");
m_resoModel.loadSettings(parent, "reso");
m_feedbackModel.loadSettings(parent, "feedback");
m_dcModel.loadSettings(parent, "dc");
}
void DispersionControls::saveSettings(QDomDocument& doc, QDomElement& parent)
{
m_amountModel.saveSettings(doc, parent, "amount");
m_freqModel.saveSettings(doc, parent, "freq");
m_resoModel.saveSettings(doc, parent, "reso");
m_feedbackModel.saveSettings(doc, parent, "feedback");
m_dcModel.saveSettings(doc, parent, "dc");
}
} // namespace lmms
| 2,139
|
C++
|
.cpp
| 57
| 35.526316
| 77
| 0.757986
|
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,625
|
CarlaRack.cpp
|
LMMS_lmms/plugins/CarlaRack/CarlaRack.cpp
|
/*
* carlarack.cpp - Carla for LMMS (Rack)
*
* Copyright (C) 2014-2018 Filipe Coelho <falktx@falktx.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 "Carla.h"
#include "embed.h"
#include "plugin_export.h"
#include "InstrumentTrack.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT carlarack_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Carla Rack",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Carla Rack Instrument" ),
"falkTX <falktx/at/falktx.com>",
CARLA_VERSION_HEX,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
PLUGIN_EXPORT Plugin* lmms_plugin_main(Model* m, void*)
{
return new CarlaInstrument(static_cast<InstrumentTrack*>(m), &carlarack_plugin_descriptor, false);
}
}
} // namespace lmms
| 1,587
|
C++
|
.cpp
| 50
| 28.84
| 102
| 0.726916
|
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,626
|
SaProcessor.cpp
|
LMMS_lmms/plugins/SpectrumAnalyzer/SaProcessor.cpp
|
/* SaProcessor.cpp - implementation of SaProcessor class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* Based partially on Eq plugin code,
* Copyright (c) 2014-2017, David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SaProcessor.h"
#include <algorithm>
#ifdef SA_DEBUG
#include <chrono>
#endif
#include <cmath>
#ifdef SA_DEBUG
#include <iomanip>
#include <iostream>
#endif
#include <QMutexLocker>
#include "fft_helpers.h"
#include "lmms_constants.h"
#include "LocklessRingBuffer.h"
#include "SaControls.h"
#include <cassert>
#include <limits>
namespace lmms
{
SaProcessor::SaProcessor(const SaControls *controls) :
m_controls(controls),
m_terminate(false),
m_inBlockSize(FFT_BLOCK_SIZES[0]),
m_fftBlockSize(FFT_BLOCK_SIZES[0]),
m_sampleRate(Engine::audioEngine()->outputSampleRate()),
m_framesFilledUp(0),
m_spectrumActive(false),
m_waterfallActive(false),
m_waterfallNotEmpty(0),
m_reallocating(false)
{
m_fftWindow.resize(m_inBlockSize, 1.0);
precomputeWindow(m_fftWindow.data(), m_inBlockSize, FFTWindow::BlackmanHarris);
m_bufferL.resize(m_inBlockSize, 0);
m_bufferR.resize(m_inBlockSize, 0);
m_filteredBufferL.resize(m_fftBlockSize, 0);
m_filteredBufferR.resize(m_fftBlockSize, 0);
m_spectrumL = (fftwf_complex *) fftwf_malloc(binCount() * sizeof (fftwf_complex));
m_spectrumR = (fftwf_complex *) fftwf_malloc(binCount() * sizeof (fftwf_complex));
m_fftPlanL = fftwf_plan_dft_r2c_1d(m_fftBlockSize, m_filteredBufferL.data(), m_spectrumL, FFTW_MEASURE);
m_fftPlanR = fftwf_plan_dft_r2c_1d(m_fftBlockSize, m_filteredBufferR.data(), m_spectrumR, FFTW_MEASURE);
m_absSpectrumL.resize(binCount(), 0);
m_absSpectrumR.resize(binCount(), 0);
m_normSpectrumL.resize(binCount(), 0);
m_normSpectrumR.resize(binCount(), 0);
m_waterfallHeight = 100; // a small safe value
m_history_work.resize(waterfallWidth() * m_waterfallHeight * sizeof qRgb(0,0,0), 0);
m_history.resize(waterfallWidth() * m_waterfallHeight * sizeof qRgb(0,0,0), 0);
}
SaProcessor::~SaProcessor()
{
if (m_fftPlanL != nullptr) {fftwf_destroy_plan(m_fftPlanL);}
if (m_fftPlanR != nullptr) {fftwf_destroy_plan(m_fftPlanR);}
if (m_spectrumL != nullptr) {fftwf_free(m_spectrumL);}
if (m_spectrumR != nullptr) {fftwf_free(m_spectrumR);}
m_fftPlanL = nullptr;
m_fftPlanR = nullptr;
m_spectrumL = nullptr;
m_spectrumR = nullptr;
}
// Load data from audio thread ringbuffer and run FFT analysis if buffer is full enough.
void SaProcessor::analyze(LocklessRingBuffer<SampleFrame> &ring_buffer)
{
LocklessRingBufferReader<SampleFrame> reader(ring_buffer);
// Processing thread loop
while (!m_terminate)
{
// If there is nothing to read, wait for notification from the writing side.
if (reader.empty()) {reader.waitForData();}
// skip waterfall render if processing can't keep up with input
bool overload = ring_buffer.free() < ring_buffer.capacity() / 2;
auto in_buffer = reader.read_max(ring_buffer.capacity() / 4);
std::size_t frame_count = in_buffer.size();
// Process received data only if any view is visible and not paused.
// Also, to prevent a momentary GUI freeze under high load (due to lock
// starvation), skip analysis when buffer reallocation is requested.
if ((m_spectrumActive || m_waterfallActive) && !m_controls->m_pauseModel.value() && !m_reallocating)
{
const bool stereo = m_controls->m_stereoModel.value();
fpp_t in_frame = 0;
while (in_frame < frame_count)
{
// Lock data access to prevent reallocation from changing
// buffers and control variables.
QMutexLocker data_lock(&m_dataAccess);
// Fill sample buffers and check for zero input.
bool block_empty = true;
for (; in_frame < frame_count && m_framesFilledUp < m_inBlockSize; in_frame++, m_framesFilledUp++)
{
if (stereo)
{
m_bufferL[m_framesFilledUp] = in_buffer[in_frame][0];
m_bufferR[m_framesFilledUp] = in_buffer[in_frame][1];
}
else
{
m_bufferL[m_framesFilledUp] =
m_bufferR[m_framesFilledUp] = (in_buffer[in_frame][0] + in_buffer[in_frame][1]) * 0.5f;
}
if (in_buffer[in_frame][0] != 0.f || in_buffer[in_frame][1] != 0.f)
{
block_empty = false;
}
}
// Run analysis only if buffers contain enough data.
if (m_framesFilledUp < m_inBlockSize) {break;}
// Print performance analysis once per 2 seconds if debug is enabled
#ifdef SA_DEBUG
unsigned int total_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
if (total_time - m_last_dump_time > 2000000000)
{
std::cout << "FFT analysis: " << std::fixed << std::setprecision(2)
<< m_sum_execution / m_dump_count << " ms avg / "
<< m_max_execution << " ms peak, executing "
<< m_dump_count << " times per second ("
<< m_sum_execution / 20.0 << " % CPU usage)." << std::endl;
m_last_dump_time = total_time;
m_sum_execution = m_max_execution = m_dump_count = 0;
}
#endif
// update sample rate
m_sampleRate = Engine::audioEngine()->outputSampleRate();
// apply FFT window
for (unsigned int i = 0; i < m_inBlockSize; i++)
{
m_filteredBufferL[i] = m_bufferL[i] * m_fftWindow[i];
m_filteredBufferR[i] = m_bufferR[i] * m_fftWindow[i];
}
// Run FFT on left channel, convert the result to absolute magnitude
// spectrum and normalize it.
fftwf_execute(m_fftPlanL);
absspec(m_spectrumL, m_absSpectrumL.data(), binCount());
normalize(m_absSpectrumL, m_normSpectrumL, m_inBlockSize);
// repeat analysis for right channel if stereo processing is enabled
if (stereo)
{
fftwf_execute(m_fftPlanR);
absspec(m_spectrumR, m_absSpectrumR.data(), binCount());
normalize(m_absSpectrumR, m_normSpectrumR, m_inBlockSize);
}
// count empty lines so that empty history does not have to update
if (block_empty && m_waterfallNotEmpty)
{
m_waterfallNotEmpty -= 1;
}
else if (!block_empty)
{
m_waterfallNotEmpty = m_waterfallHeight + 2;
}
if (m_waterfallActive && m_waterfallNotEmpty)
{
// move waterfall history one line down and clear the top line
auto pixel = (QRgb*)m_history_work.data();
std::copy(pixel,
pixel + waterfallWidth() * m_waterfallHeight - waterfallWidth(),
pixel + waterfallWidth());
memset(pixel, 0, waterfallWidth() * sizeof (QRgb));
// add newest result on top
float accL = 0; // accumulators for merging multiple bins
float accR = 0;
for (unsigned int i = 0; i < binCount(); i++)
{
// fill line with red color to indicate lost data if CPU cannot keep up
if (overload && i < waterfallWidth())
{
pixel[i] = qRgb(42, 0, 0);
continue;
}
// Every frequency bin spans a frequency range that must be
// partially or fully mapped to a pixel. Any inconsistency
// may be seen in the spectrogram as dark or white lines --
// play white noise to confirm your change did not break it.
float band_start = freqToXPixel(binToFreq(i) - binBandwidth() / 2.0, waterfallWidth());
float band_end = freqToXPixel(binToFreq(i + 1) - binBandwidth() / 2.0, waterfallWidth());
if (m_controls->m_logXModel.value())
{
// Logarithmic scale
if (band_end - band_start > 1.0)
{
// band spans multiple pixels: draw all pixels it covers
for (auto target = static_cast<std::size_t>(std::max(band_start, 0.f));
target < band_end && target < waterfallWidth(); target++)
{
pixel[target] = makePixel(m_normSpectrumL[i], m_normSpectrumR[i]);
}
// save remaining portion of the band for the following band / pixel
// (in case the next band uses sub-pixel drawing)
accL = (band_end - (int)band_end) * m_normSpectrumL[i];
accR = (band_end - (int)band_end) * m_normSpectrumR[i];
}
else
{
// sub-pixel drawing; add contribution of current band
int target = static_cast<int>(band_start);
if ((int)band_start == (int)band_end)
{
// band ends within current target pixel, accumulate
accL += (band_end - band_start) * m_normSpectrumL[i];
accR += (band_end - band_start) * m_normSpectrumR[i];
}
else
{
// Band ends in the next pixel -- finalize the current pixel.
// Make sure contribution is split correctly on pixel boundary.
accL += ((int)band_end - band_start) * m_normSpectrumL[i];
accR += ((int)band_end - band_start) * m_normSpectrumR[i];
if (target >= 0 && static_cast<std::size_t>(target) < waterfallWidth()) {
pixel[target] = makePixel(accL, accR);
}
// save remaining portion of the band for the following band / pixel
accL = (band_end - (int)band_end) * m_normSpectrumL[i];
accR = (band_end - (int)band_end) * m_normSpectrumR[i];
}
}
}
else
{
// Linear: always draws one or more pixels per band
for (auto target = static_cast<std::size_t>(std::max(band_start, 0.f));
target < band_end && target < waterfallWidth(); target++)
{
pixel[target] = makePixel(m_normSpectrumL[i], m_normSpectrumR[i]);
}
}
}
// Copy work buffer to result buffer. Done only if requested, so
// that time isn't wasted on updating faster than display FPS.
// (The copy is about as expensive as the movement.)
if (m_flipRequest)
{
m_history = m_history_work;
m_flipRequest = false;
}
}
// clean up before checking for more data from input buffer
const unsigned int overlaps = m_controls->m_windowOverlapModel.value();
if (overlaps == 1) // Discard buffer, each sample used only once
{
m_framesFilledUp = 0;
}
else
{
// Drop only a part of the buffer from the beginning, so that new
// data can be added to the end. This means the older samples will
// be analyzed again, but in a different position in the window,
// making short transient signals show up better in the waterfall.
const unsigned int drop = m_inBlockSize / overlaps;
std::move(m_bufferL.begin() + drop, m_bufferL.end(), m_bufferL.begin());
std::move(m_bufferR.begin() + drop, m_bufferR.end(), m_bufferR.begin());
m_framesFilledUp -= drop;
}
#ifdef SA_DEBUG
// measure overall FFT processing speed
total_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - total_time;
m_dump_count++;
m_sum_execution += total_time / 1000000.0;
if (total_time / 1000000.0 > m_max_execution) {m_max_execution = total_time / 1000000.0;}
#endif
} // frame filler and processing
} // process if active
} // thread loop end
}
// Produce a spectrogram pixel from normalized spectrum data.
// Values over 1.0 will cause the color components to overflow: this is left
// intentionally untreated as it clearly indicates which frequency is clipping.
// Gamma correction is applied to make small values more visible and to make
// a linear gradient actually appear roughly linear. The correction should be
// around 0.42 to 0.45 for sRGB displays (or lower for bigger visibility boost).
QRgb SaProcessor::makePixel(float left, float right) const
{
const float gamma_correction = m_controls->m_waterfallGammaModel.value();
if (m_controls->m_stereoModel.value())
{
float ampL = pow(left, gamma_correction);
float ampR = pow(right, gamma_correction);
return qRgb(m_controls->m_colorL.red() * ampL + m_controls->m_colorR.red() * ampR,
m_controls->m_colorL.green() * ampL + m_controls->m_colorR.green() * ampR,
m_controls->m_colorL.blue() * ampL + m_controls->m_colorR.blue() * ampR);
}
else
{
float ampL = pow(left, gamma_correction);
// make mono color brighter to compensate for the fact it is not summed
return qRgb(m_controls->m_colorMonoW.red() * ampL,
m_controls->m_colorMonoW.green() * ampL,
m_controls->m_colorMonoW.blue() * ampL);
}
}
// Inform the processor whether any display widgets actually need it.
void SaProcessor::setSpectrumActive(bool active)
{
m_spectrumActive = active;
}
void SaProcessor::setWaterfallActive(bool active)
{
m_waterfallActive = active;
}
// Reallocate data buffers according to newly set block size.
void SaProcessor::reallocateBuffers()
{
m_zeroPadFactor = m_controls->m_zeroPaddingModel.value();
// get new block sizes and bin count based on selected index
const unsigned int new_size_index = m_controls->m_blockSizeModel.value();
const unsigned int new_in_size = new_size_index < FFT_BLOCK_SIZES.size()
? FFT_BLOCK_SIZES[new_size_index]
: FFT_BLOCK_SIZES.back();
const unsigned int new_fft_size = (new_size_index + m_zeroPadFactor < FFT_BLOCK_SIZES.size())
? FFT_BLOCK_SIZES[new_size_index + m_zeroPadFactor]
: FFT_BLOCK_SIZES.back();
const unsigned int new_bins = new_fft_size / 2 + 1;
// Use m_reallocating to tell analyze() to avoid asking for the lock. This
// is needed because under heavy load the FFT thread requests data lock so
// often that this routine could end up waiting even for several seconds.
m_reallocating = true;
// Lock data shared with SaSpectrumView and SaWaterfallView.
// Reallocation lock must be acquired first to avoid deadlock (a view class
// may already have it and request the "stronger" data lock on top of that).
QMutexLocker reloc_lock(&m_reallocationAccess);
QMutexLocker data_lock(&m_dataAccess);
// destroy old FFT plan and free the result buffer
if (m_fftPlanL != nullptr) {fftwf_destroy_plan(m_fftPlanL);}
if (m_fftPlanR != nullptr) {fftwf_destroy_plan(m_fftPlanR);}
if (m_spectrumL != nullptr) {fftwf_free(m_spectrumL);}
if (m_spectrumR != nullptr) {fftwf_free(m_spectrumR);}
// allocate new space, create new plan and resize containers
m_fftWindow.resize(new_in_size, 1.0);
precomputeWindow(m_fftWindow.data(), new_in_size, (FFTWindow) m_controls->m_windowModel.value());
m_bufferL.resize(new_in_size, 0);
m_bufferR.resize(new_in_size, 0);
m_filteredBufferL.resize(new_fft_size, 0);
m_filteredBufferR.resize(new_fft_size, 0);
m_spectrumL = (fftwf_complex *) fftwf_malloc(new_bins * sizeof (fftwf_complex));
m_spectrumR = (fftwf_complex *) fftwf_malloc(new_bins * sizeof (fftwf_complex));
m_fftPlanL = fftwf_plan_dft_r2c_1d(new_fft_size, m_filteredBufferL.data(), m_spectrumL, FFTW_MEASURE);
m_fftPlanR = fftwf_plan_dft_r2c_1d(new_fft_size, m_filteredBufferR.data(), m_spectrumR, FFTW_MEASURE);
if (m_fftPlanL == nullptr || m_fftPlanR == nullptr)
{
#ifdef SA_DEBUG
std::cerr << "Analyzer: failed to create new FFT plan!" << std::endl;
#endif
}
m_absSpectrumL.resize(new_bins, 0);
m_absSpectrumR.resize(new_bins, 0);
m_normSpectrumL.resize(new_bins, 0);
m_normSpectrumR.resize(new_bins, 0);
m_waterfallHeight = m_controls->m_waterfallHeightModel.value();
m_history_work.resize((new_bins < m_waterfallMaxWidth ? new_bins : m_waterfallMaxWidth)
* m_waterfallHeight
* sizeof qRgb(0,0,0), 0);
m_history.resize((new_bins < m_waterfallMaxWidth ? new_bins : m_waterfallMaxWidth)
* m_waterfallHeight
* sizeof qRgb(0,0,0), 0);
// done; publish new sizes and clean up
m_inBlockSize = new_in_size;
m_fftBlockSize = new_fft_size;
data_lock.unlock();
reloc_lock.unlock();
m_reallocating = false;
clear();
}
// Precompute a new FFT window based on currently selected type.
void SaProcessor::rebuildWindow()
{
// computation is done in fft_helpers
QMutexLocker lock(&m_dataAccess);
precomputeWindow(m_fftWindow.data(), m_inBlockSize, (FFTWindow) m_controls->m_windowModel.value());
}
// Clear all data buffers and replace contents with zeros.
// Note: may take a few milliseconds, do not call in a loop!
void SaProcessor::clear()
{
const unsigned int overlaps = m_controls->m_windowOverlapModel.value();
QMutexLocker lock(&m_dataAccess);
// If there is any window overlap, leave space only for the new samples
// and treat the rest at initialized with zeros. Prevents missing
// transients at the start of the very first block.
m_framesFilledUp = m_inBlockSize - m_inBlockSize / overlaps;
std::fill(m_bufferL.begin(), m_bufferL.end(), 0);
std::fill(m_bufferR.begin(), m_bufferR.end(), 0);
std::fill(m_filteredBufferL.begin(), m_filteredBufferL.end(), 0);
std::fill(m_filteredBufferR.begin(), m_filteredBufferR.end(), 0);
std::fill(m_absSpectrumL.begin(), m_absSpectrumL.end(), 0);
std::fill(m_absSpectrumR.begin(), m_absSpectrumR.end(), 0);
std::fill(m_normSpectrumL.begin(), m_normSpectrumL.end(), 0);
std::fill(m_normSpectrumR.begin(), m_normSpectrumR.end(), 0);
std::fill(m_history_work.begin(), m_history_work.end(), 0);
std::fill(m_history.begin(), m_history.end(), 0);
}
// Clear only history work buffer. Used to flush old data when waterfall
// is shown after a period of inactivity.
void SaProcessor::clearHistory()
{
QMutexLocker lock(&m_dataAccess);
std::fill(m_history_work.begin(), m_history_work.end(), 0);
}
// Check if result buffers contain any non-zero values
bool SaProcessor::spectrumNotEmpty()
{
QMutexLocker lock(&m_reallocationAccess);
return notEmpty(m_normSpectrumL) || notEmpty(m_normSpectrumR);
}
// --------------------------------------
// Frequency conversion helpers
//
// Get sample rate value that is valid for currently stored results.
unsigned int SaProcessor::getSampleRate() const
{
return m_sampleRate;
}
// Maximum frequency of a sampled signal is equal to half of its sample rate.
float SaProcessor::getNyquistFreq() const
{
return getSampleRate() / 2.0f;
}
// FFTW automatically discards upper half of the symmetric FFT output, so
// the useful bin count is the transform size divided by 2, plus zero.
unsigned int SaProcessor::binCount() const
{
return m_fftBlockSize / 2 + 1;
}
// Return the final width of waterfall display buffer.
// Normally the waterfall width equals the number of frequency bins, but the
// FFT transform can easily produce more bins than can be reasonably useful for
// currently used display resolutions. This function limits width of the final
// image to a given size, which is then used during waterfall render and display.
unsigned int SaProcessor::waterfallWidth() const
{
return binCount() < m_waterfallMaxWidth ? binCount() : m_waterfallMaxWidth;
}
// Return the center frequency of given frequency bin.
float SaProcessor::binToFreq(unsigned int bin_index) const
{
return getNyquistFreq() * bin_index / binCount();
}
// Return width of the frequency range that falls into one bin.
// The binCount is lowered by one since half of the first and last bin is
// actually outside the frequency range.
float SaProcessor::binBandwidth() const
{
return getNyquistFreq() / (binCount() - 1);
}
float SaProcessor::getFreqRangeMin(bool linear) const
{
switch (static_cast<FrequencyRange>(m_controls->m_freqRangeModel.value()))
{
case FrequencyRange::Audible: return FRANGE_AUDIBLE_START;
case FrequencyRange::Bass: return FRANGE_BASS_START;
case FrequencyRange::Mids: return FRANGE_MIDS_START;
case FrequencyRange::High: return FRANGE_HIGH_START;
default:
case FrequencyRange::Full: return linear ? 0 : LOWEST_LOG_FREQ;
}
}
float SaProcessor::getFreqRangeMax() const
{
switch (static_cast<FrequencyRange>(m_controls->m_freqRangeModel.value()))
{
case FrequencyRange::Audible: return FRANGE_AUDIBLE_END;
case FrequencyRange::Bass: return FRANGE_BASS_END;
case FrequencyRange::Mids: return FRANGE_MIDS_END;
case FrequencyRange::High: return FRANGE_HIGH_END;
default:
case FrequencyRange::Full: return getNyquistFreq();
}
}
// Map frequency to pixel x position on a display of given width.
// NOTE: Results of this function may be cached by SaSpectrumView. If you use
// a new function call or variable that can affect results of this function,
// make sure to also add it as a trigger for cache update in SaSpectrumView.
float SaProcessor::freqToXPixel(float freq, unsigned int width) const
{
if (m_controls->m_logXModel.value())
{
if (freq <= 1) {return 0;}
float min = log10(getFreqRangeMin());
float range = log10(getFreqRangeMax()) - min;
return (log10(freq) - min) / range * width;
}
else
{
float min = getFreqRangeMin();
float range = getFreqRangeMax() - min;
return (freq - min) / range * width;
}
}
// Map pixel x position on display of given width back to frequency.
float SaProcessor::xPixelToFreq(float x, unsigned int width) const
{
if (m_controls->m_logXModel.value())
{
float min = log10(getFreqRangeMin());
float max = log10(getFreqRangeMax());
float range = max - min;
return pow(10, min + x / width * range);
}
else
{
float min = getFreqRangeMin();
float range = getFreqRangeMax() - min;
return min + x / width * range;
}
}
// --------------------------------------
// Amplitude conversion helpers
//
float SaProcessor::getAmpRangeMin(bool linear) const
{
// return very low limit to make sure zero gets included at linear grid
if (linear) {return -900;}
switch (static_cast<AmplitudeRange>(m_controls->m_ampRangeModel.value()))
{
case AmplitudeRange::Extended: return ARANGE_EXTENDED_START;
case AmplitudeRange::Silent: return ARANGE_SILENT_START;
case AmplitudeRange::Loud: return ARANGE_LOUD_START;
default:
case AmplitudeRange::Audible: return ARANGE_AUDIBLE_START;
}
}
float SaProcessor::getAmpRangeMax() const
{
switch (static_cast<AmplitudeRange>(m_controls->m_ampRangeModel.value()))
{
case AmplitudeRange::Extended: return ARANGE_EXTENDED_END;
case AmplitudeRange::Silent: return ARANGE_SILENT_END;
case AmplitudeRange::Loud: return ARANGE_LOUD_END;
default:
case AmplitudeRange::Audible: return ARANGE_AUDIBLE_END;
}
}
// Map linear amplitude to pixel y position on a display of given height.
// Note that display coordinates are flipped: amplitude grows from [height] to zero.
float SaProcessor::ampToYPixel(float amplitude, unsigned int height) const
{
if (m_controls->m_logYModel.value())
{
// logarithmic scale: convert linear amplitude to dB (relative to 1.0)
assert (amplitude >= 0);
float amplitude_dB = 10 * std::log10(std::max(amplitude, std::numeric_limits<float>::min()));
if (amplitude_dB < getAmpRangeMin())
{
return height;
}
else
{
float max = getAmpRangeMax();
float range = getAmpRangeMin() - max;
return (amplitude_dB - max) / range * height;
}
}
else
{
// linear scale: convert returned ranges from dB to linear scale
float max = pow(10, getAmpRangeMax() / 10);
float range = pow(10, getAmpRangeMin() / 10) - max;
return (amplitude - max) / range * height;
}
}
// Map pixel y position on display of given height back to amplitude.
// Note that display coordinates are flipped: amplitude grows from [height] to zero.
// Also note that in logarithmic Y mode the returned amplitude is in dB, not linear.
float SaProcessor::yPixelToAmp(float y, unsigned int height) const
{
if (m_controls->m_logYModel.value())
{
float max = getAmpRangeMax();
float range = getAmpRangeMin() - max;
return max + range * (y / height);
}
else
{
// linear scale: convert returned ranges from dB to linear scale
float max = pow(10, getAmpRangeMax() / 10);
float range = pow(10, getAmpRangeMin() / 10) - max;
return max + range * (y / height);
}
}
} // namespace lmms
| 24,249
|
C++
|
.cpp
| 601
| 36.793677
| 105
| 0.706062
|
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,627
|
SaControls.cpp
|
LMMS_lmms/plugins/SpectrumAnalyzer/SaControls.cpp
|
/*
* SaControls.cpp - definition of SaControls class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SaControls.h"
#include <QDomElement>
#include "Analyzer.h"
#include "SaControlsDialog.h"
namespace lmms
{
SaControls::SaControls(Analyzer *effect) :
EffectControls(effect),
m_effect(effect),
// initialize bool models and set default values
m_pauseModel(false, this, tr("Pause")),
m_refFreezeModel(false, this, tr("Reference freeze")),
m_waterfallModel(false, this, tr("Waterfall")),
m_smoothModel(false, this, tr("Averaging")),
m_stereoModel(false, this, tr("Stereo")),
m_peakHoldModel(false, this, tr("Peak hold")),
m_logXModel(true, this, tr("Logarithmic frequency")),
m_logYModel(true, this, tr("Logarithmic amplitude")),
// default values of combo boxes are set after they are populated
m_freqRangeModel(this, tr("Frequency range")),
m_ampRangeModel(this, tr("Amplitude range")),
m_blockSizeModel(this, tr("FFT block size")),
m_windowModel(this, tr("FFT window type")),
// Advanced settings knobs
m_envelopeResolutionModel(0.25f, 0.1f, 3.0f, 0.05f, this, tr("Peak envelope resolution")),
m_spectrumResolutionModel(1.5f, 0.1f, 3.0f, 0.05f, this, tr("Spectrum display resolution")),
m_peakDecayFactorModel(0.992f, 0.95f, 0.999f, 0.001f, this, tr("Peak decay multiplier")),
m_averagingWeightModel(0.15f, 0.01f, 0.5f, 0.01f, this, tr("Averaging weight")),
m_waterfallHeightModel(300.0f, 50.0f, 1000.0f, 50.0f, this, tr("Waterfall history size")),
m_waterfallGammaModel(0.30f, 0.10f, 1.00f, 0.05f, this, tr("Waterfall gamma correction")),
m_windowOverlapModel(2.0f, 1.0f, 4.0f, 1.0f, this, tr("FFT window overlap")),
m_zeroPaddingModel(2.0f, 0.0f, 4.0f, 1.0f, this, tr("FFT zero padding"))
{
// Frequency and amplitude ranges; order must match
// FrequencyRange and AmplitudeRange defined in SaControls.h
m_freqRangeModel.addItem(tr("Full (auto)"));
m_freqRangeModel.addItem(tr("Audible"));
m_freqRangeModel.addItem(tr("Bass"));
m_freqRangeModel.addItem(tr("Mids"));
m_freqRangeModel.addItem(tr("High"));
m_freqRangeModel.setValue(m_freqRangeModel.findText(tr("Full (auto)")));
m_ampRangeModel.addItem(tr("Extended"));
m_ampRangeModel.addItem(tr("Audible"));
m_ampRangeModel.addItem(tr("Loud"));
m_ampRangeModel.addItem(tr("Silent"));
m_ampRangeModel.setValue(m_ampRangeModel.findText(tr("Audible")));
// FFT block size labels are generated automatically, based on
// FFT_BLOCK_SIZES vector defined in fft_helpers.h
for (unsigned int i = 0; i < FFT_BLOCK_SIZES.size(); i++)
{
if (i == 0)
{
m_blockSizeModel.addItem((std::to_string(FFT_BLOCK_SIZES[i]) + " ").c_str() + tr("(High time res.)"));
}
else if (i == FFT_BLOCK_SIZES.size() - 1)
{
m_blockSizeModel.addItem((std::to_string(FFT_BLOCK_SIZES[i]) + " ").c_str() + tr("(High freq. res.)"));
}
else
{
m_blockSizeModel.addItem(std::to_string(FFT_BLOCK_SIZES[i]).c_str());
}
}
m_blockSizeModel.setValue(m_blockSizeModel.findText("2048"));
// Window type order must match FFTWindow defined in fft_helpers.h
m_windowModel.addItem(tr("Rectangular (Off)"));
m_windowModel.addItem(tr("Blackman-Harris (Default)"));
m_windowModel.addItem(tr("Hamming"));
m_windowModel.addItem(tr("Hanning"));
m_windowModel.setValue(m_windowModel.findText(tr("Blackman-Harris (Default)")));
// Colors
// Background color is defined by Qt / theme.
// Make sure the sum of colors for L and R channel results into a neutral
// color that has at least one component equal to 255 (i.e. ideally white).
// This means the color overflows to zero exactly when signal reaches
// clipping threshold, indicating the problematic frequency to user.
// Mono waterfall color should have similarly at least one component at 255.
m_colorL = QColor(51, 148, 204, 135);
m_colorR = QColor(204, 107, 51, 135);
m_colorMono = QColor(51, 148, 204, 204);
m_colorMonoW = QColor(64, 185, 255, 255);
m_colorBG = QColor(7, 7, 7, 255); // ~20 % gray (after gamma correction)
m_colorGrid = QColor(30, 34, 38, 255); // ~40 % gray (slightly cold / blue)
m_colorLabels = QColor(192, 202, 212, 255); // ~90 % gray (slightly cold / blue)
}
// Create the SaControlDialog widget which handles display of GUI elements.
gui::EffectControlDialog* SaControls::createView()
{
return new gui::SaControlsDialog(this, m_effect->getProcessor());
}
void SaControls::loadSettings(const QDomElement &_this)
{
m_waterfallModel.loadSettings(_this, "Waterfall");
m_smoothModel.loadSettings(_this, "Smooth");
m_stereoModel.loadSettings(_this, "Stereo");
m_peakHoldModel.loadSettings(_this, "PeakHold");
m_logXModel.loadSettings(_this, "LogX");
m_logYModel.loadSettings(_this, "LogY");
m_freqRangeModel.loadSettings(_this, "RangeX");
m_ampRangeModel.loadSettings(_this, "RangeY");
m_blockSizeModel.loadSettings(_this, "BlockSize");
m_windowModel.loadSettings(_this, "WindowType");
m_envelopeResolutionModel.loadSettings(_this, "EnvelopeRes");
m_spectrumResolutionModel.loadSettings(_this, "SpectrumRes");
m_peakDecayFactorModel.loadSettings(_this, "PeakDecayFactor");
m_averagingWeightModel.loadSettings(_this, "AverageWeight");
m_waterfallHeightModel.loadSettings(_this, "WaterfallHeight");
m_waterfallGammaModel.loadSettings(_this, "WaterfallGamma");
m_windowOverlapModel.loadSettings(_this, "WindowOverlap");
m_zeroPaddingModel.loadSettings(_this, "ZeroPadding");
}
void SaControls::saveSettings(QDomDocument &doc, QDomElement &parent)
{
m_waterfallModel.saveSettings(doc, parent, "Waterfall");
m_smoothModel.saveSettings(doc, parent, "Smooth");
m_stereoModel.saveSettings(doc, parent, "Stereo");
m_peakHoldModel.saveSettings(doc, parent, "PeakHold");
m_logXModel.saveSettings(doc, parent, "LogX");
m_logYModel.saveSettings(doc, parent, "LogY");
m_freqRangeModel.saveSettings(doc, parent, "RangeX");
m_ampRangeModel.saveSettings(doc, parent, "RangeY");
m_blockSizeModel.saveSettings(doc, parent, "BlockSize");
m_windowModel.saveSettings(doc, parent, "WindowType");
m_envelopeResolutionModel.saveSettings(doc, parent, "EnvelopeRes");
m_spectrumResolutionModel.saveSettings(doc, parent, "SpectrumRes");
m_peakDecayFactorModel.saveSettings(doc, parent, "PeakDecayFactor");
m_averagingWeightModel.saveSettings(doc, parent, "AverageWeight");
m_waterfallHeightModel.saveSettings(doc, parent, "WaterfallHeight");
m_waterfallGammaModel.saveSettings(doc, parent, "WaterfallGamma");
m_windowOverlapModel.saveSettings(doc, parent, "WindowOverlap");
m_zeroPaddingModel.saveSettings(doc, parent, "ZeroPadding");
}
} // namespace lmms
| 7,380
|
C++
|
.cpp
| 156
| 45.179487
| 106
| 0.747986
|
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,628
|
SaSpectrumView.cpp
|
LMMS_lmms/plugins/SpectrumAnalyzer/SaSpectrumView.cpp
|
/* SaSpectrumView.cpp - implementation of SaSpectrumView class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* Based partially on Eq plugin code,
* Copyright (c) 2014-2017, David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SaSpectrumView.h"
#include <algorithm>
#include <cmath>
#include <QMouseEvent>
#include <QMutexLocker>
#include <QPainter>
#include <QString>
#include "fft_helpers.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "SaControls.h"
#include "SaProcessor.h"
#ifdef SA_DEBUG
#include <chrono>
#endif
namespace lmms::gui
{
SaSpectrumView::SaSpectrumView(SaControls *controls, SaProcessor *processor, QWidget *_parent) :
QWidget(_parent),
m_controls(controls),
m_processor(processor),
m_freezeRequest(false),
m_frozen(false),
m_cachedRangeMin(-1),
m_cachedRangeMax(-1),
m_cachedLogX(true),
m_cachedDisplayWidth(0),
m_cachedBinCount(0),
m_cachedSampleRate(0)
{
setMinimumSize(360, 170);
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
connect(getGUI()->mainWindow(), SIGNAL(periodicUpdate()), this, SLOT(periodicUpdate()));
m_displayBufferL.resize(m_processor->binCount(), 0);
m_displayBufferR.resize(m_processor->binCount(), 0);
m_peakBufferL.resize(m_processor->binCount(), 0);
m_peakBufferR.resize(m_processor->binCount(), 0);
m_freqRangeIndex = m_controls->m_freqRangeModel.value();
m_ampRangeIndex = m_controls->m_ampRangeModel.value();
m_logFreqTics = makeLogFreqTics(m_processor->getFreqRangeMin(), m_processor->getFreqRangeMax());
m_linearFreqTics = makeLinearFreqTics(m_processor->getFreqRangeMin(), m_processor->getFreqRangeMax());
m_logAmpTics = makeLogAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
m_linearAmpTics = makeLinearAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
m_cursor = QPointF(0, 0);
// Initialize the size of bin → pixel X position LUT to the maximum allowed number of bins + 1.
m_cachedBinToX.resize(FFT_BLOCK_SIZES.back() / 2 + 2);
#ifdef SA_DEBUG
m_execution_avg = m_path_avg = m_draw_avg = 0;
#endif
}
// Compose and draw all the content; periodically called by Qt.
// NOTE: Performance sensitive! If the drawing takes too long, it will drag
// the FPS down for the entire program! Use SA_DEBUG to display timings.
void SaSpectrumView::paintEvent(QPaintEvent *event)
{
#ifdef SA_DEBUG
int total_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
#endif
// 0) Constants and init
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
// drawing and path-making are split into multiple methods for clarity;
// display boundaries are updated here and shared as member variables
m_displayTop = 1;
m_displayBottom = height() -20;
m_displayLeft = 26;
m_displayRight = width() -26;
m_displayWidth = m_displayRight - m_displayLeft;
// recompute range labels if needed
if (m_freqRangeIndex != m_controls->m_freqRangeModel.value())
{
m_logFreqTics = makeLogFreqTics(m_processor->getFreqRangeMin(), m_processor->getFreqRangeMax());
m_linearFreqTics = makeLinearFreqTics(m_processor->getFreqRangeMin(true), m_processor->getFreqRangeMax());
m_freqRangeIndex = m_controls->m_freqRangeModel.value();
}
if (m_ampRangeIndex != m_controls->m_ampRangeModel.value())
{
m_logAmpTics = makeLogAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
m_linearAmpTics = makeLinearAmpTics(m_processor->getAmpRangeMin(true), m_processor->getAmpRangeMax());
m_ampRangeIndex = m_controls->m_ampRangeModel.value();
}
// generate freeze request or clear "frozen" status based on freeze button
if (!m_frozen && m_controls->m_refFreezeModel.value())
{
m_freezeRequest = true;
}
else if (!m_controls->m_refFreezeModel.value())
{
m_frozen = false;
}
// 1) Background, grid and labels
drawGrid(painter);
// 2) Spectrum display
drawSpectrum(painter);
// 3) Overlays
// draw cursor (if it is within bounds)
drawCursor(painter);
// always draw the display outline
painter.setPen(QPen(m_controls->m_colorGrid, 2, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawRoundedRect(m_displayLeft, 1,
m_displayWidth, m_displayBottom,
2.0, 2.0);
#ifdef SA_DEBUG
// display performance measurements if enabled
total_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - total_time;
m_execution_avg = 0.95 * m_execution_avg + 0.05 * total_time / 1000000.0;
painter.setPen(QPen(m_controls->m_colorLabels, 1,
Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawText(m_displayRight -150, 10, 130, 16, Qt::AlignLeft,
QString("Exec avg.: ").append(std::to_string(m_execution_avg).substr(0, 5).c_str()).append(" ms"));
painter.drawText(m_displayRight -150, 30, 130, 16, Qt::AlignLeft,
QString("Buff. upd. avg: ").append(std::to_string(m_refresh_avg).substr(0, 5).c_str()).append(" ms"));
painter.drawText(m_displayRight -150, 50, 130, 16, Qt::AlignLeft,
QString("Path build avg: ").append(std::to_string(m_path_avg).substr(0, 5).c_str()).append(" ms"));
painter.drawText(m_displayRight -150, 70, 130, 16, Qt::AlignLeft,
QString("Path draw avg: ").append(std::to_string(m_draw_avg).substr(0, 5).c_str()).append(" ms"));
#endif
}
// Refresh data and draw the spectrum.
void SaSpectrumView::drawSpectrum(QPainter &painter)
{
#ifdef SA_DEBUG
int draw_time = 0;
#endif
// draw the graph only if there is any input, averaging residue or peaks
if (m_decaySum > 0 || m_processor->spectrumNotEmpty())
{
// update data buffers and reconstruct paths
refreshPaths();
// draw stored paths
#ifdef SA_DEBUG
draw_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
#endif
// in case stereo is disabled, mono data are stored in left channel structures
if (m_controls->m_stereoModel.value())
{
painter.fillPath(m_pathR, QBrush(m_controls->m_colorR));
painter.fillPath(m_pathL, QBrush(m_controls->m_colorL));
}
else
{
painter.fillPath(m_pathL, QBrush(m_controls->m_colorMono));
}
// draw the peakBuffer only if peak hold or reference freeze is active
if (m_controls->m_peakHoldModel.value() || m_controls->m_refFreezeModel.value())
{
if (m_controls->m_stereoModel.value())
{
painter.setPen(QPen(m_controls->m_colorR, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawPath(m_pathPeakR);
painter.setPen(QPen(m_controls->m_colorL, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawPath(m_pathPeakL);
}
else
{
painter.setPen(QPen(m_controls->m_colorL, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawPath(m_pathPeakL);
}
}
#ifdef SA_DEBUG
draw_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - draw_time;
#endif
}
#ifdef SA_DEBUG
// save performance measurement result
m_draw_avg = 0.95 * m_draw_avg + 0.05 * draw_time / 1000000.0;
#endif
}
// Read newest FFT results from SaProcessor, update local display buffers
// and build QPainter paths.
void SaSpectrumView::refreshPaths()
{
// Reallocation lock is required for the entire function, to keep display
// buffer size consistent with block size.
QMutexLocker reloc_lock(&m_processor->m_reallocationAccess);
// check if bin count changed and reallocate display buffers accordingly
if (m_processor->binCount() != m_displayBufferL.size())
{
m_displayBufferL.clear();
m_displayBufferR.clear();
m_peakBufferL.clear();
m_peakBufferR.clear();
m_displayBufferL.resize(m_processor->binCount(), 0);
m_displayBufferR.resize(m_processor->binCount(), 0);
m_peakBufferL.resize(m_processor->binCount(), 0);
m_peakBufferR.resize(m_processor->binCount(), 0);
}
// update display buffers for left and right channel
#ifdef SA_DEBUG
int refresh_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
#endif
m_decaySum = 0;
updateBuffers(m_processor->getSpectrumL(), m_displayBufferL.data(), m_peakBufferL.data());
updateBuffers(m_processor->getSpectrumR(), m_displayBufferR.data(), m_peakBufferR.data());
#ifdef SA_DEBUG
refresh_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - refresh_time;
#endif
// if there was a freeze request, it was taken care of during the update
if (m_controls->m_refFreezeModel.value() && m_freezeRequest)
{
m_freezeRequest = false;
m_frozen = true;
}
#ifdef SA_DEBUG
int path_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
#endif
// Use updated display buffers to prepare new paths for QPainter.
// This is the second slowest action (first is the subsequent drawing); use
// the resolution parameter to balance display quality and performance.
m_pathL = makePath(m_displayBufferL, m_controls->m_spectrumResolutionModel.value());
if (m_controls->m_stereoModel.value())
{
m_pathR = makePath(m_displayBufferR, m_controls->m_spectrumResolutionModel.value());
}
if (m_controls->m_peakHoldModel.value() || m_controls->m_refFreezeModel.value())
{
m_pathPeakL = makePath(m_peakBufferL, m_controls->m_envelopeResolutionModel.value());
if (m_controls->m_stereoModel.value())
{
m_pathPeakR = makePath(m_peakBufferR, m_controls->m_envelopeResolutionModel.value());
}
}
#ifdef SA_DEBUG
path_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - path_time;
#endif
#ifdef SA_DEBUG
// save performance measurement results
m_refresh_avg = 0.95 * m_refresh_avg + 0.05 * refresh_time / 1000000.0;
m_path_avg = .95f * m_path_avg + .05f * path_time / 1000000.f;
#endif
}
// Update display buffers: add new data, update average and peaks / reference.
// Output the sum of all displayed values -- draw only if it is non-zero.
// NOTE: The calling function is responsible for acquiring SaProcessor
// reallocation access lock! Data access lock is not needed: the final result
// buffer is updated very quickly and the worst case is that one frame will be
// part new, part old. At reasonable frame rate, such difference is invisible..
void SaSpectrumView::updateBuffers(const float *spectrum, float *displayBuffer, float *peakBuffer)
{
for (auto n = std::size_t{0}; n < m_processor->binCount(); n++)
{
// Update the exponential average if enabled, or simply copy the value.
if (!m_controls->m_pauseModel.value())
{
if (m_controls->m_smoothModel.value())
{
const float smoothFactor = m_controls->m_averagingWeightModel.value();
displayBuffer[n] = spectrum[n] * smoothFactor + displayBuffer[n] * (1 - smoothFactor);
}
else
{
displayBuffer[n] = spectrum[n];
}
}
// Update peak-hold and reference freeze data (using a shared curve).
// Peak hold and freeze can be combined: decay only if not frozen.
// Ref. freeze operates on the (possibly averaged) display buffer.
if (m_controls->m_refFreezeModel.value() && m_freezeRequest)
{
peakBuffer[n] = displayBuffer[n];
}
else if (m_controls->m_peakHoldModel.value() && !m_controls->m_pauseModel.value())
{
if (spectrum[n] > peakBuffer[n])
{
peakBuffer[n] = spectrum[n];
}
else if (!m_controls->m_refFreezeModel.value())
{
peakBuffer[n] = peakBuffer[n] * m_controls->m_peakDecayFactorModel.value();
}
}
else if (!m_controls->m_refFreezeModel.value() && !m_controls->m_peakHoldModel.value())
{
peakBuffer[n] = 0;
}
// take note if there was actually anything to display
m_decaySum += displayBuffer[n] + peakBuffer[n];
}
}
// Use display buffer to build a path that can be drawn or filled by QPainter.
// Resolution controls the performance / quality tradeoff; the value specifies
// number of points in x axis per device pixel. Values over 1.0 still
// contribute to quality and accuracy thanks to anti-aliasing.
QPainterPath SaSpectrumView::makePath(std::vector<float> &displayBuffer, float resolution = 1.0)
{
// convert resolution to number of path points per logical pixel
float pixel_limit = resolution * window()->devicePixelRatio();
QPainterPath path;
path.moveTo(m_displayLeft, m_displayBottom);
// Translate frequency bins to path points.
// Display is flipped: y values grow towards zero, initial max is bottom.
// Bins falling to interval [x_start, x_next) contribute to a single point.
float max = m_displayBottom;
float x_start = -1; // lower bound of currently constructed point
// Speed up bin → x position translation by building a LUT cache.
// Update the cache only when range or display width are changed.
float rangeMin = m_processor->getFreqRangeMin(m_controls->m_logXModel.value());
float rangeMax = m_processor->getFreqRangeMax();
if (rangeMin != m_cachedRangeMin || rangeMax != m_cachedRangeMax || m_displayWidth != m_cachedDisplayWidth ||
m_controls->m_logXModel.value() != m_cachedLogX || m_processor->binCount() + 1 != m_cachedBinCount ||
m_processor->getSampleRate() != m_cachedSampleRate)
{
m_cachedRangeMin = rangeMin;
m_cachedRangeMax = rangeMax;
m_cachedDisplayWidth = m_displayWidth;
m_cachedLogX = m_controls->m_logXModel.value();
m_cachedBinCount = m_processor->binCount() + 1;
m_cachedSampleRate = m_processor->getSampleRate();
for (unsigned int n = 0; n < m_cachedBinCount; n++)
{
m_cachedBinToX[n] = freqToXPixel(binToFreq(n), m_displayWidth);
}
}
for (unsigned int n = 0; n < m_processor->binCount(); n++)
{
float x = m_cachedBinToX[n];
float x_next = m_cachedBinToX[n + 1];
float y = ampToYPixel(displayBuffer[n], m_displayBottom);
// consider making a point only if x falls within display bounds
if (0 < x && x < m_displayWidth)
{
if (x_start == -1)
{
x_start = x;
// the first displayed bin is stretched to the left edge to prevent
// creating a misleading slope leading to zero (at log. scale)
path.lineTo(m_displayLeft, y + m_displayTop);
}
// Opt.: QPainter is very slow -- draw at most [pixel_limit] points
// per logical pixel. As opposed to limiting the bin count, this
// allows high resolution display if user resizes the analyzer.
// Look at bins that share the pixel and use the highest value:
max = y < max ? y : max;
// And make the final point in the middle of current interval.
if ((int)(x * pixel_limit) != (int)(x_next * pixel_limit))
{
x = (x + x_start) / 2;
path.lineTo(x + m_displayLeft, max + m_displayTop);
max = m_displayBottom;
x_start = x_next;
}
}
else
{
// stop processing after a bin falls outside right edge
// and align it to the edge to prevent a gap
if (n > 0 && x > 0)
{
path.lineTo(m_displayRight, y + m_displayTop);
break;
}
}
}
path.lineTo(m_displayRight, m_displayBottom);
path.closeSubpath();
return path;
}
// Draw background, grid and associated frequency and amplitude labels.
void SaSpectrumView::drawGrid(QPainter &painter)
{
std::vector<std::pair<int, std::string>> *freqTics = nullptr;
std::vector<std::pair<float, std::string>> *ampTics = nullptr;
float pos = 0;
float label_width = 24;
float label_height = 15;
float margin = 5;
// always draw the background
painter.fillRect(m_displayLeft, m_displayTop,
m_displayWidth, m_displayBottom,
m_controls->m_colorBG);
// select logarithmic or linear frequency grid and draw it
if (m_controls->m_logXModel.value())
{
freqTics = &m_logFreqTics;
}
else
{
freqTics = &m_linearFreqTics;
}
// draw frequency grid (line.first is display position)
painter.setPen(QPen(m_controls->m_colorGrid, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
for (auto &line: *freqTics)
{
painter.drawLine(m_displayLeft + freqToXPixel(line.first, m_displayWidth),
2,
m_displayLeft + freqToXPixel(line.first, m_displayWidth),
m_displayBottom);
}
// print frequency labels (line.second is label)
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
for (auto & line: *freqTics)
{
pos = m_displayLeft + freqToXPixel(line.first, m_displayWidth);
// align first and last label to the edge if needed, otherwise center them
if (line == freqTics->front() && pos - label_width / 2 < m_displayLeft)
{
painter.drawText(m_displayLeft, m_displayBottom + margin,
label_width, label_height, Qt::AlignLeft | Qt::TextDontClip,
QString(line.second.c_str()));
}
else if (line == freqTics->back() && pos + label_width / 2 > m_displayRight)
{
painter.drawText(m_displayRight - label_width, m_displayBottom + margin,
label_width, label_height, Qt::AlignRight | Qt::TextDontClip,
QString(line.second.c_str()));
}
else
{
painter.drawText(pos - label_width / 2, m_displayBottom + margin,
label_width, label_height, Qt::AlignHCenter | Qt::TextDontClip,
QString(line.second.c_str()));
}
}
margin = 2;
// select logarithmic or linear amplitude grid and draw it
if (m_controls->m_logYModel.value())
{
ampTics = &m_logAmpTics;
}
else
{
ampTics = &m_linearAmpTics;
}
// draw amplitude grid
painter.setPen(QPen(m_controls->m_colorGrid, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
for (auto & line: *ampTics)
{
painter.drawLine(m_displayLeft + 1,
ampToYPixel(line.first, m_displayBottom),
m_displayRight - 1,
ampToYPixel(line.first, m_displayBottom));
}
// print amplitude labels
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
bool stereo = m_controls->m_stereoModel.value();
for (auto & line: *ampTics)
{
pos = ampToYPixel(line.first, m_displayBottom);
// align first and last labels to edge if needed, otherwise center them
if (line == ampTics->back() && pos < 8)
{
if (stereo)
{
painter.setPen(QPen(m_controls->m_colorL.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
}
painter.drawText(m_displayLeft - label_width - margin, m_displayTop - 2,
label_width, label_height, Qt::AlignRight | Qt::AlignTop | Qt::TextDontClip,
QString(line.second.c_str()));
if (stereo)
{
painter.setPen(QPen(m_controls->m_colorR.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
}
painter.drawText(m_displayRight + margin, m_displayTop - 2,
label_width, label_height, Qt::AlignLeft | Qt::AlignTop | Qt::TextDontClip,
QString(line.second.c_str()));
}
else if (line == ampTics->front() && pos > m_displayBottom - label_height)
{
if (stereo)
{
painter.setPen(QPen(m_controls->m_colorL.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
}
painter.drawText(m_displayLeft - label_width - margin, m_displayBottom - label_height + 2,
label_width, label_height, Qt::AlignRight | Qt::AlignBottom | Qt::TextDontClip,
QString(line.second.c_str()));
if (stereo)
{
painter.setPen(QPen(m_controls->m_colorR.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
}
painter.drawText(m_displayRight + margin, m_displayBottom - label_height + 2,
label_width, label_height, Qt::AlignLeft | Qt::AlignBottom | Qt::TextDontClip,
QString(line.second.c_str()));
}
else
{
if (stereo)
{
painter.setPen(QPen(m_controls->m_colorL.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
}
painter.drawText(m_displayLeft - label_width - margin, pos - label_height / 2,
label_width, label_height, Qt::AlignRight | Qt::AlignVCenter | Qt::TextDontClip,
QString(line.second.c_str()));
if (stereo)
{
painter.setPen(QPen(m_controls->m_colorR.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
}
painter.drawText(m_displayRight + margin, pos - label_height / 2,
label_width, label_height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip,
QString(line.second.c_str()));
}
}
}
// Draw cursor and its coordinates if it is within display bounds.
void SaSpectrumView::drawCursor(QPainter &painter)
{
if ( m_cursor.x() >= m_displayLeft
&& m_cursor.x() <= m_displayRight
&& m_cursor.y() >= m_displayTop
&& m_cursor.y() <= m_displayBottom)
{
// cursor lines
painter.setPen(QPen(m_controls->m_colorGrid.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawLine(QPointF(m_cursor.x(), m_displayTop), QPointF(m_cursor.x(), m_displayBottom));
painter.drawLine(QPointF(m_displayLeft, m_cursor.y()), QPointF(m_displayRight, m_cursor.y()));
// coordinates: background box
QFontMetrics fontMetrics = painter.fontMetrics();
unsigned int const box_left = 5;
unsigned int const box_top = 5;
unsigned int const box_margin = 3;
unsigned int const box_height = 2*(fontMetrics.size(Qt::TextSingleLine, "0 HzdBFS").height() + box_margin);
unsigned int const box_width = fontMetrics.size(Qt::TextSingleLine, "-99.9 dBFS").width() + 2*box_margin;
painter.setPen(QPen(m_controls->m_colorLabels.darker(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.fillRect(m_displayLeft + box_left, m_displayTop + box_top,
box_width, box_height, QColor(0, 0, 0, 64));
// coordinates: text
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
QString tmps;
// frequency
int xFreq = (int)m_processor->xPixelToFreq(m_cursor.x() - m_displayLeft, m_displayWidth);
tmps = QString("%1 Hz").arg(xFreq);
painter.drawText(m_displayLeft + box_left + box_margin,
m_displayTop + box_top + box_margin,
box_width, box_height / 2, Qt::AlignLeft, tmps);
// amplitude
float yAmp = m_processor->yPixelToAmp(m_cursor.y(), m_displayBottom);
if (m_controls->m_logYModel.value())
{
tmps = QString(std::to_string(yAmp).substr(0, 5).c_str()).append(" dBFS");
}
else
{
// add 0.0005 to get proper rounding to 3 decimal places
tmps = QString(std::to_string(0.0005f + yAmp).substr(0, 5).c_str());
}
painter.drawText(m_displayLeft + box_left + box_margin,
m_displayTop + box_top + box_height / 2,
box_width, box_height / 2, Qt::AlignLeft, tmps);
}
}
// Wrappers for most used SaProcessor helpers (to make local code more compact).
float SaSpectrumView::binToFreq(unsigned int bin_index)
{
return m_processor->binToFreq(bin_index);
}
float SaSpectrumView::freqToXPixel(float frequency, unsigned int width)
{
return m_processor->freqToXPixel(frequency, width);
}
float SaSpectrumView::ampToYPixel(float amplitude, unsigned int height)
{
return m_processor->ampToYPixel(amplitude, height);
}
// Generate labels suitable for logarithmic frequency scale.
// Low / high limits are in Hz. Lowest possible label is 10 Hz.
std::vector<std::pair<int, std::string>> SaSpectrumView::makeLogFreqTics(int low, int high)
{
std::vector<std::pair<int, std::string>> result;
auto a = std::array{10, 20, 50}; // sparse series multipliers
auto b = std::array{14, 30, 70}; // additional (denser) series
// generate main steps (powers of 10); use the series to specify smaller steps
for (int i = 1; i <= high; i *= 10)
{
for (int j = 0; j < 3; j++)
{
// insert a label from sparse series if it falls within bounds
if (i * a[j] >= low && i * a[j] <= high)
{
if (i * a[j] < 1000)
{
result.emplace_back(i * a[j], std::to_string(i * a[j]));
}
else
{
result.emplace_back(i * a[j], std::to_string(i * a[j] / 1000) + "k");
}
}
// also insert denser series if high and low values are close
if ((log10(high) - log10(low) < 2) && (i * b[j] >= low && i * b[j] <= high))
{
if (i * b[j] < 1500)
{
result.emplace_back(i * b[j], std::to_string(i * b[j]));
}
else
{
result.emplace_back(i * b[j], std::to_string(i * b[j] / 1000) + "k");
}
}
}
}
return result;
}
// Generate labels suitable for linear frequency scale.
// Low / high limits are in Hz.
std::vector<std::pair<int, std::string>> SaSpectrumView::makeLinearFreqTics(int low, int high)
{
std::vector<std::pair<int, std::string>> result;
int increment;
// select a suitable increment based on zoom level
if (high - low < 500) {increment = 50;}
else if (high - low < 1000) {increment = 100;}
else if (high - low < 5000) {increment = 1000;}
else {increment = 2000;}
// generate steps based on increment, starting at 0
for (int i = 0; i <= high; i += increment)
{
if (i >= low)
{
if (i < 1000)
{
result.emplace_back(i, std::to_string(i));
}
else
{
result.emplace_back(i, std::to_string(i/1000) + "k");
}
}
}
return result;
}
// Generate labels suitable for logarithmic (dB) amplitude scale.
// Low / high limits are in dB; 0 dB amplitude = 1.0 linear.
// Treating results as power ratio, i.e., 3 dB should be about twice as loud.
std::vector<std::pair<float, std::string>> SaSpectrumView::makeLogAmpTics(int low, int high)
{
std::vector<std::pair<float, std::string>> result;
double increment;
// Base zoom level on selected range and how close is the current height
// to the sizeHint() (denser scale for bigger window).
if ((high - low) < 20 * ((float)height() / sizeHint().height()))
{
increment = pow(10, 0.3); // 3 dB steps when really zoomed in
}
else if (high - low < 45 * ((float)height() / sizeHint().height()))
{
increment = pow(10, 0.6); // 6 dB steps when sufficiently zoomed in
}
else
{
increment = 10; // 10 dB steps otherwise
}
// Generate n dB increments, start checking at -90 dB. Limits are tweaked
// just a little bit to make sure float comparisons do not miss edges.
for (float i = 0.000000001f; 10 * log10(i) <= (high + 0.001); i *= increment)
{
if (10 * log10(i) >= (low - 0.001))
{
result.emplace_back(i, std::to_string((int)std::round(10 * log10(i))));
}
}
return result;
}
// Generate labels suitable for linear amplitude scale.
// Low / high limits are in dB; 0 dB amplitude = 1.0 linear.
// Smallest possible label is 0.001, largest is 999. This includes the majority
// of useful labels; going lower or higher would require increasing margin size
// so that the text can fit. That would be a waste of space -- the linear scale
// would only make the experience worse for the main, logarithmic (dB) scale.
std::vector<std::pair<float, std::string>> SaSpectrumView::makeLinearAmpTics(int low, int high)
{
std::vector<std::pair<float, std::string>> result;
// make about 5 labels when window is small, 10 if it is big
float split = (float)height() / sizeHint().height() >= 1.5 ? 10.0 : 5.0;
// convert limits to linear scale
float lin_low = pow(10, low / 10.0);
float lin_high = pow(10, high / 10.0);
// Linear scale will vary widely, so instead of trying to craft extra nice
// multiples, just generate a few evenly spaced increments across the range,
// paying attention only to the decimal places to keep labels short.
// Limits are shifted a bit so that float comparisons do not miss edges.
for (double i = 0; i <= (lin_high + 0.0001); i += (lin_high - lin_low) / split)
{
if (i >= (lin_low - 0.0001))
{
if (i >= 9.99 && i < 99.9)
{
double nearest = std::round(i);
result.emplace_back(nearest, std::to_string(nearest).substr(0, 2));
}
else if (i >= 0.099)
{ // also covers numbers above 100
double nearest = std::round(i * 10) / 10;
result.emplace_back(nearest, std::to_string(nearest).substr(0, 3));
}
else if (i >= 0.0099)
{
double nearest = std::round(i * 1000) / 1000;
result.emplace_back(nearest, std::to_string(nearest).substr(0, 4));
}
else if (i >= 0.00099)
{
double nearest = std::round(i * 10000) / 10000;
result.emplace_back(nearest, std::to_string(nearest).substr(1, 4));
}
else if (i > -0.01 && i < 0.01)
{
result.emplace_back(i, "0"); // an exception, zero is short..
}
}
}
return result;
}
// Periodic update is called by LMMS.
void SaSpectrumView::periodicUpdate()
{
// check if the widget is visible; if it is not, processing can be paused
m_processor->setSpectrumActive(isVisible());
// tell Qt it is time for repaint
update();
}
// Handle mouse input: set new cursor position.
// For some reason (a bug?), localPos() only returns integers. As a workaround
// the fractional part is taken from windowPos() (which works correctly).
void SaSpectrumView::mouseMoveEvent(QMouseEvent *event)
{
m_cursor = QPointF( event->localPos().x() - (event->windowPos().x() - (long)event->windowPos().x()),
event->localPos().y() - (event->windowPos().y() - (long)event->windowPos().y()));
}
void SaSpectrumView::mousePressEvent(QMouseEvent *event)
{
m_cursor = QPointF( event->localPos().x() - (event->windowPos().x() - (long)event->windowPos().x()),
event->localPos().y() - (event->windowPos().y() - (long)event->windowPos().y()));
}
// Handle resize event: rebuild grid and labels
void SaSpectrumView::resizeEvent(QResizeEvent *event)
{
// frequency does not change density with size
// amplitude does: rebuild labels
m_logAmpTics = makeLogAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
m_linearAmpTics = makeLinearAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
}
} // namespace lmms::gui
| 29,926
|
C++
|
.cpp
| 758
| 36.44723
| 110
| 0.703742
|
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,629
|
SaWaterfallView.cpp
|
LMMS_lmms/plugins/SpectrumAnalyzer/SaWaterfallView.cpp
|
/* SaWaterfallViewView.cpp - implementation of SaWaterfallViewView class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SaWaterfallView.h"
#include <algorithm>
#ifdef SA_DEBUG
#include <chrono>
#endif
#include <cmath>
#include <QImage>
#include <QMouseEvent>
#include <QMutexLocker>
#include <QPainter>
#include <QString>
#include "EffectControlDialog.h"
#include "GuiApplication.h"
#include "MainWindow.h"
#include "SaControls.h"
#include "SaProcessor.h"
namespace lmms::gui
{
SaWaterfallView::SaWaterfallView(SaControls *controls, SaProcessor *processor, QWidget *_parent) :
QWidget(_parent),
m_controls(controls),
m_processor(processor)
{
m_controlDialog = (EffectControlDialog*) _parent;
setMinimumSize(300, 150);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
connect(getGUI()->mainWindow(), SIGNAL(periodicUpdate()), this, SLOT(periodicUpdate()));
m_displayTop = 1;
m_displayBottom = height() -2;
m_displayLeft = 26;
m_displayRight = width() -26;
m_displayWidth = m_displayRight - m_displayLeft;
m_displayHeight = m_displayBottom - m_displayTop;
m_timeTics = makeTimeTics();
m_oldSecondsPerLine = 0;
m_oldHeight = 0;
m_cursor = QPointF(0, 0);
#ifdef SA_DEBUG
m_execution_avg = 0;
#endif
}
// Compose and draw all the content; called by Qt.
// Not as performance sensitive as SaSpectrumView, most of the processing is
// done directly in SaProcessor.
void SaWaterfallView::paintEvent(QPaintEvent *event)
{
#ifdef SA_DEBUG
unsigned int draw_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
#endif
// update boundary
m_displayBottom = height() -2;
m_displayRight = width() -26;
m_displayWidth = m_displayRight - m_displayLeft;
m_displayHeight = m_displayBottom - m_displayTop;
float label_width = 20;
float label_height = 16;
float margin = 2;
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
// check if time labels need to be rebuilt
if (secondsPerLine() != m_oldSecondsPerLine || m_processor->waterfallHeight() != m_oldHeight)
{
m_timeTics = makeTimeTics();
m_oldSecondsPerLine = secondsPerLine();
m_oldHeight = m_processor->waterfallHeight();
}
// print time labels
float pos = 0;
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
for (auto & line: m_timeTics)
{
pos = timeToYPixel(line.first, m_displayHeight);
// align first and last label to the edge if needed, otherwise center them
if (line == m_timeTics.front() && pos < label_height / 2)
{
painter.drawText(m_displayLeft - label_width - margin, m_displayTop - 1,
label_width, label_height, Qt::AlignRight | Qt::AlignTop | Qt::TextDontClip,
QString(line.second.c_str()));
painter.drawText(m_displayRight + margin, m_displayTop - 1,
label_width, label_height, Qt::AlignLeft | Qt::AlignTop | Qt::TextDontClip,
QString(line.second.c_str()));
}
else if (line == m_timeTics.back() && pos > m_displayBottom - label_height + 2)
{
painter.drawText(m_displayLeft - label_width - margin, m_displayBottom - label_height,
label_width, label_height, Qt::AlignRight | Qt::AlignBottom | Qt::TextDontClip,
QString(line.second.c_str()));
painter.drawText(m_displayRight + margin, m_displayBottom - label_height + 2,
label_width, label_height, Qt::AlignLeft | Qt::AlignBottom | Qt::TextDontClip,
QString(line.second.c_str()));
}
else
{
painter.drawText(m_displayLeft - label_width - margin, pos - label_height / 2,
label_width, label_height, Qt::AlignRight | Qt::AlignVCenter | Qt::TextDontClip,
QString(line.second.c_str()));
painter.drawText(m_displayRight + margin, pos - label_height / 2,
label_width, label_height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip,
QString(line.second.c_str()));
}
}
// draw the spectrogram precomputed in SaProcessor
if (m_processor->waterfallNotEmpty())
{
QMutexLocker lock(&m_processor->m_reallocationAccess);
QImage temp = QImage(m_processor->getHistory(), // raw pixel data to display
m_processor->waterfallWidth(), // width = number of frequency bins
m_processor->waterfallHeight(), // height = number of history lines
QImage::Format_RGB32);
lock.unlock();
temp.setDevicePixelRatio(devicePixelRatio()); // display at native resolution
painter.drawImage(m_displayLeft, m_displayTop,
temp.scaled(m_displayWidth * devicePixelRatio(),
m_displayHeight * devicePixelRatio(),
Qt::IgnoreAspectRatio,
Qt::SmoothTransformation));
m_processor->flipRequest();
}
else
{
painter.fillRect(m_displayLeft, m_displayTop, m_displayWidth, m_displayHeight, QColor(0,0,0));
}
// draw cursor (if it is within bounds)
drawCursor(painter);
// always draw the outline
painter.setPen(QPen(m_controls->m_colorGrid, 2, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawRoundedRect(m_displayLeft, m_displayTop, m_displayWidth, m_displayHeight, 2.0, 2.0);
#ifdef SA_DEBUG
draw_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - draw_time;
m_execution_avg = 0.95 * m_execution_avg + 0.05 * draw_time / 1000000.0;
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawText(m_displayRight -150, 10, 100, 16, Qt::AlignLeft,
QString("Exec avg.: ").append(std::to_string(m_execution_avg).substr(0, 5).c_str()).append(" ms"));
#endif
}
// Helper functions for time conversion
float SaWaterfallView::samplesPerLine()
{
return (float)m_processor->inBlockSize() / m_controls->m_windowOverlapModel.value();
}
float SaWaterfallView::secondsPerLine()
{
return samplesPerLine() / m_processor->getSampleRate();
}
// Convert time value to Y coordinate for display of given height.
float SaWaterfallView::timeToYPixel(float time, int height)
{
float pixels_per_line = (float)height / m_processor->waterfallHeight();
return pixels_per_line * time / secondsPerLine();
}
// Convert Y coordinate on display of given height back to time value.
float SaWaterfallView::yPixelToTime(float position, int height)
{
if (height == 0) {height = 1;}
float pixels_per_line = (float)height / m_processor->waterfallHeight();
return (position / pixels_per_line) * secondsPerLine();
}
// Generate labels for linear time scale.
std::vector<std::pair<float, std::string>> SaWaterfallView::makeTimeTics()
{
std::vector<std::pair<float, std::string>> result;
// get time value of the last line
float limit = yPixelToTime(m_displayBottom, m_displayHeight);
// set increment to about 30 pixels (but min. 0.1 s)
const float increment = std::max(std::round(10 * limit / (m_displayHeight / 30)) / 10, 0.1f);
// NOTE: labels positions are rounded to match the (rounded) label value
for (float i = 0; i <= limit; i += increment)
{
if (i > 99)
{
result.emplace_back(std::round(i), std::to_string(std::round(i)).substr(0, 3));
}
else if (i < 10)
{
result.emplace_back(std::round(i * 10) / 10, std::to_string(std::round(i * 10) / 10).substr(0, 3));
}
else
{
result.emplace_back(std::round(i), std::to_string(std::round(i)).substr(0, 2));
}
}
return result;
}
// Periodically trigger repaint and check if the widget is visible.
// If it is not, stop drawing and inform the processor.
void SaWaterfallView::periodicUpdate()
{
m_processor->setWaterfallActive(isVisible());
if (isVisible()) {update();}
}
// Adjust window size and widget visibility when waterfall is enabled or disabbled.
void SaWaterfallView::updateVisibility()
{
// get container of the control dialog to be resized if needed
QWidget *subWindow = m_controlDialog->parentWidget();
if (m_controls->m_waterfallModel.value())
{
// clear old data before showing the waterfall
m_processor->clearHistory();
setVisible(true);
// increase window size if it is too small
if (subWindow->size().height() < m_controlDialog->sizeHint().height())
{
subWindow->resize(subWindow->size().width(), m_controlDialog->sizeHint().height());
}
}
else
{
setVisible(false);
// decrease window size only if it does not violate sizeHint
subWindow->resize(subWindow->size().width(), m_controlDialog->sizeHint().height());
}
}
// Draw cursor and its coordinates if it is within display bounds.
void SaWaterfallView::drawCursor(QPainter &painter)
{
if ( m_cursor.x() >= m_displayLeft
&& m_cursor.x() <= m_displayRight
&& m_cursor.y() >= m_displayTop
&& m_cursor.y() <= m_displayBottom)
{
// cursor lines
painter.setPen(QPen(m_controls->m_colorGrid.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.drawLine(QPointF(m_cursor.x(), m_displayTop), QPointF(m_cursor.x(), m_displayBottom));
painter.drawLine(QPointF(m_displayLeft, m_cursor.y()), QPointF(m_displayRight, m_cursor.y()));
// coordinates: background box
QFontMetrics fontMetrics = painter.fontMetrics();
unsigned int const box_left = 5;
unsigned int const box_top = 5;
unsigned int const box_margin = 3;
unsigned int const box_height = 2*(fontMetrics.size(Qt::TextSingleLine, "0 Hz").height() + box_margin);
unsigned int const box_width = fontMetrics.size(Qt::TextSingleLine, "20000 Hz ").width() + 2*box_margin;
painter.setPen(QPen(m_controls->m_colorLabels.darker(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
painter.fillRect(m_displayLeft + box_left, m_displayTop + box_top,
box_width, box_height, QColor(0, 0, 0, 64));
// coordinates: text
painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
QString tmps;
// frequency
int freq = (int)m_processor->xPixelToFreq(m_cursor.x() - m_displayLeft, m_displayWidth);
tmps = QString("%1 Hz").arg(freq);
painter.drawText(m_displayLeft + box_left + box_margin,
m_displayTop + box_top + box_margin,
box_width, box_height / 2, Qt::AlignLeft, tmps);
// time
float time = yPixelToTime(m_cursor.y(), m_displayBottom);
tmps = QString(std::to_string(time).substr(0, 5).c_str()).append(" s");
painter.drawText(m_displayLeft + box_left + box_margin,
m_displayTop + box_top + box_height / 2,
box_width, box_height / 2, Qt::AlignLeft, tmps);
}
}
// Handle mouse input: set new cursor position.
// For some reason (a bug?), localPos() only returns integers. As a workaround
// the fractional part is taken from windowPos() (which works correctly).
void SaWaterfallView::mouseMoveEvent(QMouseEvent *event)
{
m_cursor = QPointF( event->localPos().x() - (event->windowPos().x() - (long)event->windowPos().x()),
event->localPos().y() - (event->windowPos().y() - (long)event->windowPos().y()));
}
void SaWaterfallView::mousePressEvent(QMouseEvent *event)
{
m_cursor = QPointF( event->localPos().x() - (event->windowPos().x() - (long)event->windowPos().x()),
event->localPos().y() - (event->windowPos().y() - (long)event->windowPos().y()));
}
// Handle resize event: rebuild time labels
void SaWaterfallView::resizeEvent(QResizeEvent *event)
{
m_timeTics = makeTimeTics();
}
} // namespace lmms::gui
| 11,968
|
C++
|
.cpp
| 292
| 38.082192
| 106
| 0.717986
|
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,630
|
Analyzer.cpp
|
LMMS_lmms/plugins/SpectrumAnalyzer/Analyzer.cpp
|
/*
* Analyzer.cpp - definition of Analyzer class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* Based partially on Eq plugin code,
* Copyright (c) 2014-2017, David French <dave/dot/french3/at/googlemail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Analyzer.h"
#ifdef SA_DEBUG
#include <chrono>
#include <iostream>
#endif
#include "embed.h"
#include "lmms_basics.h"
#include "plugin_export.h"
namespace lmms
{
extern "C" {
Plugin::Descriptor PLUGIN_EXPORT analyzer_plugin_descriptor =
{
"spectrumanalyzer",
"Spectrum Analyzer",
QT_TRANSLATE_NOOP("PluginBrowser", "A graphical spectrum analyzer."),
"Martin Pavelek <he29/dot/HS/at/gmail/dot/com>",
0x0112,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
};
}
Analyzer::Analyzer(Model *parent, const Plugin::Descriptor::SubPluginFeatures::Key *key) :
Effect(&analyzer_plugin_descriptor, parent, key),
m_processor(&m_controls),
m_controls(this),
m_processorThread(m_processor, m_inputBuffer),
// Buffer is sized to cover 4* the current maximum LMMS audio buffer size,
// so that it has some reserve space in case data processor is busy.
m_inputBuffer(4 * m_maxBufferSize)
{
m_processorThread.start();
}
Analyzer::~Analyzer()
{
m_processor.terminate();
m_inputBuffer.wakeAll();
m_processorThread.wait();
}
// Take audio data and pass them to the spectrum processor.
Effect::ProcessStatus Analyzer::processImpl(SampleFrame* buf, const fpp_t frames)
{
// Measure time spent in audio thread; both average and peak should be well under 1 ms.
#ifdef SA_DEBUG
unsigned int audio_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
if (audio_time - m_last_dump_time > 5000000000) // print every 5 seconds
{
std::cout << "Analyzer audio thread: " << m_sum_execution / m_dump_count << " ms avg / "
<< m_max_execution << " ms peak." << std::endl;
m_last_dump_time = audio_time;
m_sum_execution = m_max_execution = m_dump_count = 0;
}
#endif
// Skip processing if the controls dialog isn't visible, it would only waste CPU cycles.
if (m_controls.isViewVisible())
{
// To avoid processing spikes on audio thread, data are stored in
// a lockless ringbuffer and processed in a separate thread.
m_inputBuffer.write(buf, frames, true);
}
#ifdef SA_DEBUG
audio_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - audio_time;
m_dump_count++;
m_sum_execution += audio_time / 1000000.0;
if (audio_time / 1000000.0 > m_max_execution) {m_max_execution = audio_time / 1000000.0;}
#endif
return ProcessStatus::Continue;
}
extern "C" {
// needed for getting plugin out of shared lib
PLUGIN_EXPORT Plugin *lmms_plugin_main(Model *parent, void *data)
{
return new Analyzer(parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key *>(data));
}
}
} // namespace lmms
| 3,674
|
C++
|
.cpp
| 104
| 33.105769
| 101
| 0.735716
|
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,631
|
SaControlsDialog.cpp
|
LMMS_lmms/plugins/SpectrumAnalyzer/SaControlsDialog.cpp
|
/*
* SaControlsDialog.cpp - definition of SaControlsDialog class.
*
* Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "SaControlsDialog.h"
#include <QGridLayout>
#include <QLabel>
#include <QSizePolicy>
#include <QSplitter>
#include <QWidget>
#include "ComboBox.h"
#include "ComboBoxModel.h"
#include "Knob.h"
#include "LedCheckBox.h"
#include "PixmapButton.h"
#include "SaControls.h"
#include "SaProcessor.h"
#include "SaSpectrumView.h"
#include "SaWaterfallView.h"
namespace lmms::gui
{
// The entire GUI layout is built here.
SaControlsDialog::SaControlsDialog(SaControls *controls, SaProcessor *processor) :
EffectControlDialog(controls),
m_controls(controls),
m_processor(processor)
{
// Top level placement of sections is handled by QSplitter widget.
auto master_layout = new QHBoxLayout;
auto display_splitter = new QSplitter(Qt::Vertical);
master_layout->addWidget(display_splitter);
master_layout->setContentsMargins(2, 6, 2, 8);
setLayout(master_layout);
// Display splitter top: controls section
auto controls_widget = new QWidget;
auto controls_layout = new QHBoxLayout;
controls_layout->setContentsMargins(0, 0, 0, 0);
controls_widget->setLayout(controls_layout);
controls_widget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
controls_widget->setMaximumHeight(m_configHeight);
display_splitter->addWidget(controls_widget);
// Basic configuration
auto config_widget = new QWidget;
auto config_layout = new QGridLayout;
config_widget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
config_widget->setMaximumHeight(m_configHeight);
config_widget->setLayout(config_layout);
controls_layout->addWidget(config_widget);
controls_layout->setStretchFactor(config_widget, 10);
// Pre-compute target pixmap size based on monitor DPI.
// Using setDevicePixelRatio() on pixmap allows the SVG image to be razor
// sharp on High-DPI screens, but the desired size must be manually
// enlarged. No idea how to make Qt do it in a more reasonable way.
QSize iconSize = QSize(22.0 * devicePixelRatio(), 22.0 * devicePixelRatio());
QSize buttonSize = 1.2 * iconSize;
QSize advButtonSize = QSize((m_configHeight * devicePixelRatio()) / 3, m_configHeight * devicePixelRatio());
// pause and freeze buttons
auto pauseButton = new PixmapButton(this, tr("Pause"));
pauseButton->setToolTip(tr("Pause data acquisition"));
static auto s_pauseOnPixmap
= PLUGIN_NAME::getIconPixmap("play").scaled(buttonSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
static auto s_pauseOffPixmap
= PLUGIN_NAME::getIconPixmap("pause").scaled(buttonSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
s_pauseOnPixmap.setDevicePixelRatio(devicePixelRatio());
s_pauseOffPixmap.setDevicePixelRatio(devicePixelRatio());
pauseButton->setActiveGraphic(s_pauseOnPixmap);
pauseButton->setInactiveGraphic(s_pauseOffPixmap);
pauseButton->setCheckable(true);
pauseButton->setModel(&controls->m_pauseModel);
config_layout->addWidget(pauseButton, 0, 0, 2, 1, Qt::AlignHCenter);
auto refFreezeButton = new PixmapButton(this, tr("Reference freeze"));
refFreezeButton->setToolTip(tr("Freeze current input as a reference / disable falloff in peak-hold mode."));
static auto s_freezeOnPixmap
= PLUGIN_NAME::getIconPixmap("freeze").scaled(buttonSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
static auto s_freezeOffPixmap
= PLUGIN_NAME::getIconPixmap("freeze_off").scaled(buttonSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
s_freezeOnPixmap.setDevicePixelRatio(devicePixelRatio());
s_freezeOffPixmap.setDevicePixelRatio(devicePixelRatio());
refFreezeButton->setActiveGraphic(s_freezeOnPixmap);
refFreezeButton->setInactiveGraphic(s_freezeOffPixmap);
refFreezeButton->setCheckable(true);
refFreezeButton->setModel(&controls->m_refFreezeModel);
config_layout->addWidget(refFreezeButton, 2, 0, 2, 1, Qt::AlignHCenter);
// misc configuration switches
auto waterfallButton = new LedCheckBox(tr("Waterfall"), this);
waterfallButton->setToolTip(tr("Display real-time spectrogram"));
waterfallButton->setCheckable(true);
waterfallButton->setMinimumSize(100, 12);
waterfallButton->setModel(&controls->m_waterfallModel);
config_layout->addWidget(waterfallButton, 0, 1);
auto smoothButton = new LedCheckBox(tr("Averaging"), this);
smoothButton->setToolTip(tr("Enable exponential moving average"));
smoothButton->setCheckable(true);
smoothButton->setMinimumSize(100, 12);
smoothButton->setModel(&controls->m_smoothModel);
config_layout->addWidget(smoothButton, 1, 1);
auto stereoButton = new LedCheckBox(tr("Stereo"), this);
stereoButton->setToolTip(tr("Display stereo channels separately"));
stereoButton->setCheckable(true);
stereoButton->setMinimumSize(100, 12);
stereoButton->setModel(&controls->m_stereoModel);
config_layout->addWidget(stereoButton, 2, 1);
auto peakHoldButton = new LedCheckBox(tr("Peak hold"), this);
peakHoldButton->setToolTip(tr("Display envelope of peak values"));
peakHoldButton->setCheckable(true);
peakHoldButton->setMinimumSize(100, 12);
peakHoldButton->setModel(&controls->m_peakHoldModel);
config_layout->addWidget(peakHoldButton, 3, 1);
// frequency: linear / log. switch and range selector
auto logXButton = new PixmapButton(this, tr("Logarithmic frequency"));
logXButton->setToolTip(tr("Switch between logarithmic and linear frequency scale"));
static auto s_logXOnPixmap
= PLUGIN_NAME::getIconPixmap("x_log").scaled(iconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
static auto s_logXOffPixmap
= PLUGIN_NAME::getIconPixmap("x_linear").scaled(iconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
s_logXOnPixmap.setDevicePixelRatio(devicePixelRatio());
s_logXOffPixmap.setDevicePixelRatio(devicePixelRatio());
logXButton->setActiveGraphic(s_logXOnPixmap);
logXButton->setInactiveGraphic(s_logXOffPixmap);
logXButton->setCheckable(true);
logXButton->setModel(&controls->m_logXModel);
config_layout->addWidget(logXButton, 0, 2, 2, 1, Qt::AlignRight);
auto freqRangeCombo = new ComboBox(this, tr("Frequency range"));
freqRangeCombo->setToolTip(tr("Frequency range"));
freqRangeCombo->setMinimumSize(100, ComboBox::DEFAULT_HEIGHT);
freqRangeCombo->setMaximumSize(200, ComboBox::DEFAULT_HEIGHT);
freqRangeCombo->setModel(&controls->m_freqRangeModel);
config_layout->addWidget(freqRangeCombo, 0, 3, 2, 1);
// amplitude: linear / log switch and range selector
auto logYButton = new PixmapButton(this, tr("Logarithmic amplitude"));
logYButton->setToolTip(tr("Switch between logarithmic and linear amplitude scale"));
static auto s_logYOnPixmap
= PLUGIN_NAME::getIconPixmap("y_log").scaled(iconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
static auto s_logYOffPixmap
= PLUGIN_NAME::getIconPixmap("y_linear").scaled(iconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
s_logYOnPixmap.setDevicePixelRatio(devicePixelRatio());
s_logYOffPixmap.setDevicePixelRatio(devicePixelRatio());
logYButton->setActiveGraphic(s_logYOnPixmap);
logYButton->setInactiveGraphic(s_logYOffPixmap);
logYButton->setCheckable(true);
logYButton->setModel(&controls->m_logYModel);
config_layout->addWidget(logYButton, 2, 2, 2, 1, Qt::AlignRight);
auto ampRangeCombo = new ComboBox(this, tr("Amplitude range"));
ampRangeCombo->setToolTip(tr("Amplitude range"));
ampRangeCombo->setMinimumSize(100, ComboBox::DEFAULT_HEIGHT);
ampRangeCombo->setMaximumSize(200, ComboBox::DEFAULT_HEIGHT);
ampRangeCombo->setModel(&controls->m_ampRangeModel);
config_layout->addWidget(ampRangeCombo, 2, 3, 2, 1);
// FFT: block size: icon and selector
auto blockSizeLabel = new QLabel("", this);
static auto s_blockSizeIcon = PLUGIN_NAME::getIconPixmap("block_size");
s_blockSizeIcon.setDevicePixelRatio(devicePixelRatio());
blockSizeLabel->setPixmap(s_blockSizeIcon.scaled(iconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
config_layout->addWidget(blockSizeLabel, 0, 4, 2, 1, Qt::AlignRight);
auto blockSizeCombo = new ComboBox(this, tr("FFT block size"));
blockSizeCombo->setToolTip(tr("FFT block size"));
blockSizeCombo->setMinimumSize(100, 22);
blockSizeCombo->setMaximumSize(200, 22);
blockSizeCombo->setModel(&controls->m_blockSizeModel);
config_layout->addWidget(blockSizeCombo, 0, 5, 2, 1);
processor->reallocateBuffers();
connect(&controls->m_blockSizeModel, &ComboBoxModel::dataChanged, [=] {processor->reallocateBuffers();});
// FFT: window type: icon and selector
auto windowLabel = new QLabel("", this);
static auto s_windowIcon = PLUGIN_NAME::getIconPixmap("window");
s_windowIcon.setDevicePixelRatio(devicePixelRatio());
windowLabel->setPixmap(s_windowIcon.scaled(iconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
config_layout->addWidget(windowLabel, 2, 4, 2, 1, Qt::AlignRight);
auto windowCombo = new ComboBox(this, tr("FFT window type"));
windowCombo->setToolTip(tr("FFT window type"));
windowCombo->setMinimumSize(100, ComboBox::DEFAULT_HEIGHT);
windowCombo->setMaximumSize(200, ComboBox::DEFAULT_HEIGHT);
windowCombo->setModel(&controls->m_windowModel);
config_layout->addWidget(windowCombo, 2, 5, 2, 1);
processor->rebuildWindow();
connect(&controls->m_windowModel, &ComboBoxModel::dataChanged, [=] {processor->rebuildWindow();});
// set stretch factors so that combo boxes expand first
config_layout->setColumnStretch(3, 2);
config_layout->setColumnStretch(5, 3);
// Advanced configuration
auto advanced_widget = new QWidget;
auto advanced_layout = new QGridLayout;
advanced_widget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
advanced_widget->setMaximumHeight(m_configHeight);
advanced_widget->setLayout(advanced_layout);
advanced_widget->hide();
controls_layout->addWidget(advanced_widget);
controls_layout->setStretchFactor(advanced_widget, 10);
// Peak envelope resolution
auto envelopeResolutionKnob = new Knob(KnobType::Small17, this);
envelopeResolutionKnob->setModel(&controls->m_envelopeResolutionModel);
envelopeResolutionKnob->setLabel(tr("Envelope res."));
envelopeResolutionKnob->setToolTip(tr("Increase envelope resolution for better details, decrease for better GUI performance."));
envelopeResolutionKnob->setHintText(tr("Maximum number of envelope points drawn per pixel:"), "");
advanced_layout->addWidget(envelopeResolutionKnob, 0, 0, 1, 1, Qt::AlignCenter);
// Spectrum graph resolution
auto spectrumResolutionKnob = new Knob(KnobType::Small17, this);
spectrumResolutionKnob->setModel(&controls->m_spectrumResolutionModel);
spectrumResolutionKnob->setLabel(tr("Spectrum res."));
spectrumResolutionKnob->setToolTip(tr("Increase spectrum resolution for better details, decrease for better GUI performance."));
spectrumResolutionKnob->setHintText(tr("Maximum number of spectrum points drawn per pixel:"), "");
advanced_layout->addWidget(spectrumResolutionKnob, 1, 0, 1, 1, Qt::AlignCenter);
// Peak falloff speed
auto peakDecayFactorKnob = new Knob(KnobType::Small17, this);
peakDecayFactorKnob->setModel(&controls->m_peakDecayFactorModel);
peakDecayFactorKnob->setLabel(tr("Falloff factor"));
peakDecayFactorKnob->setToolTip(tr("Decrease to make peaks fall faster."));
peakDecayFactorKnob->setHintText(tr("Multiply buffered value by"), "");
advanced_layout->addWidget(peakDecayFactorKnob, 0, 1, 1, 1, Qt::AlignCenter);
// Averaging weight
auto averagingWeightKnob = new Knob(KnobType::Small17, this);
averagingWeightKnob->setModel(&controls->m_averagingWeightModel);
averagingWeightKnob->setLabel(tr("Averaging weight"));
averagingWeightKnob->setToolTip(tr("Decrease to make averaging slower and smoother."));
averagingWeightKnob->setHintText(tr("New sample contributes"), "");
advanced_layout->addWidget(averagingWeightKnob, 1, 1, 1, 1, Qt::AlignCenter);
// Waterfall history size
auto waterfallHeightKnob = new Knob(KnobType::Small17, this);
waterfallHeightKnob->setModel(&controls->m_waterfallHeightModel);
waterfallHeightKnob->setLabel(tr("Waterfall height"));
waterfallHeightKnob->setToolTip(tr("Increase to get slower scrolling, decrease to see fast transitions better. Warning: medium CPU usage."));
waterfallHeightKnob->setHintText(tr("Number of lines to keep:"), "");
advanced_layout->addWidget(waterfallHeightKnob, 0, 2, 1, 1, Qt::AlignCenter);
processor->reallocateBuffers();
connect(&controls->m_waterfallHeightModel, &FloatModel::dataChanged, [=] {processor->reallocateBuffers();});
// Waterfall gamma correction
auto waterfallGammaKnob = new Knob(KnobType::Small17, this);
waterfallGammaKnob->setModel(&controls->m_waterfallGammaModel);
waterfallGammaKnob->setLabel(tr("Waterfall gamma"));
waterfallGammaKnob->setToolTip(tr("Decrease to see very weak signals, increase to get better contrast."));
waterfallGammaKnob->setHintText(tr("Gamma value:"), "");
advanced_layout->addWidget(waterfallGammaKnob, 1, 2, 1, 1, Qt::AlignCenter);
// FFT window overlap
auto windowOverlapKnob = new Knob(KnobType::Small17, this);
windowOverlapKnob->setModel(&controls->m_windowOverlapModel);
windowOverlapKnob->setLabel(tr("Window overlap"));
windowOverlapKnob->setToolTip(tr("Increase to prevent missing fast transitions arriving near FFT window edges. Warning: high CPU usage."));
windowOverlapKnob->setHintText(tr("Number of times each sample is processed:"), "");
advanced_layout->addWidget(windowOverlapKnob, 0, 3, 1, 1, Qt::AlignCenter);
// FFT zero padding
auto zeroPaddingKnob = new Knob(KnobType::Small17, this);
zeroPaddingKnob->setModel(&controls->m_zeroPaddingModel);
zeroPaddingKnob->setLabel(tr("Zero padding"));
zeroPaddingKnob->setToolTip(tr("Increase to get smoother-looking spectrum. Warning: high CPU usage."));
zeroPaddingKnob->setHintText(tr("Processing buffer is"), tr(" steps larger than input block"));
advanced_layout->addWidget(zeroPaddingKnob, 1, 3, 1, 1, Qt::AlignCenter);
processor->reallocateBuffers();
connect(&controls->m_zeroPaddingModel, &FloatModel::dataChanged, [=] {processor->reallocateBuffers();});
// Advanced settings button
auto advancedButton = new PixmapButton(this, tr("Advanced settings"));
advancedButton->setToolTip(tr("Access advanced settings"));
static auto s_advancedOnPixmap = PLUGIN_NAME::getIconPixmap("advanced_on")
.scaled(advButtonSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
static auto s_advancedOffPixmap = PLUGIN_NAME::getIconPixmap("advanced_off")
.scaled(advButtonSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
s_advancedOnPixmap.setDevicePixelRatio(devicePixelRatio());
s_advancedOffPixmap.setDevicePixelRatio(devicePixelRatio());
advancedButton->setActiveGraphic(s_advancedOnPixmap);
advancedButton->setInactiveGraphic(s_advancedOffPixmap);
advancedButton->setCheckable(true);
controls_layout->addStretch(0);
controls_layout->addWidget(advancedButton);
connect(advancedButton, &PixmapButton::toggled, [=](bool checked)
{
if (checked)
{
config_widget->hide();
advanced_widget->show();
}
else
{
config_widget->show();
advanced_widget->hide();
}
}
);
// QSplitter middle and bottom: spectrum display widgets
m_spectrum = new SaSpectrumView(controls, processor, this);
display_splitter->addWidget(m_spectrum);
m_waterfall = new SaWaterfallView(controls, processor, this);
display_splitter->addWidget(m_waterfall);
m_waterfall->setVisible(m_controls->m_waterfallModel.value());
connect(&controls->m_waterfallModel, &BoolModel::dataChanged, [=] {m_waterfall->updateVisibility();});
}
// Suggest the best current widget size.
QSize SaControlsDialog::sizeHint() const
{
// Best width is determined by spectrum display sizeHint.
// Best height depends on whether waterfall is visible and
// consists of heights of the config section, spectrum, waterfall
// and some reserve for margins.
if (m_waterfall->isVisible())
{
return QSize(m_spectrum->sizeHint().width(),
m_configHeight + m_spectrum->sizeHint().height() + m_waterfall->sizeHint().height() + 50);
}
else
{
return QSize(m_spectrum->sizeHint().width(),
m_configHeight + m_spectrum->sizeHint().height() + 50);
}
}
} // namespace lmms::gui
| 16,957
|
C++
|
.cpp
| 322
| 50.39441
| 142
| 0.783893
|
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,632
|
GranularPitchShifterEffect.cpp
|
LMMS_lmms/plugins/GranularPitchShifter/GranularPitchShifterEffect.cpp
|
/*
* GranularPitchShifter.cpp
*
* Copyright (c) 2024 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "GranularPitchShifterEffect.h"
#include <cmath>
#include "embed.h"
#include "plugin_export.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT granularpitchshifter_plugin_descriptor =
{
LMMS_STRINGIFY(PLUGIN_NAME),
"Granular Pitch Shifter",
QT_TRANSLATE_NOOP("PluginBrowser", "Granular pitch shifter"),
"Lost Robot <r94231/at/gmail/dot/com>",
0x0100,
Plugin::Type::Effect,
new PluginPixmapLoader("logo"),
nullptr,
nullptr,
} ;
}
GranularPitchShifterEffect::GranularPitchShifterEffect(Model* parent, const Descriptor::SubPluginFeatures::Key* key) :
Effect(&granularpitchshifter_plugin_descriptor, parent, key),
m_granularpitchshifterControls(this),
m_prefilter({PrefilterLowpass(), PrefilterLowpass()})
{
autoQuitModel()->setValue(autoQuitModel()->maxValue());
changeSampleRate();
}
Effect::ProcessStatus GranularPitchShifterEffect::processImpl(SampleFrame* buf, const fpp_t frames)
{
const float d = dryLevel();
const float w = wetLevel();
const ValueBuffer* pitchBuf = m_granularpitchshifterControls.m_pitchModel.valueBuffer();
const ValueBuffer* pitchSpreadBuf = m_granularpitchshifterControls.m_pitchSpreadModel.valueBuffer();
const float size = m_granularpitchshifterControls.m_sizeModel.value();
const float shape = m_granularpitchshifterControls.m_shapeModel.value();
const float jitter = m_granularpitchshifterControls.m_jitterModel.value();
const float twitch = m_granularpitchshifterControls.m_twitchModel.value();
const float spray = m_granularpitchshifterControls.m_sprayModel.value();
const float spraySpread = m_granularpitchshifterControls.m_spraySpreadModel.value();
const float density = m_granularpitchshifterControls.m_densityModel.value();
const float glide = m_granularpitchshifterControls.m_glideModel.value();
const int minLatency = m_granularpitchshifterControls.m_minLatencyModel.value() * m_sampleRate;
const float densityInvRoot = std::sqrt(1.f / density);
const float feedback = m_granularpitchshifterControls.m_feedbackModel.value();
const float fadeLength = 1.f / m_granularpitchshifterControls.m_fadeLengthModel.value();
const bool prefilter = m_granularpitchshifterControls.m_prefilterModel.value();
if (glide != m_oldGlide)
{
m_oldGlide = glide;
m_glideCoef = glide > 0 ? std::exp(-1 / (glide * m_sampleRate)) : 0;
}
const float shapeK = cosWindowApproxK(shape);
const int sizeSamples = m_sampleRate / size;
const float waitMult = sizeSamples / (density * 2);
for (fpp_t f = 0; f < frames; ++f)
{
const double pitch = (pitchBuf ? pitchBuf->value(f) : m_granularpitchshifterControls.m_pitchModel.value()) * (1. / 12.);
const double pitchSpread = (pitchSpreadBuf ? pitchSpreadBuf->value(f) : m_granularpitchshifterControls.m_pitchSpreadModel.value()) * (1. / 24.);
// interpolate pitch depending on glide
for (int i = 0; i < 2; ++i)
{
double targetVal = pitch + pitchSpread * (i ? 1. : -1.);
if (targetVal == m_truePitch[i]) { continue; }
m_updatePitches = true;
m_truePitch[i] = m_glideCoef * m_truePitch[i] + (1. - m_glideCoef) * targetVal;
// we crudely lock the pitch to the target value once it gets close enough, so we can save on CPU
if (std::abs(targetVal - m_truePitch[i]) < GlideSnagRadius) { m_truePitch[i] = targetVal; }
}
// this stuff is computationally expensive, so we should only do it when necessary
if (m_updatePitches)
{
m_updatePitches = false;
std::array<double, 2> speed = {
std::exp2(m_truePitch[0]),
std::exp2(m_truePitch[1])
};
std::array<double, 2> ratio = {
speed[0] / m_speed[0],
speed[1] / m_speed[1]
};
for (int i = 0; i < m_grainCount; ++i)
{
for (int j = 0; j < 2; ++j)
{
m_grains[i].grainSpeed[j] *= ratio[j];
// we unfortunately need to do extra stuff to ensure these don't shoot past the write index...
if (m_grains[i].grainSpeed[j] > 1)
{
double distance = m_writePoint - m_grains[i].readPoint[j] - SafetyLatency;
if (distance <= 0) { distance += m_ringBufLength; }
double grainSpeedRequired = ((m_grains[i].grainSpeed[j] - 1.) / distance) * (1. - m_grains[i].phase);
m_grains[i].phaseSpeed[j] = std::max(m_grains[i].phaseSpeed[j], grainSpeedRequired);
}
}
}
m_speed[0] = speed[0];
m_speed[1] = speed[1];
// prevent aliasing by lowpassing frequencies that the pitch shifting would push above nyquist
m_prefilter[0].setCoefs(m_sampleRate, std::min(m_nyquist / static_cast<float>(speed[0]), m_nyquist) * PrefilterBandwidth);
m_prefilter[1].setCoefs(m_sampleRate, std::min(m_nyquist / static_cast<float>(speed[1]), m_nyquist) * PrefilterBandwidth);
}
std::array<float, 2> s = {0, 0};
std::array<float, 2> filtered = {buf[f][0], buf[f][1]};
// spawn a new grain if it's time
if (++m_timeSinceLastGrain >= m_nextWaitRandomization * waitMult)
{
m_timeSinceLastGrain = 0;
double randThing = fast_rand() * static_cast<double>(FAST_RAND_RATIO) * 2. - 1.;
m_nextWaitRandomization = std::exp2(randThing * twitch);
double grainSpeed = 1. / std::exp2(randThing * jitter);
std::array<float, 2> sprayResult = {0, 0};
if (spray > 0)
{
sprayResult[0] = fast_rand() * FAST_RAND_RATIO * spray * m_sampleRate;
sprayResult[1] = linearInterpolate(
sprayResult[0],
fast_rand() * FAST_RAND_RATIO * spray * m_sampleRate,
spraySpread);
}
std::array<int, 2> readPoint;
int latency = std::max(static_cast<int>(std::max(sizeSamples * (std::max(m_speed[0], m_speed[1]) * grainSpeed - 1.), 0.) + SafetyLatency), minLatency);
for (int i = 0; i < 2; ++i)
{
readPoint[i] = m_writePoint - latency - sprayResult[i];
if (readPoint[i] < 0) { readPoint[i] += m_ringBufLength; }
}
const double phaseInc = 1. / sizeSamples;
m_grains.push_back(Grain(grainSpeed * m_speed[0], grainSpeed * m_speed[1], phaseInc, phaseInc, readPoint[0], readPoint[1]));
++m_grainCount;
}
for (int i = 0; i < m_grainCount; ++i)
{
m_grains[i].phase += std::max(m_grains[i].phaseSpeed[0], m_grains[i].phaseSpeed[1]);
if (m_grains[i].phase >= 1)
{
// grain is done, delete it
std::swap(m_grains[i], m_grains[m_grainCount-1]);
m_grains.pop_back();
--i;
--m_grainCount;
continue;
}
m_grains[i].readPoint[0] += m_grains[i].grainSpeed[0];
m_grains[i].readPoint[1] += m_grains[i].grainSpeed[1];
if (m_grains[i].readPoint[0] >= m_ringBufLength) { m_grains[i].readPoint[0] -= m_ringBufLength; }
if (m_grains[i].readPoint[1] >= m_ringBufLength) { m_grains[i].readPoint[1] -= m_ringBufLength; }
const float fadePos = std::clamp((-std::abs(-2.f * static_cast<float>(m_grains[i].phase) + 1.f) + 0.5f) * fadeLength + 0.5f, 0.f, 1.f);
const float windowVal = cosHalfWindowApprox(fadePos, shapeK);
s[0] += getHermiteSample(m_grains[i].readPoint[0], 0) * windowVal;
s[1] += getHermiteSample(m_grains[i].readPoint[1], 1) * windowVal;
}
// note that adding two signals together, when uncorrelated, results in a signal power multiplication of sqrt(2), not 2
s[0] *= densityInvRoot;
s[1] *= densityInvRoot;
// 1-pole highpass for DC offset removal, to make feedback safer
s[0] -= (m_dcVal[0] = (1.f - m_dcCoeff) * s[0] + m_dcCoeff * m_dcVal[0]);
s[1] -= (m_dcVal[1] = (1.f - m_dcCoeff) * s[1] + m_dcCoeff * m_dcVal[1]);
// cheap safety saturator to protect against infinite feedback
if (feedback > 0)
{
s[0] = safetySaturate(s[0]);
s[1] = safetySaturate(s[1]);
}
if (++m_writePoint >= m_ringBufLength)
{
m_writePoint = 0;
}
if (prefilter)
{
filtered[0] = m_prefilter[0].process(filtered[0]);
filtered[1] = m_prefilter[1].process(filtered[1]);
}
m_ringBuf[m_writePoint][0] = filtered[0] + s[0] * feedback;
m_ringBuf[m_writePoint][1] = filtered[1] + s[1] * feedback;
buf[f][0] = d * buf[f][0] + w * s[0];
buf[f][1] = d * buf[f][1] + w * s[1];
}
if (m_sampleRateNeedsUpdate)
{
m_sampleRateNeedsUpdate = false;
changeSampleRate();
}
return Effect::ProcessStatus::ContinueIfNotQuiet;
}
void GranularPitchShifterEffect::changeSampleRate()
{
const int range = m_granularpitchshifterControls.m_rangeModel.value();
const float ringBufLength = RangeSeconds[range];
m_sampleRate = Engine::audioEngine()->outputSampleRate();
m_nyquist = m_sampleRate / 2;
m_ringBufLength = m_sampleRate * ringBufLength;
m_ringBuf.resize(m_ringBufLength);
for (size_t i = 0; i < static_cast<std::size_t>(m_ringBufLength); ++i)
{
m_ringBuf[i][0] = 0;
m_ringBuf[i][1] = 0;
}
m_writePoint = 0;
m_oldGlide = -1;
m_updatePitches = true;
m_grains.clear();
m_grainCount = 0;
m_grains.reserve(8);// arbitrary
m_dcCoeff = std::exp(-2.0 * F_PI * DcRemovalHz / m_sampleRate);
const double pitch = m_granularpitchshifterControls.m_pitchModel.value() * (1. / 12.);
const double pitchSpread = m_granularpitchshifterControls.m_pitchSpreadModel.value() * (1. / 24.);
m_truePitch[0] = pitch - pitchSpread;
m_truePitch[1] = pitch + pitchSpread;
m_speed[0] = std::exp2(m_truePitch[0]);
m_speed[1] = std::exp2(m_truePitch[1]);
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin* lmms_plugin_main(Model* parent, void* data)
{
return new GranularPitchShifterEffect(parent, static_cast<const Plugin::Descriptor::SubPluginFeatures::Key*>(data));
}
}
} // namespace lmms
| 10,302
|
C++
|
.cpp
| 245
| 38.685714
| 154
| 0.69995
|
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,633
|
GranularPitchShifterControlDialog.cpp
|
LMMS_lmms/plugins/GranularPitchShifter/GranularPitchShifterControlDialog.cpp
|
/*
* GranularPitchShifterControlDialog.cpp
*
* Copyright (c) 2024 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "GranularPitchShifterControlDialog.h"
#include "GranularPitchShifterControls.h"
#include "embed.h"
#include "LcdFloatSpinBox.h"
#include "Knob.h"
#include "GuiApplication.h"
#include "PixmapButton.h"
namespace lmms::gui
{
GranularPitchShifterControlDialog::GranularPitchShifterControlDialog(GranularPitchShifterControls* controls) :
EffectControlDialog(controls)
{
setAutoFillBackground(true);
QPalette pal;
pal.setBrush(backgroundRole(), PLUGIN_NAME::getIconPixmap("artwork"));
setPalette(pal);
setFixedSize(305, 180);
auto makeKnob = [this](KnobType style, int x, int y, const QString& hintText, const QString& unit, FloatModel* model)
{
Knob* newKnob = new Knob(style, this);
newKnob->move(x, y);
newKnob->setModel(model);
newKnob->setHintText(hintText, unit);
return newKnob;
};
makeKnob(KnobType::Bright26, 19, 78, tr("Grain Size:"), " Hz", &controls->m_sizeModel);
makeKnob(KnobType::Bright26, 116, 10, tr("Spray:"), " seconds", &controls->m_sprayModel);
makeKnob(KnobType::Bright26, 158, 10, tr("Jitter:"), " octaves", &controls->m_jitterModel);
makeKnob(KnobType::Bright26, 200, 10, tr("Twitch:"), " octaves", &controls->m_twitchModel);
makeKnob(KnobType::Bright26, 188, 60, tr("Spray Stereo Spread:"), "", &controls->m_spraySpreadModel);
makeKnob(KnobType::Bright26, 135, 110, tr("Grain Shape:"), "", &controls->m_shapeModel);
makeKnob(KnobType::Bright26, 188, 110, tr("Fade Length:"), "", &controls->m_fadeLengthModel);
makeKnob(KnobType::Bright26, 258, 45, tr("Feedback:"), "", &controls->m_feedbackModel);
makeKnob(KnobType::Bright26, 258, 92, tr("Minimum Allowed Latency:"), " seconds", &controls->m_minLatencyModel);
makeKnob(KnobType::Small17, 66, 157, tr("Density:"), "x", &controls->m_densityModel);
makeKnob(KnobType::Small17, 8, 157, tr("Glide:"), " seconds", &controls->m_glideModel);
LcdFloatSpinBox* pitchBox = new LcdFloatSpinBox(3, 2, "11green", tr("Pitch"), this);
pitchBox->move(15, 41);
pitchBox->setModel(&controls->m_pitchModel);
pitchBox->setToolTip(tr("Pitch"));
pitchBox->setSeamless(true, true);
LcdFloatSpinBox* pitchSpreadBox = new LcdFloatSpinBox(3, 2, "11green", tr("Pitch Stereo Spread"), this);
pitchSpreadBox->move(133, 66);
pitchSpreadBox->setModel(&controls->m_pitchSpreadModel);
pitchSpreadBox->setToolTip(tr("Pitch Stereo Spread"));
pitchSpreadBox->setSeamless(true, true);
QPushButton button("Show Help", this);
connect(&button, &QPushButton::clicked, this, &GranularPitchShifterControlDialog::showHelpWindow);
PixmapButton* m_helpBtn = new PixmapButton(this, nullptr);
m_helpBtn->move(278, 159);
m_helpBtn->setActiveGraphic(PLUGIN_NAME::getIconPixmap("help_active"));
m_helpBtn->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("help_inactive"));
m_helpBtn->setToolTip(tr("Open help window"));
connect(m_helpBtn, SIGNAL(clicked()), this, SLOT(showHelpWindow()));
PixmapButton* prefilterButton = new PixmapButton(this, tr("Prefilter"));
prefilterButton->move(8, 133);
prefilterButton->setActiveGraphic(PLUGIN_NAME::getIconPixmap("prefilter_active"));
prefilterButton->setInactiveGraphic(PLUGIN_NAME::getIconPixmap("prefilter_inactive"));
prefilterButton->setCheckable(true);
prefilterButton->setModel(&controls->m_prefilterModel);
prefilterButton->setToolTip(tr("Prefilter"));
ComboBox* rangeBox = new ComboBox(this);
rangeBox->setGeometry(189, 155, 80, 22);
rangeBox->setModel(&controls->m_rangeModel);
controls->updateRange();
}
void GranularPitchShifterControlDialog::showHelpWindow() {
GranularPitchShifterHelpView::getInstance()->close();
GranularPitchShifterHelpView::getInstance()->show();
}
QString GranularPitchShifterHelpView::s_helpText=
"<div style='text-align: center;'>"
"<b>Granular Pitch Shifter</b><br><br>"
"Plugin by Lost Robot<br>"
"GUI by thismoon<br>"
"</div>"
"<h3>Grain:</h3>"
"<b>Pitch</b> - The amount of pitch shifting to perform, in 12EDO semitones.<br>"
"<b>Size</b> - The length of each grain, in Hz. By default, new grains will be created at double this rate. <br>In most cases, you'll want this to be set to higher frequencies when shifting the pitch upward, and vice-versa. <br>"
"<br><h3>Random:</h3>"
"<b>Spray</b> - The amount of randomization for the playback position of each grain, in seconds. <br>This does not change when the grain plays, but rather what audio the grain is pulling from. <br>For example, a value of 0.5 seconds will allow each grain to play back audio from up to half of a second ago.<br>It's oftentimes recommended to use at least a small amount of Spray, as this will break up the periodicity in the grains, which is usually the main artifact caused by a granular pitch shifter. <br>This will also make the grains uncorrelated with each other, guaranteeing that a grain Shape value of 2 will always be optimal.<br>"
"<b>Jitter</b> - The amount of randomization for the pitch of each grain, in octaves.<br> This does not impact how often grains are created.<br>"
"<b>Twitch</b> - The amount of randomization for how often new grains are created, in octaves. <br>Jitter and Twitch both use the same random numbers, so if they're at the same value, then the grain creation timings will be changed exactly proportionally to their change in pitch.<br>"
"<br><h3>Stereo:</h3>"
"<b>Pitch</b> - The total distance in pitch between both stereo channels, in 12EDO semitones.<br> Half of the amount of pitch shifting shown will be applied to the right channel, and the opposite to the left channel.<br>"
"<b>Spray</b> - The allowed distance between each channel's randomized position with the Spray feature in the Random category. <br>A value of 1 makes the Spray values in each channel entirely unlinked."
"<br><h3>Shape:</h3>"
"<b>Shape</b> - The shape of each grain's fades. In most cases, 2 is the optimal value, providing equal-power fades. <br>However, when the plugin is performing minimal pitch shifting and has most of its parameters at default, a value of 1 may be more optimal, providing equal-gain fades. <br>All fades are designed for 50% grain overlap.<br>"
"<b>Fade</b> - The length of the grain fades. A value of 1 provides the cleanest fades, causing those fades to reach across the entire grain. <br>Values below 1 make the fade artifacts more audible, but those fades will only apply to the outer edges of each grain. <br>A value of 0 will result in clicking sounds due to the fades no longer being present.<br>"
"<br><h3>Delay:</h3>"
"<b>Feedback</b> - The amount of feedback for the pitch shifter.<br> This feeds a portion of the pitch shifter output back into the input buffer. Large values can be dangerous.<br>"
"<b>Latency</b> - The minimum amount of latency the pitch shifter will have.<br> This granular pitch shifter dynamically changes its latency to be at the minimum possible amount depending on your settings. <br>If you'd like for this latency to be more predictable, you may increase the value of this parameter until the latency no longer changes. <br>This parameter may also be used to be set the minimum amount of delay for the feedback.<br>A larger latency amount can remove subtle fluttering artifacts that may result from automating the pitch shifting amount at high speeds."
"<br><h3>Miscellaneous:</h3>"
"<b>Prefilter</b> - Enables a 12 dB lowpass filter prior to the pitch shifting which automatically adjusts its cutoff to drastically reduce any resulting aliasing.<br>"
"<b>Density</b> - The multiplier for how often grains are spawned. <br>This will increase the grain overlap above 50%. <br>It will create painful piercing sounds if you don't make use of any of the knobs in the Random category. <br>Otherwise, you can get some interesting effects similar to unison or a stationary Paulstretch. <br>Note that this knob uses by far the most CPU out of any parameter in this plugin when increased.<br>"
"<b>Glide</b> - The length of interpolation for the amount of pitch shifting.<br> A small amount of glide is very effective for cleaning up many of the artifacts that may result from changing the pitch shift amount over time. <br>"
"<b>Range</b> - The length of the pitch shifter's internal ring buffer.<br> Changing this will change the minimum and maximum values for some of the other parameters, which are listed in each of the options.<br> Increase it if you need parameter values that aren't supported with the minimum buffer length. Otherwise, it's best to leave it at its minimum value.<br>"
;
GranularPitchShifterHelpView::GranularPitchShifterHelpView():QTextEdit(s_helpText)
{
#if (QT_VERSION < QT_VERSION_CHECK(5,12,0))
// Bug workaround: https://codereview.qt-project.org/c/qt/qtbase/+/225348
using ::operator|;
#endif
setWindowTitle("Granular Pitch Shifter Help");
setTextInteractionFlags(Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse);
getGUI()->mainWindow()->addWindowedWidget(this);
parentWidget()->setAttribute(Qt::WA_DeleteOnClose, false);
parentWidget()->setWindowIcon(PLUGIN_NAME::getIconPixmap("logo"));
// No maximize button
Qt::WindowFlags flags = parentWidget()->windowFlags();
flags &= ~Qt::WindowMaximizeButtonHint;
parentWidget()->setWindowFlags(flags);
}
} // namespace lmms::gui
| 10,095
|
C++
|
.cpp
| 138
| 71.275362
| 642
| 0.762437
|
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,634
|
GranularPitchShifterControls.cpp
|
LMMS_lmms/plugins/GranularPitchShifter/GranularPitchShifterControls.cpp
|
/*
* GranularPitchShifterControls.cpp
*
* Copyright (c) 2024 Lost Robot <r94231/at/gmail/dot/com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QDomElement>
#include "GranularPitchShifterControls.h"
#include "GranularPitchShifterEffect.h"
namespace lmms
{
GranularPitchShifterControls::GranularPitchShifterControls(GranularPitchShifterEffect* effect) :
EffectControls(effect),
m_effect(effect),
m_pitchModel(1.f, -48.f, 24.f, 0.01f, this, tr("Pitch")),
m_sizeModel(10.f, 2.f, 1000.f, 0.001f, this, tr("Grain Size")),
m_sprayModel(0.005f, 0.f, 0.5f, 0.0001f, this, tr("Spray")),
m_jitterModel(0.f, 0.f, 1.f, 0.0001f, this, tr("Jitter")),
m_twitchModel(0.f, 0.f, 1.f, 0.0001f, this, tr("Twitch")),
m_pitchSpreadModel(0.f, -24.f, 24.f, 0.01f, this, tr("Pitch Stereo Spread")),
m_spraySpreadModel(0.f, 0.f, 1.f, 0.0001f, this, tr("Spray Stereo")),
m_shapeModel(2.f, 1.f, 2.f, 0.0001f, this, tr("Shape")),
m_fadeLengthModel(1.f, 0.001f, 1.f, 0.00001f, this, tr("Fade Length")),
m_feedbackModel(0.f, 0.f, 1.f, 0.00001f, this, tr("Feedback")),
m_minLatencyModel(0.01f, 0.f, 1.f, 0.00001f, this, tr("Minimum Allowed Latency")),
m_prefilterModel(true, this, tr("Prefilter")),
m_densityModel(1.f, 1.f, 16.f, 0.0001f, this, tr("Density")),
m_glideModel(0.01f, 0.f, 1.f, 0.0001f, this, tr("Glide")),
m_rangeModel(this, tr("Ring Buffer Length"))
{
m_sizeModel.setScaleLogarithmic(true);
m_sprayModel.setScaleLogarithmic(true);
m_spraySpreadModel.setScaleLogarithmic(true);
m_minLatencyModel.setScaleLogarithmic(true);
m_densityModel.setScaleLogarithmic(true);
m_glideModel.setScaleLogarithmic(true);
m_rangeModel.addItem(tr("5 Seconds"));
m_rangeModel.addItem(tr("10 Seconds (Size)"));
m_rangeModel.addItem(tr("40 Seconds (Size and Pitch)"));
m_rangeModel.addItem(tr("40 Seconds (Size and Spray and Jitter)"));
m_rangeModel.addItem(tr("120 Seconds (All of the above)"));
connect(&m_rangeModel, &ComboBoxModel::dataChanged, this, &GranularPitchShifterControls::updateRange);
}
void GranularPitchShifterControls::updateRange()
{
switch (m_rangeModel.value())
{
case 0:// 5 seconds
m_sizeModel.setRange(4.f, 1000.f, 0.001f);
m_pitchModel.setRange(-48.f, 24.f, 0.01f);
m_sprayModel.setRange(0.f, 0.5f, 0.0001f);
m_jitterModel.setRange(0.f, 1.f, 0.0001f);
break;
case 1:// 10 seconds (size)
m_sizeModel.setRange(2.f, 1000.f, 0.001f);
m_pitchModel.setRange(-48.f, 24.f, 0.01f);
m_sprayModel.setRange(0.f, 0.5f, 0.0001f);
m_jitterModel.setRange(0.f, 1.f, 0.0001f);
break;
case 2:// 40 seconds (size and pitch)
m_sizeModel.setRange(2.f, 1000.f, 0.001f);
m_pitchModel.setRange(-48.f, 48.f, 0.01f);
m_sprayModel.setRange(0.f, 0.5f, 0.0001f);
m_jitterModel.setRange(0.f, 1.f, 0.0001f);
break;
case 3:// 40 seconds (size and spray and jitter)
m_sizeModel.setRange(2.f, 1000.f, 0.001f);
m_pitchModel.setRange(-48.f, 24.f, 0.01f);
m_sprayModel.setRange(0.f, 20.f, 0.0001f);
m_jitterModel.setRange(0.f, 2.f, 0.0001f);
break;
case 4:// 120 seconds (all of the above)
m_sizeModel.setRange(2.f, 1000.f, 0.001f);
m_pitchModel.setRange(-48.f, 48.f, 0.01f);
m_sprayModel.setRange(0.f, 40.f, 0.0001f);
m_jitterModel.setRange(0.f, 2.f, 0.0001f);
break;
default:
break;
}
m_effect->sampleRateNeedsUpdate();
}
void GranularPitchShifterControls::loadSettings(const QDomElement& parent)
{
// must be loaded first so the ranges are set properly
m_rangeModel.loadSettings(parent, "range");
m_pitchModel.loadSettings(parent, "pitch");
m_sizeModel.loadSettings(parent, "size");
m_sprayModel.loadSettings(parent, "spray");
m_jitterModel.loadSettings(parent, "jitter");
m_twitchModel.loadSettings(parent, "twitch");
m_pitchSpreadModel.loadSettings(parent, "pitchSpread");
m_spraySpreadModel.loadSettings(parent, "spraySpread");
m_shapeModel.loadSettings(parent, "shape");
m_fadeLengthModel.loadSettings(parent, "fadeLength");
m_feedbackModel.loadSettings(parent, "feedback");
m_minLatencyModel.loadSettings(parent, "minLatency");
m_prefilterModel.loadSettings(parent, "prefilter");
m_densityModel.loadSettings(parent, "density");
m_glideModel.loadSettings(parent, "glide");
}
void GranularPitchShifterControls::saveSettings(QDomDocument& doc, QDomElement& parent)
{
m_rangeModel.saveSettings(doc, parent, "range");
m_pitchModel.saveSettings(doc, parent, "pitch");
m_sizeModel.saveSettings(doc, parent, "size");
m_sprayModel.saveSettings(doc, parent, "spray");
m_jitterModel.saveSettings(doc, parent, "jitter");
m_twitchModel.saveSettings(doc, parent, "twitch");
m_pitchSpreadModel.saveSettings(doc, parent, "pitchSpread");
m_spraySpreadModel.saveSettings(doc, parent, "spraySpread");
m_shapeModel.saveSettings(doc, parent, "shape");
m_fadeLengthModel.saveSettings(doc, parent, "fadeLength");
m_feedbackModel.saveSettings(doc, parent, "feedback");
m_minLatencyModel.saveSettings(doc, parent, "minLatency");
m_prefilterModel.saveSettings(doc, parent, "prefilter");
m_densityModel.saveSettings(doc, parent, "density");
m_glideModel.saveSettings(doc, parent, "glide");
}
} // namespace lmms
| 5,839
|
C++
|
.cpp
| 137
| 40.459854
| 103
| 0.741164
|
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,635
|
CarlaPatchbay.cpp
|
LMMS_lmms/plugins/CarlaPatchbay/CarlaPatchbay.cpp
|
/*
* carlapatchbay.cpp - Carla for LMMS (Patchbay)
*
* Copyright (C) 2014-2018 Filipe Coelho <falktx@falktx.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 "Carla.h"
#include "embed.h"
#include "plugin_export.h"
#include "InstrumentTrack.h"
namespace lmms
{
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT carlapatchbay_plugin_descriptor =
{
LMMS_STRINGIFY( PLUGIN_NAME ),
"Carla Patchbay",
QT_TRANSLATE_NOOP( "PluginBrowser",
"Carla Patchbay Instrument" ),
"falkTX <falktx/at/falktx.com>",
CARLA_VERSION_HEX,
Plugin::Type::Instrument,
new PluginPixmapLoader( "logo" ),
nullptr,
nullptr,
} ;
PLUGIN_EXPORT Plugin* lmms_plugin_main(Model* m, void*)
{
return new CarlaInstrument(static_cast<InstrumentTrack*>(m), &carlapatchbay_plugin_descriptor, true);
}
}
} // namespace lmms
| 1,609
|
C++
|
.cpp
| 50
| 29.3
| 105
| 0.730968
|
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.