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,133
codecsection.cpp
olive-editor_olive/app/dialog/export/codec/codecsection.cpp
/*** 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/>. ***/ #include "codecsection.h" namespace olive { CodecSection::CodecSection(QWidget *parent) : QWidget(parent) { } }
829
C++
.cpp
21
36.809524
71
0.773467
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,134
av1section.cpp
olive-editor_olive/app/dialog/export/codec/av1section.cpp
/*** 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/>. ***/ #include "av1section.h" #include <QCheckBox> #include <QComboBox> #include <QGridLayout> #include <QLabel> #include "common/qtutils.h" #include "widget/slider/integerslider.h" namespace olive { AV1Section::AV1Section(QWidget *parent) : AV1Section(AV1CRFSection::kDefaultAV1CRF, parent) { } AV1Section::AV1Section(int default_crf, QWidget *parent) : CodecSection(parent) { QGridLayout* layout = new QGridLayout(this); layout->setContentsMargins(0, 0, 0, 0); int row = 0; layout->addWidget(new QLabel(tr("Preset:")), row, 0); preset_combobox_ = new QComboBox(); preset_combobox_->setToolTip(tr("This parameter governs the efficiency/encode-time trade-off.\n" "Lower presets will result in an output with better quality for a given file size, but will take longer to encode.\n" "Higher presets can result in a very fast encode, but will make some compromises on visual quality for a given crf value.")); for (int i = 0; i <= 13; i++) preset_combobox_->addItem(QString::number(i)); preset_combobox_->setCurrentIndex(8); layout->addWidget(preset_combobox_, row, 1); row++; layout->addWidget(new QLabel(tr("Compression Method:")), row, 0); QComboBox* compression_box = new QComboBox(); compression_box->setToolTip(tr("This parameter governs the quality/size trade-off.\n" "Higher CRF values will result in a final output that takes less space, but begins to lose detail.\n" "Lower CRF values retain more detail at the cost of larger file sizes.\n" "The possible range of CRF in SVT-AV1 is 1-63.")); // These items must correspond to the CompressionMethod enum compression_box->addItem(tr("Constant Rate Factor")); layout->addWidget(compression_box, row, 1); row++; compression_method_stack_ = new QStackedWidget(); layout->addWidget(compression_method_stack_, row, 0, 1, 2); crf_section_ = new AV1CRFSection(default_crf); compression_method_stack_->addWidget(crf_section_); connect(compression_box, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), compression_method_stack_, &QStackedWidget::setCurrentIndex); } void AV1Section::AddOpts(EncodingParams *params) { CompressionMethod method = static_cast<CompressionMethod>(compression_method_stack_->currentIndex()); if (method == kConstantRateFactor) { // Set Quantizer value params->set_video_option(QStringLiteral("qp"), QString::number(crf_section_->GetValue())); } params->set_video_option(QStringLiteral("preset"), QString::number(preset_combobox_->currentIndex())); } AV1CRFSection::AV1CRFSection(int default_crf, QWidget *parent) : QWidget(parent) { QHBoxLayout* layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); crf_slider_ = new QSlider(Qt::Horizontal); crf_slider_->setMinimum(kMinimumCRF); crf_slider_->setMaximum(kMaximumCRF); crf_slider_->setValue(default_crf); layout->addWidget(crf_slider_); IntegerSlider* crf_input = new IntegerSlider(); crf_input->setMaximumWidth(QtUtils::QFontMetricsWidth(crf_input->fontMetrics(), QStringLiteral("HHHH"))); crf_input->SetMinimum(kMinimumCRF); crf_input->SetMaximum(kMaximumCRF); crf_input->SetValue(default_crf); crf_input->SetDefaultValue(default_crf); layout->addWidget(crf_input); connect(crf_slider_, &QSlider::valueChanged, crf_input, &IntegerSlider::SetValue); connect(crf_input, &IntegerSlider::ValueChanged, crf_slider_, &QSlider::setValue); } int AV1CRFSection::GetValue() const { return crf_slider_->value(); } }
4,262
C++
.cpp
95
41.6
129
0.748426
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,135
cineformsection.cpp
olive-editor_olive/app/dialog/export/codec/cineformsection.cpp
/*** 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/>. ***/ #include "cineformsection.h" #include <QGridLayout> #include <QLabel> namespace olive { CineformSection::CineformSection(QWidget *parent) : CodecSection(parent) { QGridLayout *layout = new QGridLayout(this); layout->setContentsMargins(0, 0, 0, 0); int row = 0; layout->addWidget(new QLabel(tr("Quality:")), row, 0); quality_combobox_ = new QComboBox(); /* Correspond to the following indexes for FFmpeg * * -quality <int> E..V....... set quality (from 0 to 12) (default film3+) * film3+ 0 E..V....... * film3 1 E..V....... * film2+ 2 E..V....... * film2 3 E..V....... * film1.5 4 E..V....... * film1+ 5 E..V....... * film1 6 E..V....... * high+ 7 E..V....... * high 8 E..V....... * medium+ 9 E..V....... * medium 10 E..V....... * low+ 11 E..V....... * low 12 E..V....... * */ quality_combobox_->addItem(tr("Film Scan 3+")); quality_combobox_->addItem(tr("Film Scan 3")); quality_combobox_->addItem(tr("Film Scan 2+")); quality_combobox_->addItem(tr("Film Scan 2")); quality_combobox_->addItem(tr("Film Scan 1.5")); quality_combobox_->addItem(tr("Film Scan 1+")); quality_combobox_->addItem(tr("Film Scan 1")); quality_combobox_->addItem(tr("High+")); quality_combobox_->addItem(tr("High")); quality_combobox_->addItem(tr("Medium+")); quality_combobox_->addItem(tr("Medium")); quality_combobox_->addItem(tr("Low+")); quality_combobox_->addItem(tr("Low")); // Default to "medium" quality_combobox_->setCurrentIndex(10); layout->addWidget(quality_combobox_, row, 1); } void CineformSection::AddOpts(EncodingParams *params) { params->set_video_option(QStringLiteral("quality"), QString::number(quality_combobox_->currentIndex())); } void CineformSection::SetOpts(const EncodingParams *p) { quality_combobox_->setCurrentIndex(p->video_option(QStringLiteral("quality")).toInt()); } }
2,942
C++
.cpp
70
38.957143
106
0.598878
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,136
imagesection.cpp
olive-editor_olive/app/dialog/export/codec/imagesection.cpp
/*** 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/>. ***/ #include "imagesection.h" #include <QGridLayout> #include <QLabel> namespace olive { ImageSection::ImageSection(QWidget* parent) : CodecSection(parent) { QGridLayout* layout = new QGridLayout(this); layout->setContentsMargins(0, 0, 0, 0); int row = 0; layout->addWidget(new QLabel(tr("Image Sequence:")), row, 0); image_sequence_checkbox_ = new QCheckBox(); connect(image_sequence_checkbox_, &QCheckBox::toggled, this, &ImageSection::ImageSequenceCheckBoxToggled); layout->addWidget(image_sequence_checkbox_, row, 1); row++; layout->addWidget(new QLabel(tr("Frame to Export:")), row, 0); frame_slider_ = new RationalSlider(); frame_slider_->SetMinimum(0); frame_slider_->SetValue(0); frame_slider_->SetDisplayType(RationalSlider::kTime); connect(frame_slider_, &RationalSlider::ValueChanged, this, &ImageSection::TimeChanged); layout->addWidget(frame_slider_, row, 1); } void ImageSection::ImageSequenceCheckBoxToggled(bool e) { frame_slider_->setEnabled(!e); } }
1,721
C++
.cpp
42
38.190476
108
0.758123
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,137
codecstack.cpp
olive-editor_olive/app/dialog/export/codec/codecstack.cpp
/*** 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/>. ***/ #include "codecstack.h" namespace olive { #define super QStackedWidget CodecStack::CodecStack(QWidget *parent) : super{parent} { connect(this, &CodecStack::currentChanged, this, &CodecStack::OnChange); } void CodecStack::addWidget(QWidget *widget) { super::addWidget(widget); OnChange(currentIndex()); } void CodecStack::OnChange(int index) { for (int i=0; i<count(); i++) { if (i == index) { widget(i)->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } else { widget(i)->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); } widget(i)->adjustSize(); } adjustSize(); } }
1,354
C++
.cpp
40
30.875
79
0.744043
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,138
videoparams.cpp
olive-editor_olive/app/render/videoparams.cpp
/*** 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/>. ***/ #include "videoparams.h" extern "C" { #include <libavutil/avutil.h> } #include <QCoreApplication> #include <QtMath> #include "core.h" namespace olive { const int VideoParams::kInternalChannelCount = kRGBAChannelCount; const rational VideoParams::kPixelAspectSquare(1); const rational VideoParams::kPixelAspectNTSCStandard(8, 9); const rational VideoParams::kPixelAspectNTSCWidescreen(32, 27); const rational VideoParams::kPixelAspectPALStandard(16, 15); const rational VideoParams::kPixelAspectPALWidescreen(64, 45); const rational VideoParams::kPixelAspect1080Anamorphic(4, 3); const QVector<rational> VideoParams::kSupportedFrameRates = { rational(10, 1), // 10 FPS rational(15, 1), // 15 FPS rational(24000, 1001), // 23.976 FPS rational(24, 1), // 24 FPS rational(25, 1), // 25 FPS rational(30000, 1001), // 29.97 FPS rational(30, 1), // 30 FPS rational(48000, 1001), // 47.952 FPS rational(48, 1), // 48 FPS rational(50, 1), // 50 FPS rational(60000, 1001), // 59.94 FPS rational(60, 1) // 60 FPS }; const QVector<int> VideoParams::kSupportedDividers = {1, 2, 3, 4, 6, 8, 12, 16}; const QVector<rational> VideoParams::kStandardPixelAspects = { VideoParams::kPixelAspectSquare, VideoParams::kPixelAspectNTSCStandard, VideoParams::kPixelAspectNTSCWidescreen, VideoParams::kPixelAspectPALStandard, VideoParams::kPixelAspectPALWidescreen, VideoParams::kPixelAspect1080Anamorphic }; VideoParams::VideoParams() : width_(0), height_(0), depth_(0), format_(PixelFormat::INVALID), channel_count_(0), interlacing_(Interlacing::kInterlaceNone), divider_(1) { set_defaults_for_footage(); } VideoParams::VideoParams(int width, int height, PixelFormat format, int nb_channels, const rational& pixel_aspect_ratio, Interlacing interlacing, int divider) : width_(width), height_(height), depth_(1), format_(format), channel_count_(nb_channels), pixel_aspect_ratio_(pixel_aspect_ratio), interlacing_(interlacing), divider_(divider) { calculate_effective_size(); validate_pixel_aspect_ratio(); set_defaults_for_footage(); } VideoParams::VideoParams(int width, int height, int depth, PixelFormat format, int nb_channels, const rational &pixel_aspect_ratio, VideoParams::Interlacing interlacing, int divider) : width_(width), height_(height), depth_(depth), format_(format), channel_count_(nb_channels), pixel_aspect_ratio_(pixel_aspect_ratio), interlacing_(interlacing), divider_(divider) { calculate_effective_size(); validate_pixel_aspect_ratio(); set_defaults_for_footage(); } VideoParams::VideoParams(int width, int height, const rational &time_base, PixelFormat format, int nb_channels, const rational& pixel_aspect_ratio, Interlacing interlacing, int divider) : width_(width), height_(height), depth_(1), time_base_(time_base), format_(format), channel_count_(nb_channels), pixel_aspect_ratio_(pixel_aspect_ratio), interlacing_(interlacing), divider_(divider), frame_rate_(time_base.flipped()) { calculate_effective_size(); validate_pixel_aspect_ratio(); set_defaults_for_footage(); } int VideoParams::generate_auto_divider(qint64 width, qint64 height) { const int target_res = 1280*720; qint64 megapixels = width * height; double squared_divider = double(megapixels) / double(target_res); double divider = qSqrt(squared_divider); if (divider <= kSupportedDividers.first()) { return kSupportedDividers.first(); } else if (divider >= kSupportedDividers.last()) { return kSupportedDividers.last(); } else { for (int i=1; i<kSupportedDividers.size(); i++) { int prev_divider = kSupportedDividers.at(i-1); int next_divider = kSupportedDividers.at(i); if (divider >= prev_divider && divider <= next_divider) { double prev_diff = qAbs(prev_divider - divider); double next_diff = qAbs(next_divider - divider); if (prev_diff < next_diff) { return prev_divider; } else { return next_divider; } } } // Fallback return 1; } } bool VideoParams::operator==(const VideoParams &rhs) const { return width() == rhs.width() && height() == rhs.height() && depth() == rhs.depth() && interlacing() == rhs.interlacing() && time_base() == rhs.time_base() && format() == rhs.format() && pixel_aspect_ratio() == rhs.pixel_aspect_ratio() && divider() == rhs.divider() && channel_count() == rhs.channel_count(); } bool VideoParams::operator!=(const VideoParams &rhs) const { return !(*this == rhs); } int VideoParams::GetBytesPerChannel(PixelFormat format) { switch (format) { case PixelFormat::INVALID: case PixelFormat::COUNT: break; case PixelFormat::U8: return 1; case PixelFormat::U16: case PixelFormat::F16: return 2; case PixelFormat::F32: return 4; } return 0; } int VideoParams::GetBytesPerPixel(PixelFormat format, int channels) { return GetBytesPerChannel(format) * channels; } QString VideoParams::GetNameForDivider(int div) { if (div == 1) { return QCoreApplication::translate("VideoParams", "Full"); } else { return QCoreApplication::translate("VideoParams", "1/%1").arg(div); } } QString VideoParams::GetFormatName(PixelFormat format) { switch (format) { case PixelFormat::U8: return QCoreApplication::translate("VideoParams", "8-bit"); case PixelFormat::U16: return QCoreApplication::translate("VideoParams", "16-bit Integer"); case PixelFormat::F16: return QCoreApplication::translate("VideoParams", "Half-Float (16-bit)"); case PixelFormat::F32: return QCoreApplication::translate("VideoParams", "Full-Float (32-bit)"); case PixelFormat::INVALID: case PixelFormat::COUNT: break; } return QCoreApplication::translate("VideoParams", "Unknown (0x%1)").arg(format, 0, 16); } int VideoParams::GetDividerForTargetResolution(int src_width, int src_height, int dst_width, int dst_height) { int divider = 0; int test_width, test_height; do { divider++; test_width = VideoParams::GetScaledDimension(src_width, divider); test_height = VideoParams::GetScaledDimension(src_height, divider); } while (test_width > dst_width || test_height > dst_height); return divider; } void VideoParams::calculate_effective_size() { effective_width_ = GetScaledDimension(width(), divider_); effective_height_ = GetScaledDimension(height(), divider_); effective_depth_ = (depth() == 1) ? depth() : GetScaledDimension(depth(), divider_); calculate_square_pixel_width(); } void VideoParams::validate_pixel_aspect_ratio() { if (pixel_aspect_ratio_.isNull()) { pixel_aspect_ratio_ = 1; } calculate_square_pixel_width(); } void VideoParams::set_defaults_for_footage() { enabled_ = true; stream_index_ = 0; video_type_ = kVideoTypeVideo; start_time_ = 0; duration_ = 0; premultiplied_alpha_ = false; x_ = 0; y_ = 0; color_range_ = kColorRangeDefault; } void VideoParams::calculate_square_pixel_width() { if (pixel_aspect_ratio_.denominator() != 0) { par_width_ = qRound(width_ * pixel_aspect_ratio_.toDouble()); } else { par_width_ = width_; } } bool VideoParams::is_valid() const { return (width() > 0 && height() > 0 && !pixel_aspect_ratio_.isNull() && format_ > PixelFormat::INVALID && format_ < PixelFormat::COUNT && channel_count_ > 0); } QString VideoParams::FrameRateToString(const rational &frame_rate) { return QCoreApplication::translate("VideoParams", "%1 FPS").arg(frame_rate.toDouble()); } QStringList VideoParams::GetStandardPixelAspectRatioNames() { QStringList strings = { QCoreApplication::translate("VideoParams", "Square Pixels (%1)"), QCoreApplication::translate("VideoParams", "NTSC Standard (%1)"), QCoreApplication::translate("VideoParams", "NTSC Widescreen (%1)"), QCoreApplication::translate("VideoParams", "PAL Standard (%1)"), QCoreApplication::translate("VideoParams", "PAL Widescreen (%1)"), QCoreApplication::translate("VideoParams", "HD Anamorphic 1080 (%1)") }; // Format each for (int i=0; i<strings.size(); i++) { strings.replace(i, FormatPixelAspectRatioString(strings.at(i), kStandardPixelAspects.at(i))); } return strings; } QString VideoParams::FormatPixelAspectRatioString(const QString &format, const rational &ratio) { return format.arg(QString::number(ratio.toDouble(), 'f', 4)); } int VideoParams::GetScaledDimension(int dim, int divider) { return dim / divider; } int64_t VideoParams::get_time_in_timebase_units(const rational &time) const { if (time_base_.isNull()) { return AV_NOPTS_VALUE; } return Timecode::time_to_timestamp(time, time_base_) + start_time_; } void VideoParams::Load(QXmlStreamReader *reader) { while (XMLReadNextStartElement(reader)) { if (reader->name() == QStringLiteral("width")) { set_width(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("height")) { set_height(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("depth")) { set_depth(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("timebase")) { set_time_base(rational::fromString(reader->readElementText().toStdString())); } else if (reader->name() == QStringLiteral("format")) { set_format(static_cast<PixelFormat::Format>(reader->readElementText().toInt())); } else if (reader->name() == QStringLiteral("channelcount")) { set_channel_count(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("pixelaspectratio")) { set_pixel_aspect_ratio(rational::fromString(reader->readElementText().toStdString())); } else if (reader->name() == QStringLiteral("interlacing")) { set_interlacing(static_cast<VideoParams::Interlacing>(reader->readElementText().toInt())); } else if (reader->name() == QStringLiteral("divider")) { set_divider(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("enabled")) { set_enabled(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("x")) { set_x(reader->readElementText().toFloat()); } else if (reader->name() == QStringLiteral("y")) { set_y(reader->readElementText().toFloat()); } else if (reader->name() == QStringLiteral("streamindex")) { set_stream_index(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("videotype")) { set_video_type(static_cast<VideoParams::Type>(reader->readElementText().toInt())); } else if (reader->name() == QStringLiteral("framerate")) { set_frame_rate(rational::fromString(reader->readElementText().toStdString())); } else if (reader->name() == QStringLiteral("starttime")) { set_start_time(reader->readElementText().toLongLong()); } else if (reader->name() == QStringLiteral("duration")) { set_duration(reader->readElementText().toLongLong()); } else if (reader->name() == QStringLiteral("premultipliedalpha")) { set_premultiplied_alpha(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("colorspace")) { set_colorspace(reader->readElementText()); } else if (reader->name() == QStringLiteral("colorrange")) { set_color_range(static_cast<ColorRange>(reader->readElementText().toInt())); } else { reader->skipCurrentElement(); } } } void VideoParams::Save(QXmlStreamWriter *writer) const { writer->writeTextElement(QStringLiteral("width"), QString::number(width_)); writer->writeTextElement(QStringLiteral("height"), QString::number(height_)); writer->writeTextElement(QStringLiteral("depth"), QString::number(depth_)); writer->writeTextElement(QStringLiteral("timebase"), QString::fromStdString(time_base_.toString())); writer->writeTextElement(QStringLiteral("format"), QString::number(format_)); writer->writeTextElement(QStringLiteral("channelcount"), QString::number(channel_count_)); writer->writeTextElement(QStringLiteral("pixelaspectratio"), QString::fromStdString(pixel_aspect_ratio_.toString())); writer->writeTextElement(QStringLiteral("interlacing"), QString::number(interlacing_)); writer->writeTextElement(QStringLiteral("divider"), QString::number(divider_)); writer->writeTextElement(QStringLiteral("enabled"), QString::number(enabled_)); writer->writeTextElement(QStringLiteral("x"), QString::number(x_)); writer->writeTextElement(QStringLiteral("y"), QString::number(y_)); writer->writeTextElement(QStringLiteral("streamindex"), QString::number(stream_index_)); writer->writeTextElement(QStringLiteral("videotype"), QString::number(video_type_)); writer->writeTextElement(QStringLiteral("framerate"), QString::fromStdString(frame_rate_.toString())); writer->writeTextElement(QStringLiteral("starttime"), QString::number(start_time_)); writer->writeTextElement(QStringLiteral("duration"), QString::number(duration_)); writer->writeTextElement(QStringLiteral("premultipliedalpha"), QString::number(premultiplied_alpha_)); writer->writeTextElement(QStringLiteral("colorspace"), colorspace_); writer->writeTextElement(QStringLiteral("colorrange"), QString::number(color_range_)); } }
14,155
C++
.cpp
356
36.255618
187
0.710731
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,139
managedcolor.cpp
olive-editor_olive/app/render/managedcolor.cpp
/*** 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/>. ***/ #include "managedcolor.h" namespace olive { ManagedColor::ManagedColor() { } ManagedColor::ManagedColor(const double &r, const double &g, const double &b, const double &a) : Color(r, g, b, a) { } ManagedColor::ManagedColor(const char *data, const PixelFormat &format, int channel_layout) : Color(data, format, channel_layout) { } ManagedColor::ManagedColor(const Color &c) : Color(c) { } const QString &ManagedColor::color_input() const { return color_input_; } void ManagedColor::set_color_input(const QString &color_input) { color_input_ = color_input; } const ColorTransform &ManagedColor::color_output() const { return color_transform_; } void ManagedColor::set_color_output(const ColorTransform &color_output) { color_transform_ = color_output; } }
1,490
C++
.cpp
48
28.916667
96
0.767882
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,140
previewaudiodevice.cpp
olive-editor_olive/app/render/previewaudiodevice.cpp
/*** 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/>. ***/ #include "previewaudiodevice.h" namespace olive { PreviewAudioDevice::PreviewAudioDevice(QObject *parent) : notify_interval_(0), bytes_read_(0) { } PreviewAudioDevice::~PreviewAudioDevice() { close(); } bool PreviewAudioDevice::isSequential() const { return true; } qint64 PreviewAudioDevice::readData(char *data, qint64 maxSize) { QMutexLocker locker(&lock_); qint64 copy_length = qMin(maxSize, qint64(buffer_.size())); if (copy_length) { qint64 new_bytes_read = bytes_read_ + copy_length; if (notify_interval_ > 0) { if ((bytes_read_ / notify_interval_) != (new_bytes_read / notify_interval_)) { emit Notify(); } } bytes_read_ = new_bytes_read; memcpy(data, buffer_.constData(), copy_length); buffer_ = buffer_.mid(copy_length); } return copy_length; } qint64 PreviewAudioDevice::writeData(const char *data, qint64 length) { QMutexLocker locker(&lock_); buffer_.append(data, length); return length; } void PreviewAudioDevice::clear() { QMutexLocker locker(&lock_); buffer_.clear(); bytes_read_ = 0; } }
1,808
C++
.cpp
59
27.59322
84
0.732329
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,141
previewautocacher.cpp
olive-editor_olive/app/render/previewautocacher.cpp
/*** 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/>. ***/ #include "previewautocacher.h" #include <QApplication> #include <QtConcurrent/QtConcurrent> #include "codec/conformmanager.h" #include "node/input/multicam/multicamnode.h" #include "node/inputdragger.h" #include "node/project.h" #include "render/diskmanager.h" #include "render/rendermanager.h" namespace olive { PreviewAutoCacher::PreviewAutoCacher(QObject *parent) : QObject(parent), project_(nullptr), use_custom_range_(false), pause_renders_(false), pause_thumbnails_(false), single_frame_render_(nullptr), display_color_processor_(nullptr), multicam_(nullptr), ignore_cache_requests_(false) { copier_ = new ProjectCopier(this); connect(copier_, &ProjectCopier::AddedNode, this, &PreviewAutoCacher::ConnectToNodeCache); connect(copier_, &ProjectCopier::RemovedNode, this, &PreviewAutoCacher::DisconnectFromNodeCache); // Set defaults SetPlayhead(0); // Wait a certain amount of time before requeuing when we receive an invalidate signal delayed_requeue_timer_.setInterval(OLIVE_CONFIG("AutoCacheDelay").toInt()); delayed_requeue_timer_.setSingleShot(true); connect(&delayed_requeue_timer_, &QTimer::timeout, this, &PreviewAutoCacher::TryRender); // Catch when a conform is ready connect(ConformManager::instance(), &ConformManager::ConformReady, this, &PreviewAutoCacher::ConformFinished); } PreviewAutoCacher::~PreviewAutoCacher() { // Ensure everything is cleaned up appropriately SetProject(nullptr); } RenderTicketPtr PreviewAutoCacher::GetSingleFrame(ViewerOutput *viewer, const rational &t, bool dry) { return GetSingleFrame(viewer->GetConnectedTextureOutput(), viewer, t, dry); } RenderTicketPtr PreviewAutoCacher::GetSingleFrame(Node *n, ViewerOutput *viewer, const rational &t, bool dry) { // If we have a single frame render queued (but not yet sent to the RenderManager), cancel it now CancelQueuedSingleFrameRender(); // Create a new single frame render ticket auto sfr = std::make_shared<RenderTicket>(); sfr->Start(); sfr->setProperty("time", QVariant::fromValue(t)); sfr->setProperty("dry", dry); sfr->setProperty("node", QtUtils::PtrToValue(n)); sfr->setProperty("viewer", QtUtils::PtrToValue(viewer)); // Queue it and try to render single_frame_render_ = sfr; TryRender(); return sfr; } RenderTicketPtr PreviewAutoCacher::GetRangeOfAudio(ViewerOutput *viewer, TimeRange range) { Node *copy = copier_->GetCopy(viewer->GetConnectedSampleOutput()); return RenderAudio(copy, viewer, range, nullptr); } void PreviewAutoCacher::ClearSingleFrameRenders() { QMap<RenderTicketWatcher*, QVector<RenderTicketPtr> > copy = video_immediate_passthroughs_; for (auto it=copy.cbegin(); it!=copy.cend(); it++) { it.key()->Cancel(); if (!it.key()->IsRunning()) { RenderManager::instance()->RemoveTicket(it.key()->GetTicket()); emit it.key()->GetTicket()->Finished(); } } } void PreviewAutoCacher::ClearSingleFrameRendersThatArentRunning() { QMap<RenderTicketWatcher*, QVector<RenderTicketPtr> > copy = video_immediate_passthroughs_; for (auto it=copy.cbegin(); it!=copy.cend(); it++) { if (!it.key()->IsRunning()) { it.key()->Cancel(); RenderManager::instance()->RemoveTicket(it.key()->GetTicket()); emit it.key()->GetTicket()->Finished(); } } } void PreviewAutoCacher::VideoInvalidatedFromCache(ViewerOutput *context, const TimeRange &range) { PlaybackCache *cache = static_cast<PlaybackCache*>(sender()); cache->ClearRequestRange(range); VideoInvalidatedFromNode(context, cache, range); } void PreviewAutoCacher::AudioInvalidatedFromCache(ViewerOutput *context, const TimeRange &range) { PlaybackCache *cache = static_cast<PlaybackCache*>(sender()); cache->ClearRequestRange(range); AudioInvalidatedFromNode(context, cache, range); } void PreviewAutoCacher::CancelForCache() { PlaybackCache *cache = static_cast<PlaybackCache*>(sender()); if (dynamic_cast<FrameHashCache*>(cache) || dynamic_cast<ThumbnailCache*>(cache)) { for (auto it=pending_video_jobs_.begin(); it!=pending_video_jobs_.end(); ) { if ((*it).cache == cache) { it = pending_video_jobs_.erase(it); } else { it++; } } } else if (dynamic_cast<AudioPlaybackCache*>(cache) || dynamic_cast<AudioWaveformCache*>(cache)) { for (auto it=pending_audio_jobs_.begin(); it!=pending_audio_jobs_.end(); ) { if ((*it).cache == cache) { it = pending_audio_jobs_.erase(it); } else { it++; } } } } void PreviewAutoCacher::AudioRendered() { // Receive watcher RenderTicketWatcher* watcher = static_cast<RenderTicketWatcher*>(sender()); // If the task list doesn't contain this watcher, presumably it was cleared as a result of a // viewer switch, so we'll completely ignore this watcher if (running_audio_tasks_.removeOne(watcher)) { // Assume that a "result" is a fully completed image and a non-result is a cancelled ticket TimeRange range = watcher->property("time").value<TimeRange>(); Node *node = copier_->GetOriginal(QtUtils::ValueToPtr<Node>(watcher->property("node"))); if (watcher->HasResult() && node) { if (PlaybackCache *cache = QtUtils::ValueToPtr<PlaybackCache>(watcher->property("cache"))) { AudioCacheData &d = audio_cache_data_[cache]; JobTime watcher_job_time = watcher->property("job").value<JobTime>(); TimeRangeList valid_ranges = d.job_tracker.getCurrentSubRanges(range, watcher_job_time); AudioVisualWaveform waveform = watcher->GetTicket()->property("waveform").value<AudioVisualWaveform>(); SampleBuffer buf = watcher->Get().value<SampleBuffer>(); bool incomplete = watcher->GetTicket()->property("incomplete").toBool(); if (AudioPlaybackCache *pcm = dynamic_cast<AudioPlaybackCache*>(cache)) { // WritePCM is tolerant to its buffer being null, it will just write silence instead pcm->SetParameters(buf.audio_params()); pcm->WritePCM(range, valid_ranges, watcher->Get().value<SampleBuffer>()); } else if (AudioWaveformCache *wave = dynamic_cast<AudioWaveformCache*>(cache)) { wave->SetParameters(buf.audio_params()); if (!incomplete) { wave->WriteWaveform(range, valid_ranges, &waveform); } } if (incomplete) { if (last_conform_task_ > watcher_job_time) { // Requeue now cache->Invalidate(range); } else { // Wait for conform d.needs_conform.insert(range); } } } } // Continue rendering TryRender(); } delete watcher; } void PreviewAutoCacher::VideoRendered() { RenderTicketWatcher* watcher = static_cast<RenderTicketWatcher*>(sender()); const QStringList bad_cache_names = watcher->GetTicket()->property("badcache").toStringList(); if (!bad_cache_names.empty()) { for (const QString &fn : bad_cache_names) { DiskManager::instance()->DeleteSpecificFile(fn); } } // Process passthroughs no matter what, if the viewer was switched, the passthrough map would be // cleared anyway QVector<RenderTicketPtr> tickets = video_immediate_passthroughs_.take(watcher); foreach (RenderTicketPtr t, tickets) { if (watcher->HasResult()) { t->setProperty("multicam_output", watcher->GetTicket()->property("multicam_output")); t->Finish(watcher->Get()); } else { t->Finish(); } } // If the task list doesn't contain this watcher, presumably it was cleared as a result of a // viewer switch, so we'll completely ignore this watcher if (running_video_tasks_.removeOne(watcher)) { // Assume that a "result" is a fully completed image and a non-result is a cancelled ticket if (watcher->HasResult()) { if (watcher->GetTicket()->property("cached").toBool()) { if (FrameHashCache *cache = QtUtils::ValueToPtr<FrameHashCache>(watcher->property("cache"))) { rational time = watcher->property("time").value<rational>(); JobTime job = watcher->property("job").value<JobTime>(); if (video_cache_data_.value(cache).job_tracker.isCurrent(time, job)) { cache->ValidateTime(time); } } } } // Continue rendering TryRender(); } delete watcher; } void PreviewAutoCacher::ConnectToNodeCache(Node *node) { if (ignore_cache_requests_) { return; } connect(node->video_frame_cache(), &PlaybackCache::Requested, this, &PreviewAutoCacher::VideoInvalidatedFromCache); connect(node->thumbnail_cache(), &PlaybackCache::Requested, this, &PreviewAutoCacher::VideoInvalidatedFromCache); connect(node->audio_playback_cache(), &PlaybackCache::Requested, this, &PreviewAutoCacher::AudioInvalidatedFromCache); connect(node->waveform_cache(), &PlaybackCache::Requested, this, &PreviewAutoCacher::AudioInvalidatedFromCache); connect(node->video_frame_cache(), &PlaybackCache::CancelAll, this, &PreviewAutoCacher::CancelForCache); connect(node->audio_playback_cache(), &PlaybackCache::CancelAll, this, &PreviewAutoCacher::CancelForCache); node->video_frame_cache()->ResignalRequests(); node->thumbnail_cache()->ResignalRequests(); node->audio_playback_cache()->ResignalRequests(); node->waveform_cache()->ResignalRequests(); } void PreviewAutoCacher::DisconnectFromNodeCache(Node *node) { disconnect(node->video_frame_cache(), &PlaybackCache::Requested, this, &PreviewAutoCacher::VideoInvalidatedFromCache); disconnect(node->thumbnail_cache(), &PlaybackCache::Requested, this, &PreviewAutoCacher::VideoInvalidatedFromCache); disconnect(node->audio_playback_cache(), &PlaybackCache::Requested, this, &PreviewAutoCacher::AudioInvalidatedFromCache); disconnect(node->waveform_cache(), &PlaybackCache::Requested, this, &PreviewAutoCacher::AudioInvalidatedFromCache); disconnect(node->video_frame_cache(), &PlaybackCache::CancelAll, this, &PreviewAutoCacher::CancelForCache); disconnect(node->audio_playback_cache(), &PlaybackCache::CancelAll, this, &PreviewAutoCacher::CancelForCache); } void PreviewAutoCacher::CancelQueuedSingleFrameRender() { if (single_frame_render_) { // Signal that this ticket was cancelled with no value single_frame_render_->Finish(); single_frame_render_ = nullptr; } } void PreviewAutoCacher::StartCachingRange(const TimeRange &range, TimeRangeList *range_list, RenderJobTracker *tracker) { range_list->insert(range); tracker->insert(range, copier_->GetGraphChangeTime()); } void PreviewAutoCacher::StartCachingVideoRange(ViewerOutput *context, PlaybackCache *cache, const TimeRange &range) { Node *node = cache->parent(); rational using_tb; if (ThumbnailCache *thumbs = dynamic_cast<ThumbnailCache*>(cache)) { using_tb = thumbs->GetTimebase(); } else { using_tb = context->GetVideoParams().frame_rate_as_time_base(); } cache->ClearRequestRange(range); TimeRangeListFrameIterator iterator({range}, using_tb); pending_video_jobs_.push_back({node, context, cache, range, iterator}); video_cache_data_[cache].job_tracker.insert(TimeRange(iterator.Snap(range.in()), range.out()), copier_->GetGraphChangeTime()); TryRender(); } void PreviewAutoCacher::StartCachingAudioRange(ViewerOutput *context, PlaybackCache *cache, const TimeRange &range) { Node *node = cache->parent(); cache->ClearRequestRange(range); pending_audio_jobs_.push_back({node, context, cache, range}); audio_cache_data_[cache].job_tracker.insert(range, copier_->GetGraphChangeTime()); TryRender(); } void PreviewAutoCacher::VideoInvalidatedFromNode(ViewerOutput *context, PlaybackCache *cache, const TimeRange &range) { // Ignore render requests if no video is present if (!context || !context->GetVideoParams().is_valid()) { return; } // Stop any current render tasks because a) they might be out of date now anyway, and b) we // want to dedicate all our rendering power to realtime feedback for the user //CancelVideoTasks(node); cache->ClearRequestRange(range); // If auto-cache is enabled and a slider is not being dragged, queue up to hash these frames if (!NodeInputDragger::IsInputBeingDragged()) { StartCachingVideoRange(context, cache, range); } } void PreviewAutoCacher::AudioInvalidatedFromNode(ViewerOutput *context, PlaybackCache *cache, const TimeRange &range) { // Ignore render requests if no video is present if (!context || !context->GetAudioParams().is_valid()) { return; } // We don't stop rendering audio because currently there's no system of requeuing audio if it's // cancelled, so some areas may end up unrendered forever // ClearAudioQueue(); cache->ClearRequestRange(range); // If we're auto-caching audio or require realtime waveforms, we'll have to render this StartCachingAudioRange(context, cache, range); } void PreviewAutoCacher::SetPlayhead(const rational &playhead) { cache_range_ = TimeRange(playhead - OLIVE_CONFIG("DiskCacheBehind").value<rational>(), playhead + OLIVE_CONFIG("DiskCacheAhead").value<rational>()); TryRender(); } template<typename T> void CancelTasks(const T &task_list, bool and_wait) { for (auto it=task_list.cbegin(); it!=task_list.cend(); it++) { // Signal that the ticket should not be finished (*it)->Cancel(); } if (and_wait) { // Wait for each ticket to finish for (auto it=task_list.cbegin(); it!=task_list.cend(); it++) { (*it)->WaitForFinished(); } } } void PreviewAutoCacher::CancelVideoTasks(bool and_wait_for_them_to_finish) { CancelTasks(running_video_tasks_, and_wait_for_them_to_finish); } void PreviewAutoCacher::CancelAudioTasks(bool and_wait_for_them_to_finish) { CancelTasks(running_audio_tasks_, and_wait_for_them_to_finish); } bool PreviewAutoCacher::IsRenderingCustomRange() const { /*const VideoCacheData &d = video_cache_data_.value(viewer_node_); return d.iterator.IsCustomRange() && d.iterator.HasNext();*/ return false; } void PreviewAutoCacher::SetRendersPaused(bool e) { pause_renders_ = e; if (!e) { TryRender(); } } void PreviewAutoCacher::SetThumbnailsPaused(bool e) { pause_thumbnails_ = e; if (!e) { TryRender(); } } void PreviewAutoCacher::TryRender() { delayed_requeue_timer_.stop(); if (copier_->HasUpdatesInQueue()) { // Check if we have jobs running in other threads that shouldn't be interrupted right now // NOTE: We don't check for downloads because, while they run in another thread, they don't // require any access to the graph and therefore don't risk race conditions. if (!running_audio_tasks_.isEmpty() || !running_video_tasks_.isEmpty()) { return; } // No jobs are active, we can process the update queue copier_->ProcessUpdateQueue(); } if (single_frame_render_) { // Make an explicit copy of the render ticket here - it seems that on some systems it can be set // to NULL before we're done with it... RenderTicketPtr t = single_frame_render_; single_frame_render_ = nullptr; // Check if already caching this Node *n = QtUtils::ValueToPtr<Node>(t->property("node")); Node *copy = copier_->GetCopy(n); if (copy) { RenderTicketWatcher *watcher = RenderFrame(copy, QtUtils::ValueToPtr<ViewerOutput>(t->property("viewer")), t->property("time").value<rational>(), nullptr, t->property("dry").toBool()); video_immediate_passthroughs_[watcher].append(t); } else { qWarning() << "Failed to find copied node for SFR ticket"; t->Finish(); } } if (!pause_renders_) { // Completely arbitrary number. I don't know what's optimal for this yet. const int max_tasks = 4; // Handle video tasks if (!pause_thumbnails_) { while (!pending_video_jobs_.empty()) { VideoJob &d = pending_video_jobs_.front(); if (Node *copy = copier_->GetCopy(d.node)) { // Queue next frames rational t; while (running_video_tasks_.size() < max_tasks && d.iterator.GetNext(&t)) { RenderFrame(copy, d.context, t, d.cache, false); emit SignalCacheProxyTaskProgress(double(d.iterator.frame_index()) / double(d.iterator.size())); if (!d.iterator.HasNext()) { emit StopCacheProxyTasks(); } } } else { qCritical() << "Failed to find node copy for video job"; } if (d.iterator.HasNext()) { break; } else { pending_video_jobs_.pop_front(); } } } // Handle audio tasks while (!pending_audio_jobs_.empty() && running_audio_tasks_.size() < max_tasks) { AudioJob &d = pending_audio_jobs_.front(); bool pop = true; // Start job if (Node *copy = copier_->GetCopy(d.node)) { TimeRange &queued_range = d.range; TimeRange use_range = queued_range; if (dynamic_cast<AudioWaveformCache*>(d.cache)) { rational new_out = std::min(use_range.in() + AudioVisualWaveform::kMinimumSampleRate.flipped(), use_range.out()); if (new_out != use_range.out()) { use_range.set_out(new_out); queued_range.set_in(new_out); pop = false; } } RenderAudio(copy, d.context, use_range, d.cache); } else { qCritical() << "Failed to find node copy for audio job"; } if (pop) { pending_audio_jobs_.pop_front(); } } } } RenderTicketWatcher* PreviewAutoCacher::RenderFrame(Node *node, ViewerOutput *context, const rational& time, PlaybackCache *cache, bool dry) { RenderTicketWatcher* watcher = new RenderTicketWatcher(); watcher->setProperty("job", QVariant::fromValue(copier_->GetLastUpdateTime())); watcher->setProperty("cache", QtUtils::PtrToValue(cache)); watcher->setProperty("time", QVariant::fromValue(time)); connect(watcher, &RenderTicketWatcher::Finished, this, &PreviewAutoCacher::VideoRendered); running_video_tasks_.append(watcher); RenderManager::RenderVideoParams rvp(node, context->GetVideoParams(), context->GetAudioParams(), time, copied_color_manager_, RenderMode::kOffline); if (FrameHashCache *frame_cache = dynamic_cast<FrameHashCache *>(cache)) { if (ThumbnailCache *wave_cache = dynamic_cast<ThumbnailCache *>(cache)) { Q_UNUSED(wave_cache) rvp.video_params.set_divider(VideoParams::GetDividerForTargetResolution(rvp.video_params.width(), rvp.video_params.height(), 160, 120)); rvp.force_color_output = display_color_processor_; rvp.force_format = PixelFormat::U8; } else { frame_cache->SetTimebase(context->GetVideoParams().frame_rate_as_time_base()); } rvp.AddCache(frame_cache); } rvp.return_type = dry ? RenderManager::kNull : RenderManager::kTexture; // Allow using cached images for this render job rvp.use_cache = true; // Multicam rvp.multicam = copier_->GetCopy(multicam_); watcher->SetTicket(RenderManager::instance()->RenderFrame(rvp)); return watcher; } RenderTicketPtr PreviewAutoCacher::RenderAudio(Node *node, ViewerOutput *context, const TimeRange &r, PlaybackCache *cache) { RenderTicketWatcher* watcher = new RenderTicketWatcher(); watcher->setProperty("job", QVariant::fromValue(copier_->GetLastUpdateTime())); watcher->setProperty("node", QtUtils::PtrToValue(node)); watcher->setProperty("cache", QtUtils::PtrToValue(cache)); watcher->setProperty("time", QVariant::fromValue(r)); connect(watcher, &RenderTicketWatcher::Finished, this, &PreviewAutoCacher::AudioRendered); running_audio_tasks_.append(watcher); AudioParams p = context->GetAudioParams(); p.set_format(ViewerOutput::kDefaultSampleFormat); RenderManager::RenderAudioParams rap(node, r, p, RenderMode::kOffline); rap.generate_waveforms = dynamic_cast<AudioWaveformCache*>(cache); rap.clamp = false; RenderTicketPtr ticket = RenderManager::instance()->RenderAudio(rap); watcher->SetTicket(ticket); return ticket; } void PreviewAutoCacher::ConformFinished() { // Got an audio conform, requeue all the audio currently needing a conform last_conform_task_.Acquire(); qDebug() << "CONFORM RESPONSE TEMPORARILY DISABLED"; /*for (auto it=audio_cache_data_.begin(); it!=audio_cache_data_.end(); it++) { foreach (const TimeRange &range, it.value().needs_conform) { it.key()->Request(range); } it.value().needs_conform.clear(); }*/ } void PreviewAutoCacher::CacheProxyTaskCancelled() { pending_video_jobs_.clear(); TryRender(); } void PreviewAutoCacher::ForceCacheRange(ViewerOutput *context, const TimeRange &range) { use_custom_range_ = true; custom_autocache_range_ = range; // Re-hash these frames and start rendering StartCachingVideoRange(context, context->video_frame_cache(), range); } void PreviewAutoCacher::SetProject(Project *project) { if (project_ == project) { return; } if (project_) { // We must wait for any jobs to finish because they'll be using our copied graph and we're // about to destroy it // Stop requeue timer if it's running delayed_requeue_timer_.stop(); // Handle video rendering tasks if (!running_video_tasks_.isEmpty()) { // Cancel any video tasks and wait for them to finish CancelVideoTasks(true); running_video_tasks_.clear(); } // Handle audio rendering tasks if (!running_audio_tasks_.isEmpty()) { // Cancel any audio tasks and wait for them to finish CancelAudioTasks(true); running_audio_tasks_.clear(); } // Clear any single frame render that might be queued CancelQueuedSingleFrameRender(); // Not interested in video passthroughs anymore video_immediate_passthroughs_.clear(); // Disconnect from all node cache's for (auto it=copier_->GetNodeMap().cbegin(); it!=copier_->GetNodeMap().cend(); it++) { DisconnectFromNodeCache(it.key()); } // Delete all of our copied nodes copier_->SetProject(nullptr); // Ensure all cache data is cleared video_cache_data_.clear(); audio_cache_data_.clear(); // Clear multicam reference multicam_ = nullptr; } project_ = project; if (project_) { // Copy graph (this should always be a Project) SetRendersPaused(true); copier_->SetProject(project_); for (int i=0; i<project_->nodes().size(); i++) { project_->nodes().at(i)->ConnectedToPreviewEvent(); } // Find copied viewer node copied_color_manager_ = copier_->GetCopiedProject()->color_manager(); SetRendersPaused(false); } } }
24,323
C++
.cpp
608
34.148026
142
0.681531
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,142
renderer.cpp
olive-editor_olive/app/render/renderer.cpp
/*** 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/>. ***/ #include "renderer.h" #include <QDateTime> #include <QThread> #include <QTimer> #include <QVector2D> namespace olive { Renderer::Renderer(QObject *parent) : QObject(parent) { } TexturePtr Renderer::CreateTexture(const VideoParams &params, const void *data, int linesize) { QVariant v; if (USE_TEXTURE_CACHE) { QMutexLocker locker(&texture_cache_lock_); for (auto it=texture_cache_.begin(); it!=texture_cache_.end(); it++) { if (it->width == params.effective_width() && it->height == params.effective_height() && it->depth == params.effective_depth() && it->format == params.format() && it->channel_count == params.channel_count()) { v = it->handle; texture_cache_.erase(it); break; } } } if (v.isNull()) { v = CreateNativeTexture(params.effective_width(), params.effective_height(), params.effective_depth(), params.format(), params.channel_count(), data, linesize); } else if (data) { UploadToTexture(v, params, data, linesize); } else { this->Flush(); } return CreateTextureFromNativeHandle(v, params); } void Renderer::DestroyTexture(Texture *texture) { if (USE_TEXTURE_CACHE) { // HACK: Dirty, dirty hack. OpenGL uses "contexts" to store all of its data, and each context // can only be used by the thread that created it. However there are also "shared contexts" // where assets from one context can be used in another. We use shared contexts so that // textures rendered in the background can be displayed on the screen, travelling from // a background thread to the main UI thread. However, when that texture is destroyed, it // comes back here to be placed in the texture cache. But that leads to a race condition // because it will call the background thread's renderer in the main thread. Since all // assets are shared, we could technically just get the texture to call "destroy" in the // viewer's renderer instance, but that would mean all textures would end up stranded // there unusable by the background renderer, negating the very advantage of the texture // cache in the first place. Therefore, we simply allow the thread calling to happen, and // use mutexes to prevent race conditions. // // Presumably Vulkan would not have this issue because it allows for application-wide // instances and multithreading. texture_cache_lock_.lock(); texture_cache_.push_back({texture->params().effective_width(), texture->params().effective_height(), texture->params().effective_depth(), texture->params().format(), texture->params().channel_count(), texture->id(), QDateTime::currentMSecsSinceEpoch()}); texture_cache_lock_.unlock(); if (QThread::currentThread() == this->thread()) { ClearOldTextures(); } } else { DestroyNativeTexture(texture->id()); } } TexturePtr Renderer::InterlaceTexture(TexturePtr top, TexturePtr bottom, const VideoParams &params) { color_cache_mutex_.lock(); if (interlace_texture_.isNull()) { interlace_texture_ = CreateNativeShader(ShaderCode(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/interlace.frag")))); } color_cache_mutex_.unlock(); ShaderJob job; job.Insert(QStringLiteral("top_tex_in"), NodeValue(NodeValue::kTexture, QVariant::fromValue(top))); job.Insert(QStringLiteral("bottom_tex_in"), NodeValue(NodeValue::kTexture, QVariant::fromValue(bottom))); job.Insert(QStringLiteral("resolution_in"), NodeValue(NodeValue::kVec2, QVector2D(params.effective_width(), params.effective_height()))); TexturePtr output = CreateTexture(params); BlitToTexture(interlace_texture_, job, output.get()); return output; } QVariant Renderer::GetDefaultShader() { QMutexLocker locker(&color_cache_mutex_); if (default_shader_.isNull()) { default_shader_ = CreateNativeShader(ShaderCode(QString(), QString())); } return default_shader_; } void Renderer::Destroy() { if (!default_shader_.isNull()) { DestroyNativeShader(default_shader_); default_shader_.clear(); } color_cache_.clear(); if (!interlace_texture_.isNull()) { DestroyNativeShader(interlace_texture_); interlace_texture_.clear(); } for (auto it=texture_cache_.begin(); it!=texture_cache_.end(); it++) { DestroyNativeTexture(it->handle); } texture_cache_.clear(); DestroyInternal(); } TexturePtr Renderer::CreateTextureFromNativeHandle(const QVariant &v, const VideoParams &params) { if (v.isNull()) { return nullptr; } return std::make_shared<Texture>(this, v, params); } bool Renderer::GetColorContext(const ColorTransformJob &color_job, Renderer::ColorContext *ctx) { QMutexLocker locker(&color_cache_mutex_); ColorContext& color_ctx = *ctx; QString proc_id = color_job.id(); if (color_cache_.contains(proc_id)) { color_ctx = color_cache_.value(proc_id); return true; } else { // Create shader description QString ocio_func_name; if (color_job.GetFunctionName().isEmpty()) { ocio_func_name = "OCIODisplay"; } else { ocio_func_name = color_job.GetFunctionName(); } auto shader_desc = OCIO::GpuShaderDesc::CreateShaderDesc(); shader_desc->setLanguage(OCIO::GPU_LANGUAGE_GLSL_ES_3_0); shader_desc->setFunctionName(ocio_func_name.toUtf8()); shader_desc->setResourcePrefix("ocio_"); // Generate shader color_job.GetColorProcessor()->GetProcessor()->getDefaultGPUProcessor()->extractGpuShaderInfo(shader_desc); ShaderCode code; if (const Node *shader_src = color_job.CustomShaderSource()) { // Use shader code from associated node code = shader_src->GetShaderCode({color_job.CustomShaderID(), shader_desc->getShaderText()}); } else { // Generate shader code using OCIO stub and our auto-generated name code = FileFunctions::ReadFileAsString(QStringLiteral(":shaders/colormanage.frag")); code.set_frag_code(code.frag_code().arg(shader_desc->getShaderText())); } // Try to compile shader color_ctx.compiled_shader = CreateNativeShader(code); if (color_ctx.compiled_shader.isNull()) { return false; } color_ctx.lut3d_textures.resize(shader_desc->getNum3DTextures()); for (unsigned int i=0; i<shader_desc->getNum3DTextures(); i++) { const char* tex_name = nullptr; const char* sampler_name = nullptr; unsigned int edge_len = 0; OCIO::Interpolation interpolation = OCIO::INTERP_LINEAR; shader_desc->get3DTexture(i, tex_name, sampler_name, edge_len, interpolation); if (!tex_name || !*tex_name || !sampler_name || !*sampler_name || !edge_len) { qCritical() << "3D LUT texture data is corrupted"; return false; } const float* values = nullptr; shader_desc->get3DTextureValues(i, values); if (!values) { qCritical() << "3D LUT texture values are missing"; return false; } // Allocate 3D LUT color_ctx.lut3d_textures[i].texture = CreateTexture(VideoParams(edge_len, edge_len, edge_len, PixelFormat::F32, VideoParams::kRGBChannelCount), values); color_ctx.lut3d_textures[i].name = sampler_name; color_ctx.lut3d_textures[i].interpolation = (interpolation == OCIO::INTERP_NEAREST) ? Texture::kNearest : Texture::kLinear; } color_ctx.lut1d_textures.resize(shader_desc->getNumTextures()); for (unsigned int i=0; i<shader_desc->getNumTextures(); i++) { const char* tex_name = nullptr; const char* sampler_name = nullptr; unsigned int width = 0, height = 0; OCIO::GpuShaderDesc::TextureType channel = OCIO::GpuShaderDesc::TEXTURE_RGB_CHANNEL; OCIO::Interpolation interpolation = OCIO::INTERP_LINEAR; shader_desc->getTexture(i, tex_name, sampler_name, width, height, channel, interpolation); if (!tex_name || !*tex_name || !sampler_name || !*sampler_name || !width) { qCritical() << "1D LUT texture data is corrupted"; return false; } const float* values = nullptr; shader_desc->getTextureValues(i, values); if (!values) { qCritical() << "1D LUT texture values are missing"; return false; } // Allocate 1D LUT color_ctx.lut1d_textures[i].texture = CreateTexture(VideoParams(width, height, PixelFormat::F32, (channel == OCIO::GpuShaderDesc::TEXTURE_RED_CHANNEL) ? 1 : VideoParams::kRGBChannelCount), values); color_ctx.lut1d_textures[i].name = sampler_name; color_ctx.lut1d_textures[i].interpolation = (interpolation == OCIO::INTERP_NEAREST) ? Texture::kNearest : Texture::kLinear; } color_cache_.insert(proc_id, color_ctx); return true; } } void Renderer::ClearOldTextures() { QMutexLocker locker(&texture_cache_lock_); for (auto it=texture_cache_.begin(); it!=texture_cache_.end(); ) { if (it->accessed < QDateTime::currentMSecsSinceEpoch() - MAX_TEXTURE_LIFE) { DestroyNativeTexture(it->handle); it = texture_cache_.erase(it); } else { it++; } } } void Renderer::BlitColorManaged(const ColorTransformJob &color_job, Texture *destination, const VideoParams &params) { ColorContext color_ctx; if (!GetColorContext(color_job, &color_ctx)) { return; } ShaderJob job; job.Insert(QStringLiteral("ove_maintex"), color_job.GetInputTexture()); job.Insert(QStringLiteral("ove_mvpmat"), NodeValue(NodeValue::kMatrix, color_job.GetTransformMatrix())); job.Insert(QStringLiteral("ove_cropmatrix"), NodeValue(NodeValue::kMatrix, color_job.GetCropMatrix().inverted())); job.Insert(QStringLiteral("ove_maintex_alpha"), NodeValue(NodeValue::kInt, int(color_job.GetInputAlphaAssociation()))); job.Insert(QStringLiteral("ove_force_opaque"), NodeValue(NodeValue::kBoolean, color_job.GetForceOpaque())); job.Insert(color_job.GetValues()); foreach (const ColorContext::LUT& l, color_ctx.lut3d_textures) { job.Insert(l.name, NodeValue(NodeValue::kTexture, QVariant::fromValue(l.texture))); job.SetInterpolation(l.name, l.interpolation); } foreach (const ColorContext::LUT& l, color_ctx.lut1d_textures) { job.Insert(l.name, NodeValue(NodeValue::kTexture, QVariant::fromValue(l.texture))); job.SetInterpolation(l.name, l.interpolation); } if (destination) { BlitToTexture(color_ctx.compiled_shader, job, destination, color_job.IsClearDestinationEnabled()); } else { Blit(color_ctx.compiled_shader, job, params, color_job.IsClearDestinationEnabled()); } } }
11,523
C++
.cpp
261
38.731801
203
0.689157
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,143
diskmanager.cpp
olive-editor_olive/app/render/diskmanager.cpp
/*** 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/>. ***/ #include "diskmanager.h" #include <QDataStream> #include <QDir> #include <QFile> #include <QFileInfo> #include <QMessageBox> #include <QStandardPaths> #include "common/filefunctions.h" #include "config/config.h" #include "core.h" #include "dialog/diskcache/diskcachedialog.h" namespace olive { DiskManager* DiskManager::instance_ = nullptr; DiskManager::DiskManager() { // Add default cache location QFile default_disk_cache_file(GetDefaultDiskCacheConfigFile()); if (default_disk_cache_file.open(QFile::ReadOnly)) { QString default_dir = default_disk_cache_file.readAll(); if (!default_dir.isEmpty()) { if (FileFunctions::DirectoryIsValid(default_dir)) { GetOpenFolder(default_dir); } else { QMessageBox::warning(nullptr, tr("Disk Cache Error"), tr("Unable to set custom application disk cache. Using default instead.")); } } default_disk_cache_file.close(); } // If no custom default was loaded, load default if (open_folders_.isEmpty()) { GetOpenFolder(GetDefaultDiskCachePath()); } QFile disk_cache_index(QDir(FileFunctions::GetConfigurationLocation()).filePath(QStringLiteral("diskcache2"))); if (disk_cache_index.open(QFile::ReadOnly)) { QTextStream stream(&disk_cache_index); QString line; while (stream.readLineInto(&line)) { GetOpenFolder(line); } disk_cache_index.close(); } } DiskManager::~DiskManager() { QFile default_disk_cache_file(GetDefaultDiskCacheConfigFile()); if (default_disk_cache_file.open(QFile::WriteOnly)) { if (GetDefaultDiskCachePath() != GetDefaultCachePath()) { default_disk_cache_file.write(GetDefaultCachePath().toUtf8()); } default_disk_cache_file.close(); } } void DiskManager::CreateInstance() { instance_ = new DiskManager(); } void DiskManager::DestroyInstance() { delete instance_; instance_ = nullptr; } DiskManager *DiskManager::instance() { return instance_; } void DiskManager::Accessed(const QString &cache_folder, const QString &filename) { DiskCacheFolder* f = GetOpenFolder(cache_folder); f->Accessed(filename); } void DiskManager::CreatedFile(const QString &cache_folder, const QString &filename) { DiskCacheFolder* f = GetOpenFolder(cache_folder); f->CreatedFile(filename); } void DiskManager::DeleteSpecificFile(const QString &filename) { foreach (DiskCacheFolder* f, open_folders_) { f->DeleteSpecificFile(filename); } } bool DiskManager::ClearDiskCache(const QString &cache_folder) { DiskCacheFolder* f = GetOpenFolder(cache_folder); return f->ClearCache(); } DiskCacheFolder *DiskManager::GetOpenFolder(const QString &path) { // If path is empty, this must mean default if (path.isEmpty()) { return GetDefaultCacheFolder(); } // See if we have an existing path with this name foreach (DiskCacheFolder* f, open_folders_) { if (f->GetPath() == path) { return f; } } // We must have to open this folder DiskCacheFolder* f = new DiskCacheFolder(path, this); connect(f, &DiskCacheFolder::DeletedFrame, this, &DiskManager::DeletedFrame); open_folders_.append(f); return f; } bool DiskManager::ShowDiskCacheChangeConfirmationDialog(QWidget *parent) { return (QMessageBox::question(parent, tr("Disk Cache"), tr("You've chosen to change the default disk cache location. This " "will invalidate your current cache. Would you like to continue?"), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok); } QString DiskManager::GetDefaultDiskCacheConfigFile() { return QDir(FileFunctions::GetConfigurationLocation()).filePath(QStringLiteral("defaultdiskcache")); } QString DiskManager::GetDefaultDiskCachePath() { return QDir(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)).filePath("mediacache"); } void DiskManager::ShowDiskCacheSettingsDialog(DiskCacheFolder *folder, QWidget *parent) { DiskCacheDialog d(folder, parent); d.exec(); } void DiskManager::ShowDiskCacheSettingsDialog(const QString &path, QWidget *parent) { if (!FileFunctions::DirectoryIsValid(path)) { QMessageBox::critical(parent, tr("Disk Cache Error"), tr("Failed to open disk cache at \"%1\". Try a different folder.").arg(path)); return; } DiskCacheFolder* folder = GetOpenFolder(path); ShowDiskCacheSettingsDialog(folder, parent); } DiskCacheFolder::DiskCacheFolder(const QString &path, QObject *parent) : QObject(parent) { SetPath(path); save_timer_.setInterval(OLIVE_CONFIG("DiskCacheSaveInterval").toInt()); connect(&save_timer_, &QTimer::timeout, this, &DiskCacheFolder::SaveDiskCacheIndex); save_timer_.start(); } DiskCacheFolder::~DiskCacheFolder() { CloseCacheFolder(); } bool DiskCacheFolder::ClearCache() { bool deleted_files = true; auto i = disk_data_.begin(); while (i != disk_data_.end()) { // We return a false result if any of the files fail to delete, but still try to delete as many as we can QString filename = i.key(); if (QFile::remove(filename) || !QFileInfo::exists(filename)) { emit DeletedFrame(path_, filename); i = disk_data_.erase(i); } else { qWarning() << "Failed to delete" << filename; deleted_files = false; i++; } } return deleted_files; } void DiskCacheFolder::Accessed(const QString &filename) { if (!disk_data_.contains(filename)) { return; } disk_data_[filename].access_time = QDateTime::currentMSecsSinceEpoch(); } void DiskCacheFolder::CreatedFile(const QString &filename) { qint64 file_size = QFile(filename).size(); disk_data_.insert(filename, {file_size, QDateTime::currentMSecsSinceEpoch()}); consumption_ += file_size; while (consumption_ > limit_) { DeleteLeastRecent(); } } void DiskCacheFolder::SetPath(const QString &path) { // If this is currently set to a folder, close it out now CloseCacheFolder(); // Signal that disk cache is gone if (!disk_data_.empty()) { for (auto it=disk_data_.cbegin(); it!=disk_data_.cend(); it++) { emit DeletedFrame(path_, it.key()); } disk_data_.clear(); } // Set defaults clear_on_close_ = false; consumption_ = 0; limit_ = 21474836480; // Default to 20 GB // Set path path_ = path; // Attempt to load existing index file from path QDir path_dir(path_); FileFunctions::DirectoryIsValid(path_dir); index_path_ = path_dir.filePath(QStringLiteral("index")); // Try to load any current cache index from file QFile cache_index_file(index_path_); if (cache_index_file.open(QFile::ReadOnly)) { QDataStream ds(&cache_index_file); ds >> limit_; ds >> clear_on_close_; while (!cache_index_file.atEnd()) { QString filename; HashTime h; ds >> filename; ds >> h.file_size; ds >> h.access_time; if (QFileInfo::exists(filename)) { consumption_ += h.file_size; disk_data_.insert(filename, h); } } cache_index_file.close(); } } bool DiskCacheFolder::DeleteFileInternal(QMap<QString, HashTime>::iterator hash_to_delete) { // Cache HashTime object QString filename = hash_to_delete.key(); HashTime ht = hash_to_delete.value(); // Remove from disk QFile f(filename); if (!f.exists() || f.remove()) { // Remove from internal map disk_data_.erase(hash_to_delete); // Reduce consumption consumption_ -= ht.file_size; emit DeletedFrame(path_, filename); return true; } return false; } bool DiskCacheFolder::DeleteSpecificFile(const QString &f) { for (auto it=disk_data_.begin(); it!=disk_data_.end(); it++) { if (it.key() == f) { // Break out of this loop, assuming we'll only have one instance of each filename return DeleteFileInternal(it); } } return false; } bool DiskCacheFolder::DeleteLeastRecent() { auto hash_to_delete = disk_data_.begin(); if (disk_data_.begin() != disk_data_.end()) { for (auto it=disk_data_.begin()+1; it!=disk_data_.end(); it++) { if (it->access_time < hash_to_delete->access_time) { hash_to_delete = it; } } bool e = DeleteFileInternal(hash_to_delete); if (e) { Core::instance()->WarnCacheFull(); } return e; } else { return false; } } void DiskCacheFolder::CloseCacheFolder() { if (path_.isEmpty()) { return; } if (clear_on_close_) { // If we're not moving to new and we're set to clear on close, clear now or else it'll never // get cleared later ClearCache(); } // Save current cache index SaveDiskCacheIndex(); } void DiskCacheFolder::SaveDiskCacheIndex() { QFile cache_index_file(index_path_); if (cache_index_file.open(QFile::WriteOnly)) { QDataStream ds(&cache_index_file); ds << limit_; ds << clear_on_close_; for (auto it=disk_data_.cbegin(); it!=disk_data_.cend(); it++) { const HashTime& ht = it.value(); ds << it.key(); ds << ht.file_size; ds << ht.access_time; } cache_index_file.close(); } else { qWarning() << "Failed to write cache index:" << index_path_; } } }
9,986
C++
.cpp
315
27.533333
113
0.693111
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,144
framemanager.cpp
olive-editor_olive/app/render/framemanager.cpp
/*** 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/>. ***/ #include "framemanager.h" #include <QDateTime> #include <QDebug> namespace olive { FrameManager* FrameManager::instance_ = nullptr; const int FrameManager::kFrameLifetime = 5000; void FrameManager::CreateInstance() { instance_ = new FrameManager(); } void FrameManager::DestroyInstance() { delete instance_; instance_ = nullptr; } FrameManager *FrameManager::instance() { return instance_; } char *FrameManager::Allocate(int size) { if (instance()) { return instance()->AllocateFromPool(size); } else { return new char[size]; } } void FrameManager::Deallocate(int size, char *buffer) { if (instance()) { instance()->DeallocateToPool(size, buffer); } else { delete [] buffer; } } FrameManager::FrameManager() { clear_timer_.setInterval(kFrameLifetime); connect(&clear_timer_, &QTimer::timeout, this, &FrameManager::GarbageCollection); clear_timer_.start(); } char *FrameManager::AllocateFromPool(int size) { QMutexLocker locker(&mutex_); std::list<Buffer>& buffer_list = pool_[size]; char* buf = nullptr; if (buffer_list.empty()) { buf = new char[size]; } else { // Take this buffer from the list buf = buffer_list.front().data; buffer_list.pop_front(); } return buf; } void FrameManager::DeallocateToPool(int size, char *buffer) { QMutexLocker locker(&mutex_); std::list<Buffer>& buffer_list = pool_[size]; buffer_list.push_back({QDateTime::currentMSecsSinceEpoch(), buffer}); } void FrameManager::GarbageCollection() { QMutexLocker locker(&mutex_); qint64 min_life = QDateTime::currentMSecsSinceEpoch() - kFrameLifetime; for (auto it=pool_.begin(); it!=pool_.end(); it++) { std::list<Buffer>& list = it->second; while (list.size() > 0 && list.front().time < min_life) { delete [] list.front().data; list.pop_front(); } } } FrameManager::~FrameManager() { QMutexLocker locker(&mutex_); for (auto it=pool_.begin(); it!=pool_.end(); it++) { std::list<Buffer>& list = it->second; for (auto jt=list.begin(); jt!=list.end(); jt++) { delete [] (*jt).data; } } pool_.clear(); } }
2,845
C++
.cpp
99
25.818182
83
0.709499
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,145
renderjobtracker.cpp
olive-editor_olive/app/render/renderjobtracker.cpp
/*** 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/>. ***/ #include "renderjobtracker.h" namespace olive { void RenderJobTracker::insert(const TimeRange &range, JobTime job_time) { // First remove any ranges with this (code copied TimeRangeList::util_remove(&jobs_, range); // Now append the job TimeRangeWithJob job(range, job_time); jobs_.push_back(job); } void RenderJobTracker::insert(const TimeRangeList &ranges, JobTime job_time) { foreach (const TimeRange &r, ranges) { insert(r, job_time); } } void RenderJobTracker::clear() { jobs_.clear(); } bool RenderJobTracker::isCurrent(const rational &time, JobTime job_time) const { for (auto it=jobs_.crbegin(); it!=jobs_.crend(); it++) { if (it->Contains(time)) { return job_time >= it->GetJobTime(); } } return false; } TimeRangeList RenderJobTracker::getCurrentSubRanges(const TimeRange &range, const JobTime &job_time) const { TimeRangeList current_ranges; for (auto it=jobs_.crbegin(); it!=jobs_.crend(); it++) { if (job_time >= it->GetJobTime() && it->OverlapsWith(range)) { current_ranges.insert(it->Intersected(range)); } } return current_ranges; } }
1,836
C++
.cpp
54
31.092593
106
0.735411
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,146
projectcopier.cpp
olive-editor_olive/app/render/projectcopier.cpp
/*** 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/>. ***/ #include "projectcopier.h" #include "node/group/group.h" namespace olive { ProjectCopier::ProjectCopier(QObject *parent) : QObject(parent) { original_ = nullptr; copy_ = new Project(); copy_->setParent(this); } void ProjectCopier::SetProject(Project *project) { if (original_) { // Clear current project qDeleteAll(created_nodes_); created_nodes_.clear(); copy_map_.clear(); graph_update_queue_.clear(); disconnect(original_, &Project::NodeAdded, this, &ProjectCopier::QueueNodeAdd); disconnect(original_, &Project::NodeRemoved, this, &ProjectCopier::QueueNodeRemove); disconnect(original_, &Project::InputConnected, this, &ProjectCopier::QueueEdgeAdd); disconnect(original_, &Project::InputDisconnected, this, &ProjectCopier::QueueEdgeRemove); disconnect(original_, &Project::ValueChanged, this, &ProjectCopier::QueueValueChange); disconnect(original_, &Project::InputValueHintChanged, this, &ProjectCopier::QueueValueHintChange); disconnect(original_, &Project::SettingChanged, this, &ProjectCopier::QueueProjectSettingChange); } original_ = project; if (original_) { // Add all nodes for (int i=0; i<copy_->nodes().size(); i++) { InsertIntoCopyMap(original_->nodes().at(i), copy_->nodes().at(i)); } for (int i=copy_->nodes().size(); i<original_->nodes().size(); i++) { DoNodeAdd(original_->nodes().at(i)); } // Add all connections foreach (Node* node, original_->nodes()) { for (auto it=node->input_connections().cbegin(); it!=node->input_connections().cend(); it++) { DoEdgeAdd(it->second, it->first); } } // Copy project settings Project::CopySettings(original_, copy_); // Ensure graph change value is just before the sync value UpdateGraphChangeValue(); UpdateLastSyncedValue(); // Connect signals for future node additions/deletions connect(original_, &Project::NodeAdded, this, &ProjectCopier::QueueNodeAdd, Qt::DirectConnection); connect(original_, &Project::NodeRemoved, this, &ProjectCopier::QueueNodeRemove, Qt::DirectConnection); connect(original_, &Project::InputConnected, this, &ProjectCopier::QueueEdgeAdd, Qt::DirectConnection); connect(original_, &Project::InputDisconnected, this, &ProjectCopier::QueueEdgeRemove, Qt::DirectConnection); connect(original_, &Project::ValueChanged, this, &ProjectCopier::QueueValueChange, Qt::DirectConnection); connect(original_, &Project::InputValueHintChanged, this, &ProjectCopier::QueueValueHintChange, Qt::DirectConnection); connect(original_, &Project::SettingChanged, this, &ProjectCopier::QueueProjectSettingChange, Qt::DirectConnection); } } void ProjectCopier::ProcessUpdateQueue() { // Iterate everything that happened to the graph and do the same thing on our end while (!graph_update_queue_.empty()) { QueuedJob job = graph_update_queue_.front(); graph_update_queue_.pop_front(); switch (job.type) { case QueuedJob::kNodeAdded: DoNodeAdd(job.node); break; case QueuedJob::kNodeRemoved: DoNodeRemove(job.node); break; case QueuedJob::kEdgeAdded: DoEdgeAdd(job.output, job.input); break; case QueuedJob::kEdgeRemoved: DoEdgeRemove(job.output, job.input); break; case QueuedJob::kValueChanged: DoValueChange(job.input); break; case QueuedJob::kValueHintChanged: DoValueHintChange(job.input); break; case QueuedJob::kProjectSettingChanged: DoProjectSettingChange(job.key, job.value); break; } } // Indicate that we have synchronized to this point, which is compared with the graph change // time to see if our copied graph is up to date UpdateLastSyncedValue(); } void ProjectCopier::DoNodeAdd(Node *node) { if (dynamic_cast<NodeGroup*>(node)) { // Group nodes are just dummy nodes, no need to copy them return; } // Copy node Node* copy = node->copy(); // Add to project copy->setParent(copy_); // Disable caches for copy copy->SetCachesEnabled(false); // Copy cache UUIDs copy->CopyCacheUuidsFrom(node); // Insert into map InsertIntoCopyMap(node, copy); // Keep track of our nodes created_nodes_.append(copy); } void ProjectCopier::DoNodeRemove(Node *node) { // Find our copy and remove it Node* copy = copy_map_.take(node); // Disconnect from node's caches emit RemovedNode(node); // Remove from created list created_nodes_.removeOne(copy); // Delete it delete copy; } void ProjectCopier::DoEdgeAdd(Node *output, const NodeInput &input) { // Create same connection with our copied graph Node* our_output = copy_map_.value(output); Node* our_input = copy_map_.value(input.node()); Node::ConnectEdge(our_output, NodeInput(our_input, input.input(), input.element())); } void ProjectCopier::DoEdgeRemove(Node *output, const NodeInput &input) { // Remove same connection with our copied graph Node* our_output = copy_map_.value(output); Node* our_input = copy_map_.value(input.node()); Node::DisconnectEdge(our_output, NodeInput(our_input, input.input(), input.element())); } void ProjectCopier::DoValueChange(const NodeInput &input) { if (dynamic_cast<NodeGroup*>(input.node())) { // Group nodes are just dummy nodes, no need to copy them return; } // Copy all values to our graph Node* our_input = copy_map_.value(input.node()); Node::CopyValuesOfElement(input.node(), our_input, input.input(), input.element()); } void ProjectCopier::DoValueHintChange(const NodeInput &input) { if (dynamic_cast<NodeGroup*>(input.node())) { // Group nodes are just dummy nodes, no need to copy them return; } // Copy value hint to our graph Node* our_input = copy_map_.value(input.node()); Node::ValueHint hint = input.node()->GetValueHintForInput(input.input(), input.element()); our_input->SetValueHintForInput(input.input(), hint, input.element()); } void ProjectCopier::DoProjectSettingChange(const QString &key, const QString &value) { copy_->SetSetting(key, value); } void ProjectCopier::InsertIntoCopyMap(Node *node, Node *copy) { // Insert into map copy_map_.insert(node, copy); // Copy parameters Node::CopyInputs(node, copy, false); // Connect to node's cache emit AddedNode(node); } void ProjectCopier::QueueNodeAdd(Node *node) { graph_update_queue_.push_back({QueuedJob::kNodeAdded, node, NodeInput(), nullptr, QString(), QString()}); UpdateGraphChangeValue(); } void ProjectCopier::QueueNodeRemove(Node *node) { graph_update_queue_.push_back({QueuedJob::kNodeRemoved, node, NodeInput(), nullptr, QString(), QString()}); UpdateGraphChangeValue(); } void ProjectCopier::QueueEdgeAdd(Node *output, const NodeInput &input) { graph_update_queue_.push_back({QueuedJob::kEdgeAdded, nullptr, input, output, QString(), QString()}); UpdateGraphChangeValue(); } void ProjectCopier::QueueEdgeRemove(Node *output, const NodeInput &input) { graph_update_queue_.push_back({QueuedJob::kEdgeRemoved, nullptr, input, output, QString(), QString()}); UpdateGraphChangeValue(); } void ProjectCopier::QueueValueChange(const NodeInput &input) { /*for (auto it = graph_update_queue_.begin(); it != graph_update_queue_.end(); ) { if (it->type == QueuedJob::kValueChanged && it->input == input) { it = graph_update_queue_.erase(it); } else { it++; } }*/ graph_update_queue_.push_back({QueuedJob::kValueChanged, nullptr, input, nullptr, QString(), QString()}); UpdateGraphChangeValue(); } void ProjectCopier::QueueValueHintChange(const NodeInput &input) { graph_update_queue_.push_back({QueuedJob::kValueHintChanged, nullptr, input, nullptr, QString(), QString()}); UpdateGraphChangeValue(); } void ProjectCopier::QueueProjectSettingChange(const QString &key, const QString &value) { graph_update_queue_.push_back({QueuedJob::kProjectSettingChanged, nullptr, NodeInput(), nullptr, key, value}); UpdateGraphChangeValue(); } void ProjectCopier::UpdateGraphChangeValue() { graph_changed_time_.Acquire(); } void ProjectCopier::UpdateLastSyncedValue() { last_update_time_.Acquire(); } }
8,877
C++
.cpp
233
34.60515
122
0.728839
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,147
renderticket.cpp
olive-editor_olive/app/render/renderticket.cpp
/*** 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/>. ***/ #include "renderticket.h" namespace olive { RenderTicket::RenderTicket() : is_running_(false), has_result_(false), finish_count_(0) { } void RenderTicket::WaitForFinished(QMutex *mutex) { if (is_running_) { wait_.wait(mutex); } } void RenderTicket::Start() { QMutexLocker locker(&lock_); is_running_ = true; has_result_ = false; result_.clear(); } void RenderTicket::Finish() { FinishInternal(false, QVariant()); } void RenderTicket::Finish(QVariant result) { FinishInternal(true, result); } QVariant RenderTicket::Get() { WaitForFinished(); // We don't have to mutex around this because there is no way to write to `result_` after // the ticket has finished and the above function blocks the calling thread until it is finished return result_; } void RenderTicket::WaitForFinished() { QMutexLocker locker(&lock_); WaitForFinished(&lock_); } bool RenderTicket::IsRunning(bool lock) { if (lock) { lock_.lock(); } bool running = is_running_; if (lock) { lock_.unlock(); } return running; } int RenderTicket::GetFinishCount(bool lock) { if (lock) { lock_.lock(); } int count = finish_count_; if (lock) { lock_.unlock(); } return count; } bool RenderTicket::HasResult() { QMutexLocker locker(&lock_); return has_result_; } void RenderTicket::FinishInternal(bool has_result, QVariant result) { QMutexLocker locker(&lock_); if (!is_running_) { qWarning() << "Tried to finish ticket that wasn't running"; } else { is_running_ = false; has_result_ = has_result; result_ = result; finish_count_++; wait_.wakeAll(); locker.unlock(); emit Finished(); } } RenderTicketWatcher::RenderTicketWatcher(QObject *parent) : QObject(parent), ticket_(nullptr) { } void RenderTicketWatcher::SetTicket(RenderTicketPtr ticket) { if (ticket_) { qCritical() << "Tried to set a ticket on a RenderTicketWatcher twice"; return; } if (!ticket) { qCritical() << "Tried to set a null ticket on a RenderTicketWatcher"; return; } ticket_ = ticket; // Lock ticket so we can query if it's already finished by the time this code runs QMutexLocker locker(ticket->lock()); connect(ticket_.get(), &RenderTicket::Finished, this, &RenderTicketWatcher::TicketFinished); if (!ticket_->IsRunning(false) && ticket_->GetFinishCount(false) > 0) { // Ticket has already finished before, so we emit a signal locker.unlock(); TicketFinished(); } } bool RenderTicketWatcher::IsRunning() { if (ticket_) { return ticket_->IsRunning(); } else { return false; } } void RenderTicketWatcher::WaitForFinished() { if (ticket_) { ticket_->WaitForFinished(); } } QVariant RenderTicketWatcher::Get() { if (ticket_) { return ticket_->Get(); } else { return QVariant(); } } bool RenderTicketWatcher::HasResult() { if (ticket_) { return ticket_->HasResult(); } else { return false; } } void RenderTicketWatcher::Cancel() { if (ticket_) { ticket_->Cancel(); } } void RenderTicketWatcher::TicketFinished() { emit Finished(this); } }
3,850
C++
.cpp
163
20.754601
98
0.710244
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,148
audioplaybackcache.cpp
olive-editor_olive/app/render/audioplaybackcache.cpp
/*** 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/>. ***/ #include "audioplaybackcache.h" #include <QDir> #include <QFile> #include <QRandomGenerator> #include <QUuid> #include "common/filefunctions.h" #include "node/output/viewer/viewer.h" namespace olive { const qint64 AudioPlaybackCache::kDefaultSegmentSizePerChannel = 10 * 1024 * 1024; AudioPlaybackCache::AudioPlaybackCache(QObject* parent) : PlaybackCache(parent) { } AudioPlaybackCache::~AudioPlaybackCache() { } void AudioPlaybackCache::SetParameters(const AudioParams &params) { if (params_ == params) { return; } params_ = params; } void AudioPlaybackCache::WritePCM(const TimeRange &range, const TimeRangeList &valid_ranges, const SampleBuffer &samples) { for (const TimeRange &r : valid_ranges) { if (WritePartOfSampleBuffer(samples, r.in(), r.in() - range.in(), r.length())) { Validate(r); } } } void AudioPlaybackCache::WriteSilence(const TimeRange &range) { // WritePCM will automatically fill non-existent bytes with silence, so we just have to send // it an empty sample buffer WritePCM(range, {range}, SampleBuffer()); } bool AudioPlaybackCache::WritePartOfSampleBuffer(const SampleBuffer &samples, const rational &write_start, const rational &buffer_start, const rational &length) { int64_t length_in_bytes = params_.time_to_bytes_per_channel(length); int64_t start_cache_offset = params_.time_to_bytes_per_channel(write_start); int64_t end_cache_offset = start_cache_offset + length_in_bytes; int64_t start_buffer_offset = params_.time_to_bytes_per_channel(buffer_start); int64_t end_buffer_offset = std::min(start_buffer_offset + length_in_bytes, params_.samples_to_bytes_per_channel(samples.sample_count())); int64_t current_cache_offset = start_cache_offset; int64_t current_buffer_offset = start_buffer_offset; bool success = true; while (current_cache_offset != end_cache_offset) { int64_t segment = current_cache_offset / kDefaultSegmentSizePerChannel; int64_t segment_start = segment * kDefaultSegmentSizePerChannel; int64_t segment_end = segment_start + kDefaultSegmentSizePerChannel; int64_t offset_in_segment = current_cache_offset - segment_start; int64_t write_len = segment_end - offset_in_segment; int64_t max_buffer_len = end_buffer_offset - current_buffer_offset; int64_t zero_len = 0; if (write_len > max_buffer_len) { zero_len = write_len - max_buffer_len; write_len = max_buffer_len; } for (int channel=0; channel<params_.channel_count(); channel++) { QString filename = GetSegmentFilename(segment, channel); if (!FileFunctions::DirectoryIsValid(QFileInfo(filename).dir())) { success = false; break; } QFile f(filename); if (f.open(QFile::ReadWrite)) { f.seek(offset_in_segment); f.write(reinterpret_cast<const char*>(samples.data(channel)) + current_buffer_offset, write_len); if (zero_len > 0) { QByteArray b(zero_len, 0); f.write(b.constData()); } f.close(); } else { success = false; } } current_cache_offset += write_len; current_buffer_offset += write_len; } return success; } QString AudioPlaybackCache::GetSegmentFilename(qint64 segment_index, int channel) { return GetThisCacheDirectory().filePath(QStringLiteral("%1.%2").arg(QString::number(segment_index), QString::number(channel))); } }
4,121
C++
.cpp
102
36.392157
160
0.728801
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,149
renderprocessor.cpp
olive-editor_olive/app/render/renderprocessor.cpp
/*** 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/>. ***/ #include "renderprocessor.h" #include <QOpenGLContext> #include <QVector2D> #include <QVector3D> #include <QVector4D> #include "audio/audioprocessor.h" #include "node/block/clip/clip.h" #include "node/block/transition/transition.h" #include "node/project.h" #include "rendermanager.h" namespace olive { #define super NodeTraverser RenderProcessor::RenderProcessor(RenderTicketPtr ticket, Renderer *render_ctx, DecoderCache* decoder_cache, ShaderCache *shader_cache) : ticket_(ticket), render_ctx_(render_ctx), decoder_cache_(decoder_cache), shader_cache_(shader_cache) { } TexturePtr RenderProcessor::GenerateTexture(const rational &time, const rational &frame_length) { TimeRange range = TimeRange(time, time + frame_length); NodeValueTable table; if (Node* node = QtUtils::ValueToPtr<Node>(ticket_->property("node"))) { table = GenerateTable(node, range); } NodeValue tex_val = table.Get(NodeValue::kTexture); ResolveJobs(tex_val); return tex_val.toTexture(); } FramePtr RenderProcessor::GenerateFrame(TexturePtr texture, const rational& time) { // Set up output frame parameters VideoParams frame_params = GetCacheVideoParams(); QSize frame_size = ticket_->property("size").value<QSize>(); if (!frame_size.isNull()) { frame_params.set_width(frame_size.width()); frame_params.set_height(frame_size.height()); } PixelFormat frame_format = static_cast<PixelFormat::Format>(ticket_->property("format").toInt()); if (frame_format != PixelFormat::INVALID) { frame_params.set_format(frame_format); } int force_channel_count = ticket_->property("channelcount").toInt(); if (force_channel_count != 0) { frame_params.set_channel_count(force_channel_count); } else { frame_params.set_channel_count(texture ? texture->channel_count() : VideoParams::kRGBAChannelCount); } FramePtr frame = Frame::Create(); frame->set_timestamp(time); frame->set_video_params(frame_params); frame->allocate(); if (!texture) { // Blank frame out memset(frame->data(), 0, frame->allocated_size()); } else { // Dump texture contents to frame ColorProcessorPtr output_color_transform = ticket_->property("coloroutput").value<ColorProcessorPtr>(); const VideoParams& tex_params = texture->params(); if (output_color_transform) { TexturePtr transform_tex = render_ctx_->CreateTexture(tex_params); ColorTransformJob job; job.SetColorProcessor(output_color_transform); job.SetInputTexture(texture); job.SetInputAlphaAssociation(OLIVE_CONFIG("ReassocLinToNonLin").toBool() ? kAlphaAssociated : kAlphaNone); render_ctx_->BlitColorManaged(job, transform_tex.get()); texture = transform_tex; } if (tex_params.effective_width() != frame_params.effective_width() || tex_params.effective_height() != frame_params.effective_height() || tex_params.format() != frame_params.format()) { TexturePtr blit_tex = render_ctx_->CreateTexture(frame_params); QMatrix4x4 matrix = ticket_->property("matrix").value<QMatrix4x4>(); // No color transform, just blit ShaderJob job; job.Insert(QStringLiteral("ove_maintex"), NodeValue(NodeValue::kTexture, QVariant::fromValue(texture))); job.Insert(QStringLiteral("ove_mvpmat"), NodeValue(NodeValue::kMatrix, matrix)); render_ctx_->BlitToTexture(render_ctx_->GetDefaultShader(), job, blit_tex.get()); // Replace texture that we're going to download in the next step texture = blit_tex; } render_ctx_->Flush(); render_ctx_->DownloadFromTexture(texture->id(), texture->params(), frame->data(), frame->linesize_pixels()); } return frame; } void RenderProcessor::Run() { // Depending on the render ticket type, start a job RenderManager::TicketType type = ticket_->property("type").value<RenderManager::TicketType>(); SetCancelPointer(ticket_->GetCancelAtom()); SetCacheVideoParams(ticket_->property("vparam").value<VideoParams>()); SetCacheAudioParams(ticket_->property("aparam").value<AudioParams>()); if (IsCancelled()) { ticket_->Finish(); return; } switch (type) { case RenderManager::kTypeVideo: { rational time = ticket_->property("time").value<rational>(); rational frame_length = GetCacheVideoParams().frame_rate_as_time_base(); if (GetCacheVideoParams().interlacing() != VideoParams::kInterlaceNone) { frame_length /= 2; } TexturePtr texture = GenerateTexture(time, frame_length); if (!render_ctx_) { ticket_->Finish(); } else { if (GetCacheVideoParams().interlacing() != VideoParams::kInterlaceNone) { // Get next between frame and interlace it TexturePtr top = texture; TexturePtr bottom = GenerateTexture(time + frame_length, frame_length); if (GetCacheVideoParams().interlacing() == VideoParams::kInterlacedBottomFirst) { std::swap(top, bottom); } texture = render_ctx_->InterlaceTexture(top, bottom, GetCacheVideoParams()); } if (HeardCancel()) { // Finish cancelled ticket with nothing since we can't guarantee the frame we generated // is actually "complete ticket_->Finish(); } else { FramePtr frame; QString cache = ticket_->property("cache").toString(); RenderManager::ReturnType return_type = RenderManager::ReturnType(ticket_->property("return").toInt()); if (return_type == RenderManager::kFrame || !cache.isEmpty()) { // Convert to CPU frame frame = GenerateFrame(texture, time); // Save to cache if requested if (!cache.isEmpty()) { rational timebase = ticket_->property("cachetimebase").value<rational>(); QUuid uuid = ticket_->property("cacheid").value<QUuid>(); bool cache_result = FrameHashCache::SaveCacheFrame(cache, uuid, time, timebase, frame); ticket_->setProperty("cached", cache_result); } } if (return_type == RenderManager::kTexture) { // Return GPU texture if (!texture) { texture = render_ctx_->CreateTexture(GetCacheVideoParams()); render_ctx_->ClearDestination(texture.get()); } render_ctx_->Flush(); ticket_->Finish(QVariant::fromValue(texture)); } else { ticket_->Finish(QVariant::fromValue(frame)); } } } break; } case RenderManager::kTypeAudio: { TimeRange time = ticket_->property("time").value<TimeRange>(); NodeValueTable table; if (Node* node = QtUtils::ValueToPtr<Node>(ticket_->property("node"))) { table = GenerateTable(node, time); } NodeValue sample_val = table.Get(NodeValue::kSamples); ResolveJobs(sample_val); SampleBuffer samples = sample_val.toSamples(); if (samples.is_allocated()) { if (ticket_->property("clamp").toBool() && !IsCancelled()) { samples.clamp(); } if (ticket_->property("enablewaveforms").toBool() && !IsCancelled()) { AudioVisualWaveform vis; vis.set_channel_count(samples.audio_params().channel_count()); vis.OverwriteSamples(samples, samples.audio_params().sample_rate()); ticket_->setProperty("waveform", QVariant::fromValue(vis)); } } if (HeardCancel()) { ticket_->Finish(); } else { ticket_->Finish(QVariant::fromValue(samples)); } break; } default: // Fail ticket_->Finish(); } } DecoderPtr RenderProcessor::ResolveDecoderFromInput(const QString& decoder_id, const Decoder::CodecStream &stream) { if (!stream.IsValid()) { qWarning() << "Attempted to resolve the decoder of a null stream"; return nullptr; } QMutexLocker locker(decoder_cache_->mutex()); DecoderPair decoder = decoder_cache_->value(stream); qint64 file_last_modified = QFileInfo(stream.filename()).lastModified().toMSecsSinceEpoch(); DecoderPtr dec = nullptr; if (decoder.decoder && decoder.last_modified == file_last_modified) { dec = decoder.decoder; } else { // No decoder decoder.decoder = dec = Decoder::CreateFromID(decoder_id); decoder.last_modified = file_last_modified; decoder_cache_->insert(stream, decoder); locker.unlock(); if (!dec->Open(stream)) { qWarning() << "Failed to open decoder for" << stream.filename() << "::" << stream.stream(); return nullptr; } if (!render_ctx_) { // Assume dry run and increment access time decoder.decoder->IncrementAccessTime(RenderManager::kDryRunInterval.toDouble() * 1000); } } return dec; } NodeValueDatabase RenderProcessor::GenerateDatabase(const Node *node, const TimeRange &range) { NodeValueDatabase db = super::GenerateDatabase(node, range); if (const MultiCamNode *multicam = dynamic_cast<const MultiCamNode*>(node)) { if (QtUtils::ValueToPtr<MultiCamNode>(ticket_->property("multicam")) == multicam) { int sz = multicam->GetSourceCount(); QVector<TexturePtr> multicam_tex(sz); for (int i=0; i<sz; i++) { NodeValueTable t = GenerateTable(multicam->GetConnectedRenderOutput(multicam->kSourcesInput, i), range, multicam); NodeValue val = GenerateRowValueElement(multicam, multicam->kSourcesInput, i, &t, range); ResolveJobs(val); multicam_tex[i] = val.toTexture(); } ticket_->setProperty("multicam_output", QVariant::fromValue(multicam_tex)); } } return db; } void RenderProcessor::Process(RenderTicketPtr ticket, Renderer *render_ctx, DecoderCache *decoder_cache, ShaderCache *shader_cache) { RenderProcessor p(ticket, render_ctx, decoder_cache, shader_cache); p.Run(); } void RenderProcessor::ProcessVideoFootage(TexturePtr destination, const FootageJob *stream, const rational &input_time) { if (ticket_->property("type").value<RenderManager::TicketType>() != RenderManager::kTypeVideo) { // Video cannot contribute to audio, so we do nothing here return; } // Check the still frame cache. On large frames such as high resolution still images, uploading // and color managing them for every frame is a waste of time, so we implement a small cache here // to optimize such a situation VideoParams stream_data = stream->video_params(); ColorManager* color_manager = QtUtils::ValueToPtr<ColorManager>(ticket_->property("colormanager")); QString using_colorspace = stream_data.colorspace(); if (using_colorspace.isEmpty()) { // FIXME: qWarning() << "HAVEN'T GOTTEN DEFAULT INPUT COLORSPACE"; } Decoder::CodecStream default_codec_stream(stream->filename(), stream_data.stream_index(), GetCurrentBlock()); QString decoder_id = stream->decoder(); DecoderPtr decoder = nullptr; switch (stream_data.video_type()) { case VideoParams::kVideoTypeVideo: case VideoParams::kVideoTypeStill: decoder = ResolveDecoderFromInput(decoder_id, default_codec_stream); break; case VideoParams::kVideoTypeImageSequence: { if (render_ctx_) { // Since image sequences involve multiple files, we don't engage the decoder cache decoder = Decoder::CreateFromID(decoder_id); QString frame_filename; int64_t frame_number = stream_data.get_time_in_timebase_units(input_time); frame_filename = Decoder::TransformImageSequenceFileName(stream->filename(), frame_number); // Decoder will close automatically since it's a stream_ptr decoder->Open(Decoder::CodecStream(frame_filename, stream_data.stream_index(), GetCurrentBlock())); } break; } } if (decoder && render_ctx_) { Decoder::RetrieveVideoParams p; p.divider = stream->video_params().divider(); p.maximum_format = destination->format(); if (!IsCancelled()) { VideoParams tex_params = stream->video_params(); if (tex_params.is_valid()) { TexturePtr unmanaged_texture; p.renderer = render_ctx_; p.time = (stream_data.video_type() == VideoParams::kVideoTypeVideo) ? input_time : Decoder::kAnyTimecode; p.cancelled = GetCancelPointer(); p.force_range = stream_data.color_range(); p.src_interlacing = stream_data.interlacing(); unmanaged_texture = decoder->RetrieveVideo(p); if (!IsCancelled() && unmanaged_texture) { // We convert to our rendering pixel format, since that will always be float-based which // is necessary for correct color conversion ColorProcessorPtr processor = ColorProcessor::Create(color_manager, using_colorspace, color_manager->GetReferenceColorSpace()); ColorTransformJob job; job.SetColorProcessor(processor); job.SetInputTexture(unmanaged_texture); if (stream_data.channel_count() != VideoParams::kRGBAChannelCount || stream_data.colorspace() == color_manager->GetReferenceColorSpace()) { job.SetInputAlphaAssociation(kAlphaNone); } else if (stream_data.premultiplied_alpha()) { job.SetInputAlphaAssociation(kAlphaAssociated); } else { job.SetInputAlphaAssociation(kAlphaUnassociated); } render_ctx_->BlitColorManaged(job, destination.get()); } } } } } void RenderProcessor::ProcessAudioFootage(SampleBuffer &destination, const FootageJob *stream, const TimeRange &input_time) { DecoderPtr decoder = ResolveDecoderFromInput(stream->decoder(), Decoder::CodecStream(stream->filename(), stream->audio_params().stream_index(), nullptr)); if (decoder) { const AudioParams& audio_params = GetCacheAudioParams(); Decoder::RetrieveAudioStatus status = decoder->RetrieveAudio(destination, input_time, audio_params, stream->cache_path(), loop_mode(), static_cast<RenderMode::Mode>(ticket_->property("mode").toInt())); if (status == Decoder::kWaitingForConform) { ticket_->setProperty("incomplete", true); } } } void RenderProcessor::ProcessShader(TexturePtr destination, const Node *node, const ShaderJob *job) { if (!render_ctx_) { return; } QString full_shader_id = QStringLiteral("%1:%2").arg(node->id(), job->GetShaderID()); QMutexLocker locker(shader_cache_->mutex()); QVariant shader = shader_cache_->value(full_shader_id); if (shader.isNull()) { // Since we have shader code, compile it now shader = render_ctx_->CreateNativeShader(node->GetShaderCode(job->GetShaderID())); if (shader.isNull()) { // Couldn't find or build the shader required return; } shader_cache_->insert(full_shader_id, shader); } locker.unlock(); // Run shader render_ctx_->BlitToTexture(shader, *job, destination.get()); } void RenderProcessor::ProcessSamples(SampleBuffer &destination, const Node *node, const TimeRange &range, const SampleJob &job) { if (!job.samples().is_allocated()) { return; } NodeValueRow value_db; const AudioParams& audio_params = GetCacheAudioParams(); for (size_t i=0;i<job.samples().sample_count();i++) { // Calculate the exact rational time at this sample double sample_to_second = static_cast<double>(i) / static_cast<double>(audio_params.sample_rate()); rational this_sample_time = rational::fromDouble(range.in().toDouble() + sample_to_second); // Update all non-sample and non-footage inputs for (auto j=job.GetValues().constBegin(); j!=job.GetValues().constEnd(); j++) { TimeRange r = TimeRange(this_sample_time, this_sample_time); NodeValueTable value = ProcessInput(node, j.key(), r); value_db.insert(j.key(), GenerateRowValue(node, j.key(), &value, r)); } node->ProcessSamples(value_db, job.samples(), destination, i); } } void RenderProcessor::ProcessColorTransform(TexturePtr destination, const Node *node, const ColorTransformJob *job) { if (!render_ctx_) { return; } render_ctx_->BlitColorManaged(*job, destination.get()); } void RenderProcessor::ProcessFrameGeneration(TexturePtr destination, const Node *node, const GenerateJob *job) { if (!render_ctx_) { return; } FramePtr frame = Frame::Create(); frame->set_video_params(destination->params()); frame->allocate(); node->GenerateFrame(frame, *job); destination->Upload(frame->data(), frame->linesize_pixels()); } TexturePtr RenderProcessor::ProcessVideoCacheJob(const CacheJob *val) { FramePtr frame = FrameHashCache::LoadCacheFrame(val->GetFilename()); if (frame) { TexturePtr tex = CreateTexture(frame->video_params()); if (tex) { tex->Upload(frame->data(), frame->linesize_pixels()); return tex; } } else { QStringList s = ticket_->property("badcache").toStringList(); s.append(val->GetFilename()); ticket_->setProperty("badcache", s); } return nullptr; } TexturePtr RenderProcessor::CreateTexture(const VideoParams &p) { if (render_ctx_) { return render_ctx_->CreateTexture(p); } else { return super::CreateTexture(p); } } void RenderProcessor::ConvertToReferenceSpace(TexturePtr destination, TexturePtr source, const QString &input_cs) { if (!render_ctx_) { return; } ColorManager* color_manager = QtUtils::ValueToPtr<ColorManager>(ticket_->property("colormanager")); ColorProcessorPtr cp = ColorProcessor::Create(color_manager, input_cs, color_manager->GetReferenceColorSpace()); ColorTransformJob ctj; ctj.SetColorProcessor(cp); ctj.SetInputTexture(source); ctj.SetInputAlphaAssociation(kAlphaAssociated); render_ctx_->BlitColorManaged(ctj, destination.get()); } bool RenderProcessor::UseCache() const { return static_cast<RenderMode::Mode>(ticket_->property("mode").toInt()) == RenderMode::kOffline; } }
18,883
C++
.cpp
447
36.129754
156
0.682454
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,150
playbackcache.cpp
olive-editor_olive/app/render/playbackcache.cpp
/*** 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/>. ***/ #include "playbackcache.h" #include "node/output/viewer/viewer.h" #include "node/project.h" #include "node/project/sequence/sequence.h" #include "render/diskmanager.h" namespace olive { void PlaybackCache::Invalidate(const TimeRange &r) { if (r.in() == r.out()) { qWarning() << "Tried to invalidate zero-length range"; return; } validated_.remove(r); if (!passthroughs_.empty()) { TimeRangeList::util_remove(&passthroughs_, r); } InvalidateEvent(r); emit Invalidated(r); if (saving_enabled_) { SaveState(); } } Node *PlaybackCache::parent() const { return dynamic_cast<Node*>(QObject::parent()); } QDir PlaybackCache::GetThisCacheDirectory() const { return GetThisCacheDirectory(GetCacheDirectory(), GetUuid()); } QDir PlaybackCache::GetThisCacheDirectory(const QString &cache_path, const QUuid &cache_id) { return QDir(cache_path).filePath(cache_id.toString()); } void PlaybackCache::LoadState() { QDir cache_dir = GetThisCacheDirectory(); QFile f(cache_dir.filePath(QStringLiteral("state"))); if (!f.exists()) { // No state exists, assume nothing valid validated_.clear(); passthroughs_.clear(); return; } qint64 file_time = f.fileTime(QFileDevice::FileModificationTime).toMSecsSinceEpoch(); if (file_time > last_loaded_state_ && f.open(QFile::ReadOnly)) { QDataStream s(&f); uint32_t version; s >> version; LoadStateEvent(s); switch (version) { case 1: { int valid_count, pass_count; s >> valid_count; for (int i=0; i<valid_count; i++) { int in_num, in_den, out_num, out_den; s >> in_num; s >> in_den; s >> out_num; s >> out_den; validated_.insert(TimeRange(rational(in_num, in_den), rational(out_num, out_den))); } s >> pass_count; for (int i=0; i<pass_count; i++) { QUuid id; int in_num, in_den, out_num, out_den; s >> in_num; s >> in_den; s >> out_num; s >> out_den; s >> id; Passthrough p = TimeRange(rational(in_num, in_den), rational(out_num, out_den)); p.cache = id; passthroughs_.push_back(p); } break; } } f.close(); last_loaded_state_ = file_time; } } void PlaybackCache::SaveState() { if (!DiskManager::instance()) { return; } QDir cache_dir = GetThisCacheDirectory(); QFile f(cache_dir.filePath(QStringLiteral("state"))); if (validated_.isEmpty() && passthroughs_.empty()) { if (f.exists()) { f.remove(); } } else { if (FileFunctions::DirectoryIsValid(cache_dir)) { if (f.open(QFile::WriteOnly)) { QDataStream s(&f); uint32_t version = 1; s << version; SaveStateEvent(s); // Using "int" for backwards compatibility with when we used QVector, could potentially overflow s << int(validated_.size()); for (const TimeRange &r : validated_) { s << r.in().numerator(); s << r.in().denominator(); s << r.out().numerator(); s << r.out().denominator(); } // Using "int" for backwards compatibility with when we used QVector, could potentially overflow s << int(passthroughs_.size()); for (const Passthrough &p : passthroughs_) { s << p.in().numerator(); s << p.in().denominator(); s << p.out().numerator(); s << p.out().denominator(); s << p.cache; } f.close(); last_loaded_state_ = f.fileTime(QFileDevice::FileModificationTime).toMSecsSinceEpoch(); } } } } void PlaybackCache::Draw(QPainter *p, const rational &start, double scale, const QRect &rect) const { p->fillRect(rect, Qt::red); foreach (const TimeRange& range, GetValidatedRanges()) { int range_left = rect.left() + (range.in() - start).toDouble() * scale; if (range_left >= rect.right()) { continue; } int range_right = rect.left() + (range.out() - start).toDouble() * scale; if (range_right < rect.left()) { continue; } int adjusted_left = std::max(range_left, rect.left()); int adjusted_right = std::min(range_right, rect.right()); p->fillRect(adjusted_left, rect.top(), adjusted_right - adjusted_left, rect.height(), Qt::green); } } void PlaybackCache::SetPassthrough(PlaybackCache *cache) { for (const TimeRange &r : cache->GetValidatedRanges()) { Passthrough p = r; p.cache = cache->GetUuid(); passthroughs_.push_back(p); } passthroughs_.insert(passthroughs_.end(), cache->GetPassthroughs().begin(), cache->GetPassthroughs().end()); if (saving_enabled_) { SaveState(); } } void PlaybackCache::InvalidateAll() { Invalidate(TimeRange(0, RATIONAL_MAX)); } void PlaybackCache::Request(ViewerOutput *context, const TimeRange &r) { request_context_ = context; requested_.insert(r); emit Requested(request_context_, r); } void PlaybackCache::Validate(const TimeRange &r, bool signal) { validated_.insert(r); if (signal) { emit Validated(r); } if (saving_enabled_) { SaveState(); } } void PlaybackCache::InvalidateEvent(const TimeRange &) { } Project *PlaybackCache::GetProject() const { return Project::GetProjectFromObject(this); } PlaybackCache::PlaybackCache(QObject *parent) : QObject(parent), saving_enabled_(true), last_loaded_state_(0) { uuid_ = QUuid::createUuid(); } void PlaybackCache::SetUuid(const QUuid &u) { uuid_ = u; LoadState(); } TimeRangeList PlaybackCache::GetInvalidatedRanges(TimeRange intersecting) const { TimeRangeList invalidated; // Prevent TimeRange from being below 0, some other behavior in Olive relies on this behavior // and it seemed reasonable to have safety code in here intersecting.set_out(qMax(rational(0), intersecting.out())); intersecting.set_in(qMax(rational(0), intersecting.in())); invalidated.insert(intersecting); foreach (const TimeRange &range, validated_) { invalidated.remove(range); } foreach (const TimeRange &range, passthroughs_) { invalidated.remove(range); } return invalidated; } bool PlaybackCache::HasInvalidatedRanges(const TimeRange &intersecting) const { return !validated_.contains(intersecting); } QString PlaybackCache::GetCacheDirectory() const { Project* project = GetProject(); if (project) { return project->cache_path(); } else { return DiskManager::instance()->GetDefaultCachePath(); } } }
7,280
C++
.cpp
240
25.704167
110
0.663653
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,151
rendermanager.cpp
olive-editor_olive/app/render/rendermanager.cpp
/*** 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/>. ***/ #include "rendermanager.h" #include <QApplication> #include <QMatrix4x4> #include <QThread> #include "config/config.h" #include "core.h" #include "render/opengl/openglrenderer.h" #include "renderprocessor.h" #include "task/conform/conform.h" #include "task/taskmanager.h" #include "window/mainwindow/mainwindow.h" namespace olive { RenderManager* RenderManager::instance_ = nullptr; const rational RenderManager::kDryRunInterval = rational(10); RenderManager::RenderManager(QObject *parent) : backend_(kOpenGL), aggressive_gc_(0) { if (backend_ == kOpenGL) { context_ = new OpenGLRenderer(); decoder_cache_ = new DecoderCache(); shader_cache_ = new ShaderCache(); } else { qCritical() << "Tried to initialize unknown graphics backend"; context_ = nullptr; decoder_cache_ = nullptr; } if (context_) { video_thread_ = CreateThread(context_); dry_run_thread_ = CreateThread(); audio_thread_ = CreateThread(); waveform_threads_.resize(QThread::idealThreadCount()); for (size_t i=0; i<waveform_threads_.size(); i++) { waveform_threads_[i] = CreateThread(); } auto_cacher_ = new PreviewAutoCacher(this); } decoder_clear_timer_ = new QTimer(this); decoder_clear_timer_->setInterval(kDecoderMaximumInactivity); connect(decoder_clear_timer_, &QTimer::timeout, this, &RenderManager::ClearOldDecoders); decoder_clear_timer_->start(); } RenderManager::~RenderManager() { if (context_) { delete shader_cache_; delete decoder_cache_; for (RenderThread *rt : render_threads_) { rt->quit(); rt->wait(); } context_->PostDestroy(); delete context_; } } RenderThread *RenderManager::CreateThread(Renderer *renderer) { auto t = new RenderThread(renderer, decoder_cache_, shader_cache_, this); render_threads_.push_back(t); t->start(QThread::IdlePriority); return t; } RenderTicketPtr RenderManager::RenderFrame(const RenderVideoParams &params) { // Create ticket RenderTicketPtr ticket = std::make_shared<RenderTicket>(); ticket->setProperty("node", QtUtils::PtrToValue(params.node)); ticket->setProperty("time", QVariant::fromValue(params.time)); ticket->setProperty("size", params.force_size); ticket->setProperty("matrix", params.force_matrix); ticket->setProperty("format", static_cast<PixelFormat::Format>(params.force_format)); ticket->setProperty("usecache", params.use_cache); ticket->setProperty("channelcount", params.force_channel_count); ticket->setProperty("mode", params.mode); ticket->setProperty("type", kTypeVideo); ticket->setProperty("colormanager", QtUtils::PtrToValue(params.color_manager)); ticket->setProperty("coloroutput", QVariant::fromValue(params.force_color_output)); Q_ASSERT(params.video_params.is_valid()); ticket->setProperty("vparam", QVariant::fromValue(params.video_params)); ticket->setProperty("aparam", QVariant::fromValue(params.audio_params)); ticket->setProperty("return", params.return_type); ticket->setProperty("cache", params.cache_dir); ticket->setProperty("cachetimebase", QVariant::fromValue(params.cache_timebase)); ticket->setProperty("cacheid", QVariant::fromValue(params.cache_id)); ticket->setProperty("multicam", QtUtils::PtrToValue(params.multicam)); if (params.return_type == ReturnType::kNull) { dry_run_thread_->AddTicket(ticket); } else { video_thread_->AddTicket(ticket); } return ticket; } RenderTicketPtr RenderManager::RenderAudio(const RenderAudioParams &params) { // Create ticket RenderTicketPtr ticket = std::make_shared<RenderTicket>(); ticket->setProperty("node", QtUtils::PtrToValue(params.node)); ticket->setProperty("time", QVariant::fromValue(params.range)); ticket->setProperty("type", kTypeAudio); ticket->setProperty("enablewaveforms", params.generate_waveforms); ticket->setProperty("clamp", params.clamp); ticket->setProperty("aparam", QVariant::fromValue(params.audio_params)); ticket->setProperty("mode", params.mode); if (params.generate_waveforms) { size_t thread_index = last_waveform_thread_%waveform_threads_.size(); RenderThread *thread = waveform_threads_[thread_index]; thread->AddTicket(ticket); last_waveform_thread_++; } else { audio_thread_->AddTicket(ticket); } return ticket; } bool RenderManager::RemoveTicket(RenderTicketPtr ticket) { for (RenderThread *rt : render_threads_) { if (rt->RemoveTicket(ticket)) { return true; } } return false; } void RenderManager::SetAggressiveGarbageCollection(bool enabled) { aggressive_gc_ += enabled ? 1 : -1; if (aggressive_gc_ > 0) { decoder_clear_timer_->setInterval(kDecoderMaximumInactivityAggressive); } else { decoder_clear_timer_->setInterval(kDecoderMaximumInactivity); } } void RenderManager::ClearOldDecoders() { QMutexLocker locker(decoder_cache_->mutex()); qint64 min_age = QDateTime::currentMSecsSinceEpoch() - kDecoderMaximumInactivity; for (auto it=decoder_cache_->begin(); it!=decoder_cache_->end(); ) { DecoderPair decoder = it.value(); if (decoder.decoder->GetLastAccessedTime() < min_age) { decoder.decoder->Close(); it = decoder_cache_->erase(it); } else { it++; } } } RenderThread::RenderThread(Renderer *renderer, DecoderCache *decoder_cache, ShaderCache *shader_cache, QObject *parent) : QThread(parent), cancelled_(false), context_(renderer), decoder_cache_(decoder_cache), shader_cache_(shader_cache) { if (context_) { context_->Init(); context_->moveToThread(this); } } void RenderThread::AddTicket(RenderTicketPtr ticket) { QMutexLocker locker(&mutex_); ticket->moveToThread(this); queue_.push_back(ticket); wait_.wakeOne(); } bool RenderThread::RemoveTicket(RenderTicketPtr ticket) { QMutexLocker locker(&mutex_); auto it = std::find(queue_.begin(), queue_.end(), ticket); if (it == queue_.end()) { return false; } queue_.erase(it); return true; } void RenderThread::quit() { QMutexLocker locker(&mutex_); cancelled_ = true; wait_.wakeOne(); } void RenderThread::run() { if (context_) { context_->PostInit(); } QMutexLocker locker(&mutex_); while (!cancelled_) { if (queue_.empty()) { wait_.wait(&mutex_); } if (cancelled_) { break; } if (!queue_.empty()) { RenderTicketPtr ticket = queue_.front(); queue_.pop_front(); locker.unlock(); // Setup the ticket for ::Process ticket->Start(); if (ticket->IsCancelled()) { ticket->Finish(); } else { RenderProcessor::Process(ticket, context_, decoder_cache_, shader_cache_); } locker.relock(); } } if (context_) { context_->Destroy(); context_->moveToThread(this->thread()); } } }
7,518
C++
.cpp
227
29.60793
121
0.716674
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,152
subtitleparams.cpp
olive-editor_olive/app/render/subtitleparams.cpp
/*** 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/>. ***/ #include "subtitleparams.h" #include <QCoreApplication> #include "common/xmlutils.h" namespace olive { QString SubtitleParams::GenerateASSHeader() { // NOTE: We'll probably implement more customization as we support ASS better. Right now, we only // natively support SRT and only make this header because FFmpeg requires it. static const int kAssDefaultPlayResX = 384; static const int kAssDefaultPlayResY = 288; static const QString kAssDefaultFont = QStringLiteral("Arial"); static const int kAssDefaultFontSize = 16; static const int kAssDefaultPrimaryColor = 0xFFFFFF; // White static const int kAssDefaultSecondaryColor = 0xFFFFFF; // White static const int kAssDefaultOutlineColor = 0x000000; // Black static const int kAssDefaultBackColor = 0x000000; // Black static const int kAssBold = 0; static const int kAssItalic = 0; static const int kAssUnderline = 0; static const int kAssStrike = 0; static const int kAssBorderStyle = 1; static const int kAssAlignment = 2; QString ass_code; // Header info ass_code.append(QStringLiteral("[Script Info]\r\n")); ass_code.append(QStringLiteral("; Script generated by %1 %2\r\n").arg(QCoreApplication::applicationName(), QCoreApplication::applicationVersion())); ass_code.append(QStringLiteral("ScriptType: v4.00+\r\n")); ass_code.append(QStringLiteral("PlayResX: %1\r\n").arg(QString::number(kAssDefaultPlayResX))); ass_code.append(QStringLiteral("PlayResY: %1\r\n").arg(QString::number(kAssDefaultPlayResY))); ass_code.append(QStringLiteral("ScaledBorderAndShadow: yes\r\n")); ass_code.append(QStringLiteral("\r\n")); // ASSv4 header ass_code.append(QStringLiteral("[V4+ Styles]\r\n")); ass_code.append(QStringLiteral("Format: Name, ")); ass_code.append(QStringLiteral("Fontname, Fontsize, ")); ass_code.append(QStringLiteral("PrimaryColour, SecondaryColour, OutlineColour, BackColour, ")); ass_code.append(QStringLiteral("Bold, Italic, Underline, StrikeOut, ")); ass_code.append(QStringLiteral("ScaleX, ScaleY, ")); ass_code.append(QStringLiteral("Spacing, Angle, ")); ass_code.append(QStringLiteral("BorderStyle, Outline, Shadow, ")); ass_code.append(QStringLiteral("Alignment, MarginL, MarginR, MarginV, ")); ass_code.append(QStringLiteral("Encoding\r\n")); ass_code.append(QStringLiteral("Style: ")); // Name ass_code.append(QStringLiteral("Default,")); // Font{name,size} ass_code.append(QStringLiteral("%1,%2,").arg(kAssDefaultFont, QString::number(kAssDefaultFontSize))); // {Primary,Secondary,Outline,Back}Colour ass_code.append(QStringLiteral("&H%1,&H%2,&H%3,&H%4,").arg(QString::number(kAssDefaultPrimaryColor, 16), QString::number(kAssDefaultSecondaryColor, 16), QString::number(kAssDefaultOutlineColor, 16), QString::number(kAssDefaultBackColor, 16))); // Bold, Italic, Underline, StrikeOut ass_code.append(QStringLiteral("%1,%2,%3,%4,").arg(QString::number(kAssBold), QString::number(kAssItalic), QString::number(kAssUnderline), QString::number(kAssStrike))); // Scale{X,Y} ass_code.append(QStringLiteral("100,100,")); // Spacing, Angle ass_code.append(QStringLiteral("0,0,")); // BorderStyle, Outline, Shadow ass_code.append(QStringLiteral("%1,1,0,").arg(QString::number(kAssBorderStyle))); // Alignment, Margin[LRV] ass_code.append(QStringLiteral("%1,10,10,10,").arg(QString::number(kAssAlignment))); // Encoding ass_code.append(QStringLiteral("0\r\n")); ass_code.append(QStringLiteral("\r\n")); ass_code.append(QStringLiteral("[Events]\r\n")); ass_code.append(QStringLiteral("Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\r\n")); return ass_code; } void SubtitleParams::Load(QXmlStreamReader *reader) { this->clear(); while (XMLReadNextStartElement(reader)) { if (reader->name() == QStringLiteral("streamindex")) { set_stream_index(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("enabled")) { set_enabled(reader->readElementText().toInt()); } else if (reader->name() == QStringLiteral("subtitles")) { while (XMLReadNextStartElement(reader)) { if (reader->name() == QStringLiteral("subtitle")) { rational in, out; QString text; XMLAttributeLoop(reader, attr) { if (attr.name() == QStringLiteral("in")) { in = rational::fromString(attr.value().toString().toStdString()); } else if (attr.name() == QStringLiteral("out")) { out = rational::fromString(attr.value().toString().toStdString()); } } text = reader->readElementText(); this->push_back(Subtitle(TimeRange(in, out), text)); } else { reader->skipCurrentElement(); } } } else { reader->skipCurrentElement(); } } } void SubtitleParams::Save(QXmlStreamWriter *writer) const { writer->writeTextElement(QStringLiteral("streamindex"), QString::number(stream_index_)); writer->writeTextElement(QStringLiteral("enabled"), QString::number(enabled_)); writer->writeStartElement(QStringLiteral("subtitles")); for (auto it=this->cbegin(); it!=this->cend(); it++) { writer->writeStartElement(QStringLiteral("subtitle")); writer->writeAttribute(QStringLiteral("in"), QString::fromStdString(it->time().in().toString())); writer->writeAttribute(QStringLiteral("out"), QString::fromStdString(it->time().out().toString())); writer->writeCharacters(it->text()); writer->writeEndElement(); // subtitle } writer->writeEndElement(); // subtitles } }
6,662
C++
.cpp
132
43.704545
150
0.682259
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,153
colorprocessor.cpp
olive-editor_olive/app/render/colorprocessor.cpp
/*** 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/>. ***/ #include "colorprocessor.h" #include "common/define.h" #include "common/ocioutils.h" #include "node/color/colormanager/colormanager.h" namespace olive { ColorProcessor::ColorProcessor(ColorManager *config, const QString &input, const ColorTransform &transform, Direction direction) { const QString& output = (transform.output().isEmpty()) ? config->GetDefaultDisplay() : transform.output(); if (transform.is_display()) { const QString& view = (transform.view().isEmpty()) ? config->GetDefaultView(output) : transform.view(); auto display_transform = OCIO::DisplayViewTransform::Create(); display_transform->setSrc(input.toUtf8()); display_transform->setDisplay(output.toUtf8()); display_transform->setView(view.toUtf8()); display_transform->setDirection(direction == kNormal ? OCIO::TRANSFORM_DIR_FORWARD : OCIO::TRANSFORM_DIR_INVERSE); if (transform.look().isEmpty()) { processor_ = config->GetConfig()->getProcessor(display_transform); } else { auto group = OCIO::GroupTransform::Create(); const char* out_cs = OCIO::LookTransform::GetLooksResultColorSpace(config->GetConfig(), config->GetConfig()->getCurrentContext(), transform.look().toUtf8()); auto lt = OCIO::LookTransform::Create(); lt->setSrc(input.toUtf8()); lt->setDst(out_cs); lt->setLooks(transform.look().toUtf8()); lt->setSkipColorSpaceConversion(false); group->appendTransform(lt); display_transform->setSrc(out_cs); group->appendTransform(display_transform); processor_ = config->GetConfig()->getProcessor(group); } } else { try { if (direction == kNormal) { processor_ = config->GetConfig()->getProcessor(input.toUtf8(), output.toUtf8()); } else { processor_ = config->GetConfig()->getProcessor(output.toUtf8(), input.toUtf8()); } } catch (OCIO::Exception &e) { qWarning() << "ColorProcessor exception:" << e.what(); } } cpu_processor_ = processor_->getDefaultCPUProcessor(); } ColorProcessor::ColorProcessor(OCIO::ConstProcessorRcPtr processor) { processor_ = processor; cpu_processor_ = processor_->getDefaultCPUProcessor(); } void ColorProcessor::ConvertFrame(Frame *f) { OCIO::BitDepth ocio_bit_depth = OCIOUtils::GetOCIOBitDepthFromPixelFormat(f->format()); if (ocio_bit_depth == OCIO::BIT_DEPTH_UNKNOWN) { qCritical() << "Tried to color convert frame with no format"; return; } OCIO::PackedImageDesc img(f->data(), f->width(), f->height(), f->channel_count(), ocio_bit_depth, OCIO::AutoStride, OCIO::AutoStride, f->linesize_bytes()); cpu_processor_->apply(img); } Color ColorProcessor::ConvertColor(const Color& in) { // I've been bamboozled float c[4] = {float(in.red()), float(in.green()), float(in.blue()), float(in.alpha())}; cpu_processor_->applyRGBA(c); return Color(c[0], c[1], c[2], c[3]); } ColorProcessorPtr ColorProcessor::Create(ColorManager *config, const QString& input, const ColorTransform &transform, Direction direction) { return std::make_shared<ColorProcessor>(config, input, transform, direction); } ColorProcessorPtr ColorProcessor::Create(OCIO::ConstProcessorRcPtr processor) { return std::make_shared<ColorProcessor>(processor); } OCIO::ConstProcessorRcPtr ColorProcessor::GetProcessor() { return processor_; } void ColorProcessor::ConvertFrame(FramePtr f) { ConvertFrame(f.get()); } }
4,475
C++
.cpp
105
35.819048
138
0.670819
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,154
audiowaveformcache.cpp
olive-editor_olive/app/render/audiowaveformcache.cpp
/*** 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/>. ***/ #include "audiowaveformcache.h" namespace olive { #define super PlaybackCache AudioWaveformCache::AudioWaveformCache(QObject *parent) : super{parent} { waveforms_ = std::make_shared<AudioVisualWaveform>(); } void AudioWaveformCache::WriteWaveform(const TimeRange &range, const TimeRangeList &valid_ranges, const AudioVisualWaveform *waveform) { // Write each valid range to the segments foreach (const TimeRange& r, valid_ranges) { if (waveform) { waveforms_->OverwriteSums(*waveform, r.in(), r.in() - range.in(), r.length()); } Validate(r); } } void DrawSubRect(QPainter *painter, const QRect &rect, const double &scale, const TimeRange &wave_range, const AudioVisualWaveform &waveform, const TimeRange &subrange) { // Find start time of passthrough TimeRange intersect = wave_range.Intersected(subrange); // Create new rect that starts at the offset of pass_start from start_time // Set rect width to either length of passthrough or until the end QRect pass_rect(rect.x() + (intersect.in() - wave_range.in()).toDouble() * scale, rect.y(), intersect.length().toDouble() * scale, rect.height()); // Draw waveform with this info AudioVisualWaveform::DrawWaveform(painter, pass_rect, scale, waveform, intersect.in()); } void AudioWaveformCache::Draw(QPainter *painter, const QRect &rect, const double &scale, const rational &start_time) const { if (!passthroughs_.empty()) { TimeRange wave_range(start_time, start_time + rational::fromDouble(rect.width() / scale)); TimeRangeList draw_range = {wave_range}; for (const WaveformPassthrough &p : passthroughs_) { if (draw_range.OverlapsWith(p, true, false)) { DrawSubRect(painter, rect, scale, wave_range, *p.waveform, p); // Remove this range draw_range.remove(p); } } for (const TimeRange &r : draw_range) { DrawSubRect(painter, rect, scale, wave_range, *waveforms_, r); } } else { AudioVisualWaveform::DrawWaveform(painter, rect, scale, *waveforms_, start_time); } } AudioVisualWaveform::Sample AudioWaveformCache::GetSummaryFromTime(const rational &start, const rational &length) const { return waveforms_->GetSummaryFromTime(start, length); } rational AudioWaveformCache::length() const { return waveforms_->length(); } void AudioWaveformCache::SetPassthrough(PlaybackCache *cache) { AudioWaveformCache *c = static_cast<AudioWaveformCache*>(cache); for (const TimeRange &r : c->GetValidatedRanges()) { WaveformPassthrough t = r; t.waveform = c->waveforms_; passthroughs_.push_back(t); } passthroughs_.insert(passthroughs_.end(), c->passthroughs_.begin(), c->passthroughs_.end()); SetParameters(c->GetParameters()); SetSavingEnabled(c->IsSavingEnabled()); } void AudioWaveformCache::InvalidateEvent(const TimeRange& range) { TimeRangeList::util_remove(&passthroughs_, range); super::InvalidateEvent(range); } }
3,695
C++
.cpp
90
37.244444
168
0.732123
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,155
framehashcache.cpp
olive-editor_olive/app/render/framehashcache.cpp
/*** 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/>. ***/ #include "framehashcache.h" #include <OpenEXR/ImfFloatAttribute.h> #include <OpenEXR/ImfFrameBuffer.h> #include <OpenEXR/ImfHeader.h> #include <OpenEXR/ImfInputFile.h> #include <OpenEXR/ImfIntAttribute.h> #include <OpenEXR/ImfOutputFile.h> #include <OpenEXR/ImfChannelList.h> #include <QDir> #include <QFileInfo> #include "codec/frame.h" #include "common/filefunctions.h" #include "common/oiioutils.h" #include "render/diskmanager.h" namespace olive { #define super PlaybackCache FrameHashCache::FrameHashCache(QObject *parent) : super(parent) { if (DiskManager::instance()) { connect(DiskManager::instance(), &DiskManager::DeletedFrame, this, &FrameHashCache::HashDeleted); connect(DiskManager::instance(), &DiskManager::InvalidateProject, this, &FrameHashCache::ProjectInvalidated); } } void FrameHashCache::SetTimebase(const rational &tb) { timebase_ = tb; } void FrameHashCache::ValidateTimestamp(const int64_t &ts) { TimeRange frame_range(ToTime(ts), ToTime(ts+1)); Validate(frame_range); } void FrameHashCache::ValidateTime(const rational &time) { Validate(TimeRange(time, time + timebase_)); } QString FrameHashCache::GetValidCacheFilename(const rational &time) const { if (IsFrameCached(time)) { return CachePathName(time); } else if (!GetPassthroughs().empty()) { for (const Passthrough &p : GetPassthroughs()) { if (p.Contains(time)) { return CachePathName(GetCacheDirectory(), p.cache, time, timebase_); } } } return QString(); } bool FrameHashCache::SaveCacheFrame(const int64_t &time, FramePtr frame) const { return SaveCacheFrame(GetCacheDirectory(), GetUuid(), time, frame); } bool FrameHashCache::SaveCacheFrame(const QString &cache_path, const QUuid &uuid, const int64_t &time, FramePtr frame) { if (cache_path.isEmpty()) { qWarning() << "Failed to save cache frame with empty path"; return false; } QString fn = CachePathName(cache_path, uuid, time); bool ret = SaveCacheFrame(fn, frame); // Register frame with the disk manager if (ret) { QMetaObject::invokeMethod(DiskManager::instance(), "CreatedFile", Q_ARG(QString, cache_path), Q_ARG(QString, fn)); } return ret; } bool FrameHashCache::SaveCacheFrame(const QString &cache_path, const QUuid &uuid, const rational &time, const rational &tb, FramePtr frame) { if (cache_path.isEmpty()) { qWarning() << "Failed to save cache frame with empty path"; return false; } QString fn = CachePathName(cache_path, uuid, time, tb); bool ret = SaveCacheFrame(fn, frame); // Register frame with the disk manager if (ret) { QMetaObject::invokeMethod(DiskManager::instance(), "CreatedFile", Q_ARG(QString, cache_path), Q_ARG(QString, fn)); } return ret; } FramePtr FrameHashCache::LoadCacheFrame(const QString &cache_path, const QUuid &uuid, const int64_t &time) { // Minor optimization, we store frames currently being saved just in case something tries to load // while we're saving. This should *occasionally* optimize and also prevent scenarios where // we try to load a frame that's half way through being saved. QString filename = CachePathName(cache_path, uuid, time); if (cache_path.isEmpty()) { qWarning() << "Failed to load cache frame with empty path"; return nullptr; } return LoadCacheFrame(filename); } FramePtr FrameHashCache::LoadCacheFrame(const int64_t &hash) const { return LoadCacheFrame(GetCacheDirectory(), GetUuid(), hash); } FramePtr FrameHashCache::LoadCacheFrame(const QString &fn) { FramePtr frame = nullptr; if (!fn.isEmpty() && QFileInfo::exists(fn)) { try { Imf::InputFile file(fn.toUtf8(), 0); Imath::Box2i dw = file.header().dataWindow(); Imf::PixelType pix_type = file.header().channels().begin().channel().type; int width = dw.max.x - dw.min.x + 1; int height = dw.max.y - dw.min.y + 1; bool has_alpha = file.header().channels().findChannel("A"); int div = qMax(1, static_cast<const Imf::IntAttribute&>(file.header()["oliveDivider"]).value()); PixelFormat image_format; if (pix_type == Imf::HALF) { image_format = PixelFormat::F16; } else { image_format = PixelFormat::F32; } int channel_count = has_alpha ? VideoParams::kRGBAChannelCount : VideoParams::kRGBChannelCount; frame = Frame::Create(); frame->set_video_params(VideoParams(width * div, height * div, image_format, channel_count, rational::fromDouble(file.header().pixelAspectRatio()), VideoParams::kInterlaceNone, div)); frame->allocate(); int bpc = VideoParams::GetBytesPerChannel(image_format); size_t xs = channel_count * bpc; size_t ys = frame->linesize_bytes(); Imf::FrameBuffer framebuffer; framebuffer.insert("R", Imf::Slice(pix_type, frame->data(), xs, ys)); framebuffer.insert("G", Imf::Slice(pix_type, frame->data() + bpc, xs, ys)); framebuffer.insert("B", Imf::Slice(pix_type, frame->data() + 2*bpc, xs, ys)); if (has_alpha) { framebuffer.insert("A", Imf::Slice(pix_type, frame->data() + 3*bpc, xs, ys)); } file.setFrameBuffer(framebuffer); file.readPixels(dw.min.y, dw.max.y); } catch (const std::exception &e) { // Not an EXR, maybe it's a JPEG? QImage img; if (img.load(fn, "jpg")) { // FIXME: Hardcoded const int div = 1; const PixelFormat image_format = PixelFormat::U8; const int channel_count = 4; const rational par(1, 1); // Convert to frame (FIXME: might be slow? may be a better way to do this on the GPU) img.convertTo(QImage::Format_RGBA8888_Premultiplied); frame = Frame::Create(); frame->set_video_params(VideoParams(img.width() * div, img.height() * div, image_format, channel_count, par, VideoParams::kInterlaceNone, div)); frame->allocate(); for (int i=0; i<img.height(); i++) { memcpy(frame->data() + frame->linesize_bytes() * i, img.bits() + img.bytesPerLine() * i, frame->width() * frame->video_params().GetBytesPerPixel()); } } else { qCritical() << "Failed to read cache frame:" << e.what(); // Clear frame to signal that nothing was loaded frame = nullptr; // Assume this frame is corrupt in some way and delete it QMetaObject::invokeMethod(DiskManager::instance(), "DeleteSpecificFile", Q_ARG(QString, fn)); } } } return frame; } void FrameHashCache::SetPassthrough(PlaybackCache *cache) { super::SetPassthrough(cache); SetTimebase(static_cast<FrameHashCache*>(cache)->GetTimebase()); } void FrameHashCache::LoadStateEvent(QDataStream &stream) { uint32_t version; int num, den; stream >> version; switch (version) { case 1: stream >> num; stream >> den; timebase_ = rational(num, den); break; } } void FrameHashCache::SaveStateEvent(QDataStream &stream) { uint32_t version = 1; stream << version; stream << timebase_.numerator(); stream << timebase_.denominator(); } rational FrameHashCache::ToTime(const int64_t &ts) const { return Timecode::timestamp_to_time(ts, timebase_); } int64_t FrameHashCache::ToTimestamp(const rational &ts, Timecode::Rounding rounding) const { return Timecode::time_to_timestamp(ts, timebase_, rounding); } void FrameHashCache::HashDeleted(const QString& path, const QString &filename) { QString cache_dir = GetCacheDirectory(); if (cache_dir.isEmpty() || path != cache_dir) { return; } QFileInfo info(filename); if (GetUuid().toString() != info.dir().dirName()) { return; } int64_t timestamp = info.fileName().toLongLong(); Invalidate(TimeRange(ToTime(timestamp), ToTime(timestamp + 1))); } void FrameHashCache::ProjectInvalidated(Project *p) { if (GetProject() == p) { InvalidateAll(); } } QString FrameHashCache::CachePathName(const int64_t &time) const { return CachePathName(GetCacheDirectory(), GetUuid(), time); } QString FrameHashCache::CachePathName(const rational &time) const { return CachePathName(GetCacheDirectory(), GetUuid(), time, timebase_); } QString FrameHashCache::CachePathName(const QString &cache_path, const QUuid &cache_id, const int64_t &time) { QString filename = GetThisCacheDirectory(cache_path, cache_id).filePath(QString::number(time)); // Register that in some way this hash has been accessed if (DiskManager::instance()) { QMetaObject::invokeMethod(DiskManager::instance(), "Accessed", Q_ARG(QString, cache_path), Q_ARG(QString, filename)); } return filename; } QString FrameHashCache::CachePathName(const QString &cache_path, const QUuid &cache_id, const rational &time, const rational &tb) { return CachePathName(cache_path, cache_id, Timecode::time_to_timestamp(time, tb, Timecode::kRound)); } bool FrameHashCache::SaveCacheFrame(const QString &filename, const FramePtr frame) { // Ensure directory is created QDir cache_dir = QFileInfo(filename).dir(); if (!FileFunctions::DirectoryIsValid(cache_dir)) { return false; } if (VideoParams::FormatIsFloat(frame->format())) { // Floating point types are stored in EXR Imf::PixelType pix_type; if (frame->format() == PixelFormat::F16) { pix_type = Imf::HALF; } else { pix_type = Imf::FLOAT; } Imf::Header header(frame->width(), frame->height()); header.channels().insert("R", Imf::Channel(pix_type)); header.channels().insert("G", Imf::Channel(pix_type)); header.channels().insert("B", Imf::Channel(pix_type)); if (frame->channel_count() == VideoParams::kRGBAChannelCount) { header.channels().insert("A", Imf::Channel(pix_type)); } header.compression() = Imf::DWAA_COMPRESSION; header.insert("dwaCompressionLevel", Imf::FloatAttribute(200.0f)); header.pixelAspectRatio() = frame->video_params().pixel_aspect_ratio().toDouble(); header.insert("oliveDivider", Imf::IntAttribute(frame->video_params().divider())); try { Imf::OutputFile out(filename.toUtf8(), header, 0); int bpc = VideoParams::GetBytesPerChannel(frame->format()); size_t xs = frame->channel_count() * bpc; size_t ys = frame->linesize_bytes(); Imf::FrameBuffer framebuffer; framebuffer.insert("R", Imf::Slice(pix_type, frame->data(), xs, ys)); framebuffer.insert("G", Imf::Slice(pix_type, frame->data() + bpc, xs, ys)); framebuffer.insert("B", Imf::Slice(pix_type, frame->data() + 2*bpc, xs, ys)); if (frame->channel_count() == VideoParams::kRGBAChannelCount) { framebuffer.insert("A", Imf::Slice(pix_type, frame->data() + 3*bpc, xs, ys)); } out.setFrameBuffer(framebuffer); out.writePixels(frame->height()); return true; } catch (const std::exception &e) { qCritical() << "Failed to write cache frame:" << e.what(); return false; } } else { QImage::Format fmt = QImage::Format_Invalid; switch (frame->format()) { case PixelFormat::U8: if (frame->channel_count() == VideoParams::kRGBAChannelCount){ fmt = QImage::Format_RGBA8888_Premultiplied; } else if (frame->channel_count() == VideoParams::kRGBChannelCount){ fmt = QImage::Format_RGB888; } break; case PixelFormat::U16: if (frame->channel_count() == VideoParams::kRGBAChannelCount){ fmt = QImage::Format_RGBA64_Premultiplied; } break; case PixelFormat::F16: case PixelFormat::F32: case PixelFormat::COUNT: case PixelFormat::INVALID: break; } if (fmt == QImage::Format_Invalid) { return false; } QImage img(reinterpret_cast<const uchar*>(frame->data()), frame->width(), frame->height(), frame->linesize_bytes(), fmt); return img.save(filename, "jpg"); } } }
13,069
C++
.cpp
335
33.18209
139
0.66635
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,156
texture.cpp
olive-editor_olive/app/render/texture.cpp
/*** 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/>. ***/ #include "texture.h" #include "renderer.h" namespace olive { const Texture::Interpolation Texture::kDefaultInterpolation = Texture::kMipmappedLinear; Texture::~Texture() { if (renderer_) { renderer_->DestroyTexture(this); } if (job_) { delete job_; } } void Texture::Upload(void *data, int linesize) { if (renderer_) { renderer_->UploadToTexture(this->id(), this->params(), data, linesize); } } void Texture::Download(void *data, int linesize) { if (renderer_) { renderer_->DownloadFromTexture(this->id(), this->params(), data, linesize); } } }
1,297
C++
.cpp
40
29.675
88
0.73934
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,157
openglrenderer.cpp
olive-editor_olive/app/render/opengl/openglrenderer.cpp
/*** 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/>. ***/ #include "openglrenderer.h" #include <iostream> #include <QDateTime> #include <QDebug> #include <QOpenGLExtraFunctions> #include "config/config.h" namespace olive { const int OpenGLRenderer::kTextureCacheMaxSize = 5000; const QVector<GLfloat> blit_vertices = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f }; const QVector<GLfloat> blit_texcoords = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f }; class ErrorPrinter { public: ErrorPrinter(const char* name, QOpenGLFunctions* f) { GLuint err = f->glGetError(); if (err > 0) qDebug() << name << "entered with" << err; name_ = name; functions_ = f; } ~ErrorPrinter() { GLuint err = functions_->glGetError(); if (err > 0) qDebug() << name_ << "exited with" << err; } private: const char* name_; QOpenGLFunctions* functions_; }; #define PRINT_GL_ERRORS ErrorPrinter __e(__FUNCTION__, functions_) #define GL_PREAMBLE \ //QMutexLocker __l(&global_opengl_mutex); //QMutex global_opengl_mutex; OpenGLRenderer::OpenGLRenderer(QObject* parent) : Renderer(parent), context_(nullptr), framebuffer_(0) { } OpenGLRenderer::~OpenGLRenderer() { Destroy(); PostDestroy(); } void OpenGLRenderer::Init(QOpenGLContext *existing_ctx) { if (context_) { qCritical() << "Can't initialize already initialized OpenGLRenderer"; return; } context_ = existing_ctx; } bool OpenGLRenderer::Init() { GL_PREAMBLE; if (context_) { qCritical() << "Can't initialize already initialized OpenGLRenderer"; return false; } surface_.create(); context_ = new QOpenGLContext(this); context_->setShareContext(QOpenGLContext::globalShareContext()); if (!context_->create()) { qCritical() << "Failed to create OpenGL context"; return false; } context_->moveToThread(this->thread()); return true; } void OpenGLRenderer::PostDestroy() { // Destroy surface if we created it if (surface_.isValid()) { surface_.destroy(); } } void OpenGLRenderer::PostInit() { GL_PREAMBLE; // Make context current on that surface if (context_->parent() == this && !context_->makeCurrent(&surface_)) { qCritical() << "Failed to makeCurrent() on offscreen surface in thread" << thread(); return; } functions_ = context_->functions(); // Store OpenGL functions instance functions_->glBlendFunc(GL_ONE, GL_ZERO); // Set up framebuffer used for various things functions_->glGenFramebuffers(1, &framebuffer_); } void OpenGLRenderer::DestroyInternal() { if (context_) { GL_PREAMBLE; // Delete framebuffer functions_->glDeleteFramebuffers(1, &framebuffer_); framebuffer_ = 0; // Delete context if it belongs to us if (context_->parent() == this) { delete context_; } context_ = nullptr; } } void OpenGLRenderer::ClearDestination(Texture *texture, double r, double g, double b, double a) { GL_PREAMBLE; if (texture) { AttachTextureAsDestination(texture->id()); } ClearDestinationInternal(r, g, b, a); if (texture) { DetachTextureAsDestination(); } } QVariant OpenGLRenderer::CreateNativeTexture(int width, int height, int depth, PixelFormat format, int channel_count, const void *data, int linesize) { GL_PREAMBLE; bool is_3d = depth > 1; // Generate new texture GLuint texture; functions_->glGenTextures(1, &texture); texture_params_.insert(texture, {width, height, depth, format, channel_count}); functions_->glPixelStorei(GL_UNPACK_ROW_LENGTH, linesize); GLenum target_current = is_3d ? GL_TEXTURE_BINDING_3D : GL_TEXTURE_BINDING_2D; GLenum target = is_3d ? GL_TEXTURE_3D : GL_TEXTURE_2D; GLint current_tex; functions_->glGetIntegerv(target_current, &current_tex); functions_->glBindTexture(target, texture); if (is_3d) { context_->extraFunctions()->glTexImage3D(target, 0, GetInternalFormat(format, channel_count), width, height, depth, 0, GetPixelFormat(channel_count), GetPixelType(format), data); } else { functions_->glTexImage2D(target, 0, GetInternalFormat(format, channel_count), width, height, 0, GetPixelFormat(channel_count), GetPixelType(format), data); } functions_->glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); functions_->glBindTexture(target, current_tex); return texture; } void OpenGLRenderer::AttachTextureAsDestination(const QVariant &texture) { PRINT_GL_ERRORS; functions_->glBindFramebuffer(GL_FRAMEBUFFER, framebuffer_); functions_->glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture.value<GLuint>(), 0); } void OpenGLRenderer::DetachTextureAsDestination() { functions_->glBindFramebuffer(GL_FRAMEBUFFER, 0); } void OpenGLRenderer::DestroyNativeTexture(QVariant texture) { GLuint t = texture.value<GLuint>(); if (t > 0) { functions_->glDeleteTextures(1, &t); } } QVariant OpenGLRenderer::CreateNativeShader(ShaderCode code) { GL_PREAMBLE; PRINT_GL_ERRORS; GLuint vert = CompileShader(GL_VERTEX_SHADER, code.vert_code()); GLuint frag = CompileShader(GL_FRAGMENT_SHADER, code.frag_code()); GLuint program = 0; if (frag && vert) { program = functions_->glCreateProgram(); functions_->glAttachShader(program, frag); functions_->glAttachShader(program, vert); functions_->glLinkProgram(program); GLint success; functions_->glGetProgramiv(program, GL_LINK_STATUS, &success); if (!success) { qWarning() << "Failed to link OpenGL shader program"; functions_->glDeleteProgram(program); program = 0; } } functions_->glDeleteShader(frag); functions_->glDeleteShader(vert); return program; } void OpenGLRenderer::DestroyNativeShader(QVariant shader) { GL_PREAMBLE; GLuint program = shader.value<GLuint>(); functions_->glDeleteProgram(program); } void OpenGLRenderer::UploadToTexture(const QVariant &handle, const VideoParams &p, const void *data, int linesize) { GL_PREAMBLE; GLuint t = handle.value<GLuint>(); bool is_3d = p.is_3d(); GLenum tex_type = !is_3d ? GL_TEXTURE_2D : GL_TEXTURE_3D; GLenum tex_binding = !is_3d ? GL_TEXTURE_BINDING_2D : GL_TEXTURE_BINDING_3D; // Store currently bound texture so it can be restored later GLint current_tex; functions_->glGetIntegerv(tex_binding, &current_tex); functions_->glBindTexture(tex_type, t); functions_->glPixelStorei(GL_UNPACK_ROW_LENGTH, linesize); { PRINT_GL_ERRORS; if (!is_3d) { functions_->glTexSubImage2D(tex_type, 0, 0, 0, p.effective_width(), p.effective_height(), GetPixelFormat(p.channel_count()), GetPixelType(p.format()), data); } else { context_->extraFunctions()->glTexSubImage3D(tex_type, 0, 0, 0, 0, p.effective_width(), p.effective_height(), p.effective_depth(), GetPixelFormat(p.channel_count()), GetPixelType(p.format()), data); } } functions_->glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); functions_->glBindTexture(tex_type, current_tex); } void OpenGLRenderer::DownloadFromTexture(const QVariant &id, const VideoParams &p, void *data, int linesize) { GL_PREAMBLE; GLint current_tex; functions_->glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_tex); AttachTextureAsDestination(id); functions_->glPixelStorei(GL_PACK_ROW_LENGTH, linesize); { PRINT_GL_ERRORS; functions_->glReadPixels(0, 0, p.effective_width(), p.effective_height(), GetPixelFormat(p.channel_count()), GetPixelType(p.format()), data); } functions_->glPixelStorei(GL_PACK_ROW_LENGTH, 0); DetachTextureAsDestination(); functions_->glBindTexture(GL_TEXTURE_2D, current_tex); } void OpenGLRenderer::Flush() { GL_PREAMBLE; if (OLIVE_CONFIG("UseGLFinish").toBool()) { functions_->glFinish(); } else { functions_->glFlush(); } } Color OpenGLRenderer::GetPixelFromTexture(Texture *texture, const QPointF &pt) { AttachTextureAsDestination(texture->id()); QByteArray data(VideoParams::GetBytesPerPixel(texture->format(), texture->channel_count()), Qt::Uninitialized); functions_->glReadPixels(pt.x(), pt.y(), 1, 1, GetPixelFormat(texture->channel_count()), GetPixelType(texture->format()), data.data()); Color c = Color::fromData(data.data(), texture->format(), texture->channel_count()); if (texture->channel_count() == VideoParams::kRGBChannelCount) { // No alpha channel, set to 1.0 c.set_alpha(1.0); } DetachTextureAsDestination(); return c; } struct TextureToBind { TexturePtr texture; Texture::Interpolation interpolation; }; void OpenGLRenderer::Blit(QVariant s, ShaderJob job, Texture *destination, VideoParams destination_params, bool clear_destination) { GL_PREAMBLE; // If this node is iterative, we'll pick up which input here QMap<QString, GLuint> texture_index_map; QVector<TextureToBind> textures_to_bind; GLuint shader = s.value<GLuint>(); functions_->glUseProgram(shader); for (auto it=job.GetValues().constBegin(); it!=job.GetValues().constEnd(); it++) { // See if the shader has takes this parameter as an input GLint variable_location = functions_->glGetUniformLocation(shader, it.key().toUtf8().constData()); if (variable_location == -1) { continue; } // This variable is used in the shader, let's set it const NodeValue& value = it.value(); // Arrays are not currently supported in this system if (value.array()) { continue; } switch (value.type()) { case NodeValue::kInt: // kInt technically specifies a LongLong, but OpenGL doesn't support those. This may lead to // over/underflows if the number is large enough, but the likelihood of that is quite low. functions_->glUniform1i(variable_location, value.toInt()); break; case NodeValue::kFloat: // kFloat technically specifies a double but as above, OpenGL doesn't support those. functions_->glUniform1f(variable_location, value.toDouble()); break; case NodeValue::kVec2: { QVector2D v = value.toVec2(); functions_->glUniform2fv(variable_location, 1, reinterpret_cast<const GLfloat*>(&v)); break; } case NodeValue::kVec3: { QVector3D v = value.toVec3(); functions_->glUniform3fv(variable_location, 1, reinterpret_cast<const GLfloat*>(&v)); break; } case NodeValue::kVec4: { QVector4D v = value.toVec4(); functions_->glUniform4fv(variable_location, 1, reinterpret_cast<const GLfloat*>(&v)); break; } case NodeValue::kMatrix: functions_->glUniformMatrix4fv(variable_location, 1, false, value.toMatrix().constData()); break; case NodeValue::kCombo: functions_->glUniform1i(variable_location, value.toInt()); break; case NodeValue::kColor: { Color color = value.toColor(); functions_->glUniform4f(variable_location, color.red(), color.green(), color.blue(), color.alpha()); break; } case NodeValue::kBoolean: functions_->glUniform1i(variable_location, value.toBool()); break; case NodeValue::kTexture: { TexturePtr texture = value.toTexture(); // Set value to bound texture functions_->glUniform1i(variable_location, textures_to_bind.size()); texture_index_map.insert(it.key(), textures_to_bind.size()); textures_to_bind.append({texture, job.GetInterpolation(it.key())}); // Set enable flag if shader wants it GLuint tex_id = texture ? texture->id().value<GLuint>() : 0; int enable_param_location = functions_->glGetUniformLocation(shader, QStringLiteral("%1_enabled").arg(it.key()).toUtf8().constData()); if (enable_param_location > -1) { functions_->glUniform1i(enable_param_location, tex_id > 0); } break; } case NodeValue::kSamples: case NodeValue::kText: case NodeValue::kRational: case NodeValue::kFont: case NodeValue::kFile: case NodeValue::kVideoParams: case NodeValue::kAudioParams: case NodeValue::kSubtitleParams: case NodeValue::kBezier: case NodeValue::kBinary: case NodeValue::kNone: case NodeValue::kDataTypeCount: break; } } // Bind all textures for (int i=0; i<textures_to_bind.size(); i++) { const TextureToBind& t = textures_to_bind.at(i); TexturePtr texture = t.texture; GLuint tex_id = texture ? texture->id().value<GLuint>() : 0; functions_->glActiveTexture(GL_TEXTURE0 + i); GLenum target = (texture && texture->params().is_3d()) ? GL_TEXTURE_3D : GL_TEXTURE_2D; functions_->glBindTexture(target, tex_id); if (tex_id) { PrepareInputTexture(target, t.interpolation); if (texture->channel_count() == 1 && destination_params.channel_count() != 1) { // Interpret this texture as a grayscale texture functions_->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); functions_->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED); functions_->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); } } } // Ensure matrix is set, at least to identity GLint mvpmat_location = functions_->glGetUniformLocation(shader, "ove_mvpmat"); if (mvpmat_location > -1) { functions_->glUniformMatrix4fv(mvpmat_location, 1, false, job.Get(QStringLiteral("ove_mvpmat")).toMatrix().constData()); } // Set the viewport to the "physical" resolution of the destination functions_->glViewport(0, 0, destination_params.effective_width(), destination_params.effective_height()); // Bind vertex array object QOpenGLVertexArrayObject vao_; vao_.create(); vao_.bind(); // Set buffers QOpenGLBuffer vert_vbo_; vert_vbo_.create(); vert_vbo_.bind(); // If the job has vertex coordinate overrides use them instead of the defaults. if (!job.GetVertexCoordinates().isEmpty()) { Q_ASSERT(job.GetVertexCoordinates().size() == 18); vert_vbo_.allocate(job.GetVertexCoordinates().constData(), job.GetVertexCoordinates().size() * sizeof(float)); } else { vert_vbo_.allocate(blit_vertices.constData(), blit_vertices.size() * sizeof(GLfloat)); } vert_vbo_.release(); QOpenGLBuffer frag_vbo_; frag_vbo_.create(); frag_vbo_.bind(); frag_vbo_.allocate(blit_texcoords.constData(), blit_texcoords.size() * sizeof(GLfloat)); frag_vbo_.release(); GLint vertex_location = functions_->glGetAttribLocation(shader, "a_position"); if (vertex_location != -1) { vert_vbo_.bind(); functions_->glEnableVertexAttribArray(vertex_location); functions_->glVertexAttribPointer(vertex_location, 3, GL_FLOAT, GL_FALSE, 0, nullptr); vert_vbo_.release(); } GLint tex_location = functions_->glGetAttribLocation(shader, "a_texcoord"); if (tex_location != -1) { frag_vbo_.bind(); functions_->glEnableVertexAttribArray(tex_location); functions_->glVertexAttribPointer(tex_location, 2, GL_FLOAT, GL_FALSE, 0, nullptr); frag_vbo_.release(); } // Some shaders optimize through multiple iterations which requires ping-ponging textures // - If there are only two iterations, we can just create one backend texture and then the // destination can be the second // - If there are more than two iterations, we need to ping pong back and forth between two // textures. We can still use the destination as the last iteration, but we'll need textures // for the iterative process. int real_iteration_count; if (job.GetIterationCount() > 1 && !job.GetIterativeInput().isEmpty()) { real_iteration_count = job.GetIterationCount(); } else { real_iteration_count = 1; } TexturePtr output_tex, input_tex; if (real_iteration_count > 1) { // Create one texture to bounce off output_tex = CreateTexture(destination_params); if (real_iteration_count > 2) { // Create a second texture bounce off input_tex = CreateTexture(destination_params); } } GLint iteration_location = functions_->glGetUniformLocation(shader, "ove_iteration"); for (int iteration=0; iteration<real_iteration_count; iteration++) { // Set iteration number if (iteration_location > -1) { functions_->glUniform1i(iteration_location, iteration); } // Replace iterative input if (iteration == real_iteration_count-1) { // This is the last iteration, draw to the destination if (destination) { // If we have a destination texture, draw to it AttachTextureAsDestination(destination->id()); } else if (iteration > 0) { // Otherwise, if we were iterating before, detach texture now DetachTextureAsDestination(); } // Clear the destination if the caller requested it if (clear_destination) { ClearDestinationInternal(); } } else { // Always draw to output_tex, which gets swapped with input_tex every iteration AttachTextureAsDestination(output_tex->id()); } if (iteration > 0) { // If this is not the first iteration, replace the iterative texture with the one we // last drew const QString &iterative_input = job.GetIterativeInput(); functions_->glActiveTexture(GL_TEXTURE0 + texture_index_map.value(iterative_input)); functions_->glBindTexture(GL_TEXTURE_2D, input_tex->id().value<GLuint>()); // At this time, we only support iterating 2D textures PrepareInputTexture(GL_TEXTURE_2D, job.GetInterpolation(iterative_input)); } // Swap so that the next iteration, the texture we draw now will be the input texture next std::swap(output_tex, input_tex); // Blit this texture through this shader { PRINT_GL_ERRORS; functions_->glDrawArrays(GL_TRIANGLES, 0, blit_vertices.size() / 3); } } if (destination) { // Reset framebuffer to default if we were drawing to a texture DetachTextureAsDestination(); } // Release any textures we bound before for (int i=textures_to_bind.size()-1; i>=0; i--) { TexturePtr texture = textures_to_bind.at(i).texture; GLenum target = (texture && texture->params().is_3d()) ? GL_TEXTURE_3D : GL_TEXTURE_2D; functions_->glActiveTexture(GL_TEXTURE0 + i); functions_->glBindTexture(target, 0); } // Release shader functions_->glUseProgram(0); // Release vertex array object frag_vbo_.destroy(); vert_vbo_.destroy(); vao_.release(); vao_.destroy(); } GLint OpenGLRenderer::GetInternalFormat(PixelFormat format, int channel_layout) { switch (format) { case PixelFormat::U8: switch (channel_layout) { case 1: return GL_R8; case 2: return GL_RG8; case 3: return GL_RGB8; case 4: return GL_RGBA8; } break; case PixelFormat::U16: switch (channel_layout) { case 1: return GL_R16; case 2: return GL_RG16; case 3: return GL_RGB16; case 4: return GL_RGBA16; } break; case PixelFormat::F16: switch (channel_layout) { case 1: return GL_R16F; case 2: return GL_RG16F; case 3: return GL_RGB16F; case 4: return GL_RGBA16F; } break; case PixelFormat::F32: switch (channel_layout) { case 1: return GL_R32F; case 2: return GL_RG32F; case 3: return GL_RGB32F; case 4: return GL_RGBA32F; } break; case PixelFormat::INVALID: case PixelFormat::COUNT: break; } return GL_INVALID_VALUE; } GLenum OpenGLRenderer::GetPixelType(PixelFormat format) { switch (format) { case PixelFormat::U8: return GL_UNSIGNED_BYTE; case PixelFormat::U16: return GL_UNSIGNED_SHORT; case PixelFormat::F16: return GL_HALF_FLOAT; case PixelFormat::F32: return GL_FLOAT; case PixelFormat::INVALID: case PixelFormat::COUNT: break; } return GL_INVALID_VALUE; } GLenum OpenGLRenderer::GetPixelFormat(int channel_count) { switch (channel_count) { case 1: return GL_RED; case 3: return GL_RGB; case 4: return GL_RGBA; default: return GL_INVALID_VALUE; } } void OpenGLRenderer::PrepareInputTexture(GLenum target, Texture::Interpolation interp) { switch (interp) { case Texture::kNearest: functions_->glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); functions_->glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); break; case Texture::kLinear: functions_->glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); functions_->glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); break; case Texture::kMipmappedLinear: functions_->glGenerateMipmap(target); functions_->glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); functions_->glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); break; } functions_->glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); functions_->glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (target == GL_TEXTURE_3D) { functions_->glTexParameteri(target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); } } void OpenGLRenderer::ClearDestinationInternal(double r, double g, double b, double a) { functions_->glClearColor(r, g, b, a); functions_->glClear(GL_COLOR_BUFFER_BIT); } GLuint OpenGLRenderer::CompileShader(GLenum type, const QString &code) { static const QString shader_preamble = // Use appropriate GL 3.2 shader header QStringLiteral("#version 150\n\n" "precision highp float;\n\n"); QString complete_code; if (!code.startsWith(QStringLiteral("#version"))) { complete_code = shader_preamble; } if (code.isEmpty()) { // Use default code if (type == GL_FRAGMENT_SHADER) { complete_code.append(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/default.frag"))); } else if (type == GL_VERTEX_SHADER) { complete_code.append(FileFunctions::ReadFileAsString(QStringLiteral(":/shaders/default.vert"))); } } else { complete_code.append(code); } QByteArray code_utf8 = complete_code.toUtf8(); const char *code_cstr = code_utf8.constData(); GLuint shader = functions_->glCreateShader(type); functions_->glShaderSource(shader, 1, &code_cstr, nullptr); functions_->glCompileShader(shader); GLint success; functions_->glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { qWarning() << "Failed to compile OpenGL shader"; QByteArray error_log(10240, Qt::Uninitialized); functions_->glGetShaderInfoLog(shader, error_log.size(), nullptr, error_log.data()); std::cout << error_log.constData() << std::endl << code_cstr << std::endl; functions_->glDeleteShader(shader); shader = 0; } return shader; } }
24,183
C++
.cpp
687
29.978166
149
0.679566
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,158
acceleratedjob.cpp
olive-editor_olive/app/render/job/acceleratedjob.cpp
/*** 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/>. ***/ #include "acceleratedjob.h" namespace olive { }
762
C++
.cpp
17
41.941176
71
0.773406
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,159
mainstatusbar.cpp
olive-editor_olive/app/window/mainwindow/mainstatusbar.cpp
/*** 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/>. ***/ #include "mainstatusbar.h" #include <QCoreApplication> namespace olive { MainStatusBar::MainStatusBar(QWidget *parent) : QStatusBar(parent), manager_(nullptr), connected_task_(nullptr) { setSizeGripEnabled(false); bar_ = new QProgressBar(); addPermanentWidget(bar_); bar_->setMinimum(0); bar_->setMaximum(100); bar_->setVisible(false); showMessage(tr("Welcome to %1 %2").arg(QCoreApplication::applicationName(), QCoreApplication::applicationVersion()), 10000); } void MainStatusBar::ConnectTaskManager(TaskManager *manager) { if (manager_) { disconnect(manager_, &TaskManager::TaskListChanged, this, &MainStatusBar::UpdateStatus); } manager_ = manager; if (manager_) { connect(manager_, &TaskManager::TaskListChanged, this, &MainStatusBar::UpdateStatus); } } void MainStatusBar::UpdateStatus() { if (!manager_) { return; } if (manager_->GetTaskCount() == 0) { clearMessage(); bar_->setVisible(false); bar_->setValue(0); } else { Task* t = manager_->GetFirstTask(); if (manager_->GetTaskCount() == 1) { showMessage(t->GetTitle()); } else { showMessage(tr("Running %n background task(s)", nullptr, manager_->GetTaskCount())); } bar_->setVisible(true); if (connected_task_) { disconnect(connected_task_, &Task::ProgressChanged, this, &MainStatusBar::SetProgressBarValue); disconnect(connected_task_, &Task::destroyed, this, &MainStatusBar::ConnectedTaskDeleted); } connected_task_ = t; connect(connected_task_, &Task::ProgressChanged, this, &MainStatusBar::SetProgressBarValue); connect(connected_task_, &Task::destroyed, this, &MainStatusBar::ConnectedTaskDeleted); } } void MainStatusBar::SetProgressBarValue(double d) { bar_->setValue(qRound(100.0 * d)); } void MainStatusBar::ConnectedTaskDeleted() { connected_task_ = nullptr; } void MainStatusBar::mouseDoubleClickEvent(QMouseEvent* e) { QStatusBar::mouseDoubleClickEvent(e); emit DoubleClicked(); } }
2,778
C++
.cpp
82
29.939024
101
0.719476
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,160
mainwindowlayoutinfo.cpp
olive-editor_olive/app/window/mainwindow/mainwindowlayoutinfo.cpp
#include "mainwindowlayoutinfo.h" namespace olive { void MainWindowLayoutInfo::toXml(QXmlStreamWriter *writer) const { writer->writeAttribute(QStringLiteral("version"), QString::number(kVersion)); writer->writeStartElement(QStringLiteral("folders")); foreach (Folder* folder, open_folders_) { writer->writeTextElement(QStringLiteral("folder"), QString::number(reinterpret_cast<quintptr>(folder))); } writer->writeEndElement(); // folders writer->writeStartElement(QStringLiteral("timeline")); foreach (Sequence *sequence, open_sequences_) { writer->writeTextElement(QStringLiteral("sequence"), QString::number(reinterpret_cast<quintptr>(sequence))); } writer->writeEndElement(); // timeline writer->writeStartElement(QStringLiteral("viewers")); foreach (Sequence *sequence, open_sequences_) { writer->writeTextElement(QStringLiteral("viewer"), QString::number(reinterpret_cast<quintptr>(sequence))); } writer->writeEndElement(); // viewers writer->writeStartElement(QStringLiteral("data")); for (auto it = panel_data_.cbegin(); it != panel_data_.cend(); it++) { writer->writeStartElement(QStringLiteral("panel")); writer->writeAttribute(QStringLiteral("id"), it->first); const PanelWidget::Info &info = it->second; for (auto jt = info.cbegin(); jt != info.cend(); jt++) { writer->writeStartElement(QStringLiteral("option")); writer->writeAttribute(QStringLiteral("name"), jt->first); writer->writeCharacters(jt->second); writer->writeEndElement(); // option } writer->writeEndElement(); // panel } writer->writeEndElement(); // data writer->writeTextElement(QStringLiteral("state"), QString(state_.toBase64())); } MainWindowLayoutInfo MainWindowLayoutInfo::fromXml(QXmlStreamReader *reader, const QHash<quintptr, Node *> &node_ptrs) { MainWindowLayoutInfo info; unsigned int file_version = 0; XMLAttributeLoop(reader, attr) { if (attr.name() == QStringLiteral("version")) { file_version = attr.value().toUInt(); } } // Really basic version checking, in the future we may use this to parse multiple versions if (file_version != kVersion) { } while (XMLReadNextStartElement(reader)) { if (reader->name() == QStringLiteral("folders")) { while (XMLReadNextStartElement(reader)) { if (reader->name() == QStringLiteral("folder")) { quintptr item_id = reader->readElementText().toULongLong(); Folder* open_item = static_cast<Folder*>(node_ptrs.value(item_id)); info.open_folders_.push_back(open_item); } else { reader->skipCurrentElement(); } } } else if (reader->name() == QStringLiteral("timeline")) { while (XMLReadNextStartElement(reader)) { if (reader->name() == QStringLiteral("sequence")) { quintptr item_id = reader->readElementText().toULongLong(); Sequence *open_seq = static_cast<Sequence*>(node_ptrs.value(item_id)); info.open_sequences_.push_back(open_seq); } else { reader->skipCurrentElement(); } } } else if (reader->name() == QStringLiteral("state")) { info.state_ = QByteArray::fromBase64(reader->readElementText().toLatin1()); } else if (reader->name() == QStringLiteral("data")) { while (XMLReadNextStartElement(reader)) { if (reader->name() == QStringLiteral("panel")) { QString id; XMLAttributeLoop(reader, attr) { if (attr.name() == QStringLiteral("id")) { id = attr.value().toString(); } } if (!id.isEmpty()) { PanelWidget::Info i; while (XMLReadNextStartElement(reader)) { if (reader->name() == QStringLiteral("option")) { QString name; XMLAttributeLoop(reader, attr) { if (attr.name() == QStringLiteral("name")) { name = attr.value().toString(); } } if (!name.isEmpty()) { i[name] = reader->readElementText(); } } else { reader->skipCurrentElement(); } } info.panel_data_[id] = i; } } else { reader->skipCurrentElement(); } } } else { reader->skipCurrentElement(); } } return info; } void MainWindowLayoutInfo::add_folder(olive::Folder *f) { open_folders_.push_back(f); } void MainWindowLayoutInfo::add_sequence(Sequence *seq) { open_sequences_.push_back(seq); } void MainWindowLayoutInfo::add_viewer(ViewerOutput *viewer) { open_viewers_.push_back(viewer); } void MainWindowLayoutInfo::set_panel_data(const QString &id, const PanelWidget::Info &data) { panel_data_[id] = data; } void MainWindowLayoutInfo::move_panel_data(const QString &old, const QString &now) { PanelWidget::Info tmp = panel_data_.at(old); panel_data_.erase(old); panel_data_[now] = tmp; } void MainWindowLayoutInfo::set_state(const QByteArray &layout) { state_ = layout; } }
5,143
C++
.cpp
136
31.095588
118
0.643938
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,161
mainwindow.cpp
olive-editor_olive/app/window/mainwindow/mainwindow.cpp
/*** 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/>. ***/ #include "mainwindow.h" #include <QApplication> #include <QDebug> #include <QMessageBox> #include <QScreen> #ifdef Q_OS_LINUX #include <QOffscreenSurface> #endif #include "dialog/about/about.h" #include "mainmenu.h" #include "mainstatusbar.h" #include "timeline/timelineundoworkarea.h" namespace olive { #define super KDDockWidgets::MainWindow MainWindow::MainWindow(QWidget *parent) : super(QStringLiteral("OliveMain"), KDDockWidgets::MainWindowOption_None, parent), project_(nullptr) { // Resizes main window to desktop geometry on startup. Fixes the following issues: // * Qt on Windows has a bug that "de-maximizes" the window when widgets are added, resizing the // window beforehand works around that issue and we just set it to whatever size is available. // * On Linux, it seems the window starts off at a vastly different size and then maximizes // which throws off the proportions and makes the resulting layout wonky. if (!qApp->screens().empty()) { resize(qApp->screens().at(0)->availableSize()); } #ifdef Q_OS_WINDOWS // Set up taskbar button progress bar (used for some modal tasks like exporting) taskbar_btn_id_ = RegisterWindowMessage(TEXT("TaskbarButtonCreated")); taskbar_interface_ = nullptr; #endif first_show_ = true; // Create and set main menu MainMenu* main_menu = new MainMenu(this); setMenuBar(main_menu); LoadCustomShortcuts(); // Create and set status bar MainStatusBar* status_bar = new MainStatusBar(this); status_bar->ConnectTaskManager(TaskManager::instance()); connect(status_bar, &MainStatusBar::DoubleClicked, this, &MainWindow::StatusBarDoubleClicked); setStatusBar(status_bar); // Create standard panels node_panel_ = new NodePanel(); footage_viewer_panel_ = new FootageViewerPanel(); param_panel_ = new ParamPanel(); curve_panel_ = new CurvePanel(); sequence_viewer_panel_ = new SequenceViewerPanel(); multicam_panel_ = new MulticamPanel(); pixel_sampler_panel_ = new PixelSamplerPanel(); project_panel_ = new ProjectPanel(QStringLiteral("ProjectPanel")); tool_panel_ = new ToolPanel(); task_man_panel_ = new TaskManagerPanel(); AppendTimelinePanel(); audio_monitor_panel_ = new AudioMonitorPanel(); scope_panel_ = new ScopePanel(); history_panel_ = new HistoryPanel(); // HACK: The pixel sampler is closed by default, which signals to Core that // it's no longer visible. However KDDockWidgets doesn't appear to // emit the "shown" signal before emitting the "hidden" signals, resulting // in Core thinking there are -1 pixel samplers open. To mitigate that, // we force "shown" to emit ourselves here. emit pixel_sampler_panel_->shown(); // Make node-related connections connect(node_panel_, &NodePanel::NodeSelectionChangedWithContexts, param_panel_, &ParamPanel::SetSelectedNodes); connect(node_panel_, &NodePanel::NodeGroupOpened, this, &MainWindow::NodePanelGroupOpenedOrClosed); connect(node_panel_, &NodePanel::NodeGroupClosed, this, &MainWindow::NodePanelGroupOpenedOrClosed); connect(param_panel_, &ParamPanel::FocusedNodeChanged, sequence_viewer_panel_, &ViewerPanel::SetGizmos); connect(param_panel_, &ParamPanel::RequestViewerToStartEditingText, sequence_viewer_panel_, &ViewerPanel::RequestStartEditingText); connect(param_panel_, &ParamPanel::FocusedNodeChanged, curve_panel_, &CurvePanel::SetNode); connect(param_panel_, &ParamPanel::SelectedNodesChanged, node_panel_, &NodePanel::Select); connect(project_panel_, &ProjectPanel::ProjectNameChanged, this, &MainWindow::UpdateTitle); connect(node_panel_, &NodePanel::NodeSelectionChanged, sequence_viewer_panel_, &ViewerPanel::SetNodeViewSelections); // Route play/pause/shuttle commands from these panels to the sequence viewer sequence_viewer_panel_->ConnectTimeBasedPanel(param_panel_); sequence_viewer_panel_->ConnectTimeBasedPanel(curve_panel_); sequence_viewer_panel_->ConnectTimeBasedPanel(multicam_panel_); connect(PanelManager::instance(), &PanelManager::FocusedPanelChanged, this, &MainWindow::FocusedPanelChanged); sequence_viewer_panel_->AddPlaybackDevice(multicam_panel_->GetMulticamWidget()->GetDisplayWidget()); sequence_viewer_panel_->ConnectMulticamWidget(multicam_panel_->GetMulticamWidget()); scope_panel_->SetViewerPanel(sequence_viewer_panel_); UpdateTitle(); QMetaObject::invokeMethod(this, &MainWindow::SetDefaultLayout, Qt::QueuedConnection); } MainWindow::~MainWindow() { #ifdef Q_OS_WINDOWS if (taskbar_interface_) { taskbar_interface_->Release(); } #endif } void MainWindow::LoadLayout(const MainWindowLayoutInfo &info) { foreach (Folder* folder, info.open_folders()) { OpenFolder(folder, true); } foreach (Sequence *sequence, info.open_sequences()) { OpenSequence(sequence, info.open_sequences().size() == 1); } foreach (ViewerOutput *viewer, info.open_viewers()) { OpenNodeInViewer(viewer); } for (auto it=info.panel_data().cbegin(); it!=info.panel_data().cend(); it++) { // Find panel with this ID if (PanelWidget *panel = PanelManager::instance()->GetPanelWithName(it->first)) { panel->LoadData(it->second); } } KDDockWidgets::LayoutSaver().restoreLayout(qUncompress(info.state())); } QString TransformNameForSerialization(const QString &unique, int i) { return QStringLiteral("%1:%2").arg(unique.split(':').at(0), QString::number(i)); } void CorrectPanelDataIfNecessary(const QString &unique_name, int index, MainWindowLayoutInfo &info, QByteArray &layout) { QString corrected = TransformNameForSerialization(unique_name, index); if (corrected != unique_name) { info.move_panel_data(unique_name, corrected); layout.replace(unique_name.toUtf8(), corrected.toUtf8()); } } MainWindowLayoutInfo MainWindow::SaveLayout() const { MainWindowLayoutInfo info; QByteArray layout = premaximized_state_.isEmpty() ? KDDockWidgets::LayoutSaver().serializeLayout() : premaximized_state_; foreach (PanelWidget *panel, PanelManager::instance()->panels()) { info.set_panel_data(panel->uniqueName(), panel->SaveData()); } for (int i = 0; i < folder_panels_.size(); i++) { auto panel = folder_panels_.at(i); info.add_folder(panel->get_root()); CorrectPanelDataIfNecessary(panel->uniqueName(), i, info, layout); } for (int i = 0; i < timeline_panels_.size(); i++) { auto panel = timeline_panels_.at(i); info.add_sequence(panel->GetSequence()); CorrectPanelDataIfNecessary(panel->uniqueName(), i, info, layout); } for (int i = 0; i < viewer_panels_.size(); i++) { auto panel = viewer_panels_.at(i); info.add_viewer(panel->GetConnectedViewer()); CorrectPanelDataIfNecessary(panel->uniqueName(), i, info, layout); } info.set_state(qCompress(layout)); return info; } TimelinePanel* MainWindow::OpenSequence(Sequence *sequence, bool enable_focus) { // See if this sequence is already open, and switch to it if so foreach (TimelinePanel* tl, timeline_panels_) { if (tl->GetConnectedViewer() == sequence) { tl->raise(); return tl; } } // See if we have any sequences open or not TimelinePanel* panel; if (!timeline_panels_.first()->GetConnectedViewer()) { panel = timeline_panels_.first(); } else { panel = AppendTimelinePanel(); //enable_focus = false; } panel->ConnectViewerNode(sequence); if (enable_focus) { TimelineFocused(sequence); UpdateAudioMonitorParams(sequence); } return panel; } void MainWindow::CloseSequence(Sequence *sequence) { // We defer to RemoveTimelinePanel() to close the panels, which may delete and remove indices from timeline_panels_. // We make a copy so that our array here doesn't get ruined by what RemoveTimelinePanel() does QList<TimelinePanel*> copy = timeline_panels_; foreach (TimelinePanel* tp, copy) { if (tp->GetConnectedViewer() == sequence) { RemoveTimelinePanel(tp); } } } bool MainWindow::IsSequenceOpen(Sequence *sequence) const { foreach (TimelinePanel* tp, timeline_panels_) { if (tp->GetConnectedViewer() == sequence) { return true; } } return false; } void MainWindow::OpenFolder(Folder *i, bool floating) { ProjectPanel* panel = AppendPanelInternal(QStringLiteral("FolderPanel"), folder_panels_); panel->set_project(i->project()); panel->set_root(i); if (floating) { panel->setFloating(floating); } else { project_panel_->addDockWidgetAsTab(panel); } // If the panel is closed, just destroy it connect(panel, &ProjectPanel::CloseRequested, this, &MainWindow::FolderPanelCloseRequested); } void MainWindow::OpenNodeInViewer(ViewerOutput *node) { ViewerPanel *existing = nullptr; for (auto it = viewer_panels_.cbegin(); it != viewer_panels_.cend(); it++) { ViewerPanel *it2 = (*it); if (it2->GetConnectedViewer() == node) { existing = it2; break; } } if (existing) { // This node already has a viewer, raise it existing->raise(); } else { // Create a viewer for this node ViewerPanel* viewer = AppendPanelInternal(QStringLiteral("ViewerPanel"), viewer_panels_); viewer->ConnectViewerNode(node); connect(viewer, &ViewerPanel::CloseRequested, this, &MainWindow::ViewerCloseRequested); connect(node, &ViewerOutput::RemovedFromGraph, this, &MainWindow::ViewerWithPanelRemovedFromGraph); } } void MainWindow::SetFullscreen(bool fullscreen) { if (fullscreen) { setWindowState(windowState() | Qt::WindowFullScreen); } else { setWindowState(windowState() & ~Qt::WindowFullScreen); } } void MainWindow::ToggleMaximizedPanel() { KDDockWidgets::LayoutSaver saver; if (premaximized_state_.isEmpty()) { // Assume nothing is maximized at the moment // Find the currently focused panel PanelWidget* currently_hovered = PanelManager::instance()->CurrentlyHovered(); // If no panel is hovered, fallback to the currently active panel if (!currently_hovered) { currently_hovered = PanelManager::instance()->CurrentlyFocused(); // If no panel is hovered or focused, do nothing if (!currently_hovered) { return; } } // If this panel is not actually on the main window, this is a no-op if (currently_hovered->isFloating()) { return; } // Save the current state so it can be restored later premaximized_state_ = saver.serializeLayout(); // For every other panel that is on the main window, hide it foreach (PanelWidget* panel, PanelManager::instance()->panels()) { if (!panel->isFloating() && panel != currently_hovered) { panel->close(); } } } else { // Preserve currently focused panel auto currently_focused_panel = PanelManager::instance()->CurrentlyFocused(false); // Assume we are currently maximized, restore the state PanelManager::instance()->SetSuppressChangedSignal(true); saver.restoreLayout(premaximized_state_); premaximized_state_.clear(); currently_focused_panel->raise(); currently_focused_panel->setFocus(); PanelManager::instance()->SetSuppressChangedSignal(false); } } void MainWindow::SetProject(Project *p) { if (project_ == p) { return; } if (project_) { // Clear all data param_panel_->SetContexts(QVector<Node*>()); node_panel_->SetContexts(QVector<Node*>()); // Close any nodes open in TimeBasedWidgets foreach (PanelWidget* panel, PanelManager::instance()->panels()) { TimeBasedPanel* tbp = dynamic_cast<TimeBasedPanel*>(panel); if (tbp && tbp->GetConnectedViewer() && tbp->GetConnectedViewer()->project() == project_) { if (dynamic_cast<TimelinePanel*>(tbp)) { // Prefer our CloseSequence function which will delete any unnecessary timeline panels CloseSequence(static_cast<Sequence*>(tbp->GetConnectedViewer())); } else { tbp->DisconnectViewerNode(); } } } // Close any extra folder panels foreach (ProjectPanel* panel, folder_panels_) { panel->close(); } // Close any extra viewer panels foreach (ViewerPanel *viewer, viewer_panels_) { viewer->close(); } } project_ = p; project_panel_->set_project(p); if (project_) { project_panel_->setFocus(); } } void MainWindow::SetApplicationProgressStatus(ProgressStatus status) { #if defined(Q_OS_WINDOWS) if (taskbar_interface_) { switch (status) { case kProgressShow: taskbar_interface_->SetProgressState(reinterpret_cast<HWND>(this->winId()), TBPF_NORMAL); break; case kProgressNone: taskbar_interface_->SetProgressState(reinterpret_cast<HWND>(this->winId()), TBPF_NOPROGRESS); break; case kProgressError: taskbar_interface_->SetProgressState(reinterpret_cast<HWND>(this->winId()), TBPF_ERROR); break; } } #elif defined(Q_OS_MAC) #endif } void MainWindow::SetApplicationProgressValue(int value) { #if defined(Q_OS_WINDOWS) if (taskbar_interface_) { taskbar_interface_->SetProgressValue(reinterpret_cast<HWND>(this->winId()), value, 100); } #elif defined(Q_OS_MAC) #endif } void MainWindow::SelectFootage(const QVector<Footage *> &e) { SelectFootageForProjectPanel(e, project_panel_); for (ProjectPanel *p : folder_panels_) { SelectFootageForProjectPanel(e, p); } } void MainWindow::closeEvent(QCloseEvent *e) { // Try to close all projects (this will return false if the user chooses not to close) if (!Core::instance()->CloseProject(false)) { e->ignore(); return; } scope_panel_->SetViewerPanel(nullptr); PanelManager::instance()->DeleteAllPanels(); SaveCustomShortcuts(); QMainWindow::closeEvent(e); } #ifdef Q_OS_WINDOWS bool MainWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) { if (static_cast<MSG*>(message)->message == taskbar_btn_id_) { // Attempt to create taskbar button progress handle HRESULT hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, reinterpret_cast<void**>(&taskbar_interface_)); if (SUCCEEDED(hr)) { hr = taskbar_interface_->HrInit(); if (FAILED(hr)) { taskbar_interface_->Release(); taskbar_interface_ = nullptr; } } } return QMainWindow::nativeEvent(eventType, message, result); } #endif void MainWindow::StatusBarDoubleClicked() { task_man_panel_->show(); task_man_panel_->raise(); } void MainWindow::NodePanelGroupOpenedOrClosed() { NodePanel *p = static_cast<NodePanel*>(sender()); param_panel_->SetContexts(p->GetContexts()); } void MainWindow::TimelinePanelSelectionChanged(const QVector<Block *> &blocks) { TimelinePanel *panel = static_cast<TimelinePanel *>(sender()); if (PanelManager::instance()->CurrentlyFocused(false) == panel) { UpdateNodePanelContextFromTimelinePanel(panel); sequence_viewer_panel_->SetTimelineSelectedBlocks(blocks); } } void MainWindow::ShowWelcomeDialog() { if (OLIVE_CONFIG("ShowWelcomeDialog").toBool()) { AboutDialog ad(true, this); ad.exec(); } } void MainWindow::RevealViewerInProject(ViewerOutput *r) { // Rather than just using the resident ProjectPanel, find the most recently focused one since // that's probably the one people will want auto panels = PanelManager::instance()->GetPanelsOfType<ProjectPanel>(); foreach (ProjectPanel *p, panels) { if (p->SelectItem(r)) { break; } } } void MainWindow::RevealViewerInFootageViewer(ViewerOutput *r, const TimeRange &range) { footage_viewer_panel_->ConnectViewerNode(r); auto command = new MultiUndoCommand(); if (!r->GetWorkArea()->enabled()) { command->add_child(new WorkareaSetEnabledCommand(r->project(), r->GetWorkArea(), true)); } command->add_child(new WorkareaSetRangeCommand(r->GetWorkArea(), range)); Core::instance()->undo_stack()->push(command, tr("Set Footage Workarea")); r->SetPlayhead(range.in()); } #ifdef Q_OS_LINUX void MainWindow::ShowNouveauWarning() { QMessageBox::warning(this, tr("Driver Warning"), tr("Olive has detected your system is using the Nouveau graphics driver.\n\nThis driver is " "known to have stability and performance issues with Olive. It is highly recommended " "you install the proprietary NVIDIA driver before continuing to use Olive."), QMessageBox::Ok); } #endif void MainWindow::UpdateTitle() { if (Core::instance()->GetActiveProject()) { setWindowTitle(QStringLiteral("%1 %2 - [*]%3").arg(QApplication::applicationName(), QApplication::applicationVersion(), Core::instance()->GetActiveProject()->pretty_filename())); } else { setWindowTitle(QStringLiteral("%1 %2").arg(QApplication::applicationName(), QApplication::applicationVersion())); } } void MainWindow::TimelineCloseRequested() { TimelinePanel *t = static_cast<TimelinePanel*>(sender()); RemoveTimelinePanel(t); } void MainWindow::ViewerCloseRequested() { ViewerPanel* panel = static_cast<ViewerPanel*>(sender()); if (panel == scope_panel_->GetConnectedViewerPanel()) { scope_panel_->SetViewerPanel(sequence_viewer_panel_); } RemovePanelInternal(viewer_panels_, panel); panel->deleteLater(); } void MainWindow::ViewerWithPanelRemovedFromGraph() { ViewerOutput* vo = static_cast<ViewerOutput*>(sender()); ViewerPanel *panel = nullptr; foreach (ViewerPanel *p, viewer_panels_) { if (p->GetConnectedViewer() == vo) { panel = p; break; } } if (panel) { RemovePanelInternal(viewer_panels_, panel); panel->deleteLater(); disconnect(vo, &ViewerOutput::RemovedFromGraph, this, &MainWindow::ViewerWithPanelRemovedFromGraph); } } void MainWindow::FolderPanelCloseRequested() { ProjectPanel* panel = static_cast<ProjectPanel*>(sender()); RemovePanelInternal(folder_panels_, panel); panel->deleteLater(); } TimelinePanel* MainWindow::AppendTimelinePanel() { TimelinePanel *previous = nullptr; if (!timeline_panels_.empty()) { previous = timeline_panels_.last(); } TimelinePanel* panel = AppendPanelInternal(QStringLiteral("TimelinePanel"), timeline_panels_); if (previous) { previous->addDockWidgetAsTab(panel); } else { panel->SetSignalInsteadOfClose(false); } connect(panel, &PanelWidget::CloseRequested, this, &MainWindow::TimelineCloseRequested); connect(panel, &TimelinePanel::RequestCaptureStart, sequence_viewer_panel_, &SequenceViewerPanel::StartCapture); connect(panel, &TimelinePanel::BlockSelectionChanged, this, &MainWindow::TimelinePanelSelectionChanged); connect(panel, &TimelinePanel::RevealViewerInProject, this, &MainWindow::RevealViewerInProject); connect(panel, &TimelinePanel::RevealViewerInFootageViewer, this, &MainWindow::RevealViewerInFootageViewer); sequence_viewer_panel_->ConnectTimeBasedPanel(panel); return panel; } void MainWindow::RemoveTimelinePanel(TimelinePanel *panel) { // Stop showing this timeline in the viewer TimelineFocused(nullptr); panel->ConnectViewerNode(nullptr); if (timeline_panels_.size() != 1) { RemovePanelInternal(timeline_panels_, panel); panel->deleteLater(); } } void MainWindow::TimelineFocused(ViewerOutput* viewer) { sequence_viewer_panel_->ConnectViewerNode(viewer); multicam_panel_->ConnectViewerNode(viewer); param_panel_->ConnectViewerNode(viewer); curve_panel_->ConnectViewerNode(viewer); } QString MainWindow::GetCustomShortcutsFile() { return QDir(FileFunctions::GetConfigurationLocation()).filePath(QStringLiteral("shortcuts")); } void LoadCustomShortcutsInternal(QMenu* menu, const QMap<QString, QString>& shortcuts) { QList<QAction*> actions = menu->actions(); foreach (QAction* a, actions) { if (a->menu()) { LoadCustomShortcutsInternal(a->menu(), shortcuts); } else if (!a->isSeparator()) { QString action_id = a->property("id").toString(); if (shortcuts.contains(action_id)) { a->setShortcut(shortcuts.value(action_id)); } } } } void MainWindow::LoadCustomShortcuts() { QFile shortcut_file(GetCustomShortcutsFile()); if (shortcut_file.exists() && shortcut_file.open(QFile::ReadOnly)) { QMap<QString, QString> shortcuts; QString shortcut_str = QString::fromUtf8(shortcut_file.readAll()); QStringList shortcut_list = shortcut_str.split(QStringLiteral("\n")); foreach (const QString& s, shortcut_list) { QStringList shortcut_line = s.split(QStringLiteral("\t")); if (shortcut_line.size() >= 2) { shortcuts.insert(shortcut_line.at(0), shortcut_line.at(1)); } } shortcut_file.close(); if (!shortcuts.isEmpty()) { QList<QAction*> menus = menuBar()->actions(); foreach (QAction* menu, menus) { LoadCustomShortcutsInternal(menu->menu(), shortcuts); } } } } void SaveCustomShortcutsInternal(QMenu* menu, QMap<QString, QString>* shortcuts) { QList<QAction*> actions = menu->actions(); foreach (QAction* a, actions) { if (a->menu()) { SaveCustomShortcutsInternal(a->menu(), shortcuts); } else if (!a->isSeparator()) { QString default_shortcut = a->property("keydefault").value<QKeySequence>().toString(); QString current_shortcut = a->shortcut().toString(); if (current_shortcut != default_shortcut) { QString action_id = a->property("id").toString(); shortcuts->insert(action_id, current_shortcut); } } } } void MainWindow::SaveCustomShortcuts() { QMap<QString, QString> shortcuts; QList<QAction*> menus = menuBar()->actions(); foreach (QAction* menu, menus) { SaveCustomShortcutsInternal(menu->menu(), &shortcuts); } QFile shortcut_file(GetCustomShortcutsFile()); if (shortcuts.isEmpty()) { if (shortcut_file.exists()) { // No custom shortcuts, remove any existing file shortcut_file.remove(); } } else if (shortcut_file.open(QFile::WriteOnly)) { for (auto it=shortcuts.cbegin(); it!=shortcuts.cend(); it++) { if (it != shortcuts.cbegin()) { shortcut_file.write(QStringLiteral("\n").toUtf8()); } shortcut_file.write(it.key().toUtf8()); shortcut_file.write(QStringLiteral("\t").toUtf8()); shortcut_file.write(it.value().toUtf8()); } shortcut_file.close(); } else { qCritical() << "Failed to save custom keyboard shortcuts"; } } void MainWindow::UpdateAudioMonitorParams(ViewerOutput *viewer) { if (!audio_monitor_panel_->IsPlaying()) { audio_monitor_panel_->SetParams(viewer ? viewer->GetAudioParams() : AudioParams()); } } void MainWindow::UpdateNodePanelContextFromTimelinePanel(TimelinePanel *panel) { // Add selected blocks (if any) const QVector<Block*> &blocks = panel->GetSelectedBlocks(); QVector<Node *> context(blocks.size()); for (int i=0; i<blocks.size(); i++) { context[i] = blocks.at(i); } // If no selected blocks, set the context to the sequence ViewerOutput *viewer = panel->GetConnectedViewer(); if (viewer && context.isEmpty()) { context.append(viewer); } node_panel_->SetContexts(context); param_panel_->SetContexts(context); } void MainWindow::SelectFootageForProjectPanel(const QVector<Footage *> &e, ProjectPanel *p) { p->DeselectAll(); for (Footage *f : e) { if (p->get_root()->HasChildRecursive(f)) { p->SelectItem(f, false); } } } void MainWindow::FocusedPanelChanged(PanelWidget *panel) { // Update audio monitor panel if (TimeBasedPanel* tbp = dynamic_cast<TimeBasedPanel*>(panel)) { UpdateAudioMonitorParams(tbp->GetConnectedViewer()); } if (NodePanel *node_panel = dynamic_cast<NodePanel*>(panel)) { // Set param view contexts to these const QVector<Node*> &new_ctxs = node_panel->GetContexts(); if (new_ctxs != param_panel_->GetContexts()) { param_panel_->SetContexts(new_ctxs); } } else if (TimelinePanel* timeline = dynamic_cast<TimelinePanel*>(panel)) { // Signal timeline focus TimelineFocused(timeline->GetConnectedViewer()); UpdateNodePanelContextFromTimelinePanel(timeline); } else if (ProjectPanel* project = dynamic_cast<ProjectPanel*>(panel)) { // Signal project panel focus Q_UNUSED(project) UpdateTitle(); } else if (ViewerPanelBase *viewer = dynamic_cast<ViewerPanelBase*>(panel)) { // Update scopes for viewer scope_panel_->SetViewerPanel(viewer); } } void MainWindow::SetDefaultLayout() { KDDockWidgets::InitialOption o; o.preferredSize = QSize(0, centralAreaGeometry().height()); // Top left - Tabify footage viewer, param panel, and node panel addDockWidget(footage_viewer_panel_, KDDockWidgets::Location_OnTop, nullptr, o); footage_viewer_panel_->addDockWidgetAsTab(param_panel_); footage_viewer_panel_->addDockWidgetAsTab(node_panel_); param_panel_->raise(); // Top right - sequence viewer addDockWidget(sequence_viewer_panel_, KDDockWidgets::Location_OnRight, footage_viewer_panel_, o); // Bottom center - timelines addDockWidget(timeline_panels_.first(), KDDockWidgets::Location_OnBottom); // Left of timeline - tool panel o.preferredSize = QSize(1, 0); addDockWidget(tool_panel_, KDDockWidgets::Location_OnLeft, timeline_panels_.first(), o); // Right of timeline - audio monitor o.preferredSize = QSize(320, 0); addDockWidget(audio_monitor_panel_, KDDockWidgets::Location_OnRight, timeline_panels_.first(), o); // Bottom left - project panel addDockWidget(project_panel_, KDDockWidgets::Location_OnLeft, tool_panel_); project_panel_->addDockWidgetAsTab(history_panel_); project_panel_->raise(); // Hidden panels pixel_sampler_panel_->close(); task_man_panel_->close(); curve_panel_->close(); scope_panel_->close(); multicam_panel_->close(); for (auto it = folder_panels_.cbegin(); it != folder_panels_.cend(); it++) { (*it)->close(); } for (auto it = viewer_panels_.cbegin(); it != viewer_panels_.cend(); it++) { (*it)->close(); } for (auto it = timeline_panels_.cbegin(); it != timeline_panels_.cend(); it++) { auto p = *it; if (p != timeline_panels_.first()) { p->addDockWidgetAsTab(p); } } // Set to unmaximized panels premaximized_state_.clear(); } void MainWindow::showEvent(QShowEvent *e) { QMainWindow::showEvent(e); if (first_show_) { QMetaObject::invokeMethod(Core::instance(), "CheckForAutoRecoveries", Qt::QueuedConnection); #ifdef Q_OS_LINUX // Check for nouveau since that driver really doesn't work with Olive QOffscreenSurface surface; surface.create(); QOpenGLContext context; context.create(); context.makeCurrent(&surface); const char* vendor = reinterpret_cast<const char*>(context.functions()->glGetString(GL_VENDOR)); qDebug() << "Using graphics driver:" << vendor; if (!strcmp(vendor, "nouveau")) { QMetaObject::invokeMethod(this, "ShowNouveauWarning", Qt::QueuedConnection); } #endif QMetaObject::invokeMethod(this, "ShowWelcomeDialog", Qt::QueuedConnection); first_show_ = false; } } template<typename T> T *MainWindow::AppendPanelInternal(const QString &panel_name, QList<T*>& list) { T* panel = new T(TransformNameForSerialization(panel_name, list.size())); // For some reason raise() on its own doesn't do anything, we need both panel->show(); panel->raise(); list.append(panel); // Let us handle the panel closing rather than the panel itself panel->SetSignalInsteadOfClose(true); return panel; } template<typename T> void MainWindow::RemovePanelInternal(QList<T *> &list, T *panel) { list.removeOne(panel); } }
28,641
C++
.cpp
755
33.765563
133
0.712322
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,162
mainwindowundo.cpp
olive-editor_olive/app/window/mainwindow/mainwindowundo.cpp
/*** 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/>. ***/ #include "mainwindowundo.h" #include "core.h" #include "window/mainwindow/mainwindow.h" namespace olive { void OpenSequenceCommand::redo() { Core::instance()->main_window()->OpenSequence(sequence_); } void OpenSequenceCommand::undo() { Core::instance()->main_window()->CloseSequence(sequence_); } void CloseSequenceCommand::redo() { Core::instance()->main_window()->CloseSequence(sequence_); } void CloseSequenceCommand::undo() { Core::instance()->main_window()->OpenSequence(sequence_); } }
1,219
C++
.cpp
35
32.542857
71
0.765158
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,163
mainmenu.cpp
olive-editor_olive/app/window/mainwindow/mainmenu.cpp
/*** 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/>. ***/ #include "mainmenu.h" #include <QActionGroup> #include <QDesktopServices> #include <QEvent> #include <QStyleFactory> #include "config/config.h" #include "core.h" #include "dialog/actionsearch/actionsearch.h" #include "dialog/diskcache/diskcachedialog.h" #include "dialog/task/task.h" #include "panel/panelmanager.h" #include "tool/tool.h" #include "ui/style/style.h" #include "undo/undostack.h" #include "widget/menu/menushared.h" #include "mainwindow.h" namespace olive { MainMenu::MainMenu(MainWindow *parent) : QMenuBar(parent) { // // FILE MENU // file_menu_ = new Menu(this, this, &MainMenu::FileMenuAboutToShow); file_new_menu_ = new Menu(file_menu_); MenuShared::instance()->AddItemsForNewMenu(file_new_menu_); file_open_item_ = file_menu_->AddItem("openproj", Core::instance(), &Core::OpenProject, tr("Ctrl+O")); file_open_recent_menu_ = new Menu(file_menu_); file_open_recent_separator_ = file_open_recent_menu_->addSeparator(); file_open_recent_clear_item_ = file_open_recent_menu_->AddItem("clearopenrecent", Core::instance(), &Core::ClearOpenRecentList); file_save_item_ = file_menu_->AddItem("saveproj", Core::instance(), &Core::SaveProject, tr("Ctrl+S")); file_save_as_item_ = file_menu_->AddItem("saveprojas", Core::instance(), &Core::SaveProjectAs, tr("Ctrl+Shift+S")); file_menu_->addSeparator(); file_revert_item_ = file_menu_->AddItem("revert", Core::instance(), &Core::RevertProject, tr("F12")); file_menu_->addSeparator(); file_import_item_ = file_menu_->AddItem("import", Core::instance(), &Core::DialogImportShow, tr("Ctrl+I")); file_menu_->addSeparator(); file_export_menu_ = new Menu(file_menu_); file_export_media_item_ = file_export_menu_->AddItem("export", Core::instance(), &Core::DialogExportShow, tr("Ctrl+M")); file_menu_->addSeparator(); file_project_properties_item_ = file_menu_->AddItem("projectproperties", Core::instance(), &Core::DialogProjectPropertiesShow, tr("Shift+F10")); file_menu_->addSeparator(); file_exit_item_ = file_menu_->AddItem("exit", parent, &MainWindow::close); // // EDIT MENU // edit_menu_ = new Menu(this); connect(edit_menu_, &Menu::aboutToShow, this, &MainMenu::EditMenuAboutToShow); connect(edit_menu_, &Menu::aboutToHide, this, &MainMenu::EditMenuAboutToHide); edit_undo_item_ = Core::instance()->undo_stack()->GetUndoAction(); Menu::ConformItem(edit_undo_item_, "undo", tr("Ctrl+Z")); edit_menu_->addAction(edit_undo_item_); edit_redo_item_ = Core::instance()->undo_stack()->GetRedoAction(); Menu::ConformItem(edit_redo_item_, "redo", tr("Ctrl+Shift+Z")); edit_menu_->addAction(edit_redo_item_); edit_menu_->addSeparator(); MenuShared::instance()->AddItemsForEditMenu(edit_menu_, true); { // Create "alternate delete" action so we can pick up backspace as well as delete while still // keeping them configurable edit_delete2_item_ = new QAction(); Menu::ConformItem(edit_delete2_item_, "delete2", MenuShared::instance(), &MenuShared::DeleteSelectedTriggered, tr("Backspace")); auto actions = edit_menu_->actions(); edit_menu_->insertAction(actions.at(actions.indexOf(MenuShared::instance()->edit_delete_item()) + 1), edit_delete2_item_); } edit_menu_->addSeparator(); edit_select_all_item_ = edit_menu_->AddItem("selectall", this, &MainMenu::SelectAllTriggered, tr("Ctrl+A")); edit_deselect_all_item_ = edit_menu_->AddItem("deselectall", this, &MainMenu::DeselectAllTriggered, tr("Ctrl+Shift+A")); edit_menu_->addSeparator(); MenuShared::instance()->AddItemsForClipEditMenu(edit_menu_); edit_menu_->addSeparator(); edit_insert_item_ = edit_menu_->AddItem("insert", this, &MainMenu::InsertTriggered, tr(",")); edit_overwrite_item_ = edit_menu_->AddItem("overwrite", this, &MainMenu::OverwriteTriggered, tr(".")); edit_menu_->addSeparator(); edit_ripple_to_in_item_ = edit_menu_->AddItem("rippletoin", this, &MainMenu::RippleToInTriggered, tr("Q")); edit_ripple_to_out_item_ = edit_menu_->AddItem("rippletoout", this, &MainMenu::RippleToOutTriggered, tr("W")); edit_edit_to_in_item_ = edit_menu_->AddItem("edittoin", this, &MainMenu::EditToInTriggered, tr("Ctrl+Alt+Q")); edit_edit_to_out_item_ = edit_menu_->AddItem("edittoout", this, &MainMenu::EditToOutTriggered, tr("Ctrl+Alt+W")); edit_menu_->addSeparator(); edit_nudge_left_item_ = edit_menu_->AddItem("nudgeleft", this, &MainMenu::NudgeLeftTriggered, tr("Alt+Left")); edit_nudge_right_item_ = edit_menu_->AddItem("nudgeright", this, &MainMenu::NudgeRightTriggered, tr("Alt+Right")); edit_move_in_to_playhead_item_ = edit_menu_->AddItem("moveintoplayhead", this, &MainMenu::MoveInToPlayheadTriggered, tr("[")); edit_move_out_to_playhead_item_ = edit_menu_->AddItem("moveouttoplayhead", this, &MainMenu::MoveOutToPlayheadTriggered, tr("]")); edit_menu_->addSeparator(); MenuShared::instance()->AddItemsForInOutMenu(edit_menu_); edit_delete_inout_item_ = edit_menu_->AddItem("deleteinout", this, &MainMenu::DeleteInOutTriggered, tr(";")); edit_ripple_delete_inout_item_ = edit_menu_->AddItem("rippledeleteinout", this, &MainMenu::RippleDeleteInOutTriggered, tr("'")); edit_menu_->addSeparator(); edit_set_marker_item_ = edit_menu_->AddItem("marker", this, &MainMenu::SetMarkerTriggered, tr("M")); // // VIEW MENU // view_menu_ = new Menu(this, this, &MainMenu::ViewMenuAboutToShow); view_zoom_in_item_ = view_menu_->AddItem("zoomin", this, &MainMenu::ZoomInTriggered, tr("=")); view_zoom_out_item_ = view_menu_->AddItem("zoomout", this, &MainMenu::ZoomOutTriggered, tr("-")); view_increase_track_height_item_ = view_menu_->AddItem("vzoomin", this, &MainMenu::IncreaseTrackHeightTriggered, tr("Ctrl+=")); view_decrease_track_height_item_ = view_menu_->AddItem("vzoomout", this, &MainMenu::DecreaseTrackHeightTriggered, tr("Ctrl+-")); view_show_all_item_ = view_menu_->AddItem("showall", this, &MainMenu::ToggleShowAllTriggered, tr("\\")); view_show_all_item_->setCheckable(true); view_menu_->addSeparator(); view_full_screen_item_ = view_menu_->AddItem("fullscreen", parent, &MainWindow::SetFullscreen, tr("F11")); view_full_screen_item_->setCheckable(true); view_full_screen_viewer_item_ = view_menu_->AddItem("fullscreenviewer", this, &MainMenu::FullScreenViewerTriggered); // // PLAYBACK MENU // playback_menu_ = new Menu(this, this, &MainMenu::PlaybackMenuAboutToShow); playback_gotostart_item_ = playback_menu_->AddItem("gotostart", this, &MainMenu::GoToStartTriggered, tr("Home")); playback_prevframe_item_ = playback_menu_->AddItem("prevframe", this, &MainMenu::PrevFrameTriggered, tr("Left")); playback_playpause_item_ = playback_menu_->AddItem("playpause", this, &MainMenu::PlayPauseTriggered, tr("Space")); playback_playinout_item_ = playback_menu_->AddItem("playintoout", this, &MainMenu::PlayInToOutTriggered, tr("Shift+Space")); playback_nextframe_item_ = playback_menu_->AddItem("nextframe", this, &MainMenu::NextFrameTriggered, tr("Right")); playback_gotoend_item_ = playback_menu_->AddItem("gotoend", this, &MainMenu::GoToEndTriggered, tr("End")); playback_menu_->addSeparator(); playback_prevcut_item_ = playback_menu_->AddItem("prevcut", this, &MainMenu::GoToPrevCutTriggered, tr("Up")); playback_nextcut_item_ = playback_menu_->AddItem("nextcut", this, &MainMenu::GoToNextCutTriggered, tr("Down")); playback_menu_->addSeparator(); playback_gotoin_item_ = playback_menu_->AddItem("gotoin", this, &MainMenu::GoToInTriggered, tr("Shift+I")); playback_gotoout_item_ = playback_menu_->AddItem("gotoout", this, &MainMenu::GoToOutTriggered, tr("Shift+O")); playback_menu_->addSeparator(); playback_shuttleleft_item_ = playback_menu_->AddItem("decspeed", this, &MainMenu::ShuttleLeftTriggered, tr("J")); playback_shuttlestop_item_ = playback_menu_->AddItem("pause", this, &MainMenu::ShuttleStopTriggered, tr("K")); playback_shuttleright_item_ = playback_menu_->AddItem("incspeed", this, &MainMenu::ShuttleRightTriggered, tr("L")); playback_menu_->addSeparator(); playback_loop_item_ = playback_menu_->AddItem("loop", this, &MainMenu::LoopTriggered); playback_loop_item_->setCheckable(true); // // SEQUENCE MENU // sequence_menu_ = new Menu(this, this, &MainMenu::SequenceMenuAboutToShow); sequence_cache_item_ = sequence_menu_->AddItem("seqcache", this, &MainMenu::SequenceCacheTriggered); sequence_cache_in_to_out_item_ = sequence_menu_->AddItem("seqcacheinout", this, &MainMenu::SequenceCacheInOutTriggered); sequence_menu_->addSeparator(); sequence_disk_cache_clear_item_ = sequence_menu_->AddItem("seqcacheclear", this, &MainMenu::SequenceCacheClearTriggered); // TEMP: Hide sequence cache items for now. Want to see if clip caching will supersede it. sequence_cache_item_->setVisible(false); sequence_cache_in_to_out_item_->setVisible(false); // // WINDOW MENU // window_menu_ = new Menu(this, this, &MainMenu::WindowMenuAboutToShow); window_menu_separator_ = window_menu_->addSeparator(); window_maximize_panel_item_ = window_menu_->AddItem("maximizepanel", parent, &MainWindow::ToggleMaximizedPanel, tr("`")); window_menu_->addSeparator(); window_reset_layout_item_ = window_menu_->AddItem("resetdefaultlayout", parent, &MainWindow::SetDefaultLayout); // // TOOLS MENU // tools_menu_ = new Menu(this, this, &MainMenu::ToolsMenuAboutToShow); tools_menu_->setToolTipsVisible(true); tools_group_ = new QActionGroup(this); tools_pointer_item_ = tools_menu_->AddItem("pointertool", this, &MainMenu::ToolItemTriggered, tr("V")); tools_pointer_item_->setCheckable(true); tools_pointer_item_->setData(Tool::kPointer); tools_group_->addAction(tools_pointer_item_); tools_trackselect_item_ = tools_menu_->AddItem("trackselecttool", this, &MainMenu::ToolItemTriggered, tr("D")); tools_trackselect_item_->setCheckable(true); tools_trackselect_item_->setData(Tool::kTrackSelect); tools_group_->addAction(tools_trackselect_item_); tools_edit_item_ = tools_menu_->AddItem("edittool", this, &MainMenu::ToolItemTriggered, tr("X")); tools_edit_item_->setCheckable(true); tools_edit_item_->setData(Tool::kEdit); tools_group_->addAction(tools_edit_item_); tools_ripple_item_ = tools_menu_->AddItem("rippletool", this, &MainMenu::ToolItemTriggered, tr("B")); tools_ripple_item_->setCheckable(true); tools_ripple_item_->setData(Tool::kRipple); tools_group_->addAction(tools_ripple_item_); tools_rolling_item_ = tools_menu_->AddItem("rollingtool", this, &MainMenu::ToolItemTriggered, tr("N")); tools_rolling_item_->setCheckable(true); tools_rolling_item_->setData(Tool::kRolling); tools_group_->addAction(tools_rolling_item_); tools_razor_item_ = tools_menu_->AddItem("razortool", this, &MainMenu::ToolItemTriggered, tr("C")); tools_razor_item_->setCheckable(true); tools_razor_item_->setData(Tool::kRazor); tools_group_->addAction(tools_razor_item_); tools_slip_item_ = tools_menu_->AddItem("sliptool", this, &MainMenu::ToolItemTriggered, tr("Y")); tools_slip_item_->setCheckable(true); tools_slip_item_->setData(Tool::kSlip); tools_group_->addAction(tools_slip_item_); tools_slide_item_ = tools_menu_->AddItem("slidetool", this, &MainMenu::ToolItemTriggered, tr("U")); tools_slide_item_->setCheckable(true); tools_slide_item_->setData(Tool::kSlide); tools_group_->addAction(tools_slide_item_); tools_hand_item_ = tools_menu_->AddItem("handtool", this, &MainMenu::ToolItemTriggered, tr("H")); tools_hand_item_->setCheckable(true); tools_hand_item_->setData(Tool::kHand); tools_group_->addAction(tools_hand_item_); tools_zoom_item_ = tools_menu_->AddItem("zoomtool", this, &MainMenu::ToolItemTriggered, tr("Z")); tools_zoom_item_->setCheckable(true); tools_zoom_item_->setData(Tool::kZoom); tools_group_->addAction(tools_zoom_item_); tools_transition_item_ = tools_menu_->AddItem("transitiontool", this, &MainMenu::ToolItemTriggered, tr("T")); tools_transition_item_->setCheckable(true); tools_transition_item_->setData(Tool::kTransition); tools_group_->addAction(tools_transition_item_); tools_add_item_ = tools_menu_->AddItem("addtool", this, &MainMenu::ToolItemTriggered, tr("A")); tools_add_item_->setCheckable(true); tools_add_item_->setData(Tool::kAdd); tools_group_->addAction(tools_add_item_); tools_record_item_ = tools_menu_->AddItem("recordtool", this, &MainMenu::ToolItemTriggered, tr("R")); tools_record_item_->setCheckable(true); tools_record_item_->setData(Tool::kRecord); tools_group_->addAction(tools_record_item_); tools_menu_->addSeparator(); tools_add_item_menu_ = new Menu(tools_menu_); tools_menu_->addMenu(tools_add_item_menu_); MenuShared::instance()->AddItemsForAddableObjectsMenu(tools_add_item_menu_); tools_menu_->addSeparator(); tools_snapping_item_ = tools_menu_->AddItem("snapping", Core::instance(), &Core::SetSnapping, tr("S")); tools_snapping_item_->setCheckable(true); tools_snapping_item_->setChecked(Core::instance()->snapping()); tools_menu_->addSeparator(); tools_preferences_item_ = tools_menu_->AddItem("prefs", Core::instance(), &Core::DialogPreferencesShow, tr("Ctrl+,")); #ifndef NDEBUG tools_magic_item_ = tools_menu_->AddItem("magic", Core::instance(), &Core::SetMagic); tools_magic_item_->setCheckable(true); #endif // // HELP MENU // help_menu_ = new Menu(this); help_action_search_item_ = help_menu_->AddItem("actionsearch", this, &MainMenu::ActionSearchTriggered, tr("/")); help_menu_->addSeparator(); help_feedback_item_ = help_menu_->AddItem("feedback", this, &MainMenu::HelpFeedbackTriggered); help_menu_->addSeparator(); help_about_item_ = help_menu_->AddItem("about", Core::instance(), &Core::DialogAboutShow); connect(Core::instance(), &Core::OpenRecentListChanged, this, &MainMenu::RepopulateOpenRecent); PopulateOpenRecent(); Retranslate(); } void MainMenu::changeEvent(QEvent *e) { if (e->type() == QEvent::LanguageChange) { Retranslate(); } QMenuBar::changeEvent(e); } void MainMenu::ToolItemTriggered() { // Assume the sender is a QAction QAction* action = static_cast<QAction*>(sender()); // Assume its data() is a member of Tool::Item Tool::Item tool = static_cast<Tool::Item>(action->data().toInt()); // Set the Tool in Core Core::instance()->SetTool(tool); } void MainMenu::FileMenuAboutToShow() { Project* active_project = Core::instance()->GetActiveProject(); file_save_item_->setEnabled(active_project); file_save_as_item_->setEnabled(active_project); if (active_project) { file_save_item_->setText(tr("&Save '%1'").arg(active_project->name())); file_save_as_item_->setText(tr("Save '%1' &As").arg(active_project->name())); } else { file_save_item_->setText(tr("&Save Project")); file_save_as_item_->setText(tr("Save Project &As")); } } void MainMenu::EditMenuAboutToShow() { edit_delete2_item_->setVisible(false); } void MainMenu::EditMenuAboutToHide() { edit_delete2_item_->setVisible(true); } void MainMenu::ViewMenuAboutToShow() { // Parent is QMainWindow view_full_screen_item_->setChecked(parentWidget()->isFullScreen()); // Make sure we're displaying the correct options for the timebase TimeBasedPanel* p = PanelManager::instance()->MostRecentlyFocused<TimeBasedPanel>(); if (p) { if (p->timebase().denominator() != 0) { view_menu_->addSeparator(); MenuShared::instance()->AddItemsForTimeRulerMenu(view_menu_); } } // Ensure checked timecode display mode is correct MenuShared::instance()->AboutToShowTimeRulerActions(p->timebase()); } void MainMenu::ToolsMenuAboutToShow() { // Ensure checked Tool is correct QList<QAction*> tool_actions = tools_group_->actions(); foreach (QAction* a, tool_actions) { if (a->data() == Core::instance()->tool()) { a->setChecked(true); break; } } // Ensure snapping value is correct tools_snapping_item_->setChecked(Core::instance()->snapping()); } void MainMenu::PlaybackMenuAboutToShow() { playback_loop_item_->setChecked(OLIVE_CONFIG("Loop").toBool()); } void MainMenu::SequenceMenuAboutToShow() { TimeBasedPanel* p = PanelManager::instance()->MostRecentlyFocused<TimeBasedPanel>(); bool can_cache_sequence = (p && p->GetConnectedViewer()); sequence_cache_item_->setEnabled(can_cache_sequence); sequence_cache_in_to_out_item_->setEnabled(can_cache_sequence); } void MainMenu::WindowMenuAboutToShow() { // Remove any previous items while (window_menu_->actions().first() != window_menu_separator_) { window_menu_->removeAction(window_menu_->actions().first()); } QList<QAction*> panel_actions; // Alphabetize actions - keeps actions in a consistent order since PanelManager::panels() is // ordered from most recently focused to least, which may be confusing user experience. foreach (PanelWidget* panel, PanelManager::instance()->panels()) { QAction* panel_action = panel->toggleAction(); bool inserted = false; for (int i=0;i<panel_actions.size();i++) { if (panel_actions.at(i)->text() > panel_action->text()) { panel_actions.insert(i, panel_action); inserted = true; break; } } if (!inserted) { panel_actions.append(panel_action); } } // Add new items window_menu_->insertActions(window_menu_separator_, panel_actions); } void MainMenu::PopulateOpenRecent() { if (Core::instance()->GetRecentProjects().isEmpty()) { // Insert dummy/disabled action to show there's nothing QAction* a = new QAction(tr("(None)")); a->setEnabled(false); file_open_recent_menu_->insertAction(file_open_recent_separator_, a); } else { // Populate menu with recently opened projects for (int i=0;i<Core::instance()->GetRecentProjects().size();i++) { QAction* a = new QAction(Core::instance()->GetRecentProjects().at(i)); a->setData(i); connect(a, &QAction::triggered, this, &MainMenu::OpenRecentItemTriggered); file_open_recent_menu_->insertAction(file_open_recent_separator_, a); } } } void MainMenu::RepopulateOpenRecent() { CloseOpenRecentMenu(); PopulateOpenRecent(); } void MainMenu::CloseOpenRecentMenu() { while (file_open_recent_menu_->actions().first() != file_open_recent_separator_) { file_open_recent_menu_->removeAction(file_open_recent_menu_->actions().first()); } } void MainMenu::ZoomInTriggered() { PanelManager::instance()->CurrentlyFocused()->ZoomIn(); } void MainMenu::ZoomOutTriggered() { PanelManager::instance()->CurrentlyFocused()->ZoomOut(); } void MainMenu::IncreaseTrackHeightTriggered() { PanelManager::instance()->CurrentlyFocused()->IncreaseTrackHeight(); } void MainMenu::DecreaseTrackHeightTriggered() { PanelManager::instance()->CurrentlyFocused()->DecreaseTrackHeight(); } void MainMenu::GoToStartTriggered() { PanelManager::instance()->CurrentlyFocused()->GoToStart(); } void MainMenu::PrevFrameTriggered() { PanelManager::instance()->CurrentlyFocused()->PrevFrame(); } void MainMenu::PlayPauseTriggered() { PanelManager::instance()->CurrentlyFocused()->PlayPause(); } void MainMenu::PlayInToOutTriggered() { PanelManager::instance()->CurrentlyFocused()->PlayInToOut(); } void MainMenu::LoopTriggered(bool enabled) { OLIVE_CONFIG("Loop") = enabled; } void MainMenu::NextFrameTriggered() { PanelManager::instance()->CurrentlyFocused()->NextFrame(); } void MainMenu::GoToEndTriggered() { PanelManager::instance()->CurrentlyFocused()->GoToEnd(); } void MainMenu::SelectAllTriggered() { PanelManager::instance()->CurrentlyFocused()->SelectAll(); } void MainMenu::DeselectAllTriggered() { PanelManager::instance()->CurrentlyFocused()->DeselectAll(); } void MainMenu::InsertTriggered() { FootageManagementPanel* project_panel = PanelManager::instance()->MostRecentlyFocused<FootageManagementPanel>(); TimelinePanel *timeline_panel = PanelManager::instance()->MostRecentlyFocused<TimelinePanel>(); if (project_panel && timeline_panel) { timeline_panel->InsertFootageAtPlayhead(project_panel->GetSelectedFootage()); } } void MainMenu::OverwriteTriggered() { FootageManagementPanel* project_panel = PanelManager::instance()->MostRecentlyFocused<FootageManagementPanel>(); TimelinePanel *timeline_panel = PanelManager::instance()->MostRecentlyFocused<TimelinePanel>(); if (project_panel && timeline_panel) { timeline_panel->OverwriteFootageAtPlayhead(project_panel->GetSelectedFootage()); } } void MainMenu::RippleToInTriggered() { PanelManager::instance()->CurrentlyFocused()->RippleToIn(); } void MainMenu::RippleToOutTriggered() { PanelManager::instance()->CurrentlyFocused()->RippleToOut(); } void MainMenu::EditToInTriggered() { PanelManager::instance()->CurrentlyFocused()->EditToIn(); } void MainMenu::EditToOutTriggered() { PanelManager::instance()->CurrentlyFocused()->EditToOut(); } void MainMenu::NudgeLeftTriggered() { PanelManager::instance()->CurrentlyFocused()->NudgeLeft(); } void MainMenu::NudgeRightTriggered() { PanelManager::instance()->CurrentlyFocused()->NudgeRight(); } void MainMenu::MoveInToPlayheadTriggered() { PanelManager::instance()->CurrentlyFocused()->MoveInToPlayhead(); } void MainMenu::MoveOutToPlayheadTriggered() { PanelManager::instance()->CurrentlyFocused()->MoveOutToPlayhead(); } void MainMenu::ActionSearchTriggered() { ActionSearch as(parentWidget()); as.SetMenuBar(this); as.exec(); } void MainMenu::ShuttleLeftTriggered() { PanelManager::instance()->CurrentlyFocused()->ShuttleLeft(); } void MainMenu::ShuttleStopTriggered() { PanelManager::instance()->CurrentlyFocused()->ShuttleStop(); } void MainMenu::ShuttleRightTriggered() { PanelManager::instance()->CurrentlyFocused()->ShuttleRight(); } void MainMenu::GoToPrevCutTriggered() { PanelManager::instance()->CurrentlyFocused()->GoToPrevCut(); } void MainMenu::GoToNextCutTriggered() { PanelManager::instance()->CurrentlyFocused()->GoToNextCut(); } void MainMenu::SetMarkerTriggered() { PanelManager::instance()->CurrentlyFocused()->SetMarker(); } void MainMenu::FullScreenViewerTriggered() { PanelManager::instance()->MostRecentlyFocused<ViewerPanel>()->SetFullScreen(); } void MainMenu::ToggleShowAllTriggered() { PanelManager::instance()->CurrentlyFocused()->ToggleShowAll(); } void MainMenu::DeleteInOutTriggered() { PanelManager::instance()->CurrentlyFocused()->DeleteInToOut(); } void MainMenu::RippleDeleteInOutTriggered() { PanelManager::instance()->CurrentlyFocused()->RippleDeleteInToOut(); } void MainMenu::GoToInTriggered() { PanelManager::instance()->CurrentlyFocused()->GoToIn(); } void MainMenu::GoToOutTriggered() { PanelManager::instance()->CurrentlyFocused()->GoToOut(); } void MainMenu::OpenRecentItemTriggered() { Core::instance()->OpenProjectFromRecentList(static_cast<QAction*>(sender())->data().toInt()); } void MainMenu::SequenceCacheTriggered() { Core::instance()->CacheActiveSequence(false); } void MainMenu::SequenceCacheInOutTriggered() { Core::instance()->CacheActiveSequence(true); } void MainMenu::SequenceCacheClearTriggered() { DiskCacheDialog::ClearDiskCache( Core::instance()->GetActiveProject()->cache_path(), Core::instance()->main_window() ); } void MainMenu::HelpFeedbackTriggered() { QDesktopServices::openUrl(QStringLiteral("https://github.com/olive-editor/olive/issues")); } void MainMenu::Retranslate() { // MenuShared is not a QWidget and therefore does not receive a LanguageEvent, we use MainMenu's to update it MenuShared::instance()->Retranslate(); // File menu file_menu_->setTitle(tr("&File")); file_new_menu_->setTitle(tr("&New")); file_open_item_->setText(tr("&Open Project")); file_open_recent_menu_->setTitle(tr("Open &Recent")); file_open_recent_clear_item_->setText(tr("&Clear Recent List")); file_revert_item_->setText(tr("Revert")); file_import_item_->setText(tr("&Import...")); file_export_menu_->setTitle(tr("&Export")); file_export_media_item_->setText(tr("&Media...")); file_project_properties_item_->setText(tr("Project Properties")); file_exit_item_->setText(tr("E&xit")); // Edit menu edit_menu_->setTitle(tr("&Edit")); Core::instance()->undo_stack()->UpdateActions(); // Update undo and redo edit_delete2_item_->setText(tr("Delete (alt)")); edit_insert_item_->setText(tr("Insert")); edit_overwrite_item_->setText(tr("Overwrite")); edit_select_all_item_->setText(tr("Select &All")); edit_deselect_all_item_->setText(tr("Deselect All")); edit_ripple_to_in_item_->setText(tr("Ripple to In Point")); edit_ripple_to_out_item_->setText(tr("Ripple to Out Point")); edit_edit_to_in_item_->setText(tr("Edit to In Point")); edit_edit_to_out_item_->setText(tr("Edit to Out Point")); edit_nudge_left_item_->setText(tr("Nudge Left")); edit_nudge_right_item_->setText(tr("Nudge Right")); edit_move_in_to_playhead_item_->setText(tr("Move In Point to Playhead")); edit_move_out_to_playhead_item_->setText(tr("Move Out Point to Playhead")); edit_delete_inout_item_->setText(tr("Delete In/Out Point")); edit_ripple_delete_inout_item_->setText(tr("Ripple Delete In/Out Point")); edit_set_marker_item_->setText(tr("Set/Edit Marker")); // View menu view_menu_->setTitle(tr("&View")); view_zoom_in_item_->setText(tr("Zoom In")); view_zoom_out_item_->setText(tr("Zoom Out")); view_increase_track_height_item_->setText(tr("Increase Track Height")); view_decrease_track_height_item_->setText(tr("Decrease Track Height")); view_show_all_item_->setText(tr("Toggle Show All")); // View menu (cont'd) view_full_screen_item_->setText(tr("Full Screen")); view_full_screen_viewer_item_->setText(tr("Full Screen Viewer")); // Playback menu playback_menu_->setTitle(tr("&Playback")); playback_gotostart_item_->setText(tr("Go to Start")); playback_prevframe_item_->setText(tr("Previous Frame")); playback_playpause_item_->setText(tr("Play/Pause")); playback_playinout_item_->setText(tr("Play In to Out")); playback_nextframe_item_->setText(tr("Next Frame")); playback_gotoend_item_->setText(tr("Go to End")); playback_prevcut_item_->setText(tr("Go to Previous Cut")); playback_nextcut_item_->setText(tr("Go to Next Cut")); playback_gotoin_item_->setText(tr("Go to In Point")); playback_gotoout_item_->setText(tr("Go to Out Point")); playback_shuttleleft_item_->setText(tr("Shuttle Left")); playback_shuttlestop_item_->setText(tr("Shuttle Stop")); playback_shuttleright_item_->setText(tr("Shuttle Right")); playback_loop_item_->setText(tr("Loop")); // Sequence menu sequence_menu_->setTitle(tr("&Sequence")); sequence_cache_item_->setText(tr("Cache Entire Sequence")); sequence_cache_in_to_out_item_->setText(tr("Cache Sequence In/Out")); sequence_disk_cache_clear_item_->setText(tr("Clear Disk Cache")); // Window menu window_menu_->setTitle(tr("&Window")); window_maximize_panel_item_->setText(tr("Maximize Panel")); window_reset_layout_item_->setText(tr("Reset to Default Layout")); // Tools menu tools_menu_->setTitle(tr("&Tools")); tools_pointer_item_->setText(tr("Pointer Tool")); tools_trackselect_item_->setText(tr("Track Select Tool")); tools_edit_item_->setText(tr("Edit Tool")); tools_ripple_item_->setText(tr("Ripple Tool")); tools_rolling_item_->setText(tr("Rolling Tool")); tools_razor_item_->setText(tr("Razor Tool")); tools_slip_item_->setText(tr("Slip Tool")); tools_slide_item_->setText(tr("Slide Tool")); tools_hand_item_->setText(tr("Hand Tool")); tools_zoom_item_->setText(tr("Zoom Tool")); tools_transition_item_->setText(tr("Transition Tool")); tools_add_item_->setText(tr("Add Tool")); tools_record_item_->setText(tr("Record Tool")); tools_snapping_item_->setText(tr("Enable Snapping")); tools_preferences_item_->setText(tr("Preferences")); tools_add_item_menu_->setTitle(tr("Add Tool Item")); #ifndef NDEBUG tools_magic_item_->setText("Magic"); #endif // Help menu help_menu_->setTitle(tr("&Help")); help_action_search_item_->setText(tr("A&ction Search")); help_feedback_item_->setText(tr("Send &Feedback...")); help_about_item_->setText(tr("&About...")); } }
28,922
C++
.cpp
649
41.710324
146
0.725434
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,164
crashhandler.cpp
olive-editor_olive/app/crashhandler/crashhandler.cpp
/*** 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/>. ***/ #include "crashhandler.h" #include <QApplication> #include <QCloseEvent> #include <QDir> #include <QFile> #include <QFontDatabase> #include <QLabel> #include <QHttpMultiPart> #include <QMessageBox> #include <QNetworkAccessManager> #include <QProcess> #include <QScrollBar> #include <QSplitter> #include <QThread> #include <QTimer> #include <QVBoxLayout> #include "common/crashpadutils.h" #include "common/filefunctions.h" #include "version.h" namespace olive { CrashHandlerDialog::CrashHandlerDialog(const QString& report_path) { setWindowTitle(tr("Olive")); setWindowFlags(Qt::WindowStaysOnTopHint); report_filename_ = report_path; waiting_for_upload_ = false; QVBoxLayout* layout = new QVBoxLayout(this); layout->addWidget(new QLabel(tr("We're sorry, Olive has crashed. Please help us fix it by " "sending an error report."))); QSplitter* splitter = new QSplitter(Qt::Vertical); splitter->setChildrenCollapsible(false); layout->addWidget(splitter); summary_edit_ = new QTextEdit(); summary_edit_->setPlaceholderText(tr("Describe what you were doing in as much detail as " "possible. If you can, provide steps to reproduce this crash.")); splitter->addWidget(summary_edit_); QWidget* crash_widget = new QWidget(); QVBoxLayout* crash_widget_layout = new QVBoxLayout(crash_widget); crash_widget_layout->setMargin(0); crash_widget_layout->addWidget(new QLabel(tr("Crash Report:"))); crash_report_ = new QTextEdit(); crash_report_->setReadOnly(true); crash_report_->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); crash_widget_layout->addWidget(crash_report_); splitter->addWidget(crash_widget); QHBoxLayout* btn_layout = new QHBoxLayout(); btn_layout->setMargin(0); btn_layout->addStretch(); send_report_btn_ = new QPushButton(tr("Send Error Report")); connect(send_report_btn_, &QPushButton::clicked, this, &CrashHandlerDialog::SendErrorReport); btn_layout->addWidget(send_report_btn_); dont_send_btn_ = new QPushButton(tr("Don't Send")); connect(dont_send_btn_, &QPushButton::clicked, this, &CrashHandlerDialog::reject); btn_layout->addWidget(dont_send_btn_); layout->addLayout(btn_layout); crash_report_->setEnabled(false); send_report_btn_->setEnabled(false); crash_report_->setText(tr("Waiting for crash report to be generated...")); GenerateReport(); } void CrashHandlerDialog::SetGUIObjectsEnabled(bool e) { summary_edit_->setEnabled(e); crash_report_->setEnabled(e); send_report_btn_->setEnabled(e); dont_send_btn_->setEnabled(e); } QString CrashHandlerDialog::GetSymbolPath() { QDir app_path(qApp->applicationDirPath()); QString symbols_path; #if BUILDFLAG(IS_WIN) symbols_path = app_path.filePath(QStringLiteral("symbols")); #elif BUILDFLAG(IS_LINUX) app_path.cdUp(); symbols_path = app_path.filePath(QStringLiteral("share/olive-editor/symbols")); #elif BUILDFLAG(IS_APPLE) app_path.cdUp(); symbols_path = app_path.filePath(QStringLiteral("Resources/symbols")); #endif return symbols_path; } void CrashHandlerDialog::GenerateReport() { QProcess* p = new QProcess(); connect(p, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &CrashHandlerDialog::ReadProcessFinished); connect(p, &QProcess::readyReadStandardOutput, this, &CrashHandlerDialog::ReadProcessHasData); QString stackwalk_filename = FileFunctions::GetFormattedExecutableForPlatform(QStringLiteral("minidump_stackwalk")); QString stackwalk_bin = QDir(qApp->applicationDirPath()).filePath(stackwalk_filename); p->start(stackwalk_bin, {report_filename_, GetSymbolPath()}); crash_report_->setText(QStringLiteral("Trying to run: %1").arg(stackwalk_bin)); } void CrashHandlerDialog::ReplyFinished(QNetworkReply* reply) { waiting_for_upload_ = false; if (reply->error() == QNetworkReply::NoError) { // Close dialog QDialog::accept(); } else { QMessageBox b(this); b.setIcon(QMessageBox::Critical); b.setWindowModality(Qt::WindowModal); b.setWindowTitle(tr("Upload Failed")); b.setText(tr("Failed to send error report (%1). Please try again later.").arg(QString::number(reply->error()))); b.addButton(QMessageBox::Ok); b.exec(); SetGUIObjectsEnabled(true); } } void CrashHandlerDialog::HandleSslErrors(QNetworkReply *reply, const QList<QSslError> &se) { QStringList errors; for (const QSslError &err : se) { errors.append(err.errorString()); } QMessageBox b(this); b.setIcon(QMessageBox::Critical); b.setWindowModality(Qt::WindowModal); b.setWindowTitle(tr("SSL Error")); b.setText(tr("Encountered the following SSL errors:\n\n%1").arg(errors.join('\n'))); b.addButton(QMessageBox::Ok); b.exec(); } void CrashHandlerDialog::AttemptToFindReport() { // If we found it, use it, otherwise wait a second and try again if (report_filename_.isEmpty()) { // Couldn't find report, try again in one second QTimer::singleShot(500, this, &CrashHandlerDialog::AttemptToFindReport); } else { GenerateReport(); } } void CrashHandlerDialog::ReadProcessHasData() { report_data_.append(static_cast<QProcess*>(sender())->readAllStandardOutput()); } void CrashHandlerDialog::ReadProcessFinished() { SetGUIObjectsEnabled(true); crash_report_->setText(report_data_); delete sender(); } void CrashHandlerDialog::SendErrorReport() { if (summary_edit_->document()->isEmpty()) { QMessageBox b(this); b.setIcon(QMessageBox::Question); b.setWindowModality(Qt::WindowModal); b.setText(tr("You must write a description to submit this crash report.")); b.addButton(QMessageBox::Ok); b.exec(); return; } QNetworkAccessManager* manager = new QNetworkAccessManager(); connect(manager, &QNetworkAccessManager::finished, this, &CrashHandlerDialog::ReplyFinished); connect(manager, &QNetworkAccessManager::sslErrors, this, &CrashHandlerDialog::HandleSslErrors); QNetworkRequest request; request.setSslConfiguration(QSslConfiguration::defaultConfiguration()); request.setUrl(QStringLiteral("https://olivevideoeditor.org/crashpad/report.php")); // Create HTTP form QHttpMultiPart* multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType); // Create description section QHttpPart desc_part; desc_part.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("text/plain; charset=UTF-8")); desc_part.setHeader(QNetworkRequest::ContentDispositionHeader, QStringLiteral("form-data; name=\"description\"")); desc_part.setBody(summary_edit_->toPlainText().toUtf8()); multipart->append(desc_part); // Create report section QHttpPart report_part; report_part.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("text/plain; charset=UTF-8")); report_part.setHeader(QNetworkRequest::ContentDispositionHeader, QStringLiteral("form-data; name=\"report\"")); report_part.setBody(report_data_); multipart->append(report_part); // Create commit section QHttpPart commit_part; commit_part.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("text/plain; charset=UTF-8")); commit_part.setHeader(QNetworkRequest::ContentDispositionHeader, QStringLiteral("form-data; name=\"commit\"")); commit_part.setBody(kAppVersionLong.toUtf8()); multipart->append(commit_part); // Create dump section QHttpPart dump_part; dump_part.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/octet-stream")); dump_part.setHeader(QNetworkRequest::ContentDispositionHeader, QStringLiteral("form-data; name=\"dump\"; filename=\"%1\"") .arg(QFileInfo(report_filename_).fileName())); QFile* dump_file = new QFile(report_filename_); dump_file->open(QFile::ReadOnly); dump_part.setBodyDevice(dump_file); dump_file->setParent(multipart); // Delete file with multipart multipart->append(dump_part); // Find symbol file QDir symbol_dir(GetSymbolPath()); QString symbol_bin_name; #if BUILDFLAG(IS_WIN) symbol_bin_name = QStringLiteral("olive-editor.pdb"); #elif BUILDFLAG(IS_APPLE) symbol_bin_name = QStringLiteral("Olive"); #else symbol_bin_name = QStringLiteral("olive-editor"); #endif symbol_dir = QDir(symbol_dir.filePath(symbol_bin_name)); QStringList folders_in_symbol_path = symbol_dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); if (folders_in_symbol_path.size() > 0) { symbol_dir = QDir(symbol_dir.filePath(folders_in_symbol_path.first())); } else { QMessageBox b(this); b.setIcon(QMessageBox::Critical); b.setWindowModality(Qt::WindowModal); b.setWindowTitle(tr("Failed to send report")); b.setText(tr("Failed to find symbols necessary to send report. " "This is a packaging issue. Please notify " "the maintainers of this package.")); b.addButton(QMessageBox::Ok); b.exec(); return; } // Create sym section QString symbol_filename; #if BUILDFLAG(IS_APPLE) symbol_filename = QStringLiteral("Olive.sym"); #else symbol_filename = QStringLiteral("olive-editor.sym"); #endif QString symbol_full_path = symbol_dir.filePath(symbol_filename); QHttpPart sym_part; sym_part.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/octet-stream")); sym_part.setHeader(QNetworkRequest::ContentDispositionHeader, QStringLiteral("form-data; name=\"sym\"; filename=\"%1\"") .arg(symbol_filename)); QFile sym_file(symbol_full_path); if (!sym_file.open(QFile::ReadOnly)) { QMessageBox b(this); b.setIcon(QMessageBox::Critical); b.setWindowModality(Qt::WindowModal); b.setWindowTitle(tr("Failed to send report")); b.setText(tr("Failed to open symbol file. You may not have " "permission to access it.")); b.addButton(QMessageBox::Ok); b.exec(); return; } QByteArray symbol_data = qCompress(sym_file.readAll(), 9); sym_file.close(); sym_part.setBody(symbol_data); multipart->append(sym_part); manager->post(request, multipart); SetGUIObjectsEnabled(false); waiting_for_upload_ = true; } void CrashHandlerDialog::closeEvent(QCloseEvent* e) { QMessageBox b(this); b.setIcon(QMessageBox::Warning); b.setWindowModality(Qt::WindowModal); b.setWindowTitle(tr("Confirm Close")); b.setText(tr("Crash report is still uploading. Closing now may result in no " "report being sent. Are you sure you wish to close?")); b.addButton(QMessageBox::Ok); b.addButton(QMessageBox::Cancel); if (waiting_for_upload_ && b.exec() == QMessageBox::Cancel) { e->ignore(); } else { e->accept(); } } } int main(int argc, char *argv[]) { QString report; #ifdef Q_OS_WINDOWS int num_args; LPWSTR *args = CommandLineToArgvW(GetCommandLineW(), &num_args); if (num_args < 2) { LocalFree(args); return 1; } report = QString::fromWCharArray(args[1]); LocalFree(args); #else if (argc < 2) { return 1; } report = argv[1]; #endif QApplication a(argc, argv); olive::CrashHandlerDialog chd(report); chd.open(); return a.exec(); }
11,826
C++
.cpp
303
35.419142
124
0.738124
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,165
testutil.h
olive-editor_olive/tests/testutil.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/>. ***/ #include <iostream> #define OLIVE_TEST_SUCCESS -1 #define OLIVE_ASSERT(x) if (!(x)) return __LINE__ #define OLIVE_ASSERT_EQUAL(x, y) if (x != y) {std::cout << " - Equal assert failed: " << x << " != " << y; return __LINE__;}void() #define OLIVE_TEST_END return OLIVE_TEST_SUCCESS #define OLIVE_ADD_TEST(x) int Test##x() #define OLIVE_ADD_DISABLED_TEST(x) int Test##x()
1,084
C++
.h
21
49.047619
130
0.733397
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,166
version.h
olive-editor_olive/app/version.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 GITHASH_H #define GITHASH_H #include <QString> namespace olive { extern QString kAppVersion; extern QString kAppVersionLong; } #endif // GITHASH_H
872
C++
.h
22
37.045455
71
0.780691
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,167
core.h
olive-editor_olive/app/core.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 CORE_H #define CORE_H #include <olive/core/core.h> #include <QFileInfoList> #include <QList> #include <QTimer> #include <QTranslator> #include "node/project/footage/footage.h" #include "node/project.h" #include "node/project/sequence/sequence.h" #include "task/task.h" #include "tool/tool.h" #include "undo/undostack.h" #include "widget/projectexplorer/projectviewmodel.h" namespace olive { class MainWindow; /** * @brief The main central Olive application instance * * This runs both in GUI and CLI modes (and handles what to init based on that). * It also contains various global functions/variables for use throughout Olive. * * The "public slots" are usually user-triggered actions and can be connected to UI elements (e.g. creating a folder, * opening the import dialog, etc.) */ class Core : public QObject { Q_OBJECT public: class CoreParams { public: CoreParams(); enum RunMode { kRunNormal, kHeadlessExport, kHeadlessPreCache }; bool fullscreen() const { return run_fullscreen_; } void set_fullscreen(bool e) { run_fullscreen_ = e; } RunMode run_mode() const { return mode_; } void set_run_mode(RunMode m) { mode_ = m; } const QString startup_project() const { return startup_project_; } void set_startup_project(const QString& p) { startup_project_ = p; } const QString& startup_language() const { return startup_language_; } void set_startup_language(const QString& s) { startup_language_ = s; } bool crash_on_startup() const { return crash_; } void set_crash_on_startup(bool e) { crash_ = true; } private: RunMode mode_; QString startup_project_; QString startup_language_; bool run_fullscreen_; bool crash_; }; /** * @brief Core Constructor * * Currently empty */ Core(const CoreParams& params); /** * @brief Core object accessible from anywhere in the code * * Use this to access Core functions. */ static Core* instance(); const CoreParams& core_params() const { return core_params_; } /** * @brief Start Olive Core * * Main application launcher. Parses command line arguments and constructs main window (if entering a GUI mode). */ void Start(); /** * @brief Stop Olive Core * * Ends all threads and frees all memory ready for the application to exit. */ void Stop(); /** * @brief Retrieve main window instance * * @return * * Pointer to the olive::MainWindow object, or nullptr if running in CLI mode. */ MainWindow* main_window(); /** * @brief Retrieve UndoStack object */ UndoStack* undo_stack(); /** * @brief Import a list of files * * FIXME: I kind of hate this, it needs a model to update correctly. Is there a way that Items can signal enough to * make passing references to the model unnecessary? * * @param urls */ void ImportFiles(const QStringList& urls, Folder *parent); /** * @brief Get the currently active tool */ const Tool::Item& tool() const; /** * @brief Get the currently selected object that the add tool should make (if the add tool is active) */ const Tool::AddableObject& GetSelectedAddableObject() const; /** * @brief Get the currently selected node that the transition tool should make (if the transition tool is active) */ const QString& GetSelectedTransition() const; /** * @brief Get current snapping value */ const bool& snapping() const; /** * @brief Returns a list of the most recently opened/saved projects */ const QStringList& GetRecentProjects() const; /** * @brief Get the currently active project * * Uses the UI/Panel system to determine which Project was the last focused on and assumes this is the active Project * that the user wishes to work on. * * @return * * The active Project file, or nullptr if the heuristic couldn't find one. */ Project* GetActiveProject() const; Folder* GetSelectedFolderInActiveProject() const; /** * @brief Gets current timecode display mode */ Timecode::Display GetTimecodeDisplay() const; /** * @brief Sets current timecode display mode */ void SetTimecodeDisplay(Timecode::Display d); /** * @brief Set how frequently an autorecovery should be saved (if the project has changed, see SetProjectModified()) */ void SetAutorecoveryInterval(int minutes); static void CopyStringToClipboard(const QString& s); static QString PasteStringFromClipboard(); /** * @brief Recursively count files in a file/directory list */ static int CountFilesInFileList(const QFileInfoList &filenames); /** * @brief Show a dialog to the user to rename a set of nodes */ bool LabelNodes(const QVector<Node *> &nodes, MultiUndoCommand *parent = nullptr); /** * @brief Create a new sequence named appropriately for the active project */ static Sequence* CreateNewSequenceForProject(const QString &format, Project *project); static Sequence* CreateNewSequenceForProject(Project *project) { return CreateNewSequenceForProject(tr("Sequence %1"), project); } /** * @brief Opens a project from the recently opened list */ void OpenProjectFromRecentList(int index); /** * @brief Closes a project */ bool CloseProject(bool auto_open_new, bool ignore_modified = false); /** * @brief Runs a modal cache task on the currently active sequence */ void CacheActiveSequence(bool in_out_only); /** * @brief Check each footage object for whether it still exists or has changed */ bool ValidateFootageInLoadedProject(Project* project, const QString &project_saved_url); /** * @brief Changes the current language */ bool SetLanguage(const QString& locale); /** * @brief Show message in main window's status bar * * Shorthand for Core::instance()->main_window()->statusBar()->showMessage(); */ void ShowStatusBarMessage(const QString& s, int timeout = 0); void ClearStatusBarMessage(); void OpenRecoveryProject(const QString& filename); void OpenNodeInViewer(ViewerOutput* viewer); void OpenExportDialogForViewer(ViewerOutput *viewer, bool start_still_image); bool IsMagicEnabled() const { return magic_; } public slots: /** * @brief Starts an open file dialog to load a project from file */ void OpenProject(); /** * @brief Saves the current project */ bool SaveProject(); /** * @brief Performs a "save as" on the current project */ bool SaveProjectAs(); void RevertProject(); /** * @brief Set the current application-wide tool * * @param tool */ void SetTool(const Tool::Item& tool); /** * @brief Set the current snapping setting */ void SetSnapping(const bool& b); /** * @brief Show an About dialog */ void DialogAboutShow(); /** * @brief Open the import footage dialog and import the files selected (runs ImportFiles()) */ void DialogImportShow(); /** * @brief Show Preferences dialog */ void DialogPreferencesShow(); /** * @brief Show Project Properties dialog */ void DialogProjectPropertiesShow(); /** * @brief Show Export dialog */ void DialogExportShow(); /** * @brief Show OTIO import dialog */ #ifdef USE_OTIO bool DialogImportOTIOShow(const QList<Sequence*>& sequences); #endif /** * @brief Create a new folder in the currently active project */ void CreateNewFolder(); /** * @brief Create a new sequence in the currently active project */ void CreateNewSequence(); /** * @brief Set the currently selected object that the add tool should make */ void SetSelectedAddableObject(const Tool::AddableObject& obj); /** * @brief Set the currently selected object that the add tool should make */ void SetSelectedTransitionObject(const QString& obj); /** * @brief Clears the list of recently opened/saved projects */ void ClearOpenRecentList(); /** * @brief Creates a new empty project and opens it */ void CreateNewProject(); void CheckForAutoRecoveries(); void BrowseAutoRecoveries(); void RequestPixelSamplingInViewers(bool e); void WarnCacheFull(); void SetMagic(bool e) { magic_ = e; } signals: /** * @brief Signal emitted when the tool is changed from somewhere */ void ToolChanged(const Tool::Item& tool); /** * @brief Signal emitted when addable object changes through SetSelectedAddableObject */ void AddableObjectChanged(Tool::AddableObject o); /** * @brief Signal emitted when the snapping setting is changed */ void SnappingChanged(const bool& b); /** * @brief Signal emitted when the default timecode display mode changed */ void TimecodeDisplayChanged(Timecode::Display d); /** * @brief Signal emitted when a change is made to the open recent list */ void OpenRecentListChanged(); /** * @brief Enable mouse color sampling functionality on all viewers * * This can be slow, so we only turn it on when we need it. */ void ColorPickerEnabled(bool e); /** * @brief A viewer with color picked enabled has emitted a color */ void ColorPickerColorEmitted(const Color &reference, const Color &display); private: /** * @brief Get the file filter than can be used with QFileDialog to open and save compatible projects */ static QString GetProjectFilter(bool include_any_filter); /** * @brief Returns the filename where the recently opened/saved projects should be stored */ static QString GetRecentProjectsFilePath(); /** * @brief Called only on startup to set the locale */ void SetStartupLocale(); /** * @brief Adds a filename to the top of the recently opened projects list (or moves it if it already exists) */ void PushRecentlyOpenedProject(const QString &s); /** * @brief Declare custom types/classes for Qt's signal/slot system * * Qt's signal/slot system requires types to be declared. In the interest of doing this only at startup, we contain * them all in a function here. */ void DeclareTypesForQt(); /** * @brief Start GUI portion of Olive * * Starts services and objects required for the GUI of Olive. It's guaranteed that running without this function will * create an application instance that is completely valid minus the UI (e.g. for CLI modes). */ void StartGUI(bool full_screen); /** * @brief Internal function for saving a project to a file */ void SaveProjectInternal(const QString &override_filename = QString()); /** * @brief Retrieves the currently most active sequence for exporting */ ViewerOutput *GetSequenceToExport(); static QString GetAutoRecoveryIndexFilename(); void SaveUnrecoveredList(); bool RevertProjectInternal(bool by_opening_existing); void SaveRecentProjectsList(); /** * @brief Adds a project to the "open projects" list */ void AddOpenProject(olive::Project* p, bool add_to_recents = false); bool AddOpenProjectFromTask(Task* task, bool add_to_recents); void SetActiveProject(Project *p); /** * @brief Internal main window object */ MainWindow* main_window_; /** * @brief List of currently open projects */ Project *open_project_; /** * @brief Currently active tool */ Tool::Item tool_; /** * @brief Currently active addable object */ Tool::AddableObject addable_object_; /** * @brief Currently selected transition */ QString selected_transition_; /** * @brief Current snapping setting */ bool snapping_; /** * @brief Internal timer for saving autorecovery files */ QTimer autorecovery_timer_; /** * @brief Application-wide undo stack instance */ UndoStack undo_stack_; /** * @brief List of most recently opened/saved projects */ QStringList recent_projects_; /** * @brief Parameters set up in main() determining how the program should run */ CoreParams core_params_; /** * @brief Static singleton core instance */ static Core* instance_; /** * @brief Internal translator */ QTranslator* translator_; /** * @brief List of projects that are unsaved but have autorecovery projects */ QVector<QUuid> autorecovered_projects_; /** * @brief Do something debug related */ bool magic_; /** * @brief How many widgets currently need pixel sampling access */ int pixel_sampling_users_; bool shown_cache_full_warning_; private slots: void SaveAutorecovery(); void ProjectSaveSucceeded(Task *task); bool AddOpenProjectFromTaskAndAddToRecents(Task* task) { return AddOpenProjectFromTask(task, true); } void ImportTaskComplete(Task *task); bool ConfirmImageSequence(const QString &filename); void ProjectWasModified(bool e); bool StartHeadlessExport(); void OpenStartupProject(); void AddRecoveryProjectFromTask(Task* task); /** * @brief Internal project open */ void OpenProjectInternal(const QString& filename, bool recovery_project = false); void ImportSingleFile(const QString &f); }; } #endif // CORE_H
14,042
C++
.h
485
25.152577
119
0.710007
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,168
timelinecommon.h
olive-editor_olive/app/timeline/timelinecommon.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 TIMELINECOMMON_H #define TIMELINECOMMON_H #include <olive/core/core.h> #include "common/define.h" using namespace olive::core; namespace olive { class Block; class Track; class Timeline { public: enum MovementMode { kNone, kMove, kTrimIn, kTrimOut }; enum ThumbnailMode { kThumbnailOff, kThumbnailInOut, kThumbnailOn }; enum WaveformMode { kWaveformsDisabled, kWaveformsEnabled }; static bool IsATrimMode(MovementMode mode) {return mode == kTrimIn || mode == kTrimOut;} struct EditToInfo { Track* track; rational nearest_time; Block* nearest_block; }; }; #define PLAYHEAD_COLOR palette().highlight().color() } #endif // TIMELINECOMMON_H
1,437
C++
.h
49
26.081633
90
0.752924
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,169
timelineundocommon.h
olive-editor_olive/app/timeline/timelineundocommon.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 TIMELINEUNDOCOMMON_H #define TIMELINEUNDOCOMMON_H #include "node/node.h" #include "node/nodeundo.h" namespace olive { inline bool NodeCanBeRemoved(Node* n) { return n->output_connections().empty(); } inline UndoCommand* CreateRemoveCommand(Node* n) { return new NodeRemoveWithExclusiveDependenciesAndDisconnect(n); } inline UndoCommand* CreateAndRunRemoveCommand(Node* n) { UndoCommand* command = CreateRemoveCommand(n); command->redo_now(); return command; } } #endif // TIMELINEUNDOCOMMON_H
1,230
C++
.h
35
32.8
71
0.785956
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,170
timelineundoripple.h
olive-editor_olive/app/timeline/timelineundoripple.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 TIMELINEUNDORIPPLE_H #define TIMELINEUNDORIPPLE_H #include "node/block/gap/gap.h" #include "node/output/track/track.h" #include "node/output/track/tracklist.h" #include "node/project/sequence/sequence.h" #include "timelineundogeneral.h" #include "timelineundosplit.h" #include "timelineundotrack.h" namespace olive { /** * @brief Clears the area between in and out * * The area between `in` and `out` is guaranteed to be freed. BLocks are trimmed and removed to free this space. * By default, nothing takes this area meaning all subsequent clips are pushed backward, however you can specify * a block to insert at the `in` point. No checking is done to ensure `insert` is the same length as `in` to `out`. */ class TrackRippleRemoveAreaCommand : public UndoCommand { public: TrackRippleRemoveAreaCommand(Track* track, const TimeRange& range); virtual ~TrackRippleRemoveAreaCommand() override; virtual Project* GetRelevantProject() const override { return track_->project(); } /** * @brief Block to insert after if you want to insert something between this ripple */ Block* GetInsertionIndex() const { return insert_previous_; } Block* GetSplicedBlock() const { if (splice_split_command_) { return splice_split_command_->new_block(); } return nullptr; } void SetAllowSplittingGaps(bool e) { allow_splitting_gaps_ = e; } protected: virtual void prepare() override; virtual void redo() override; virtual void undo() override; private: struct TrimOperation { Block* block; rational old_length; rational new_length; }; struct RemoveOperation { Block* block; Block* before; }; Track* track_; TimeRange range_; TrimOperation trim_out_; QVector<RemoveOperation> removals_; TrimOperation trim_in_; Block* insert_previous_; bool allow_splitting_gaps_; BlockSplitCommand* splice_split_command_; QVector<UndoCommand*> remove_block_commands_; }; class TrackListRippleRemoveAreaCommand : public UndoCommand { public: TrackListRippleRemoveAreaCommand(TrackList* list, rational in, rational out) : list_(list), range_(in, out) { } virtual ~TrackListRippleRemoveAreaCommand() override { qDeleteAll(commands_); } virtual Project* GetRelevantProject() const override { return list_->parent()->project(); } protected: virtual void prepare() override; virtual void redo() override; virtual void undo() override; private: TrackList* list_; QList<Track*> working_tracks_; TimeRange range_; QVector<TrackRippleRemoveAreaCommand*> commands_; }; class TimelineRippleRemoveAreaCommand : public MultiUndoCommand { public: TimelineRippleRemoveAreaCommand(Sequence* timeline, rational in, rational out); virtual Project* GetRelevantProject() const override { return timeline_->project(); } private: Sequence* timeline_; }; class TrackListRippleToolCommand : public UndoCommand { public: struct RippleInfo { Block* block; bool append_gap; }; TrackListRippleToolCommand(TrackList* track_list, const QHash<Track*, RippleInfo>& info, const rational& ripple_movement, const Timeline::MovementMode& movement_mode); virtual Project* GetRelevantProject() const override { return track_list_->parent()->project(); } protected: virtual void redo() override { ripple(true); } virtual void undo() override { ripple(false); } private: void ripple(bool redo); TrackList* track_list_; QHash<Track*, RippleInfo> info_; rational ripple_movement_; Timeline::MovementMode movement_mode_; struct WorkingData { GapBlock* created_gap = nullptr; Block* removed_gap_after; rational old_length; rational earliest_point_of_change; }; QHash<Track*, WorkingData> working_data_; QObject memory_manager_; }; class TimelineRippleDeleteGapsAtRegionsCommand : public UndoCommand { public: using RangeList = QVector<QPair<Track*, TimeRange> >; TimelineRippleDeleteGapsAtRegionsCommand(Sequence* vo, const RangeList& regions) : timeline_(vo), regions_(regions) { } virtual ~TimelineRippleDeleteGapsAtRegionsCommand() override { qDeleteAll(commands_); } virtual Project* GetRelevantProject() const override { return timeline_->project(); } bool HasCommands() const { return !commands_.isEmpty(); } protected: virtual void prepare() override; virtual void redo() override; virtual void undo() override; private: Sequence* timeline_; RangeList regions_; QVector<UndoCommand*> commands_; struct RemovalRequest { GapBlock *gap; TimeRange range; }; }; } #endif // TIMELINEUNDORIPPLE_H
5,514
C++
.h
194
24.793814
115
0.739867
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,171
timelineundoworkarea.h
olive-editor_olive/app/timeline/timelineundoworkarea.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 TIMELINEUNDOWORKAREA_H #define TIMELINEUNDOWORKAREA_H #include "node/project.h" namespace olive { class WorkareaSetEnabledCommand : public UndoCommand { public: WorkareaSetEnabledCommand(Project *project, TimelineWorkArea* points, bool enabled) : project_(project), points_(points), old_enabled_(points_->enabled()), new_enabled_(enabled) { } virtual Project* GetRelevantProject() const override { return project_; } protected: virtual void redo() override { points_->set_enabled(new_enabled_); } virtual void undo() override { points_->set_enabled(old_enabled_); } private: Project* project_; TimelineWorkArea* points_; bool old_enabled_; bool new_enabled_; }; class WorkareaSetRangeCommand : public UndoCommand { public: WorkareaSetRangeCommand(TimelineWorkArea *workarea, const TimeRange& range, const TimeRange &old_range) : workarea_(workarea), old_range_(old_range), new_range_(range) { } WorkareaSetRangeCommand(TimelineWorkArea *workarea, const TimeRange& range) : WorkareaSetRangeCommand(workarea, range, workarea->range()) { } virtual Project* GetRelevantProject() const override { return Project::GetProjectFromObject(workarea_); } protected: virtual void redo() override { workarea_->set_range(new_range_); } virtual void undo() override { workarea_->set_range(old_range_); } private: TimelineWorkArea *workarea_; TimeRange old_range_; TimeRange new_range_; }; } #endif // TIMELINEUNDOWORKAREA_H
2,274
C++
.h
78
25.897436
107
0.750461
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,172
timelineworkarea.h
olive-editor_olive/app/timeline/timelineworkarea.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 TIMELINEWORKAREA_H #define TIMELINEWORKAREA_H #include <olive/core/core.h> #include <QObject> #include <QXmlStreamReader> #include <QXmlStreamWriter> namespace olive { using namespace core; class TimelineWorkArea : public QObject { Q_OBJECT public: TimelineWorkArea(QObject* parent = nullptr); bool enabled() const; void set_enabled(bool e); const rational& in() const; const rational& out() const; const rational& length() const; const TimeRange& range() const; void set_range(const TimeRange& range); bool load(QXmlStreamReader *reader); void save(QXmlStreamWriter *writer) const; static const rational kResetIn; static const rational kResetOut; signals: void EnabledChanged(bool e); void RangeChanged(const TimeRange& r); private: bool workarea_enabled_; TimeRange workarea_range_; }; } #endif // TIMELINEWORKAREA_H
1,588
C++
.h
47
31.106383
71
0.777632
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,173
timelinecoordinate.h
olive-editor_olive/app/timeline/timelinecoordinate.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 TIMELINECOORDINATE_H #define TIMELINECOORDINATE_H #include "node/output/track/track.h" namespace olive { class TimelineCoordinate { public: TimelineCoordinate(); TimelineCoordinate(const rational& frame, const Track::Reference& track); TimelineCoordinate(const rational& frame, const Track::Type& track_type, const int& track_index); const rational& GetFrame() const; const Track::Reference& GetTrack() const; void SetFrame(const rational& frame); void SetTrack(const Track::Reference& track); private: rational frame_; Track::Reference track_; }; } #endif // TIMELINECOORDINATE_H
1,329
C++
.h
34
36.382353
99
0.779515
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,174
timelinemarker.h
olive-editor_olive/app/timeline/timelinemarker.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 TIMELINEMARKER_H #define TIMELINEMARKER_H #include <olive/core/core.h> #include <QPainter> #include <QString> #include <QXmlStreamReader> #include <QXmlStreamWriter> #include "undo/undocommand.h" using namespace olive::core; namespace olive { class TimelineMarker : public QObject { Q_OBJECT public: TimelineMarker(QObject* parent = nullptr); TimelineMarker(int color, const TimeRange& time, const QString& name = QString(), QObject* parent = nullptr); const TimeRange &time() const { return time_; } void set_time(const TimeRange& time); void set_time(const rational& time); bool has_sibling_at_time(const rational &t) const; const QString& name() const { return name_; } void set_name(const QString& name); int color() const { return color_; } void set_color(int c); static int GetMarkerHeight(const QFontMetrics &fm); QRect Draw(QPainter *p, const QPoint &pt, int max_right, double scale, bool selected); bool load(QXmlStreamReader *reader); void save(QXmlStreamWriter *writer) const; signals: void TimeChanged(const TimeRange& time); void NameChanged(const QString& name); void ColorChanged(int c); private: TimeRange time_; QString name_; int color_; }; class TimelineMarkerList : public QObject { Q_OBJECT public: TimelineMarkerList(QObject *parent = nullptr) : QObject(parent) { } inline bool empty() const { return markers_.empty(); } inline std::vector<TimelineMarker*>::iterator begin() { return markers_.begin(); } inline std::vector<TimelineMarker*>::iterator end() { return markers_.end(); } inline std::vector<TimelineMarker*>::const_iterator cbegin() const { return markers_.cbegin(); } inline std::vector<TimelineMarker*>::const_iterator cend() const { return markers_.cend(); } inline TimelineMarker *back() const { return markers_.back(); } inline TimelineMarker *front() const { return markers_.front(); } inline size_t size() const { return markers_.size(); } bool load(QXmlStreamReader *reader); void save(QXmlStreamWriter *writer) const; TimelineMarker *GetMarkerAtTime(const rational &t) const { for (auto it=markers_.cbegin(); it!=markers_.cend(); it++) { TimelineMarker *m = *it; if (m->time().in() == t) { return m; } } return nullptr; } TimelineMarker *GetClosestMarkerToTime(const rational &t) const { TimelineMarker *closest = nullptr; for (auto it=markers_.cbegin(); it!=markers_.cend(); it++) { TimelineMarker *m = *it; rational this_diff = qAbs(m->time().in() - t); if (closest) { rational stored_diff = qAbs(closest->time().in() - t); if (this_diff > stored_diff) { // Since the list is organized by time, if the diff increases, assume we are only going // to move further away from here and there's no need to check break; } } closest = m; } return closest; } signals: void MarkerAdded(TimelineMarker* marker); void MarkerRemoved(TimelineMarker* marker); void MarkerModified(TimelineMarker* marker); protected: virtual void childEvent(QChildEvent *e) override; private: void InsertIntoList(TimelineMarker *m); bool RemoveFromList(TimelineMarker *m); std::vector<TimelineMarker*> markers_; private slots: void HandleMarkerModification(); void HandleMarkerTimeChange(); }; class MarkerAddCommand : public UndoCommand { public: MarkerAddCommand(TimelineMarkerList* marker_list, const TimeRange& range, const QString& name, int color); MarkerAddCommand(TimelineMarkerList* marker_list, TimelineMarker *marker); virtual Project* GetRelevantProject() const override; protected: virtual void redo() override; virtual void undo() override; private: TimelineMarkerList* marker_list_; TimelineMarker* added_marker_; QObject memory_manager_; }; class MarkerRemoveCommand : public UndoCommand { public: MarkerRemoveCommand(TimelineMarker* marker); virtual Project* GetRelevantProject() const override; protected: virtual void redo() override; virtual void undo() override; private: TimelineMarker* marker_; QObject* marker_list_; QObject memory_manager_; }; class MarkerChangeColorCommand : public UndoCommand { public: MarkerChangeColorCommand(TimelineMarker* marker, int new_color); virtual Project* GetRelevantProject() const override; protected: virtual void redo() override; virtual void undo() override; private: TimelineMarker* marker_; int old_color_; int new_color_; }; class MarkerChangeNameCommand : public UndoCommand { public: MarkerChangeNameCommand(TimelineMarker* marker, QString name); virtual Project* GetRelevantProject() const override; protected: virtual void redo() override; virtual void undo() override; private: TimelineMarker* marker_; QString old_name_; QString new_name_; }; class MarkerChangeTimeCommand : public UndoCommand { public: MarkerChangeTimeCommand(TimelineMarker* marker, const TimeRange &time, const TimeRange &old_time); MarkerChangeTimeCommand(TimelineMarker* marker, const TimeRange &time) : MarkerChangeTimeCommand(marker, time, marker->time()) {} virtual Project* GetRelevantProject() const override; protected: virtual void redo() override; virtual void undo() override; private: TimelineMarker* marker_; TimeRange old_time_; TimeRange new_time_; }; } #endif // TIMELINEMARKER_H
6,157
C++
.h
177
31.418079
111
0.746403
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,175
timelineundosplit.h
olive-editor_olive/app/timeline/timelineundosplit.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 TIMELINEUNDOSPLIT_H #define TIMELINEUNDOSPLIT_H #include "node/output/track/track.h" namespace olive { class BlockSplitCommand : public UndoCommand { public: BlockSplitCommand(Block* block, rational point) : block_(block), new_block_(nullptr), point_(point), reconnect_tree_command_(nullptr) { } virtual ~BlockSplitCommand() override { delete reconnect_tree_command_; } virtual Project* GetRelevantProject() const override { return block_->project(); } /** * @brief Access the second block created as a result. Only valid after redo(). */ Block* new_block() { return new_block_; } protected: virtual void prepare() override; virtual void redo() override; virtual void undo() override; private: Block* block_; Block* new_block_; rational old_length_; rational point_; MultiUndoCommand* reconnect_tree_command_; NodeInput moved_transition_; }; class BlockSplitPreservingLinksCommand : public UndoCommand { public: BlockSplitPreservingLinksCommand(const QVector<Block *> &blocks, const QList<rational>& times) : blocks_(blocks), times_(times) { } virtual ~BlockSplitPreservingLinksCommand() override { qDeleteAll(commands_); } virtual Project* GetRelevantProject() const override { return blocks_.first()->project(); } Block *GetSplit(Block *original, int time_index) const; protected: virtual void prepare() override; virtual void redo() override { for (int i=0; i<commands_.size(); i++) { commands_.at(i)->redo_now(); } } virtual void undo() override { for (int i=commands_.size()-1; i>=0; i--) { commands_.at(i)->undo_now(); } } private: QVector<Block *> blocks_; QList<rational> times_; QVector<UndoCommand*> commands_; QVector< QVector<Block*> > splits_; }; class TrackSplitAtTimeCommand : public UndoCommand { public: TrackSplitAtTimeCommand(Track* track, rational point) : track_(track), point_(point), command_(nullptr) { } virtual ~TrackSplitAtTimeCommand() override { delete command_; } virtual Project* GetRelevantProject() const override { return track_->project(); } protected: virtual void prepare() override; virtual void redo() override { if (command_) { command_->redo_now(); } } virtual void undo() override { if (command_) { command_->undo_now(); } } private: Track* track_; rational point_; UndoCommand* command_; }; } #endif // TIMELINEUNDOSPLIT_H
3,274
C++
.h
127
22.275591
98
0.713825
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,176
timelineundogeneral.h
olive-editor_olive/app/timeline/timelineundogeneral.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 TIMELINEUNDOGENERAL_H #define TIMELINEUNDOGENERAL_H #include "config/config.h" #include "node/block/clip/clip.h" #include "node/block/gap/gap.h" #include "node/output/track/track.h" #include "node/output/track/tracklist.h" #include "node/output/viewer/viewer.h" #include "node/project/sequence/sequence.h" #include "timelineundosplit.h" namespace olive { class BlockResizeCommand : public UndoCommand { public: BlockResizeCommand(Block* block, rational new_length) : block_(block), new_length_(new_length) { } virtual Project* GetRelevantProject() const override { return block_->project(); } protected: virtual void redo() override; virtual void undo() override; private: Block* block_; rational old_length_; rational new_length_; }; class BlockResizeWithMediaInCommand : public UndoCommand { public: BlockResizeWithMediaInCommand(Block* block, rational new_length) : block_(block), new_length_(new_length) { } virtual Project* GetRelevantProject() const { return block_->project(); } protected: virtual void redo(); virtual void undo(); private: Block* block_; rational old_length_; rational new_length_; }; class BlockSetMediaInCommand : public UndoCommand { public: BlockSetMediaInCommand(ClipBlock* block, rational new_media_in) : block_(block), new_media_in_(new_media_in) { } virtual Project* GetRelevantProject() const { return block_->project(); } protected: virtual void redo(); virtual void undo(); private: ClipBlock* block_; rational old_media_in_; rational new_media_in_; }; class TimelineAddTrackCommand : public UndoCommand { public: TimelineAddTrackCommand(TrackList *timeline) : TimelineAddTrackCommand(timeline, OLIVE_CONFIG("AutoMergeTracks").toBool()) { } TimelineAddTrackCommand(TrackList *timeline, bool automerge_tracks); static Track* RunImmediately(TrackList *timeline) { TimelineAddTrackCommand c(timeline); c.redo(); return c.track(); } static Track* RunImmediately(TrackList *timeline, bool automerge) { TimelineAddTrackCommand c(timeline, automerge); c.redo(); return c.track(); } virtual ~TimelineAddTrackCommand() override { delete position_command_; } Track* track() const { return track_; } virtual Project* GetRelevantProject() const override { return timeline_->parent()->project(); } protected: virtual void redo() override; virtual void undo() override; private: TrackList* timeline_; Track* track_; Node* merge_; NodeInput base_; NodeInput blend_; NodeInput direct_; MultiUndoCommand* position_command_; QObject memory_manager_; }; class TimelineRemoveTrackCommand : public UndoCommand { public: TimelineRemoveTrackCommand(Track *track) : track_(track), remove_command_(nullptr) {} virtual ~TimelineRemoveTrackCommand() { delete remove_command_; } virtual Project* GetRelevantProject() const override { return track_->project(); } protected: virtual void prepare() override; virtual void redo() override; virtual void undo() override; private: Track *track_; TrackList *list_; int index_; UndoCommand *remove_command_; }; class TransitionRemoveCommand : public UndoCommand { public: TransitionRemoveCommand(TransitionBlock* block, bool remove_from_graph) : block_(block), remove_from_graph_(remove_from_graph), remove_command_(nullptr) { } virtual Project* GetRelevantProject() const override { return track_->project(); } protected: virtual void redo() override; virtual void undo() override; private: TransitionBlock* block_; Track* track_; Block* out_block_; Block* in_block_; bool remove_from_graph_; UndoCommand* remove_command_; }; class TrackReplaceBlockWithGapCommand : public UndoCommand { public: TrackReplaceBlockWithGapCommand(Track* track, Block* block, bool handle_transitions = true) : track_(track), block_(block), existing_gap_(nullptr), existing_merged_gap_(nullptr), our_gap_(nullptr), handle_transitions_(handle_transitions) { } virtual Project* GetRelevantProject() const override { return block_->project(); } protected: virtual void redo() override; virtual void undo() override; private: void CreateRemoveTransitionCommandIfNecessary(bool next); Track* track_; Block* block_; GapBlock* existing_gap_; GapBlock* existing_merged_gap_; bool existing_gap_precedes_; GapBlock* our_gap_; bool handle_transitions_; QObject memory_manager_; QVector<TransitionRemoveCommand*> transition_remove_commands_; }; class BlockEnableDisableCommand : public UndoCommand { public: BlockEnableDisableCommand(Block* block, bool enabled) : block_(block), old_enabled_(block_->is_enabled()), new_enabled_(enabled) { } virtual Project* GetRelevantProject() const override { return block_->project(); } protected: virtual void redo() override { block_->set_enabled(new_enabled_); } virtual void undo() override { block_->set_enabled(old_enabled_); } private: Block* block_; bool old_enabled_; bool new_enabled_; }; class TrackListInsertGaps : public UndoCommand { public: TrackListInsertGaps(TrackList* track_list, const rational& point, const rational& length) : track_list_(track_list), point_(point), length_(length), split_command_(nullptr) { } virtual ~TrackListInsertGaps() override { delete split_command_; } virtual Project* GetRelevantProject() const override { return track_list_->parent()->project(); } protected: virtual void prepare() override; virtual void redo() override; virtual void undo() override; private: TrackList* track_list_; rational point_; rational length_; QVector<Track*> working_tracks_; QVector<Block*> gaps_to_extend_; struct AddGap { GapBlock* gap; Block* before; Track* track; }; QVector<AddGap> gaps_added_; BlockSplitPreservingLinksCommand* split_command_; QObject memory_manager_; }; class TimelineAddDefaultTransitionCommand : public UndoCommand { public: TimelineAddDefaultTransitionCommand(const QVector<ClipBlock*> &clips, const rational &timebase) : clips_(clips), timebase_(timebase) {} virtual ~TimelineAddDefaultTransitionCommand() override { qDeleteAll(commands_); } virtual Project* GetRelevantProject() const override { return clips_.empty() ? nullptr : clips_.first()->project(); } protected: virtual void prepare() override; virtual void redo() override { for (auto it=commands_.cbegin(); it!=commands_.cend(); it++) { (*it)->redo_now(); } } virtual void undo() override { for (auto it=commands_.crbegin(); it!=commands_.crend(); it++) { (*it)->undo_now(); } } private: enum CreateTransitionMode { kIn, kOut, kOutDual }; void AddTransition(ClipBlock *c, CreateTransitionMode mode); void AdjustClipLength(ClipBlock *c, const rational &transition_length, bool out); void ValidateTransitionLength(ClipBlock *c, rational &transition_length); QVector<ClipBlock*> clips_; rational timebase_; QVector<UndoCommand*> commands_; QHash<ClipBlock*, rational> lengths_; }; } #endif // TIMELINEUNDOGENERAL_H
8,096
C++
.h
311
22.707395
99
0.736911
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,177
timelineundotrack.h
olive-editor_olive/app/timeline/timelineundotrack.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 TIMELINEUNDOTRACK_H #define TIMELINEUNDOTRACK_H #include "node/output/track/track.h" namespace olive { class TrackRippleRemoveBlockCommand : public UndoCommand { public: TrackRippleRemoveBlockCommand(Track* track, Block* block) : track_(track), block_(block) { } virtual Project* GetRelevantProject() const override { return track_->project(); } protected: virtual void redo() override { before_ = block_->previous(); track_->RippleRemoveBlock(block_); } virtual void undo() override { track_->InsertBlockAfter(block_, before_); } private: Track* track_; Block* block_; Block* before_; }; class TrackPrependBlockCommand : public UndoCommand { public: TrackPrependBlockCommand(Track* track, Block* block) : track_(track), block_(block) { } virtual Project* GetRelevantProject() const override { return track_->project(); } protected: virtual void redo() override { track_->PrependBlock(block_); } virtual void undo() override { track_->RippleRemoveBlock(block_); } private: Track* track_; Block* block_; }; class TrackInsertBlockAfterCommand : public UndoCommand { public: TrackInsertBlockAfterCommand(Track* track, Block* block, Block* before) : track_(track), block_(block), before_(before) { } virtual Project* GetRelevantProject() const override { return block_->project(); } protected: virtual void redo() override { track_->InsertBlockAfter(block_, before_); } virtual void undo() override { track_->RippleRemoveBlock(block_); } private: Track* track_; Block* block_; Block* before_; }; /** * @brief Replaces Block `old` with Block `replace` * * Both blocks must have equal lengths. */ class TrackReplaceBlockCommand : public UndoCommand { public: TrackReplaceBlockCommand(Track* track, Block* old, Block* replace) : track_(track), old_(old), replace_(replace) { } virtual Project* GetRelevantProject() const override { return track_->project(); } protected: virtual void redo() override { track_->ReplaceBlock(old_, replace_); } virtual void undo() override { track_->ReplaceBlock(replace_, old_); } private: Track* track_; Block* old_; Block* replace_; }; } #endif // TIMELINEUNDOTRACK_H
3,059
C++
.h
131
20.259542
75
0.723029
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,178
timelineundopointer.h
olive-editor_olive/app/timeline/timelineundopointer.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 TIMELINEUNDOPOINTER_H #define TIMELINEUNDOPOINTER_H #include "node/block/gap/gap.h" #include "node/output/track/track.h" #include "node/output/track/tracklist.h" #include "node/project/sequence/sequence.h" #include "timelineundogeneral.h" #include "timelineundoripple.h" namespace olive { /** * @brief Performs a trim in the timeline that only affects the block and the block adjacent * * Changes the length of one block while also changing the length of the block directly adjacent * to compensate so that the rest of the track is unaffected. * * By default, this will only affect the length of gaps. If the adjacent needs to increase its * length and is not a gap, a gap will be created and inserted to fill that time. This command can * be set to always trim even if the adjacent clip isn't a gap with SetTrimIsARollEdit() */ class BlockTrimCommand : public UndoCommand { public: BlockTrimCommand(Track *track, Block* block, rational new_length, Timeline::MovementMode mode) : track_(track), block_(block), new_length_(new_length), mode_(mode), deleted_adjacent_command_(nullptr), trim_is_a_roll_edit_(false) { } virtual ~BlockTrimCommand() override { delete deleted_adjacent_command_; } virtual Project* GetRelevantProject() const override { return track_->project(); } /** * @brief Set this if the trim should always affect the adjacent clip and not create a gap */ void SetTrimIsARollEdit(bool e) { trim_is_a_roll_edit_ = e; } /** * @brief Set whether adjacent blocks set to zero length should be removed from the whole graph * * If an adjacent block's length is set to 0, it's automatically removed from the track. By * default it also gets removed from the whole graph. Set this to FALSE to disable that * functionality. */ void SetRemoveZeroLengthFromGraph(bool e) { remove_block_from_graph_ = e; } protected: virtual void prepare() override; virtual void redo() override; virtual void undo() override; private: bool doing_nothing_; rational trim_diff_; Track* track_; Block* block_; rational old_length_; rational new_length_; Timeline::MovementMode mode_; Block* adjacent_; bool needs_adjacent_; bool we_created_adjacent_; bool we_removed_adjacent_; UndoCommand* deleted_adjacent_command_; bool trim_is_a_roll_edit_; bool remove_block_from_graph_; QObject memory_manager_; }; class TrackSlideCommand : public UndoCommand { public: TrackSlideCommand(Track* track, const QList<Block*>& moving_blocks, Block* in_adjacent, Block* out_adjacent, const rational& movement) : track_(track), blocks_(moving_blocks), movement_(movement), we_removed_in_adjacent_(false), in_adjacent_(in_adjacent), in_adjacent_remove_command_(nullptr), we_removed_out_adjacent_(false), out_adjacent_(out_adjacent), out_adjacent_remove_command_(nullptr) { Q_ASSERT(!movement_.isNull()); } virtual ~TrackSlideCommand() override { delete in_adjacent_remove_command_; delete out_adjacent_remove_command_; } virtual Project* GetRelevantProject() const override { return track_->project(); } protected: virtual void prepare() override; virtual void redo() override; virtual void undo() override; private: Track* track_; QList<Block*> blocks_; rational movement_; bool we_created_in_adjacent_; bool we_removed_in_adjacent_; Block* in_adjacent_; UndoCommand* in_adjacent_remove_command_; bool we_created_out_adjacent_; bool we_removed_out_adjacent_; Block* out_adjacent_; UndoCommand* out_adjacent_remove_command_; QObject memory_manager_; }; /** * @brief Destructively places `block` at the in point `start` * * The Block is guaranteed to be placed at the starting point specified. If there are Blocks in this area, they are * either trimmed or removed to make space for this Block. Additionally, if the Block is placed beyond the end of * the Sequence, a GapBlock is inserted to compensate. */ class TrackPlaceBlockCommand : public UndoCommand { public: TrackPlaceBlockCommand(TrackList *timeline, int track, Block* block, rational in) : timeline_(timeline), track_index_(track), in_(in), gap_(nullptr), insert_(block), ripple_remove_command_(nullptr) { } virtual ~TrackPlaceBlockCommand() override; virtual Project* GetRelevantProject() const override { return timeline_->parent()->project(); } protected: virtual void redo() override; virtual void undo() override; private: TrackList* timeline_; int track_index_; rational in_; GapBlock* gap_; Block* insert_; QVector<TimelineAddTrackCommand*> add_track_commands_; QObject memory_manager_; TrackRippleRemoveAreaCommand* ripple_remove_command_; }; } #endif // TIMELINEUNDOPOINTER_H
5,574
C++
.h
171
29.409357
138
0.743475
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,179
taskmanager.h
olive-editor_olive/app/task/taskmanager.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 TASKMANAGER_H #define TASKMANAGER_H #include <QtConcurrent/QtConcurrent> #include <QVector> #include <QUndoCommand> #include "task/task.h" namespace olive { /** * @brief An object that manages background Task objects, handling their start and end * * TaskManager handles the life of a Task object. After a new Task is created, it should be sent to TaskManager through * AddTask(). TaskManager will take ownership of the task and add it to a queue until it system resources are available * for it to run. Currently, TaskManager will run no more Tasks than there are threads on the system (one task per * thread). As Tasks finished, TaskManager will start the next in the queue. */ class TaskManager : public QObject { Q_OBJECT public: /** * @brief TaskManager Constructor */ TaskManager(); /** * @brief TaskManager Destructor * * Ensures all Tasks are deleted */ virtual ~TaskManager(); static void CreateInstance(); static void DestroyInstance(); static TaskManager* instance(); int GetTaskCount() const; Task* GetFirstTask() const; void CancelTaskAndWait(Task* t); public slots: /** * @brief Add a new Task * * Adds a new Task to the queue. If there are available threads to run it, it'll also run immediately. Otherwise, * it'll be placed into the queue and run when resources are available. * * NOTE: This function is NOT thread-safe and is currently intended to only be used from the main/GUI thread. * * NOTE: A Task object should only be added once. Adding the same Task object more than once will result in undefined * behavior. * * @param t * * The task to add and run. TaskManager takes ownership of this Task and will be responsible for freeing it. */ void AddTask(Task *t); void CancelTask(Task* t); signals: /** * @brief Signal emitted when a Task is added by AddTask() * * @param t * * Task that was added */ void TaskAdded(Task* t); /** * @brief Signal emitted when any change to the running task list has been made */ void TaskListChanged(); /** * @brief Signal emitted when a task is deleted */ void TaskRemoved(Task* t); /** * @brief Signal emitted when a task fails */ void TaskFailed(Task* t); private: /** * @brief Internal task array */ QHash<QFutureWatcher<bool>*, Task*> tasks_; /** * @brief Internal list of failed tasks */ std::list<Task*> failed_tasks_; /** * @brief Task thread pool */ QThreadPool thread_pool_; /** * @brief TaskManager singleton instance */ static TaskManager* instance_; private slots: void TaskFinished(); }; } #endif // TASKMANAGER_H
3,416
C++
.h
110
27.836364
119
0.723664
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,180
task.h
olive-editor_olive/app/task/task.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 TASK_H #define TASK_H #include <memory> #include <QDateTime> #include <QDebug> #include <QObject> #include "common/cancelableobject.h" namespace olive { /** * @brief A base class for background tasks running in Olive. * * Tasks are multithreaded by design (i.e. they will always spawn * a new thread and run in it). * * To subclass your own Task, override Action() and return TRUE on success or FALSE on failure. Note that a Task can * provide a "negative" output and still have succeeded. For example, the ProbeTask's role is to determine whether a * certain media file can be used in Olive. Even if the probe *fails* to find a Decoder for this file, the Task itself * has *succeeded* at discovering this. A failure of ProbeTask would indicate a catastrophic failure meaning it was * unable to determine anything about the file. * * Tasks should be used with the TaskManager which will manage starting and deleting them. It'll also only start as * many Tasks as there are threads on the system as to not overload them. * * Tasks support "dependency tasks", i.e. a Task that should be complete before another Task begins. */ class Task : public QObject, public CancelableObject { Q_OBJECT public: /** * @brief Task Constructor */ Task() : title_(tr("Task")), error_(tr("Unknown error")), start_time_(0) { } /** * @brief Retrieve the current title of this Task */ const QString& GetTitle() const { return title_; } /** * @brief Returns the error that occurred if Run() returns false */ const QString& GetError() const { return error_; } const qint64& GetStartTime() const { return start_time_; } public slots: /** * @brief Run this task * * @return True if the task completed successfully, false if not. * * \see GetError() if this returns false. */ bool Start() { start_time_ = QDateTime::currentMSecsSinceEpoch(); emit Started(start_time_); bool ret = Run(); // Print how long this task took for debugging purposes qDebug() << this << "took" << (QDateTime::currentMSecsSinceEpoch() - start_time_); emit Finished(this, ret); return ret; } /** * @brief Reset state so that Run() can be called again. * * Override this if your class holds any persistent state that should be cleared/modified before * it's safe for Run() to run again. */ virtual void Reset(){} /** * @brief Cancel the Task * * Sends a signal to the Task to stop as soon as possible. Always call this directly or connect * with Qt::DirectConnection, or else it'll be queued *after* the task has already finished. */ void Cancel() { CancelableObject::Cancel(); } protected: virtual bool Run() = 0; /** * @brief Set the error message * * It is recommended to use this if your Action() function ever returns FALSE to tell the user why the failure * occurred. */ void SetError(const QString& s) { error_ = s; } /** * @brief Set the Task title * * Used in the UI Task Manager to distinguish Tasks from each other. Generally this should be set in the constructor * and shouldn't need to change during the life of the Task. To show an error message, it's recommended to use * set_error() instead. */ void SetTitle(const QString& s) { title_ = s; } signals: void Started(qint64 start_time); /** * @brief Signal emitted whenever progress is made * * Emit this throughout Action() to update any attached ProgressBars on the progress of this Task. * * @param p * * A progress value between 0.0 and 1.0. */ void ProgressChanged(double d); /** * @brief Emitted when task is finished * * Do NOT delete immediately after this signal, call deleteLater() instead. */ void Finished(Task *task, bool succeeded); private: QString title_; QString error_; qint64 start_time_; }; } #endif // TASK_H
4,687
C++
.h
153
27.300654
118
0.707908
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,181
conform.h
olive-editor_olive/app/task/conform/conform.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 CONFORMTASK_H #define CONFORMTASK_H #include "codec/decoder.h" #include "node/project/footage/footage.h" #include "task/task.h" namespace olive { class ConformTask : public Task { Q_OBJECT public: ConformTask(const QString &decoder_id, const Decoder::CodecStream &stream, const AudioParams& params, const QVector<QString> &output_filenames); protected: virtual bool Run() override; private: QString decoder_id_; Decoder::CodecStream stream_; AudioParams params_; QVector<QString> output_filenames_; }; } #endif // CONFORMTASK_H
1,273
C++
.h
35
33.8
146
0.778051
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,182
customcachetask.h
olive-editor_olive/app/task/customcache/customcachetask.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 CUSTOMCACHETASK_H #define CUSTOMCACHETASK_H #include <QMutex> #include <QWaitCondition> #include "task/task.h" namespace olive { class CustomCacheTask : public Task { Q_OBJECT public: CustomCacheTask(const QString &sequence_name); void Finish(); signals: void Cancelled(); protected: virtual bool Run() override; virtual void CancelEvent() override; private: QMutex mutex_; QWaitCondition wait_cond_; bool cancelled_through_finish_; }; } #endif // CUSTOMCACHETASK_H
1,218
C++
.h
38
29.421053
71
0.777586
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,183
saveotio.h
olive-editor_olive/app/task/project/saveotio/saveotio.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 PROJECTSAVEASOTIOTASK_H #define PROJECTSAVEASOTIOTASK_H #ifdef USE_OTIO #include <opentimelineio/timeline.h> #include <opentimelineio/track.h> #include "common/otioutils.h" #include "node/project.h" #include "task/task.h" namespace olive { class SaveOTIOTask : public Task { Q_OBJECT public: SaveOTIOTask(Project* project); protected: virtual bool Run() override; private: OTIO::Timeline* SerializeTimeline(Sequence* sequence); OTIO::Track* SerializeTrack(Track* track, double sequence_rate, rational max_track_length); bool SerializeTrackList(TrackList* list, OTIO::Timeline *otio_timeline, double sequence_rate); Project* project_; }; } #endif #endif // PROJECTSAVEASOTIOTASK_H
1,428
C++
.h
39
34.128205
96
0.785975
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,184
loadotio.h
olive-editor_olive/app/task/project/loadotio/loadotio.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 OTIODECODER_H #define OTIODECODER_H #ifdef USE_OTIO #include "common/otioutils.h" #include "node/project.h" #include "task/project/load/loadbasetask.h" namespace olive { class LoadOTIOTask : public ProjectLoadBaseTask { Q_OBJECT public: LoadOTIOTask(const QString& filename); protected: virtual bool Run() override; }; } #endif #endif // OTIODECODER_H
1,087
C++
.h
32
31.5625
71
0.781731
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,185
importerrordialog.h
olive-editor_olive/app/task/project/import/importerrordialog.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 PROJECTIMPORTERRORDIALOG_H #define PROJECTIMPORTERRORDIALOG_H #include <QDialog> #include "common/define.h" namespace olive { class ProjectImportErrorDialog : public QDialog { Q_OBJECT public: ProjectImportErrorDialog(const QStringList& filenames, QWidget* parent = nullptr); }; } #endif // PROJECTIMPORTERRORDIALOG_H
1,049
C++
.h
27
36.333333
84
0.790882
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,186
import.h
olive-editor_olive/app/task/project/import/import.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 PROJECTIMPORTMANAGER_H #define PROJECTIMPORTMANAGER_H #include <QFileInfoList> #include <QUndoCommand> #include "codec/decoder.h" #include "task/task.h" #include "widget/projectexplorer/projectviewmodel.h" namespace olive { class ProjectImportTask : public Task { Q_OBJECT public: ProjectImportTask(Folder* folder, const QStringList& filenames); const int& GetFileCount() const; MultiUndoCommand* GetCommand() const { return command_; } const QStringList& GetInvalidFiles() const { return invalid_files_; } bool HasInvalidFiles() const { return !invalid_files_.isEmpty(); } const QVector<Footage*> &GetImportedFootage() const { return imported_footage_; } protected: virtual bool Run() override; private: void Import(Folder* folder, QFileInfoList import, int& counter, MultiUndoCommand *parent_command); void ValidateImageSequence(Footage *footage, QFileInfoList &info_list, int index); void AddItemToFolder(Folder* folder, Node* item, MultiUndoCommand* command); static bool ItemIsStillImageFootageOnly(Footage *footage); static bool CompareStillImageSize(Footage *footage, const QSize& sz); static int64_t GetImageSequenceLimit(const QString &start_fn, int64_t start, bool up); MultiUndoCommand* command_; Folder* folder_; QFileInfoList filenames_; int file_count_; QStringList invalid_files_; QList<QString> image_sequence_ignore_files_; QVector<Footage*> imported_footage_; }; } #endif // PROJECTIMPORTMANAGER_H
2,228
C++
.h
60
34.1
100
0.779026
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,187
save.h
olive-editor_olive/app/task/project/save/save.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 PROJECTSAVEMANAGER_H #define PROJECTSAVEMANAGER_H #include "node/project.h" #include "task/task.h" namespace olive { class ProjectSaveTask : public Task { Q_OBJECT public: ProjectSaveTask(Project* project, bool use_compression); Project* GetProject() const { return project_; } void SetOverrideFilename(const QString& filename) { override_filename_ = filename; } void SetLayout(const MainWindowLayoutInfo &layout) { layout_ = layout; } protected: virtual bool Run() override; private: Project* project_; QString override_filename_; bool use_compression_; MainWindowLayoutInfo layout_; }; } #endif // PROJECTSAVEMANAGER_H
1,399
C++
.h
46
27.5
71
0.768192
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,188
loadbasetask.h
olive-editor_olive/app/task/project/load/loadbasetask.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 PROJECTLOADBASETASK_H #define PROJECTLOADBASETASK_H #include "node/project.h" #include "task/task.h" namespace olive { class ProjectLoadBaseTask : public Task { Q_OBJECT public: ProjectLoadBaseTask(const QString& filename); Project* GetLoadedProject() const { return project_; } const QString& GetFilename() const { return filename_; } const MainWindowLayoutInfo &GetLoadedLayout() const { return layout_; } protected: Project* project_; MainWindowLayoutInfo layout_; private: QString filename_; }; } #endif // LOADBASETASK_H
1,298
C++
.h
44
26.636364
71
0.768608
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,189
load.h
olive-editor_olive/app/task/project/load/load.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 PROJECTLOADMANAGER_H #define PROJECTLOADMANAGER_H #include "loadbasetask.h" #include "window/mainwindow/mainwindowlayoutinfo.h" namespace olive { class ProjectLoadTask : public ProjectLoadBaseTask { Q_OBJECT public: ProjectLoadTask(const QString& filename); protected: virtual bool Run() override; }; } #endif // PROJECTLOADMANAGER_H
1,067
C++
.h
29
34.310345
71
0.790244
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,190
render.h
olive-editor_olive/app/task/render/render.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 RENDERTASK_H #define RENDERTASK_H #include <QtConcurrent/QtConcurrent> #include "node/block/subtitle/subtitle.h" #include "node/color/colormanager/colormanager.h" #include "node/output/viewer/viewer.h" #include "task/task.h" #include "render/renderticket.h" namespace olive { class RenderTask : public Task { Q_OBJECT public: RenderTask(); virtual ~RenderTask() override; protected: bool Render(ColorManager *manager, const TimeRangeList &video_range, const TimeRangeList &audio_range, const TimeRange &subtitle_range, RenderMode::Mode mode, FrameHashCache *cache, const QSize& force_size = QSize(0, 0), const QMatrix4x4& force_matrix = QMatrix4x4(), PixelFormat force_format = PixelFormat::INVALID, int force_channel_count = 0, ColorProcessorPtr force_color_output = nullptr); virtual bool DownloadFrame(QThread* thread, FramePtr frame, const rational &time); virtual bool FrameDownloaded(FramePtr frame, const rational &time) = 0; virtual bool AudioDownloaded(const TimeRange& range, const SampleBuffer &samples) = 0; virtual bool EncodeSubtitle(const SubtitleBlock *subtitle); ViewerOutput* viewer() const { return viewer_; } void set_viewer(ViewerOutput *v) { viewer_ = v; } const VideoParams& video_params() const { return video_params_; } void set_video_params(const VideoParams& video_params) { video_params_ = video_params; } const AudioParams& audio_params() const { return audio_params_; } void set_audio_params(const AudioParams& audio_params) { audio_params_ = audio_params; } virtual void CancelEvent() override { finished_watcher_mutex_.lock(); finished_watcher_wait_cond_.wakeAll(); finished_watcher_mutex_.unlock(); } virtual bool TwoStepFrameRendering() const { return true; } void SetNativeProgressSignallingEnabled(bool e) { native_progress_signalling_ = e; } /** * @brief Only valid after Render() is called */ int64_t GetTotalNumberOfFrames() const { return total_number_of_frames_; } private: void PrepareWatcher(RenderTicketWatcher* watcher, QThread *thread); void IncrementRunningTickets(); void StartTicket(QThread *watcher_thread, ColorManager *manager, const rational &time, RenderMode::Mode mode, FrameHashCache *cache, const QSize &force_size, const QMatrix4x4 &force_matrix, PixelFormat force_format, int force_channel_count, ColorProcessorPtr force_color_output); ViewerOutput* viewer_; VideoParams video_params_; AudioParams audio_params_; QVector<RenderTicketWatcher*> running_watchers_; std::list<RenderTicketWatcher*> finished_watchers_; int running_tickets_; QMutex finished_watcher_mutex_; QWaitCondition finished_watcher_wait_cond_; bool native_progress_signalling_; int64_t total_number_of_frames_; private slots: void TicketDone(RenderTicketWatcher *watcher); }; } #endif // RENDERTASK_H
3,725
C++
.h
105
31.552381
281
0.748115
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,191
precachetask.h
olive-editor_olive/app/task/precache/precachetask.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 PRECACHETASK_H #define PRECACHETASK_H #include "node/project/footage/footage.h" #include "node/project/sequence/sequence.h" #include "task/render/render.h" namespace olive { class PreCacheTask : public RenderTask { Q_OBJECT public: PreCacheTask(Footage* footage, int index, Sequence* sequence); virtual ~PreCacheTask() override; protected: virtual bool Run() override; virtual bool FrameDownloaded(FramePtr frame, const rational &times) override; virtual bool AudioDownloaded(const TimeRange& range, const SampleBuffer &samples) override; private: Project* project_; Footage* footage_; }; } #endif // PRECACHETASK_H
1,364
C++
.h
36
35.277778
93
0.783969
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,192
export.h
olive-editor_olive/app/task/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 EXPORTTASK_H #define EXPORTTASK_H #include "codec/encoder.h" #include "node/output/viewer/viewer.h" #include "render/colorprocessor.h" #include "render/projectcopier.h" #include "task/render/render.h" #include "task/task.h" namespace olive { class ExportTask : public RenderTask { Q_OBJECT public: ExportTask(ViewerOutput *viewer_node, ColorManager *color_manager, const EncodingParams &params); protected: virtual bool Run() override; virtual bool FrameDownloaded(FramePtr frame, const rational &time) override; virtual bool AudioDownloaded(const TimeRange& range, const SampleBuffer &samples) override; virtual bool EncodeSubtitle(const SubtitleBlock *sub) override; virtual bool TwoStepFrameRendering() const override { return false; } private: bool WriteAudioLoop(const TimeRange &time, const SampleBuffer &samples); ProjectCopier *copier_; QHash<rational, FramePtr> time_map_; QHash<TimeRange, SampleBuffer> audio_map_; ColorManager* color_manager_; EncodingParams params_; std::shared_ptr<Encoder> encoder_; std::shared_ptr<Encoder> subtitle_encoder_; ColorProcessorPtr color_processor_; int64_t frame_time_; rational audio_time_; TimeRange export_range_; }; } #endif // EXPORTTASK_H
1,979
C++
.h
53
34.471698
99
0.782815
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,193
version.h
olive-editor_olive/app/packaging/windows/version.h
#ifndef VERSION_H #define VERSION_H #define VER_FILEVERSION 1,0,0,0 #define VER_FILEVERSION_STR "1.0.0.0\0" #define VER_PRODUCTVERSION 1,0,0,0 #define VER_PRODUCTVERSION_STR "1.0\0" #define VER_COMPANYNAME_STR "Olive Team" #define VER_FILEDESCRIPTION_STR "Olive" #define VER_INTERNALNAME_STR "Olive" #define VER_LEGALCOPYRIGHT_STR "Copyright © 2018 Olive Team" #define VER_LEGALTRADEMARKS1_STR "All Rights Reserved" #define VER_LEGALTRADEMARKS2_STR VER_LEGALTRADEMARKS1_STR #define VER_ORIGINALFILENAME_STR "Olive.exe" #define VER_PRODUCTNAME_STR "Olive" #define VER_COMPANYDOMAIN_STR "www.olivevideoeditor.org" #endif // VERSION_H
719
C++
.h
16
43.625
66
0.712034
olive-editor/olive
8,144
552
131
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
19,194
viewer.h
olive-editor_olive/app/widget/viewer/viewer.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 VIEWER_WIDGET_H #define VIEWER_WIDGET_H #include <QFile> #include <QLabel> #include <QPushButton> #include <QScrollBar> #include <QTimer> #include <QWidget> #include "audio/audioprocessor.h" #include "audiowaveformview.h" #include "node/output/viewer/viewer.h" #include "render/previewaudiodevice.h" #include "render/previewautocacher.h" #include "viewerdisplay.h" #include "viewersizer.h" #include "viewerwindow.h" #include "widget/playbackcontrols/playbackcontrols.h" #include "widget/timebased/timebasedwidget.h" #include "widget/timelinewidget/timelinewidget.h" namespace olive { class MulticamWidget; /** * @brief An OpenGL-based viewer widget with playback controls (a PlaybackControls widget). */ class ViewerWidget : public TimeBasedWidget { Q_OBJECT public: enum WaveformMode { kWFAutomatic, kWFViewerOnly, kWFWaveformOnly, kWFViewerAndWaveform }; ViewerWidget(QWidget* parent = nullptr) : ViewerWidget(new ViewerDisplayWidget(), parent) {} virtual ~ViewerWidget() override; void SetPlaybackControlsEnabled(bool enabled); void SetTimeRulerEnabled(bool enabled); void TogglePlayPause(); bool IsPlaying() const; /** * @brief Enable or disable the color management menu * * While the Viewer is _always_ color managed, In some contexts, the color management may be controlled from an * external UI making the menu unnecessary. */ void SetColorMenuEnabled(bool enabled); void SetMatrix(const QMatrix4x4& mat); /** * @brief Creates a ViewerWindow widget and places it full screen on another screen * * If `screen` is nullptr, the screen will be automatically selected as whichever one contains the mouse cursor. */ void SetFullScreen(QScreen* screen = nullptr); ColorManager* color_manager() const { return display_widget_->color_manager(); } void SetGizmos(Node* node); void StartCapture(TimelineWidget *source, const TimeRange &time, const Track::Reference &track); void SetAudioScrubbingEnabled(bool e) { enable_audio_scrubbing_ = e; } void AddPlaybackDevice(ViewerDisplayWidget *vw) { playback_devices_.push_back(vw); } void SetTimelineSelectedBlocks(const QVector<Block*> &b) { timeline_selected_blocks_ = b; if (!IsPlaying()) { // If is playing, this will happen by the next frame automatically DetectMulticamNodeNow(); UpdateTextureFromNode(); } } void SetNodeViewSelections(const QVector<Node*> &n) { node_view_selected_ = n; if (!IsPlaying()) { // If is playing, this will happen by the next frame automatically DetectMulticamNodeNow(); UpdateTextureFromNode(); } } void ConnectMulticamWidget(MulticamWidget *p); public slots: void Play(bool in_to_out_only); void Play(); void Pause(); void ShuttleLeft(); void ShuttleStop(); void ShuttleRight(); void SetColorTransform(const ColorTransform& transform); /** * @brief Wrapper for ViewerGLWidget::SetSignalCursorColorEnabled() */ void SetSignalCursorColorEnabled(bool e); void CacheEntireSequence(); void CacheSequenceInOut(); void SetViewerResolution(int width, int height); void SetViewerPixelAspect(const rational& ratio); void UpdateTextureFromNode(); void RequestStartEditingText() { display_widget_->RequestStartEditingText(); } signals: /** * @brief Wrapper for ViewerGLWidget::CursorColor() */ void CursorColor(const Color& reference, const Color& display); /** * @brief Signal emitted when a new frame is loaded */ void TextureChanged(TexturePtr t); /** * @brief Wrapper for ViewerGLWidget::ColorProcessorChanged() */ void ColorProcessorChanged(ColorProcessorPtr processor); /** * @brief Wrapper for ViewerGLWidget::ColorManagerChanged() */ void ColorManagerChanged(ColorManager* color_manager); protected: ViewerWidget(ViewerDisplayWidget *display, QWidget* parent = nullptr); virtual void TimebaseChangedEvent(const rational &) override; virtual void TimeChangedEvent(const rational &time) override; virtual void ConnectNodeEvent(ViewerOutput *) override; virtual void DisconnectNodeEvent(ViewerOutput *) override; virtual void ConnectedNodeChangeEvent(ViewerOutput *) override; virtual void ConnectedWorkAreaChangeEvent(TimelineWorkArea *) override; virtual void ConnectedMarkersChangeEvent(TimelineMarkerList *) override; virtual void ScaleChangedEvent(const double& s) override; virtual void resizeEvent(QResizeEvent *event) override; PlaybackControls* controls_; ViewerDisplayWidget* display_widget() const { return display_widget_; } void IgnoreNextScrubEvent() { ignore_scrub_++; } RenderTicketPtr GetSingleFrame(const rational &t, bool dry = false); void SetWaveformMode(WaveformMode wf); private: int64_t GetTimestamp() const { return Timecode::time_to_timestamp(GetConnectedNode()->GetPlayhead(), timebase(), Timecode::kFloor); } void UpdateTimeInternal(int64_t i); void PlayInternal(int speed, bool in_to_out_only); void PauseInternal(); void PushScrubbedAudio(); void UpdateMinimumScale(); void SetColorTransform(const ColorTransform& transform, ViewerDisplayWidget* sender); QString GetCachedFilenameFromTime(const rational& time); bool FrameExistsAtTime(const rational& time); bool ViewerMightBeAStill(); void SetDisplayImage(RenderTicketPtr ticket); RenderTicketWatcher *RequestNextFrameForQueue(bool increment = true); RenderTicketPtr GetFrame(const rational& t); void FinishPlayPreprocess(); int DeterminePlaybackQueueSize(); static FramePtr DecodeCachedImage(const QString &cache_path, const QUuid &cache_id, const int64_t& time); static void DecodeCachedImage(RenderTicketPtr ticket, const QString &cache_path, const QUuid &cache_id, const int64_t &time); bool ShouldForceWaveform() const; void SetEmptyImage(); void UpdateAutoCacher(); void DecrementPrequeuedAudio(); void ArmForRecording(); void DisarmRecording(); void CloseAudioProcessor(); void DetectMulticamNode(const rational &time); bool IsVideoVisible() const; ViewerSizer* sizer_; int playback_speed_; rational last_time_; bool color_menu_enabled_; bool time_changed_from_timer_; bool play_in_to_out_only_; AudioWaveformView* waveform_view_; QHash<QScreen*, ViewerWindow*> windows_; ViewerDisplayWidget* display_widget_; ViewerDisplayWidget* context_menu_widget_; QTimer playback_backup_timer_; int64_t playback_queue_next_frame_; int64_t dry_run_next_frame_; QVector<ViewerDisplayWidget*> playback_devices_; bool prequeuing_video_; int prequeuing_audio_; QList<RenderTicketWatcher*> nonqueue_watchers_; rational last_length_; int prequeue_length_; int prequeue_count_; QVector<RenderTicketWatcher*> queue_watchers_; std::list<RenderTicketWatcher*> audio_playback_queue_; rational audio_playback_queue_time_; AudioProcessor audio_processor_; QByteArray prequeued_audio_; static const rational kAudioPlaybackInterval; static QVector<ViewerWidget*> instances_; std::list<RenderTicketWatcher*> audio_scrub_watchers_; bool record_armed_; bool recording_; TimelineWidget *recording_callback_; TimeRange recording_range_; Track::Reference recording_track_; QString recording_filename_; qint64 queue_starved_start_; RenderTicketWatcher *first_requeue_watcher_; bool enable_audio_scrubbing_; WaveformMode waveform_mode_; QVector<RenderTicketWatcher*> dry_run_watchers_; int ignore_scrub_; QVector<Block*> timeline_selected_blocks_; QVector<Node*> node_view_selected_; MulticamWidget *multicam_panel_; private slots: void PlaybackTimerUpdate(); void LengthChangedSlot(const rational& length); void InterlacingChangedSlot(VideoParams::Interlacing interlacing); void UpdateRendererVideoParameters(); void UpdateRendererAudioParameters(); void ShowContextMenu(const QPoint& pos); void SetZoomFromMenu(QAction* action); void UpdateWaveformViewFromMode(); void ContextMenuSetFullScreen(QAction* action); void ContextMenuSetPlaybackRes(QAction* action); void ContextMenuDisableSafeMargins(); void ContextMenuSetSafeMargins(); void ContextMenuSetCustomSafeMargins(); void WindowAboutToClose(); void RendererGeneratedFrame(); void RendererGeneratedFrameForQueue(); void ViewerInvalidatedVideoRange(const olive::TimeRange &range); void UpdateWaveformModeFromMenu(QAction *a); void DragEntered(QDragEnterEvent* event); void Dropped(QDropEvent* event); void QueueNextAudioBuffer(); void ReceivedAudioBufferForPlayback(); void ReceivedAudioBufferForScrubbing(); void QueueStarved(); void QueueNoLongerStarved(); void ForceRequeueFromCurrentTime(); void UpdateAudioProcessor(); void CreateAddableAt(const QRectF &f); void HandleFirstRequeueDestroy(); void ShowSubtitleProperties(); void DryRunFinished(); void RequestNextDryRun(); void SaveFrameAsImage(); void DetectMulticamNodeNow(); }; } #endif // VIEWER_WIDGET_H
9,838
C++
.h
274
32.339416
127
0.777931
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,195
viewersizer.h
olive-editor_olive/app/widget/viewer/viewersizer.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 VIEWERSIZER_H #define VIEWERSIZER_H #include <olive/core/core.h> #include <QScrollBar> #include <QWidget> namespace olive { using namespace core; /** * @brief A container widget that enforces the aspect ratio of a child widget * * Using a provided width and height, this widget calculates the aspect ratio and forces the child widget to stay * confined to that aspect ratio and centered within the widget. * * The aspect ratio is calculated width divided by height. If the aspect ratio is zero (either width or height == 0), * the widget is hidden until a valid size is provided. */ class ViewerSizer : public QWidget { Q_OBJECT public: ViewerSizer(QWidget* parent = nullptr); /** * @brief Set the widget to be adjusted by this widget * * ViewerSizer takes ownership of this widget. If a widget was previously set, it is destroyed. */ void SetWidget(QWidget* widget); QSize GetContainerSize() const; static constexpr int kZoomLevelCount = 10; static constexpr double kZoomLevels[kZoomLevelCount] = {0.05, 0.1, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 4.0, 8.0}; public slots: /** * @brief Set resolution to use * * This is not the actual resolution of the viewer, it's used to calculate the aspect ratio */ void SetChildSize(int width, int height); /** * @brief Set pixel aspect ratio */ void SetPixelAspectRatio(const rational& pixel_aspect); /** * @brief Set the zoom value of the child widget * * The number is an integer percentage (100 = 100%). Set to 0 to auto-fit. */ void SetZoom(double percent); void SetZoomAnchored(double percent, double cursor_x, double cursor_y); void HandDragMove(int x, int y); virtual bool eventFilter(QObject *watched, QEvent *event) override; signals: void RequestScale(const QMatrix4x4& matrix); void RequestTranslate(const QMatrix4x4& matrix); protected: /** * @brief Listen for resize events to ensure the child widget remains correctly sized */ virtual void resizeEvent(QResizeEvent *event) override; private: /** * @brief Main sizing function, resizes widget_ to fit aspect_ratio_ (or hides if aspect ratio is 0) */ void UpdateSize(); int GetZoomedValue(int value); double GetRealCurrentZoom() const; /** * @brief Reference to widget * * If this is nullptr, all sizing operations are no-ops */ QWidget* widget_; /** * @brief Internal resolution values */ int width_; int height_; rational pixel_aspect_; /** * @brief Internal zoom value */ double zoom_; double current_widget_scale_; QScrollBar* horiz_scrollbar_; QScrollBar* vert_scrollbar_; private slots: void ScrollBarMoved(); }; } #endif // VIEWERSIZER_H
3,446
C++
.h
103
30.368932
117
0.737764
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,196
viewersafemargininfo.h
olive-editor_olive/app/widget/viewer/viewersafemargininfo.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 VIEWERSAFEMARGININFO_H #define VIEWERSAFEMARGININFO_H #include <QtMath> #include "common/define.h" namespace olive { class ViewerSafeMarginInfo { public: ViewerSafeMarginInfo() : enabled_(false) { } ViewerSafeMarginInfo(bool enabled, double ratio = 0) : enabled_(enabled), ratio_(ratio) { } bool is_enabled() const { return enabled_; } bool custom_ratio() const { return (ratio_ > 0); } double ratio() const { return ratio_; } bool operator==(const ViewerSafeMarginInfo& rhs) const { return (enabled_ == rhs.enabled_ && qFuzzyCompare(ratio_, rhs.ratio_)); } bool operator!=(const ViewerSafeMarginInfo& rhs) const { return (enabled_ != rhs.enabled_ || !qFuzzyCompare(ratio_, rhs.ratio_)); } private: bool enabled_; double ratio_; }; } #endif // VIEWERSAFEMARGININFO_H
1,576
C++
.h
54
25.981481
76
0.731512
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,197
viewerpreventsleep.h
olive-editor_olive/app/widget/viewer/viewerpreventsleep.h
#ifndef VIEWERPREVENTSLEEP_H #define VIEWERPREVENTSLEEP_H namespace olive { void PreventSleep(bool on); } #endif // VIEWERPREVENTSLEEP_H
141
C++
.h
6
21.833333
30
0.839695
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,198
viewerplaybacktimer.h
olive-editor_olive/app/widget/viewer/viewerplaybacktimer.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 VIEWERPLAYBACKTIMER_H #define VIEWERPLAYBACKTIMER_H #include <QtGlobal> #include "common/define.h" namespace olive { class ViewerPlaybackTimer { public: void Start(const int64_t& start_timestamp, const int& playback_speed, const double& timebase); int64_t GetTimestampNow() const; private: qint64 start_msec_; int64_t start_timestamp_; int playback_speed_; double timebase_; }; } #endif // VIEWERPLAYBACKTIMER_H
1,155
C++
.h
31
34.548387
96
0.778681
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,199
viewerqueue.h
olive-editor_olive/app/widget/viewer/viewerqueue.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 VIEWERQUEUE_H #define VIEWERQUEUE_H #include "codec/frame.h" namespace olive { struct ViewerPlaybackFrame { rational timestamp; QVariant frame; }; class ViewerQueue : public std::list<ViewerPlaybackFrame> { public: ViewerQueue() = default; void AppendTimewise(const ViewerPlaybackFrame& f, int playback_speed) { if (this->empty() || (this->back().timestamp < f.timestamp) == (playback_speed > 0)) { this->push_back(f); } else { for (auto i=this->begin(); i!=this->end(); i++) { if ((i->timestamp > f.timestamp) == (playback_speed > 0)) { this->insert(i, f); break; } } } } void PurgeBefore(const rational &time, int playback_speed) { while (!this->empty() && ((playback_speed > 0 && this->front().timestamp < time) || (playback_speed < 0 && this->front().timestamp > time))) { this->pop_front(); } } }; } #endif // VIEWERQUEUE_H
1,667
C++
.h
50
29.38
131
0.686017
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,200
audiowaveformview.h
olive-editor_olive/app/widget/viewer/audiowaveformview.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 AUDIOWAVEFORMVIEW_H #define AUDIOWAVEFORMVIEW_H #include <QtConcurrent/QtConcurrent> #include <QWidget> #include "render/audioplaybackcache.h" #include "widget/timeruler/seekablewidget.h" namespace olive { class AudioWaveformView : public SeekableWidget { Q_OBJECT public: AudioWaveformView(QWidget* parent = nullptr); void SetViewer(ViewerOutput *playback); protected: virtual void drawForeground(QPainter *painter, const QRectF &rect) override; private: QThreadPool pool_; ViewerOutput *playback_; }; } #endif // AUDIOWAVEFORMVIEW_H
1,278
C++
.h
35
34
78
0.792822
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,201
viewerdisplay.h
olive-editor_olive/app/widget/viewer/viewerdisplay.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 VIEWERGLWIDGET_H #define VIEWERGLWIDGET_H #include <QMatrix4x4> #include <QRubberBand> #include "node/color/colormanager/colormanager.h" #include "node/gizmo/text.h" #include "node/node.h" #include "node/output/track/tracklist.h" #include "node/traverser.h" #include "tool/tool.h" #include "viewerplaybacktimer.h" #include "viewerqueue.h" #include "viewersafemargininfo.h" #include "viewertexteditor.h" #include "widget/manageddisplay/manageddisplay.h" #include "widget/timetarget/timetarget.h" namespace olive { /** * @brief The inner display/rendering widget of a Viewer class. * * Actual composition occurs elsewhere offscreen and * multithreaded, so its main purpose is receiving a finalized OpenGL texture and displaying it. * * The main entry point is SetTexture() which will receive an OpenGL texture ID, store it, and then call update() to * draw it on screen. The drawing function is in paintGL() (called during the update() process by Qt) and is fairly * simple OpenGL drawing code standardized around OpenGL ES 3.2 Core. * * If the texture has been modified and you're 100% sure this widget is using the same texture object, it's possible * to call update() directly to trigger a repaint, however this is not recommended. If you are not 100% sure it'll be * the same texture object, use SetTexture() since it will nearly always be faster to just set it than to check *and* * set it. */ class ViewerDisplayWidget : public ManagedDisplayWidget, public TimeTargetObject { Q_OBJECT public: /** * @brief ViewerGLWidget Constructor * * @param parent * * QWidget parent. */ ViewerDisplayWidget(QWidget* parent = nullptr); virtual ~ViewerDisplayWidget() override; const ViewerSafeMarginInfo& GetSafeMargin() const; void SetSafeMargins(const ViewerSafeMarginInfo& safe_margin); void SetGizmos(Node* node); const VideoParams &GetVideoParams() const { return gizmo_params_; } void SetVideoParams(const VideoParams &params); const AudioParams &GetAudioParams() const { return gizmo_audio_params_; } void SetAudioParams(const AudioParams &p); void SetTime(const rational& time); void SetSubtitleTracks(Sequence *list); void SetShowWidgetBackground(bool e) { show_widget_background_ = e; update(); } /** * @brief Transform a point from viewer space to the buffer space. * Multiplies by the inverted transform matrix to undo the scaling and translation. */ QPointF TransformViewerSpaceToBufferSpace(const QPointF &pos); bool IsDeinterlacing() const { return deinterlace_; } void ResetFPSTimer(); bool GetShowFPS() const { return show_fps_; } bool GetShowSubtitles() const { return show_subtitles_; } void SetShowSubtitles(bool e) { show_subtitles_ = e; update(); } void IncrementSkippedFrames(); void IncrementFrameCount() { fps_timer_update_count_++; } TexturePtr GetCurrentTexture() const { return texture_; } void Play(const int64_t &start_timestamp, const int &playback_speed, const rational &timebase, bool start_updating); void Pause(); ViewerQueue* queue() { return &queue_; } ViewerPlaybackTimer *timer() { return &timer_; } QPointF ScreenToScenePoint(const QPoint &p); virtual bool eventFilter(QObject *o, QEvent *e) override; public slots: /** * @brief Set the transformation matrix to draw with * * Set this if you want the drawing to pass through some sort of transform (most of the time you won't want this). */ void SetMatrixTranslate(const QMatrix4x4& mat); /** * @brief Set the scale matrix. */ void SetMatrixZoom(const QMatrix4x4& mat); void SetMatrixCrop(const QMatrix4x4& mat); /** * @brief Enables or disables whether this color at the cursor should be emitted * * Since tracking the mouse every movement, reading pixels, and doing color transforms are processor intensive, we * have an option for it. Ideally, this should be connected to a PixelSamplerPanel::visibilityChanged signal so that * it can automatically be enabled when the user is pixel sampling and disabled for optimization when they're not. */ void SetSignalCursorColorEnabled(bool e); void SetImage(const QVariant &buffer); void SetBlank(); /** * @brief Changes the pointer type if the tool is changed to the hand tool. Otherwise resets the pointer to it's * normal type. */ void UpdateCursor(); void ToolChanged(); /** * @brief Enables/disables a basic deinterlace on the viewer */ void SetDeinterlacing(bool e); void SetShowFPS(bool e); void RequestStartEditingText(); signals: /** * @brief Signal emitted when the user starts dragging from the viewer */ void DragStarted(const QPoint &p); /** * @brief Signal emitted when a hand drag starts */ void HandDragStarted(); /** * @brief Signal emitted when a hand drag moves */ void HandDragMoved(int x, int y); /** * @brief Signal emitted when a hand drag ends */ void HandDragEnded(); /** * @brief Signal emitted when cursor color is enabled and the user's mouse position changes */ void CursorColor(const Color& reference, const Color& display); void DragEntered(QDragEnterEvent* event); void DragLeft(QDragLeaveEvent* event); void Dropped(QDropEvent* event); void TextureChanged(TexturePtr texture); void QueueStarved(); void QueueNoLongerStarved(); void CreateAddableAt(const QRectF &rect); protected: QTransform GenerateWorldTransform(); QTransform GenerateDisplayTransform(); QTransform GenerateGizmoTransform(NodeTraverser &gt, const TimeRange &range); QTransform GenerateGizmoTransform() { NodeTraverser t; t.SetCacheVideoParams(gizmo_params_); return GenerateGizmoTransform(t, GenerateGizmoTime()); } TimeRange GenerateGizmoTime() { rational node_time = GetGizmoTime(); return TimeRange(node_time, node_time + gizmo_params_.frame_rate_as_time_base()); } virtual TexturePtr LoadCustomTextureFromFrame(const QVariant &v) { return nullptr; } protected slots: /** * @brief Paint function to display the texture (received in SetTexture()) on screen. * * Simple OpenGL drawing function for painting the texture on screen. Standardized around OpenGL ES 3.2 Core. */ virtual void OnPaint() override; virtual void OnDestroy() override; private: QPointF GetTexturePosition(const QPoint& screen_pos); QPointF GetTexturePosition(const QSize& size); QPointF GetTexturePosition(const double& x, const double& y); static void DrawTextWithCrudeShadow(QPainter* painter, const QRect& rect, const QString& text, const QTextOption &opt = QTextOption()); rational GetGizmoTime(); bool IsHandDrag(QMouseEvent* event) const; void UpdateMatrix(); NodeGizmo *TryGizmoPress(const NodeValueRow &row, const QPointF &p); void OpenTextGizmo(TextGizmo *text, QMouseEvent *event = nullptr); bool OnMousePress(QMouseEvent *e); bool OnMouseMove(QMouseEvent *e); bool OnMouseRelease(QMouseEvent *e); bool OnMouseDoubleClick(QMouseEvent *e); bool OnKeyPress(QKeyEvent *e); bool OnKeyRelease(QKeyEvent *e); void EmitColorAtCursor(QMouseEvent* e); void DrawSubtitleTracks(); QPointF GetVirtualPosForTextEdit(const QPointF &p) { return text_transform_inverted_.map(p) - text_edit_pos_; } template <typename T> void ForwardDragEventToTextEdit(T *event); bool ForwardMouseEventToTextEdit(QMouseEvent *event, bool check_if_outside = false); bool ForwardEventToTextEdit(QEvent *event); QPointF AdjustPosByVAlign(QPointF p); void CloseTextEditor(); void GenerateGizmoTransforms(); void DrawBlank(const VideoParams &device_params); /** * @brief Internal reference to the OpenGL texture to draw. Set in SetTexture() and used in paintGL(). */ TexturePtr texture_; /** * @brief Internal texture to deinterlace to */ TexturePtr deinterlace_texture_; /** * @brief Deinterlace shader */ QVariant deinterlace_shader_; /** * @brief Blank shader */ QVariant blank_shader_; /** * @brief Translation only matrix (defaults to identity). */ QMatrix4x4 translate_matrix_; /** * @brief Scale only matrix. */ QMatrix4x4 scale_matrix_; /** * @brief Crop only matrix */ QMatrix4x4 crop_matrix_; /** * @brief Cached result of translate_matrix_ and scale_matrix_ multiplied */ QMatrix4x4 combined_matrix_; QMatrix4x4 combined_matrix_flipped_; bool signal_cursor_color_; ViewerSafeMarginInfo safe_margin_; Node* gizmos_; NodeValueRow gizmo_db_; VideoParams gizmo_params_; AudioParams gizmo_audio_params_; QPoint gizmo_start_drag_; QPoint gizmo_last_drag_; TimeRange gizmo_draw_time_; NodeGizmo *current_gizmo_; bool gizmo_drag_started_; QTransform gizmo_last_draw_transform_; QTransform gizmo_last_draw_transform_inverted_; bool show_subtitles_; Sequence *subtitle_tracks_; rational time_; /** * @brief Position of mouse to calculate delta from. */ QPoint hand_last_drag_pos_; bool hand_dragging_; bool deinterlace_; qint64 fps_timer_start_; int fps_timer_update_count_; bool show_fps_; int frames_skipped_; QVector<double> frame_rate_averages_; int frame_rate_average_count_; bool show_widget_background_; QVariant load_frame_; int playback_speed_; enum PushMode { /// New frame to push to internal texture kPushFrame, /// Internal texture reference is up to date, keep showing it kPushUnnecessary, /// Draw blank/black screen kPushBlank, /// Draw nothing (not even a black frame) kPushNull, }; PushMode push_mode_; // Playback ViewerQueue queue_; ViewerPlaybackTimer timer_; rational playback_timebase_; bool add_band_; QPoint add_band_start_; QPoint add_band_end_; bool queue_starved_; TextGizmo *active_text_gizmo_; QPointF text_edit_pos_; ViewerTextEditor *text_edit_; ViewerTextEditorToolBar *text_toolbar_; QTransform text_transform_; QTransform text_transform_inverted_; private slots: void UpdateFromQueue(); void TextEditChanged(); void TextEditDestroyed(); void SubtitlesChanged(const TimeRange &r); void FocusChanged(QWidget *old, QWidget *now); QRectF UpdateActiveTextGizmoSize(); }; } #endif // VIEWERGLWIDGET_H
11,091
C++
.h
328
30.375
137
0.749601
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,202
viewerwindow.h
olive-editor_olive/app/widget/viewer/viewerwindow.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 VIEWERWINDOW_H #define VIEWERWINDOW_H #include <QWidget> #include "viewerdisplay.h" namespace olive { class ViewerWindow : public QWidget { public: ViewerWindow(QWidget* parent = nullptr); ViewerDisplayWidget* display_widget() const; /** * @brief Used to adjust resulting picture to be the right aspect ratio * * Equivalent to calling SetResolution and SetPixelAspectRatio, just slightly faster since we * only calculate the matrix once rather than twice. */ void SetVideoParams(const VideoParams &params); /** * @brief Used to adjust resulting picture to be the right aspect ratio */ void SetResolution(int width, int height); /** * @brief Used to adjust resulting picture to be the right aspect ratio */ void SetPixelAspectRatio(const rational& pixel_aspect); protected: virtual void keyPressEvent(QKeyEvent* e) override; virtual void closeEvent(QCloseEvent* e) override; private: void UpdateMatrix(); int width_; int height_; ViewerDisplayWidget* display_widget_; rational pixel_aspect_; }; } #endif // VIEWERWINDOW_H
1,816
C++
.h
51
32.54902
95
0.767375
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,203
footageviewer.h
olive-editor_olive/app/widget/viewer/footageviewer.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 FOOTAGEVIEWERWIDGET_H #define FOOTAGEVIEWERWIDGET_H #include "node/output/viewer/viewer.h" #include "viewer.h" namespace olive { class FootageViewerWidget : public ViewerWidget { Q_OBJECT public: FootageViewerWidget(QWidget* parent = nullptr); void OverrideWorkArea(const TimeRange &r); void ResetWorkArea(); private: void StartFootageDragInternal(bool enable_video, bool enable_audio); TimelineWorkArea *override_workarea_; private slots: void StartFootageDrag(); void StartVideoDrag(); void StartAudioDrag(); void VideoButtonClicked(); void AudioButtonClicked(); }; } #endif // FOOTAGEVIEWERWIDGET_H
1,358
C++
.h
38
33
71
0.787692
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,204
viewertexteditor.h
olive-editor_olive/app/widget/viewer/viewertexteditor.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 VIEWERTEXTEDITOR_H #define VIEWERTEXTEDITOR_H #include <QApplication> #include <QDebug> #include <QFontComboBox> #include <QTextEdit> #include <QPushButton> #include "widget/slider/floatslider.h" #include "widget/slider/integerslider.h" namespace olive { class ViewerTextEditorToolBar : public QWidget { Q_OBJECT public: ViewerTextEditorToolBar(QWidget *parent = nullptr); QString GetFontFamily() const { return font_combo_->currentText(); } QString GetFontStyleName() const { return style_combo_->currentText(); } public slots: void SetFontFamily(QString s) { font_combo_->blockSignals(true); font_combo_->setCurrentFont(s); UpdateFontStyleList(s); font_combo_->blockSignals(false); } void SetStyle(QString style) { style_combo_->blockSignals(true); style_combo_->setCurrentText(style); style_combo_->blockSignals(false); } void SetFontSize(double d) { font_sz_slider_->SetValue(d); } void SetUnderline(bool e) { underline_btn_->setChecked(e); } void SetStrikethrough(bool e) { strikethrough_btn_->setChecked(e); } void SetAlignment(Qt::Alignment a); void SetVerticalAlignment(Qt::Alignment a); void SetColor(const QColor &c); void SetSmallCaps(bool e) { small_caps_btn_->setChecked(e); } void SetStretch(int i) { stretch_slider_->SetValue(i); } void SetKerning(qreal i) { kerning_slider_->SetValue(i); } void SetLineHeight(qreal i) { line_height_slider_->SetValue(i); } signals: void FamilyChanged(const QString &s); void SizeChanged(double d); void StyleChanged(const QString &s); void UnderlineChanged(bool e); void StrikethroughChanged(bool e); void AlignmentChanged(Qt::Alignment alignment); void VerticalAlignmentChanged(Qt::Alignment alignment); void ColorChanged(const QColor &c); void SmallCapsChanged(bool e); void StretchChanged(int i); void KerningChanged(qreal i); void LineHeightChanged(qreal i); void FirstPaint(); protected: virtual void mousePressEvent(QMouseEvent *event) override; virtual void mouseMoveEvent(QMouseEvent *event) override; virtual void mouseReleaseEvent(QMouseEvent *event) override; virtual void closeEvent(QCloseEvent *event) override; virtual void paintEvent(QPaintEvent *event) override; private: void AddSpacer(QLayout *l); QPoint drag_anchor_; QFontComboBox *font_combo_; FloatSlider *font_sz_slider_; QComboBox *style_combo_; QPushButton *underline_btn_; QPushButton *strikethrough_btn_; QPushButton *align_left_btn_; QPushButton *align_center_btn_; QPushButton *align_right_btn_; QPushButton *align_justify_btn_; QPushButton *align_top_btn_; QPushButton *align_middle_btn_; QPushButton *align_bottom_btn_; IntegerSlider *stretch_slider_; FloatSlider *kerning_slider_; FloatSlider *line_height_slider_; QPushButton *small_caps_btn_; QPushButton *color_btn_; bool painted_; bool drag_enabled_; private slots: void UpdateFontStyleList(const QString &family); void UpdateFontStyleListAndEmitFamilyChanged(const QString &family); }; class ViewerTextEditor : public QTextEdit { Q_OBJECT public: ViewerTextEditor(double scale, QWidget *parent = nullptr); void ConnectToolBar(ViewerTextEditorToolBar *toolbar); void Paint(QPainter *p, Qt::Alignment valign); virtual void dragEnterEvent(QDragEnterEvent *e) override { return QTextEdit::dragEnterEvent(e); } virtual void dragMoveEvent(QDragMoveEvent *e) override { return QTextEdit::dragMoveEvent(e); } virtual void dragLeaveEvent(QDragLeaveEvent *e) override { return QTextEdit::dragLeaveEvent(e); } virtual void dropEvent(QDropEvent *e) override { return QTextEdit::dropEvent(e); } protected: virtual void paintEvent(QPaintEvent *event) override; private: static void UpdateToolBar(ViewerTextEditorToolBar *toolbar, const QTextCharFormat &f, const QTextBlockFormat &b, Qt::Alignment alignment); void MergeCharFormat(const QTextCharFormat &fmt); void ApplyStyle(QTextCharFormat *format, const QString &family, const QString &style); QVector<ViewerTextEditorToolBar *> toolbars_; QImage dpi_force_; QTextDocument *transparent_clone_; bool block_update_toolbar_signal_; bool forced_default_; QTextCharFormat default_fmt_; private slots: void FormatChanged(const QTextCharFormat &f); void SetFamily(const QString &s); void SetStyle(const QString &s); void SetFontStrikethrough(bool e); void SetSmallCaps(bool e); void SetFontStretch(int i); void SetFontKerning(qreal i); void SetLineHeight(qreal i); void LockScrollBarMaximumToZero(); void DocumentChanged(); }; } #endif // VIEWERTEXTEDITOR_H
5,374
C++
.h
144
34.173611
140
0.774144
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,205
manageddisplay.h
olive-editor_olive/app/widget/manageddisplay/manageddisplay.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 MANAGEDDISPLAYOBJECT_H #define MANAGEDDISPLAYOBJECT_H //#define USE_QOPENGLWINDOW #include <QMouseEvent> #include <QOpenGLContext> #ifdef USE_QOPENGLWINDOW #include <QOpenGLWindow> #else #include <QOpenGLWidget> #endif #include "node/color/colormanager/colormanager.h" #include "render/renderer.h" #include "widget/menu/menu.h" namespace olive { class ManagedDisplayWidgetOpenGL #ifdef USE_QOPENGLWINDOW : public QOpenGLWindow #else : public QOpenGLWidget #endif { Q_OBJECT public: ManagedDisplayWidgetOpenGL() = default; virtual ~ManagedDisplayWidgetOpenGL() override { if (context()) { DestroyListener(); disconnect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &ManagedDisplayWidgetOpenGL::DestroyListener); } } signals: // Render signals void OnInit(); void OnPaint(); void OnDestroy(); protected: virtual void initializeGL() override { connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &ManagedDisplayWidgetOpenGL::DestroyListener, Qt::DirectConnection); emit OnInit(); } virtual void paintGL() override { emit OnPaint(); } private slots: void DestroyListener() { makeCurrent(); emit OnDestroy(); doneCurrent(); } }; #define MANAGEDDISPLAYWIDGET_DEFAULT_DESTRUCTOR_INNER \ makeCurrent();OnDestroy();doneCurrent() #define MANAGEDDISPLAYWIDGET_DEFAULT_DESTRUCTOR(x) \ virtual ~x() override{MANAGEDDISPLAYWIDGET_DEFAULT_DESTRUCTOR_INNER;} class ManagedDisplayWidget : public QWidget { Q_OBJECT public: ManagedDisplayWidget(QWidget* parent = nullptr); virtual ~ManagedDisplayWidget() override; /** * @brief Disconnect a ColorManager (equivalent to ConnectColorManager(nullptr)) */ void DisconnectColorManager(); /** * @brief Access currently connected ColorManager (nullptr if none) */ ColorManager* color_manager() const; /** * @brief Get current color transform */ const ColorTransform& GetColorTransform() const; /** * @brief Get menu that can be used to select the colorspace */ Menu* GetColorSpaceMenu(QMenu* parent, bool auto_connect = true); /** * @brief Get menu that can be used to select the display transform */ Menu* GetDisplayMenu(QMenu* parent, bool auto_connect = true); /** * @brief Get menu that can be used to select the view transform */ Menu* GetViewMenu(QMenu* parent, bool auto_connect = true); /** * @brief Get menu that can be used to select the look transform */ Menu* GetLookMenu(QMenu* parent, bool auto_connect = true); /** * @brief Passes update signal through to inner widget */ void update(); virtual bool eventFilter(QObject *o, QEvent *e) override; public slots: /** * @brief Replaces the color transform with a new one */ void SetColorTransform(const ColorTransform& transform); /** * @brief Connect a ColorManager (ColorManagers usually belong to the Project) */ void ConnectColorManager(ColorManager* color_manager); signals: /** * @brief Emitted when the color processor changes */ void ColorProcessorChanged(ColorProcessorPtr processor); /** * @brief Emitted when a new color manager is connected */ void ColorManagerChanged(ColorManager* color_manager); void frameSwapped(); protected: /** * @brief Provides access to the color processor (nullptr if none is set) */ ColorProcessorPtr color_service(); /** * @brief Enables a context menu that allows simple access to the DVL pipeline */ void EnableDefaultContextMenu(); /** * @brief Function called whenever the processor changes * * Default functionality is just to call update() */ virtual void ColorProcessorChangedEvent(); Renderer* renderer() const { return attached_renderer_; } void makeCurrent(); void doneCurrent(); #ifdef USE_QOPENGLWINDOW QWindow* #else QWidget* #endif inner_widget() const { return inner_widget_; } /** * @brief Get inner widget as paint device for QPainter * * NOTE: This will be incompatible with QVulkanWindow so functions using it * will need to be replaced soon. */ QPaintDevice *paint_device() const; void SetInnerMouseTracking(bool e); QRect GetInnerRect() const { return wrapper_ ? wrapper_->rect() : QRect(); } VideoParams GetViewportParams() const; protected slots: /** * @brief Called whenever the internal rendering context has been created */ virtual void OnInit(); /** * @brief Called while the internal rendering context is being rendered */ virtual void OnPaint() = 0; /** * @brief Called just before the internal rendering context is destroyed */ virtual void OnDestroy(); private: /** * @brief Call this if this user has selected a different display/view/look to recreate the processor */ void SetupColorProcessor(); /** * @brief Cleanup function */ void ClearOCIOLutTexture(); /** * @brief Main drawing surface abstraction */ #ifdef USE_QOPENGLWINDOW QWindow* inner_widget_; #else QWidget* inner_widget_; #endif QWidget *wrapper_; /** * @brief Renderer abstraction */ Renderer* attached_renderer_; /** * @brief Connected color manager */ ColorManager* color_manager_; /** * @brief Color management service */ ColorProcessorPtr color_service_; /** * @brief Internal color transform storage */ ColorTransform color_transform_; private slots: /** * @brief Sets all color settings to the defaults pertaining to this configuration */ void ColorConfigChanged(); /** * @brief The default context menu shown */ void ShowDefaultContextMenu(); /** * @brief If GetDisplayMenu() is called with `auto_connect` set to true, it will be connected to this */ void MenuDisplaySelect(QAction* action); /** * @brief If GetViewMenu() is called with `auto_connect` set to true, it will be connected to this */ void MenuViewSelect(QAction* action); /** * @brief If GetLookMenu() is called with `auto_connect` set to true, it will be connected to this */ void MenuLookSelect(QAction* action); /** * @brief If GetColorSpaceMenu() is called with `auto_connect` set to true, it will be connected to this */ void MenuColorspaceSelect(QAction* action); }; } #endif // MANAGEDDISPLAYOBJECT_H
7,130
C++
.h
251
24.956175
106
0.72842
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,206
curvewidget.h
olive-editor_olive/app/widget/curvewidget/curvewidget.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 CURVEWIDGET_H #define CURVEWIDGET_H #include <QCheckBox> #include <QHBoxLayout> #include <QPushButton> #include <QWidget> #include "curveview.h" #include "widget/nodeparamview/nodeparamviewkeyframecontrol.h" #include "widget/nodeparamview/nodeparamviewwidgetbridge.h" #include "widget/nodetreeview/nodetreeview.h" #include "widget/timebased/timebasedwidget.h" namespace olive { class CurveWidget : public TimeBasedWidget, public TimeTargetObject { Q_OBJECT public: CurveWidget(QWidget* parent = nullptr); const double& GetVerticalScale(); void SetVerticalScale(const double& vscale); void DeleteSelected(); void SelectAll() { view_->SelectAll(); } void DeselectAll() { view_->DeselectAll(); } Node *GetSelectedNodeWithID(const QString &id); virtual bool CopySelected(bool cut) override; virtual bool Paste() override; public slots: void SetNodes(const QVector<Node *> &nodes); protected: virtual void TimebaseChangedEvent(const rational &) override; virtual void ScaleChangedEvent(const double &) override; virtual void TimeTargetChangedEvent(ViewerOutput *target) override; virtual void ConnectedNodeChangeEvent(ViewerOutput* n) override; virtual const QVector<KeyframeViewInputConnection*> *GetSnapKeyframes() const override { return &view_->GetKeyframeTracks(); } virtual const TimeTargetObject *GetKeyframeTimeTarget() const override { return view_; } virtual const std::vector<NodeKeyframe*> *GetSnapIgnoreKeyframes() const override { return &view_->GetSelectedKeyframes(); } private: void SetKeyframeButtonEnabled(bool enable); void SetKeyframeButtonChecked(bool checked); void SetKeyframeButtonCheckedFromType(NodeKeyframe::Type type); void ConnectInput(Node *node, const QString &input, int element); void ConnectInputInternal(Node *node, const QString &input, int element); QHash<NodeKeyframeTrackReference, QColor> keyframe_colors_; NodeTreeView* tree_view_; QPushButton* linear_button_; QPushButton* bezier_button_; QPushButton* hold_button_; CurveView* view_; NodeParamViewKeyframeControl* key_control_; QVector<Node*> nodes_; QVector<NodeKeyframeTrackReference> selected_tracks_; private slots: void SelectionChanged(); void KeyframeTypeButtonTriggered(bool checked); void InputSelectionChanged(const NodeKeyframeTrackReference& ref); void KeyframeViewDragged(int x, int y); void KeyframeViewReleased(); }; } #endif // CURVEWIDGET_H
3,219
C++
.h
88
33.5
88
0.790019
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,207
curveview.h
olive-editor_olive/app/widget/curvewidget/curveview.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 CURVEVIEW_H #define CURVEVIEW_H #include "node/keyframe.h" #include "widget/keyframeview/keyframeview.h" #include "widget/slider/floatslider.h" namespace olive { class CurveView : public KeyframeView { Q_OBJECT public: CurveView(QWidget* parent = nullptr); void ConnectInput(const NodeKeyframeTrackReference &ref); void DisconnectInput(const NodeKeyframeTrackReference &ref); void SelectKeyframesOfInput(const NodeKeyframeTrackReference &ref); void SetKeyframeTrackColor(const NodeKeyframeTrackReference& ref, const QColor& color); const QHash<NodeKeyframeTrackReference, KeyframeViewInputConnection*> &GetConnections() const { return track_connections_; } public slots: void ZoomToFit(); void ZoomToFitSelected(); void ResetZoom(); protected: virtual void drawBackground(QPainter* painter, const QRectF& rect) override; virtual void drawForeground(QPainter *painter, const QRectF &rect) override; virtual void ContextMenuEvent(Menu &m) override; virtual void SceneRectUpdateEvent(QRectF &r) override; virtual qreal GetKeyframeSceneY(KeyframeViewInputConnection *track, NodeKeyframe *key) override; virtual void DrawKeyframe(QPainter *painter, NodeKeyframe *key, KeyframeViewInputConnection *track, const QRectF &key_rect) override; virtual bool FirstChanceMousePress(QMouseEvent *event) override; virtual void FirstChanceMouseMove(QMouseEvent *event) override; virtual void FirstChanceMouseRelease(QMouseEvent *event) override; virtual void KeyframeDragStart(QMouseEvent *event) override; virtual void KeyframeDragMove(QMouseEvent *event, QString &tip) override; virtual void KeyframeDragRelease(QMouseEvent *event, MultiUndoCommand *command) override; private: void ZoomToFitInternal(bool selected_only); qreal GetItemYFromKeyframeValue(NodeKeyframe* key); qreal GetUnscaledItemYFromKeyframeValue(NodeKeyframe* key); QPointF ScalePoint(const QPointF& point); static FloatSlider::DisplayType GetFloatDisplayTypeFromKeyframe(NodeKeyframe *key); static double GetOffsetFromKeyframe(NodeKeyframe *key); void AdjustLines(); QPointF GetKeyframePosition(NodeKeyframe *key); static QPointF GenerateBezierControlPosition(const NodeKeyframe::BezierType mode, const QPointF& start_point, const QPointF& scaled_cursor_diff); QPointF GetScaledCursorPos(const QPointF &cursor_pos); QHash<NodeKeyframeTrackReference, QColor> keyframe_colors_; QHash<NodeKeyframeTrackReference, KeyframeViewInputConnection*> track_connections_; int text_padding_; int minimum_grid_space_; QVector<NodeKeyframeTrackReference> connected_inputs_; struct BezierPoint { QRectF rect; NodeKeyframe *keyframe; NodeKeyframe::BezierType type; }; QVector<BezierPoint> bezier_pts_; const BezierPoint *dragging_bezier_pt_; QPointF dragging_bezier_point_start_; QPointF dragging_bezier_point_opposing_start_; QPointF drag_start_; QVector<QVariant> drag_keyframe_values_; }; } #endif // CURVEVIEW_H
3,817
C++
.h
83
41.686747
135
0.789431
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,208
timelinewidget.h
olive-editor_olive/app/widget/timelinewidget/timelinewidget.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 TIMELINEWIDGET_H #define TIMELINEWIDGET_H #include <QScrollBar> #include <QRubberBand> #include <QWidget> #include "core.h" #include "node/block/transition/transition.h" #include "node/output/viewer/viewer.h" #include "node/project/serializer/serializer.h" #include "timeline/timelinecommon.h" #include "timelineandtrackview.h" #include "widget/slider/rationalslider.h" #include "widget/timebased/timebasedwidget.h" #include "widget/timelinewidget/timelinewidgetselections.h" #include "widget/timelinewidget/tool/import.h" #include "widget/timelinewidget/tool/tool.h" namespace olive { /** * @brief Full widget for working with TimelineOutput nodes * * Encapsulates TimelineViews, TimeRulers, and scrollbars for a complete widget to manipulate Timelines */ class TimelineWidget : public TimeBasedWidget { Q_OBJECT public: TimelineWidget(QWidget* parent = nullptr); virtual ~TimelineWidget() override; void Clear(); void SelectAll(); void DeselectAll(); void RippleToIn(); void RippleToOut(); void EditToIn(); void EditToOut(); void SplitAtPlayhead(); void DeleteSelected(bool ripple = false); void IncreaseTrackHeight(); void DecreaseTrackHeight(); void InsertFootageAtPlayhead(const QVector<ViewerOutput *> &footage); void OverwriteFootageAtPlayhead(const QVector<ViewerOutput *> &footage); void ToggleLinksOnSelected(); void AddDefaultTransitionsToSelected(); virtual bool CopySelected(bool cut) override; virtual bool Paste() override; void PasteInsert(); void DeleteInToOut(bool ripple); void ToggleSelectedEnabled(); void SetColorLabel(int index); void NudgeLeft(); void NudgeRight(); void MoveInToPlayhead(); void MoveOutToPlayhead(); void ShowSpeedDurationDialogForSelectedClips(); void RecordingCallback(const QString &filename, const TimeRange &time, const Track::Reference &track); void EnableRecordingOverlay(const TimelineCoordinate &coord); void DisableRecordingOverlay(); void AddTentativeSubtitleTrack(); void NestSelectedClips(); /** * @brief Timelines should always be connected to sequences */ Sequence* sequence() const { return static_cast<Sequence*>(GetConnectedNode()); } const QVector<Block*>& GetSelectedBlocks() const { return selected_blocks_; } QByteArray SaveSplitterState() const; void RestoreSplitterState(const QByteArray& state); static void ReplaceBlocksWithGaps(const QVector<Block *> &blocks, bool remove_from_graph, MultiUndoCommand *command, bool handle_transitions = true); /** * @brief Retrieve the QGraphicsItem at a particular scene position * * Requires a float-based scene position. If you have a screen position, use GetScenePos() first to convert it to a * scene position */ Block* GetItemAtScenePos(const TimelineCoordinate &coord); void AddSelection(const TimeRange& time, const Track::Reference& track); void AddSelection(Block* item); void RemoveSelection(const TimeRange& time, const Track::Reference& track); void RemoveSelection(Block* item); const TimelineWidgetSelections& GetSelections() const { return selections_; } void SetSelections(const TimelineWidgetSelections &s, bool process_block_changes); Track* GetTrackFromReference(const Track::Reference& ref) const; void SetViewBeamCursor(const TimelineCoordinate& coord); void SetViewTransitionOverlay(ClipBlock *out, ClipBlock *in); const QVector<TimelineViewGhostItem*>& GetGhostItems() const { return ghost_items_; } void InsertGapsAt(const rational& time, const rational& length, MultiUndoCommand *command); void StartRubberBandSelect(const QPoint& global_cursor_start); void MoveRubberBandSelect(bool enable_selecting, bool select_links); void EndRubberBandSelect(); int GetTrackY(const Track::Reference& ref); int GetTrackHeight(const Track::Reference& ref); void AddGhost(TimelineViewGhostItem* ghost); void ClearGhosts(); bool HasGhosts() const { return !ghost_items_.isEmpty(); } bool IsBlockSelected(Block* b) const { return selected_blocks_.contains(b); } void SetBlockLinksSelected(ClipBlock *block, bool selected); void QueueScroll(int value); TimelineView* GetFirstTimelineView(); rational GetTimebaseForTrackType(Track::Type type); const QRect &GetRubberBandGeometry() const; /** * @brief Track blocks that have newly been selected (this is preferred over emitting BlocksSelected directly) * * TimelineWidget keeps track of which blocks are selected internally. Calling this function will * add to that list and emit a signal to other widgets that said blocks have been selected. * * @param selected_blocks * * The list of blocks to add to the internal selection list and signal. * * @param filter * * TRUE to automatically filter blocks that are already selected from the list. In most cases, * this is preferable and should only be set to FALSE if the list is guaranteed not to contain * already selected blocks (and therefore filtering can be skipped to save time). */ void SignalSelectedBlocks(QVector<Block *> selected_blocks, bool filter = true); /** * @brief Track blocks that have been newly deselected */ void SignalDeselectedBlocks(const QVector<Block *> &deselected_blocks); /** * @brief Convenience function to deselect all blocks and signal them */ void SignalDeselectedAllBlocks(); void Refresh() { UpdateViewports(); } MultiUndoCommand *TakeSubtitleSectionCommand() { // Copy pointer MultiUndoCommand *c = subtitle_show_command_; // Set to null subtitle_show_command_ = nullptr; subtitle_tentative_track_ = nullptr; // Return command return c; } class SetSelectionsCommand : public UndoCommand { public: SetSelectionsCommand(TimelineWidget* timeline, const TimelineWidgetSelections& now, const TimelineWidgetSelections& old, bool process_block_changes = true) : timeline_(timeline), old_(old), now_(now), process_block_changes_(process_block_changes) { } virtual Project* GetRelevantProject() const override {return nullptr;} protected: virtual void redo() override { timeline_->SetSelections(now_, process_block_changes_); } virtual void undo() override { timeline_->SetSelections(old_, process_block_changes_); } private: TimelineWidget* timeline_; TimelineWidgetSelections old_; TimelineWidgetSelections now_; bool process_block_changes_; }; public slots: void ClearTentativeSubtitleTrack(); void RenameSelectedBlocks(); signals: void BlockSelectionChanged(const QVector<Block*>& selected_blocks); void RequestCaptureStart(const TimeRange &time, const Track::Reference &track); void RevealViewerInFootageViewer(ViewerOutput *r, const TimeRange &range); void RevealViewerInProject(ViewerOutput *r); protected: virtual void resizeEvent(QResizeEvent *event) override; virtual void TimeChangedEvent(const rational &) override; virtual void TimebaseChangedEvent(const rational &) override; virtual void ScaleChangedEvent(const double &) override; virtual void ConnectNodeEvent(ViewerOutput* n) override; virtual void DisconnectNodeEvent(ViewerOutput* n) override; virtual const QVector<Block*> *GetSnapBlocks() const override { return &added_blocks_; } protected slots: virtual void SendCatchUpScrollEvent() override; private: QVector<Timeline::EditToInfo> GetEditToInfo(const rational &playhead_time, Timeline::MovementMode mode); void RippleTo(Timeline::MovementMode mode); void EditTo(Timeline::MovementMode mode); void UpdateViewports(const Track::Type& type = Track::kNone); bool PasteInternal(bool insert); TimelineAndTrackView *AddTimelineAndTrackView(Qt::Alignment alignment); QHash<Node*, Node*> GenerateExistingPasteMap(const ProjectSerializer::Result &r); QRubberBand rubberband_; QVector<QPointF> rubberband_scene_pos_; TimelineWidgetSelections rubberband_old_selections_; QVector<Block*> rubberband_now_selected_; bool rubberband_enable_selecting_; bool rubberband_select_links_; TimelineWidgetSelections selections_; TimelineTool* GetActiveTool(); QVector<TimelineTool*> tools_; ImportTool* import_tool_; TimelineTool* active_tool_; QVector<TimelineViewGhostItem*> ghost_items_; QVector<TimelineAndTrackView*> views_; RationalSlider* timecode_label_; QVector<Block*> selected_blocks_; QVector<Block*> added_blocks_; int deferred_scroll_value_; bool use_audio_time_units_; QSplitter* view_splitter_; MultiUndoCommand *subtitle_show_command_; Track *subtitle_tentative_track_; QTimer *signal_block_change_timer_; class SetSplitterSizesCommand : public UndoCommand { public: SetSplitterSizesCommand(QSplitter *splitter, const QList<int> &sizes) : splitter_(splitter), new_sizes_(sizes) {} virtual Project* GetRelevantProject() const override { return nullptr; } protected: virtual void redo() override; virtual void undo() override; private: QSplitter *splitter_; QList<int> new_sizes_; QList<int> old_sizes_; }; void CenterOn(qreal scene_pos); void UpdateViewTimebases(); void NudgeInternal(rational amount); void MoveToPlayheadInternal(bool out); private slots: void ViewMousePressed(TimelineViewMouseEvent* event); void ViewMouseMoved(TimelineViewMouseEvent* event); void ViewMouseReleased(TimelineViewMouseEvent* event); void ViewMouseDoubleClicked(TimelineViewMouseEvent* event); void ViewDragEntered(TimelineViewMouseEvent* event); void ViewDragMoved(TimelineViewMouseEvent* event); void ViewDragLeft(QDragLeaveEvent* event); void ViewDragDropped(TimelineViewMouseEvent* event); void AddBlock(Block* block); void RemoveBlock(Block *blocks); void AddTrack(Track* track); void RemoveTrack(Track* track); void TrackUpdated(); void BlockUpdated(); void UpdateHorizontalSplitters(); void UpdateTimecodeWidthFromSplitters(QSplitter *s); void ShowContextMenu(); void DeferredScrollAction(); void ShowSequenceDialog(); void SetUseAudioTimeUnits(bool use); void ToolChanged(); void AddableObjectChanged(); void SetViewWaveformsEnabled(bool e); void SetViewThumbnailsEnabled(QAction *action); void FrameRateChanged(); void SampleRateChanged(); void TrackIndexChanged(int old, int now); void SignalBlockSelectionChange(); void RevealInFootageViewer(); void RevealInProject(); void TrackAboutToBeDeleted(Track *track); void SetSelectedClipsAutocaching(bool e); void CacheClips(); void CacheClipsInOut(); void CacheDiscard(); void MulticamEnabledTriggered(bool e); void ForceUpdateRubberBand(); }; } #endif // TIMELINEWIDGET_H
11,589
C++
.h
307
34.032573
161
0.774434
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,209
timelinewidgetselections.h
olive-editor_olive/app/widget/timelinewidget/timelinewidgetselections.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 TIMELINEWIDGETSELECTIONS_H #define TIMELINEWIDGETSELECTIONS_H #include <QHash> #include "node/output/track/track.h" namespace olive { class TimelineWidgetSelections : public QHash<Track::Reference, TimeRangeList> { public: TimelineWidgetSelections() = default; void ShiftTime(const rational& diff); void ShiftTracks(Track::Type type, int diff); void TrimIn(const rational& diff); void TrimOut(const rational& diff); void Subtract(const TimelineWidgetSelections &selections); TimelineWidgetSelections Subtracted(const TimelineWidgetSelections &selections) const { TimelineWidgetSelections copy = *this; copy.Subtract(selections); return copy; } }; } #endif // TIMELINEWIDGETSELECTIONS_H
1,449
C++
.h
37
36.189189
87
0.787509
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,210
timelineandtrackview.h
olive-editor_olive/app/widget/timelinewidget/timelineandtrackview.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 TIMELINEANDTRACKVIEW_H #define TIMELINEANDTRACKVIEW_H #include <QSplitter> #include <QWidget> #include "view/timelineview.h" #include "trackview/trackview.h" namespace olive { class TimelineAndTrackView : public QWidget { public: TimelineAndTrackView(Qt::Alignment vertical_alignment = Qt::AlignTop, QWidget* parent = nullptr); QSplitter* splitter() const; TimelineView* view() const; TrackView* track_view() const; private: QSplitter* splitter_; TimelineView* view_; TrackView* track_view_; private slots: void ViewValueChanged(int v); void TracksValueChanged(int v); }; } #endif // TIMELINEANDTRACKVIEW_H
1,383
C++
.h
39
32.25641
71
0.767952
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,211
trackviewsplitter.h
olive-editor_olive/app/widget/timelinewidget/trackview/trackviewsplitter.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 TRACKVIEWSPLITTER_H #define TRACKVIEWSPLITTER_H #include <QSplitter> #include "common/define.h" namespace olive { class TrackViewSplitterHandle : public QSplitterHandle { Q_OBJECT public: TrackViewSplitterHandle(Qt::Orientation orientation, QSplitter *parent); protected: virtual void mousePressEvent(QMouseEvent *e) override; virtual void mouseMoveEvent(QMouseEvent *e) override; virtual void mouseReleaseEvent(QMouseEvent *e) override; virtual void paintEvent(QPaintEvent *e) override; private: int drag_y_; bool dragging_; }; class TrackViewSplitter : public QSplitter { Q_OBJECT public: TrackViewSplitter(Qt::Alignment vertical_alignment, QWidget* parent = nullptr); void HandleReceiver(TrackViewSplitterHandle* h, int diff); void SetHeightWithSizes(QList<int> sizes); void Insert(int index, int height, QWidget* item); void Remove(int index); void SetSpacerHeight(int height); public slots: void SetTrackHeight(int index, int h); signals: void TrackHeightChanged(int index, int height); protected: virtual QSplitterHandle *createHandle() override; private: Qt::Alignment alignment_; int spacer_height_; }; } #endif // TRACKVIEWSPLITTER_H
1,924
C++
.h
55
32.327273
81
0.791531
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,212
trackviewitem.h
olive-editor_olive/app/widget/timelinewidget/trackview/trackviewitem.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 TRACKVIEWITEM_H #define TRACKVIEWITEM_H #include <QPushButton> #include <QStackedWidget> #include <QWidget> #include "node/output/track/track.h" #include "widget/clickablelabel/clickablelabel.h" #include "widget/focusablelineedit/focusablelineedit.h" #include "widget/timelinewidget/view/timelineviewmouseevent.h" namespace olive { class TrackViewItem : public QWidget { Q_OBJECT public: TrackViewItem(Track* track, QWidget* parent = nullptr); signals: void AboutToDeleteTrack(Track *track); private: QPushButton* CreateMSLButton(const QColor &checked_color) const; QStackedWidget* stack_; ClickableLabel* label_; FocusableLineEdit* line_edit_; QPushButton* mute_button_; QPushButton* solo_button_; QPushButton* lock_button_; Track* track_; private slots: void LabelClicked(); void LineEditConfirmed(); void LineEditCancelled(); void UpdateLabel(); void ShowContextMenu(const QPoint &p); void DeleteTrack(); void DeleteAllEmptyTracks(); void UpdateMuteButton(bool e); void UpdateLockButton(bool e); }; } #endif // TRACKVIEWITEM_H
1,828
C++
.h
54
30.851852
71
0.778923
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,213
trackview.h
olive-editor_olive/app/widget/timelinewidget/trackview/trackview.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 TRACKVIEW_H #define TRACKVIEW_H #include <QScrollArea> #include <QSplitter> #include "node/output/track/tracklist.h" #include "trackviewitem.h" #include "trackviewsplitter.h" namespace olive { class TrackView : public QScrollArea { Q_OBJECT public: TrackView(Qt::Alignment vertical_alignment = Qt::AlignTop, QWidget* parent = nullptr); void ConnectTrackList(TrackList* list); void DisconnectTrackList(); signals: void AboutToDeleteTrack(Track *track); protected: virtual void resizeEvent(QResizeEvent *e) override; private: TrackList* list_; TrackViewSplitter* splitter_; Qt::Alignment alignment_; int last_scrollbar_max_; private slots: void ScrollbarRangeChanged(int min, int max); void TrackHeightChanged(int index, int height); void InsertTrack(Track* track); void RemoveTrack(Track* track); }; } #endif // TRACKVIEW_H
1,601
C++
.h
47
31.191489
71
0.775817
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,214
slip.h
olive-editor_olive/app/widget/timelinewidget/tool/slip.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 SLIPTIMELINETOOL_H #define SLIPTIMELINETOOL_H #include "pointer.h" namespace olive { class SlipTool : public PointerTool { public: SlipTool(TimelineWidget* parent); protected: virtual void ProcessDrag(const TimelineCoordinate &mouse_pos) override; virtual void FinishDrag(TimelineViewMouseEvent *event) override; }; } #endif // SLIPTIMELINETOOL_H
1,079
C++
.h
28
36.035714
73
0.790183
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,215
ripple.h
olive-editor_olive/app/widget/timelinewidget/tool/ripple.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 RIPPLETIMELINETOOL_H #define RIPPLETIMELINETOOL_H #include "pointer.h" namespace olive { class RippleTool : public PointerTool { public: RippleTool(TimelineWidget* parent); protected: virtual void FinishDrag(TimelineViewMouseEvent *event) override; virtual void InitiateDrag(Block* clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers) override; }; } #endif // RIPPLETIMELINETOOL_H
1,141
C++
.h
28
38.25
125
0.792916
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,216
pointer.h
olive-editor_olive/app/widget/timelinewidget/tool/pointer.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 POINTERTIMELINETOOL_H #define POINTERTIMELINETOOL_H #include "tool.h" namespace olive { class PointerTool : public TimelineTool { public: PointerTool(TimelineWidget* parent); virtual void MousePress(TimelineViewMouseEvent *event) override; virtual void MouseMove(TimelineViewMouseEvent *event) override; virtual void MouseRelease(TimelineViewMouseEvent *event) override; virtual void HoverMove(TimelineViewMouseEvent *event) override; protected: virtual void FinishDrag(TimelineViewMouseEvent *event); virtual void InitiateDrag(Block* clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers); TimelineViewGhostItem *GetExistingGhostFromBlock(Block *block); TimelineViewGhostItem* AddGhostFromBlock(Block *block, Timeline::MovementMode mode, bool check_if_exists = false); TimelineViewGhostItem* AddGhostFromNull(const rational& in, const rational& out, const Track::Reference& track, Timeline::MovementMode mode); /** * @brief Validates Ghosts that are getting their in points trimmed * * Assumes ghost->data() is a Block. Ensures no Ghost's in point becomes a negative timecode. Also ensures no * Ghost's length becomes 0 or negative. */ rational ValidateInTrimming(rational movement); /** * @brief Validates Ghosts that are getting their out points trimmed * * Assumes ghost->data() is a Block. Ensures no Ghost's in point becomes a negative timecode. Also ensures no * Ghost's length becomes 0 or negative. */ rational ValidateOutTrimming(rational movement); virtual void ProcessDrag(const TimelineCoordinate &mouse_pos); void InitiateDragInternal(Block* clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers, bool dont_roll_trims, bool allow_nongap_rolling, bool slide_instead_of_moving); const Timeline::MovementMode& drag_movement_mode() const { return drag_movement_mode_; } void set_drag_movement_mode(const Timeline::MovementMode &d) { drag_movement_mode_ = d; } static bool CanTransitionMove(TransitionBlock *transit, const QVector<Block*> &clips); void SetMovementAllowed(bool e) { movement_allowed_ = e; } void SetTrimmingAllowed(bool e) { trimming_allowed_ = e; } void SetTrackMovementAllowed(bool e) { track_movement_allowed_ = e; } void SetGapTrimmingAllowed(bool e) { gap_trimming_allowed_ = e; } void SetClickedItem(Block *b) { clicked_item_ = b; } private: Timeline::MovementMode IsCursorInTrimHandle(Block* block, qreal cursor_x); void AddGhostInternal(TimelineViewGhostItem* ghost, Timeline::MovementMode mode); bool IsClipTrimmable(Block* clip, const QVector<Block*> &items, const Timeline::MovementMode& mode); void ProcessGhostsForSliding(); void ProcessGhostsForRolling(); bool movement_allowed_; bool trimming_allowed_; bool track_movement_allowed_; bool gap_trimming_allowed_; bool can_rubberband_select_; bool rubberband_selecting_; Track::Type drag_track_type_; Timeline::MovementMode drag_movement_mode_; Block* clicked_item_; QPoint drag_global_start_; }; } #endif // POINTERTIMELINETOOL_H
4,029
C++
.h
96
37.125
143
0.74679
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,217
transition.h
olive-editor_olive/app/widget/timelinewidget/tool/transition.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 TRANSITIONTIMELINETOOL_H #define TRANSITIONTIMELINETOOL_H #include "add.h" namespace olive { class TransitionTool : public AddTool { public: TransitionTool(TimelineWidget* parent); virtual void HoverMove(TimelineViewMouseEvent *event) override; virtual void MousePress(TimelineViewMouseEvent *event) override; virtual void MouseMove(TimelineViewMouseEvent *event) override; virtual void MouseRelease(TimelineViewMouseEvent *event) override; private: bool GetBlocksAtCoord(const TimelineCoordinate &coord, ClipBlock **primary, ClipBlock **secondary, Timeline::MovementMode *trim_mode, rational *start_point); bool dual_transition_; }; } #endif // TRANSITIONTIMELINETOOL_H
1,415
C++
.h
32
41.53125
159
0.800293
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,218
add.h
olive-editor_olive/app/widget/timelinewidget/tool/add.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 ADDTIMELINETOOL_H #define ADDTIMELINETOOL_H #include "beam.h" namespace olive { class AddTool : public BeamTool { public: AddTool(TimelineWidget* parent); virtual void MousePress(TimelineViewMouseEvent *event) override; virtual void MouseMove(TimelineViewMouseEvent *event) override; virtual void MouseRelease(TimelineViewMouseEvent *event) override; static Node *CreateAddableClip(MultiUndoCommand *command, Sequence *sequence, const Track::Reference &track, const rational &in, const rational &length, const QRectF &rect = QRectF()); protected: void MouseMoveInternal(const rational& cursor_frame, bool outwards); TimelineViewGhostItem* ghost_; rational drag_start_point_; }; } #endif // ADDTIMELINETOOL_H
1,454
C++
.h
33
41.363636
186
0.791459
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,219
trackselect.h
olive-editor_olive/app/widget/timelinewidget/tool/trackselect.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 TRACKSELECTTOOL_H #define TRACKSELECTTOOL_H #include "pointer.h" namespace olive { class TrackSelectTool : public PointerTool { public: TrackSelectTool(TimelineWidget *parent); virtual void MousePress(TimelineViewMouseEvent *event) override; private: void SelectBlocksOnTrack(Track *track, TimelineViewMouseEvent *event, QVector<Block *> *blocks, bool forward); }; } #endif // TRACKSELECTTOOL_H
1,129
C++
.h
28
37.75
112
0.789328
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,220
record.h
olive-editor_olive/app/widget/timelinewidget/tool/record.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 RECORDTIMELINETOOL_H #define RECORDTIMELINETOOL_H #include "beam.h" namespace olive { class RecordTool : public BeamTool { public: RecordTool(TimelineWidget* parent); virtual void MousePress(TimelineViewMouseEvent *event) override; virtual void MouseMove(TimelineViewMouseEvent *event) override; virtual void MouseRelease(TimelineViewMouseEvent *event) override; protected: void MouseMoveInternal(const rational& cursor_frame, bool outwards); TimelineViewGhostItem* ghost_; rational drag_start_point_; }; } #endif // RECORDTOOL_H
1,274
C++
.h
32
37.125
71
0.794454
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,221
beam.h
olive-editor_olive/app/widget/timelinewidget/tool/beam.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 BEAMTIMELINETOOL_H #define BEAMTIMELINETOOL_H #include "tool.h" namespace olive { class BeamTool : public TimelineTool { public: BeamTool(TimelineWidget *parent); virtual void HoverMove(TimelineViewMouseEvent *event) override; protected: TimelineCoordinate ValidatedCoordinate(TimelineCoordinate coord); }; } #endif // BEAMTIMELINETOOL_H
1,072
C++
.h
28
35.714286
71
0.793204
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,222
zoom.h
olive-editor_olive/app/widget/timelinewidget/tool/zoom.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 ZOOMTIMELINETOOL_H #define ZOOMTIMELINETOOL_H #include "tool.h" namespace olive { class ZoomTool : public TimelineTool { public: ZoomTool(TimelineWidget* parent); virtual void MousePress(TimelineViewMouseEvent *event) override; virtual void MouseMove(TimelineViewMouseEvent *event) override; virtual void MouseRelease(TimelineViewMouseEvent *event) override; private: QPoint drag_global_start_; }; } #endif // ZOOMTIMELINETOOL_H
1,167
C++
.h
30
36.3
71
0.79252
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,223
slide.h
olive-editor_olive/app/widget/timelinewidget/tool/slide.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 SLIDETIMELINETOOL_H #define SLIDETIMELINETOOL_H #include "pointer.h" namespace olive { class SlideTool : public PointerTool { public: SlideTool(TimelineWidget* parent); protected: virtual void InitiateDrag(Block* clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers) override; }; } #endif // SLIDETIMELINETOOL_H
1,070
C++
.h
27
37.111111
125
0.78835
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,224
rolling.h
olive-editor_olive/app/widget/timelinewidget/tool/rolling.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 ROLLINGTIMELINETOOL_H #define ROLLINGTIMELINETOOL_H #include "pointer.h" namespace olive { class RollingTool : public PointerTool { public: RollingTool(TimelineWidget* parent); protected: virtual void InitiateDrag(Block* clicked_item, Timeline::MovementMode trim_mode, Qt::KeyboardModifiers modifiers) override; }; } #endif // ROLLINGTIMELINETOOL_H
1,079
C++
.h
27
37.481481
125
0.790385
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,225
tool.h
olive-editor_olive/app/widget/timelinewidget/tool/tool.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 TIMELINETOOL_H #define TIMELINETOOL_H #include <QDragLeaveEvent> #include "widget/timelinewidget/view/timelineviewghostitem.h" #include "widget/timelinewidget/view/timelineviewmouseevent.h" namespace olive { class TimelineWidget; class TimelineTool { public: TimelineTool(TimelineWidget* parent); virtual ~TimelineTool(); virtual void MousePress(TimelineViewMouseEvent *){} virtual void MouseMove(TimelineViewMouseEvent *){} virtual void MouseRelease(TimelineViewMouseEvent *){} virtual void MouseDoubleClick(TimelineViewMouseEvent *){} virtual void HoverMove(TimelineViewMouseEvent *){} virtual void DragEnter(TimelineViewMouseEvent *){} virtual void DragMove(TimelineViewMouseEvent *){} virtual void DragLeave(QDragLeaveEvent *){} virtual void DragDrop(TimelineViewMouseEvent *){} TimelineWidget* parent(); Sequence* sequence(); static Timeline::MovementMode FlipTrimMode(const Timeline::MovementMode& trim_mode); static rational SnapMovementToTimebase(const rational& start, rational movement, const rational& timebase); protected: /** * @brief Validates Ghosts that are moving horizontally (time-based) * * Validation is the process of ensuring that whatever movements the user is making are "valid" and "legal". This * function's validation ensures that no Ghost's in point ends up in a negative timecode. */ rational ValidateTimeMovement(rational movement); /** * @brief Validates Ghosts that are moving vertically (track-based) * * This function's validation ensures that no Ghost's track ends up in a negative (non-existent) track. */ int ValidateTrackMovement(int movement, const QVector<TimelineViewGhostItem *> &ghosts); void GetGhostData(rational *earliest_point, rational *latest_point); void InsertGapsAtGhostDestination(MultiUndoCommand* command); std::vector<rational> snap_points_; bool dragging_; TimelineCoordinate drag_start_; static const int kDefaultDistanceFromOutput; private: TimelineWidget* parent_; }; } #endif // TIMELINETOOL_H
2,779
C++
.h
64
40.34375
115
0.789572
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,226
import.h
olive-editor_olive/app/widget/timelinewidget/tool/import.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 IMPORTTIMELINETOOL_H #define IMPORTTIMELINETOOL_H #include "tool.h" namespace olive { class ImportTool : public TimelineTool { public: ImportTool(TimelineWidget* parent); virtual void DragEnter(TimelineViewMouseEvent *event) override; virtual void DragMove(TimelineViewMouseEvent *event) override; virtual void DragLeave(QDragLeaveEvent *event) override; virtual void DragDrop(TimelineViewMouseEvent *event) override; using DraggedFootageData = QVector<QPair<ViewerOutput*, QVector<Track::Reference> > >; void PlaceAt(const QVector<ViewerOutput *> &footage, const rational& start, bool insert, MultiUndoCommand *command, int track_offset = 0, bool jump_to_end = false); void PlaceAt(const DraggedFootageData &footage, const rational& start, bool insert, MultiUndoCommand *command, int track_offset = 0, bool jump_to_end = false); enum DropWithoutSequenceBehavior { kDWSAsk, kDWSAuto, kDWSManual, kDWSDisable }; private: void FootageToGhosts(rational ghost_start, const DraggedFootageData &footage, const rational &dest_tb, const int &track_start); void PrepGhosts(const rational &frame, const int &track_index); void DropGhosts(bool insert, MultiUndoCommand *parent_command); TimelineViewGhostItem* CreateGhost(const TimeRange &range, const rational &media_in, const Track::Reference &track); DraggedFootageData dragged_footage_; int import_pre_buffer_; rational ghost_offset_; }; } #endif // IMPORTTIMELINETOOL_H
2,201
C++
.h
46
44.73913
166
0.787054
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,227
edit.h
olive-editor_olive/app/widget/timelinewidget/tool/edit.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 EDITTIMELINETOOL_H #define EDITTIMELINETOOL_H #include "beam.h" #include "tool.h" #include "widget/timelinewidget/timelinewidgetselections.h" namespace olive { class EditTool : public BeamTool { public: EditTool(TimelineWidget* parent); virtual void MousePress(TimelineViewMouseEvent *event) override; virtual void MouseMove(TimelineViewMouseEvent *event) override; virtual void MouseRelease(TimelineViewMouseEvent *event) override; virtual void MouseDoubleClick(TimelineViewMouseEvent *event) override; private: TimelineWidgetSelections start_selections_; TimelineCoordinate start_coord_; }; } #endif // EDITTIMELINETOOL_H
1,367
C++
.h
34
37.647059
72
0.802731
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,228
razor.h
olive-editor_olive/app/widget/timelinewidget/tool/razor.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 RAZORTIMELINETOOL_H #define RAZORTIMELINETOOL_H #include "beam.h" namespace olive { class RazorTool : public BeamTool { public: RazorTool(TimelineWidget* parent); virtual void MousePress(TimelineViewMouseEvent *event) override; virtual void MouseMove(TimelineViewMouseEvent *event) override; virtual void MouseRelease(TimelineViewMouseEvent *event) override; private: QVector<Track::Reference> split_tracks_; }; } #endif // RAZORTIMELINETOOL_H
1,181
C++
.h
30
36.8
71
0.792619
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,229
timelineview.h
olive-editor_olive/app/widget/timelinewidget/view/timelineview.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 TIMELINEVIEW_H #define TIMELINEVIEW_H #include <QGraphicsView> #include <QDragEnterEvent> #include <QDragMoveEvent> #include <QDragLeaveEvent> #include <QDropEvent> #include "node/block/clip/clip.h" #include "timelineviewmouseevent.h" #include "timelineviewghostitem.h" #include "widget/timebased/timebasedview.h" namespace olive { /** * @brief A widget for viewing and interacting Sequences * * This widget primarily exposes users to viewing and modifying Block nodes, usually through a TimelineOutput node. */ class TimelineView : public TimeBasedView { Q_OBJECT public: TimelineView(Qt::Alignment vertical_alignment = Qt::AlignTop, QWidget* parent = nullptr); int GetTrackY(int track_index) const; int GetTrackHeight(int track_index) const; QPoint GetScrollCoordinates() const; void SetScrollCoordinates(const QPoint& pt); void ConnectTrackList(TrackList* list); void SetBeamCursor(const TimelineCoordinate& coord); void SetTransitionOverlay(ClipBlock *out, ClipBlock *in); void EnableRecordingOverlay(const TimelineCoordinate &coord); void DisableRecordingOverlay(); void SetSelectionList(QHash<Track::Reference, TimeRangeList>* s) { selections_ = s; } void SetGhostList(QVector<TimelineViewGhostItem*>* ghosts) { ghosts_ = ghosts; } int SceneToTrack(double y); Block* GetItemAtScenePos(const rational& time, int track_index) const; QVector<Block*> GetItemsAtSceneRect(const QRectF &rect) const; signals: void MousePressed(TimelineViewMouseEvent* event); void MouseMoved(TimelineViewMouseEvent* event); void MouseReleased(TimelineViewMouseEvent* event); void MouseDoubleClicked(TimelineViewMouseEvent* event); void DragEntered(TimelineViewMouseEvent* event); void DragMoved(TimelineViewMouseEvent* event); void DragLeft(QDragLeaveEvent* event); void DragDropped(TimelineViewMouseEvent* event); protected: virtual void mousePressEvent(QMouseEvent *event) override; virtual void mouseMoveEvent(QMouseEvent *event) override; virtual void mouseReleaseEvent(QMouseEvent *event) override; virtual void mouseDoubleClickEvent(QMouseEvent *event) override; virtual void dragEnterEvent(QDragEnterEvent *event) override; virtual void dragMoveEvent(QDragMoveEvent *event) override; virtual void dragLeaveEvent(QDragLeaveEvent *event) override; virtual void dropEvent(QDropEvent *event) override; virtual void drawBackground(QPainter *painter, const QRectF &rect) override; virtual void drawForeground(QPainter *painter, const QRectF &rect) override; virtual void ToolChangedEvent(Tool::Item tool) override; virtual void SceneRectUpdateEvent(QRectF& rect) override; private: Track::Type ConnectedTrackType(); TimelineCoordinate ScreenToCoordinate(const QPoint& pt); TimelineCoordinate SceneToCoordinate(const QPointF& pt); TimelineViewMouseEvent CreateMouseEvent(QMouseEvent* event); TimelineViewMouseEvent CreateMouseEvent(const QPoint &pos, Qt::MouseButton button, Qt::KeyboardModifiers modifiers); void DrawBlocks(QPainter* painter, bool foreground); void DrawBlock(QPainter *painter, bool foreground, Block *block, qreal top, qreal height, const rational &in, const rational &out, const rational &media_in); void DrawBlock(QPainter *painter, bool foreground, Block *block, qreal top, qreal height) { ClipBlock *cb = dynamic_cast<ClipBlock*>(block); return DrawBlock(painter, foreground, block, top, height, block->in(), block->out(), cb ? cb->media_in() : 0); } void DrawZebraStripes(QPainter *painter, const QRectF &r); int GetHeightOfAllTracks() const; void UpdatePlayheadRect(); qreal GetTimelineLeftBound() const; qreal GetTimelineRightBound() const; void DrawThumbnail(QPainter *painter, const FrameHashCache *thumbs, const rational &time, int x, const QRect &preview_rect, QRect *thumb_rect) const; QHash<Track::Reference, TimeRangeList>* selections_; QVector<TimelineViewGhostItem*>* ghosts_; bool show_beam_cursor_; TimelineCoordinate cursor_coord_; TrackList* connected_track_list_; ClipBlock *transition_overlay_out_; ClipBlock *transition_overlay_in_; QMap<TimelineMarker*, QRectF> clip_marker_rects_; bool recording_overlay_; TimelineCoordinate recording_coord_; private slots: void TrackListChanged(); }; } #endif // TIMELINEVIEW_H
5,072
C++
.h
113
41.743363
159
0.793075
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,230
timelineviewmouseevent.h
olive-editor_olive/app/widget/timelinewidget/view/timelineviewmouseevent.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 TIMELINEVIEWMOUSEEVENT_H #define TIMELINEVIEWMOUSEEVENT_H #include <QEvent> #include <QMimeData> #include <QPointF> #include <QPoint> #include "timeline/timelinecoordinate.h" #include "widget/timebased/timescaledobject.h" namespace olive { class TimelineViewMouseEvent { public: TimelineViewMouseEvent(const QPointF& scene_pos, const QPoint &screen_pos, const double& scale_x, const rational& timebase, const Track::Reference &track, const Qt::MouseButton &button, const Qt::KeyboardModifiers& modifiers = Qt::NoModifier) : scene_pos_(scene_pos), screen_pos_(screen_pos), scale_x_(scale_x), timebase_(timebase), track_(track), button_(button), modifiers_(modifiers), source_event_(nullptr), mime_data_(nullptr), bypass_import_buffer_(false) { } TimelineCoordinate GetCoordinates(bool round_time = false) const { return TimelineCoordinate(GetFrame(round_time), track_); } const Qt::KeyboardModifiers& GetModifiers() const { return modifiers_; } /** * @brief Gets the time at this cursor point * * @param round * * If set to true, the time will be rounded to the nearest time. If set to false, the time is floored so the time is * always to the left of the cursor. The former behavior is better for clicking between frames (e.g. razor tool) and * the latter is better for clicking directly on frames (e.g. pointer tool). */ rational GetFrame(bool round = false) const { return TimeScaledObject::SceneToTime(GetSceneX(), scale_x_, timebase_, round); } const Track::Reference& GetTrack() const { return track_; } const QMimeData *GetMimeData() { return mime_data_; } void SetMimeData(const QMimeData *data) { mime_data_ = data; } void SetEvent(QEvent* event) { source_event_ = event; } qreal GetSceneX() const { return scene_pos_.x(); } const QPointF &GetScenePos() const { return scene_pos_; } const QPoint &GetScreenPos() const { return screen_pos_; } const Qt::MouseButton& GetButton() const { return button_; } void accept() { if (source_event_ != nullptr) source_event_->accept(); } void ignore() { if (source_event_ != nullptr) source_event_->ignore(); } bool GetBypassImportBuffer() const { return bypass_import_buffer_; } void SetBypassImportBuffer(bool e) { bypass_import_buffer_ = e; } private: QPointF scene_pos_; QPoint screen_pos_; double scale_x_; rational timebase_; Track::Reference track_; Qt::MouseButton button_; Qt::KeyboardModifiers modifiers_; QEvent* source_event_; const QMimeData* mime_data_; bool bypass_import_buffer_; }; } #endif // TIMELINEVIEWMOUSEEVENT_H
3,601
C++
.h
118
25.881356
118
0.693623
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,231
timelineviewghostitem.h
olive-editor_olive/app/widget/timelinewidget/view/timelineviewghostitem.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 TIMELINEVIEWGHOSTITEM_H #define TIMELINEVIEWGHOSTITEM_H #include <QVariant> #include "node/block/clip/clip.h" #include "node/block/transition/transition.h" #include "node/output/track/track.h" #include "node/project/footage/footage.h" #include "timeline/timelinecommon.h" namespace olive { /** * @brief A graphical representation of changes the user is making before they apply it */ class TimelineViewGhostItem { public: enum DataType { kAttachedBlock, kReferenceBlock, kAttachedFootage, kGhostIsSliding, kTrimIsARollEdit, kTrimShouldBeIgnored }; struct AttachedFootage { ViewerOutput* footage; QString output; }; TimelineViewGhostItem() : track_adj_(0), mode_(Timeline::kNone), can_have_zero_length_(true), can_move_tracks_(true), invisible_(false) { } static TimelineViewGhostItem* FromBlock(Block *block) { TimelineViewGhostItem* ghost = new TimelineViewGhostItem(); ghost->SetIn(block->in()); ghost->SetOut(block->out()); if (dynamic_cast<ClipBlock*>(block)) { ghost->SetMediaIn(static_cast<ClipBlock*>(block)->media_in()); } ghost->SetTrack(block->track()->ToReference()); ghost->SetData(kAttachedBlock, QtUtils::PtrToValue(block)); if (dynamic_cast<ClipBlock*>(block)) { ghost->can_have_zero_length_ = false; } else if (dynamic_cast<TransitionBlock*>(block)) { ghost->can_have_zero_length_ = false; } return ghost; } bool CanHaveZeroLength() const { return can_have_zero_length_; } bool GetCanMoveTracks() const { return can_move_tracks_; } void SetCanMoveTracks(bool e) { can_move_tracks_ = e; } const rational& GetIn() const { return in_; } const rational& GetOut() const { return out_; } const rational& GetMediaIn() const { return media_in_; } rational GetLength() const { return out_ - in_; } rational GetAdjustedLength() const { return GetAdjustedOut() - GetAdjustedIn(); } void SetIn(const rational& in) { in_ = in; } void SetOut(const rational& out) { out_ = out; } void SetMediaIn(const rational& media_in) { media_in_ = media_in; } void SetInAdjustment(const rational& in_adj) { in_adj_ = in_adj; } void SetOutAdjustment(const rational& out_adj) { out_adj_ = out_adj; } void SetTrackAdjustment(const int& track_adj) { track_adj_ = track_adj; } void SetMediaInAdjustment(const rational& media_in_adj) { media_in_adj_ = media_in_adj; } const rational& GetInAdjustment() const { return in_adj_; } const rational& GetOutAdjustment() const { return out_adj_; } const rational& GetMediaInAdjustment() const { return media_in_adj_; } const int& GetTrackAdjustment() const { return track_adj_; } rational GetAdjustedIn() const { return in_ + in_adj_; } rational GetAdjustedOut() const { return out_ + out_adj_; } rational GetAdjustedMediaIn() const { return media_in_ + media_in_adj_; } Track::Reference GetAdjustedTrack() const { return Track::Reference(track_.type(), track_.index() + track_adj_); } const Timeline::MovementMode& GetMode() const { return mode_; } void SetMode(const Timeline::MovementMode& mode) { mode_ = mode; } bool HasBeenAdjusted() const { return GetInAdjustment() != 0 || GetOutAdjustment() != 0 || GetMediaInAdjustment() != 0 || GetTrackAdjustment() != 0; } QVariant GetData(int key) const { return data_.value(key); } void SetData(int key, const QVariant& value) { data_.insert(key, value); } const Track::Reference& GetTrack() const { return track_; } void SetTrack(const Track::Reference& track) { track_ = track; } bool IsInvisible() const { return invisible_; } void SetInvisible(bool e) { invisible_ = e; } protected: private: rational in_; rational out_; rational media_in_; rational in_adj_; rational out_adj_; rational media_in_adj_; int track_adj_; Timeline::MovementMode mode_; bool can_have_zero_length_; bool can_move_tracks_; Track::Reference track_; QHash<int, QVariant> data_; bool invisible_; }; } Q_DECLARE_METATYPE(olive::TimelineViewGhostItem::AttachedFootage) #endif // TIMELINEVIEWGHOSTITEM_H
5,130
C++
.h
216
20.018519
87
0.694685
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,232
interlacedcombobox.h
olive-editor_olive/app/widget/standardcombos/interlacedcombobox.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 INTERLACEDCOMBOBOX_H #define INTERLACEDCOMBOBOX_H #include <QComboBox> #include "render/videoparams.h" namespace olive { class InterlacedComboBox : public QComboBox { Q_OBJECT public: InterlacedComboBox(QWidget* parent = nullptr) : QComboBox(parent) { // These must match the Interlacing enum in VideoParams this->addItem(tr("None (Progressive)")); this->addItem(tr("Top-Field First")); this->addItem(tr("Bottom-Field First")); } VideoParams::Interlacing GetInterlaceMode() const { return static_cast<VideoParams::Interlacing>(this->currentIndex()); } void SetInterlaceMode(VideoParams::Interlacing mode) { this->setCurrentIndex(mode); } }; } #endif // INTERLACEDCOMBOBOX_H
1,451
C++
.h
42
31.47619
71
0.761119
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